ACME(1)ACME(1)

ИМЯ
acme, win, awd – интерактивные текстовые окна

СИНТАКСИС
acme [ −abr ] [ −f varfont ] [ −F fixfont ] [ −c ncol ] [ −m mtpt ] [ −l файл | файл(файлы) ... ]
win [ command ]
awd [ label ]

ОПИСАНИЕ
Acme управляет окнами текста, которые могут быть отредактированы интерактивно или внешними программами. Интерактивный интерфейс использует клавиатуру и мышь; внешние программы используют набор файлов, предоставляемых acme; подробнее в acme(4).
Указанные файлы загружаются в окна acme перед тем как acme начнёт принимать ввод. С аргументом −l состояние всей программы загружается из файлa, который создаётся при помощи команды Dump (рассматривается ниже). Все последующие имена файлов будут проигнорированы. Обычные текстовые файлы отображаются как текст; каталоги отображаются табличным списком их содержимого, как вывод команды ls −p directory|mc , только к названиям подкаталогов добавится косая черта в конце.
Аргумент −f (−F) устанавливает основной шрифт, обычно — пропорциональный (альтернативно — моноширинный); Значение по-умолчанию — /usr/local/plan9/font/lucsans/euro.8.font (.../lucm/unicode.9.font). Интервалы табуляции устанавливаются равными ширине 4 нулевых символов соответствующего шрифта. (или значению переменной окружения $tabstop )
Аргумент −m предписывает acme использовать FUSE (см. 9pfuse(4)) чтобы смонтировать себя в mtpt. (Экспериментально.)

Окна
Acme окна состоят из двух частей: однострочный заголовок (tag) , под ним - многострочное тело. Тело, содержит представление файла, как в программе sam(1), или вывод программы, как в окне rio(1). Заголовок состоит из ряда разделённых пробелами слов, после которых идёт вертикальная черта, а далее произвольный текст. Первое слово — имя окна, обычно соответствующее имени ассоциированного файла или каталога, остальные слова — команды доступные в данном окне. После черты можно добавить любой текст; Например, строки для поиска или commands to execute in that window. команды для выполнения в этом окне. Изменения текста слева от черты будут проигнорированы, кроме случая изменения имени окна.
Если окно содержит каталог, имя (первое слово заголовка) будет оканчиваться косой чертой.

Скроллинг
Каждое окно имеет полосу прокрутки слева от тела окна. Полоса прокрутки ведёт себя почти также как в sam(1) или rio(1) за исключением того, что прокрутка происходит когда кнопка нажата, нежели отпущена и продолжается до тех пор, пока кнопка мыши удерживается нажатой внутри полосы прокрутки. Например, чтобы медленно пролистывать файл, нажмите и удерживайте кнопку 3 возле верхней части полосы прокрутки. Перемещение указателя мыши ниже по полосе увеличивает скорость прокрутки. (Экспериментальная опция меняет поведение кнопок 1 и 3 на противоположное, делая их работу похожей на программу xterm(1).)

Компоновка
Окна в Acme располагаются столбцами. По умолчанию при запуске создается два столбца; это поведение можно переопределить аргументом −c . Расположение окон автоматическое, но может быть изменено при помощи маркера расположения (layout box) в верхнем левом углу каждого окна и столбца. Нажатие и удержание любой кнопки мыши в области маркера позволяет перемещать соответствующее окно или столбец. В окне щелчок по маркеру расположения увеличивает размер окна не перемещая его: кнопка 1 немного расширяет окно, кнопка 2 растягивает его насколько возможно, оставляя от других окон в столбце лишь заголовки, а клик кнопкой 3 полностью заполняет весь столбец, временно скрывая другие окна в нём. (Они вернутся вновь все вместе, когда хотя бы одному из них потребуется внимание). Маркер расположения в обычном состоянии "белый"; Если он становится "тёмным" по- центру, это показывает что файл ’измененён’: acme полагает, что он был изменён относительно своего исходного содержимого.
Заголовки находятся вверху каждого столбца и вдоль всего окна приложения. Acme предзаполняет их полезными командами. Кроме того, самый верхний заголовок отображает список длительно выполняемых команд.

Typing
The behavior of typed text is similar to that in rio(1) except that the characters are delivered to the tag or body under the mouse; there is no ‘click to type’. (The experimental option −b causes typing to go to the most recently clicked-at or made window.) The usual backspacing conventions apply. As in sam(1) but not rio, the ESC key selects the text typed since the last mouse action, a feature particularly useful when executing commands. A side effect is that typing ESC with text already selected is identical to a Cut command (q.v.).
Most text, including the names of windows, may be edited uniformly. The only exception is that the command names to the left of the bar in a tag are maintained automatically; changes to them are repaired by acme.
When a window is in autoindent mode (see the Indent command below) and a newline character is typed, acme copies leading white space on the current line to the new line, and when a window is Put, acme removes all trailing end-of-line white space before writing the file. The option −a causes each window to start in autoindent mode.

Directory context
Each window’s tag names a directory: explicitly if the window holds a directory; implicitly if it holds a regular file (e.g. the directory /adm if the window holds /adm/users). This directory provides a context for interpreting file names in that window. For example, the string users in a window labeled /adm/ or /adm/keys will be interpreted as the file name /adm/users. The directory is defined purely textually, so it can be a non-existent directory or a real directory associated with a non-existent file (e.g. /adm/not−a−file). File names beginning with a slash are assumed to be absolute file names.

Errors
Windows whose names begin with or + conventionally hold diagnostics and other data not directly associated with files. A window labeled +Errors receives all diagnostics produced by acme itself. Diagnostics from commands run by acme appear in a window named directory/+Errors where directory is identified by the context of the command. These error windows are created when needed.

Кнопка мыши 1
Кнопка мыши 1 выделяет текст точно так же, как в sam(1) или rio(1), включая обычные соглашения о двойном щелчке.

Mouse button 2
Подобно выделению текста с помощью кнопки 1, кнопка 2 указывает текст, который следует выполнить как команду. Если выделенный текст содержит несколько слов разделенных пробелами, первое слово является именем команды, а остальные - ее аргументами. Если кнопка 2 нажата и отпущена без выделения текста, то acme the indicated text to find a command to run: начинает искать, какую команду он должен выполнить: if the click is within button-1-selected text, если клик был по выделенному кнопкой мыши 1 тексту, acme использует это выделение в качестве команды; иначе, acme берёт самую большую строку допустимых символов имени файла на которую пришелся клик. Допустимые символы имени файла - это алфавитно-цифровые символы и _ . − + /. Это поведение похоже на двойной клик с кнопкой 1 но, поскольку пустая команда не имела бы смысла, требуется только один клик.
Некоторые команды, по-соглашению начинающиеся с заглавной буквы, являются встроенными (built-ins) и исполняются непосредственно acme:
Cut   Delete Удаляет последний выделенный фрагмент текста и помещает его в буфер обмена.
Del   Закрывает окно. Если содержимое окна было изменено, выводит предупреждение; повторное нажатие Del закроет окно.
Delcol
Удаляет столбец вместе со всеми его окнами после проверки отсутствия несохранённых изменений в окнах.
Delete
Удалить окно без проверки на наличие изменений.
Dump   Записать состояние acme в указанный файл, либо, если имя файла не указано, в $HOME/acme.dump по-умолчанию.
Edit   Рассматривайте аргумент как команду редактирования текста в стиле sam(1). Язык Sam поддерживается полностью, кроме команд k, n, q, and !. The = command is slightly different: it includes the file name and gives only the line address unless the command is explicitly =#. The ‘current window’ for the command is the body
of the window in which the Edit command is executed. Usually the Edit command would be typed in a tag; longer commands may be prepared in a scratch window and executed, with Edit itself in the current window, using the 2-1 chord described below.
Exit   Выйти из acme после проверки окон на несохраненные изменения.
Font   Без аргументов, меняет шрифт c моноширинного на пропорциональный и наоборот . Given a file name argument, change the font of the window to that stored in the named file. Если указан аргумент имени файла, меняется шрифт окна на тот, который хранится в данном файле. If the file name argument is prefixed by
Если имя файла начинается с префикса var (fix), также задаётся используемый по умолчанию пропорциональный (моноширинный) шрифт для последующего применения именно к этому шрифту. Другие окна не будут затронуты.
Get   Загрузить файл в окно, заменив предыдущее содержимое (после проверки на наличие изменений, аналогично Del). При клике без аргумента используется существующее имя файла окна. Если указан аргумент, загружается указанный файл, но имя файла окна не изменяется. ID    Вывести ID номер окна (см,далее).
Incl   When opening ‘include’ files (those enclosed in <>) with button 3, acme searches in directories /$objtype/include and /sys/include. Incl adds its arguments to a supplementary list of include directories, analogous to the −I option to the compilers. This list is per-window and is inherited when windows are created by actions in that
window, so Incl is most usefully applied to a directory containing relevant source. With no arguments, Incl prints the supplementary list. This command is largely superseded by plumbing (see plumb(7)).
Indent
Устанавливает режим автоматического отступа согласно аргументу: on и off для текущего окна; ON и OFF для существующих и будущих окон.
Kill   Посылает сигнал kill командам, инициированным acme, имена которых указаны в качестве аргументов.
Load   Восстановить состояние acme из файла (по-умолчанию, $HOME/acme.dump) созданного командой Dump .
Local
In the Plan 9 acme, this prefix causes a command to be run in acme’sown file name space and environment variable group. On Unix this is impossible. Local is recognized as a prefix, but has no effect on the command being executed.
Look   Искать в теле окна вхождения текста. Переданного в аргументе или, если он не указан, выделенный текст в теле окна.
New   Создать новое окно. При наличии аргументов, загрузить указанные файлы в новые окна.
Newcol
Создать новый столбец.
PasteЗаменить последний выделенный текст содержимым буфера обмена ( snarf буфера).
Put   Записать содержимое окна в указанный файл. Без аргументов, записать в файл, имя которого указано в заголовке окна.
Putall
Записать все измененные окна, имена которых указывают на существующие обычные файлы.
Redo   Обратное действие от Undo.
Send   Добавить выделенный текст или содержимое буфера обмена в конец тела окна; используется в основном с win.
SnarfПоместить выделенный текст в буфер обмена (snarf буффер).
Sort   Расположить окна в столбце сверху вниз в лексикографическом порядке на основе их имен.
Tab   Установить ширину отступов табуляции для текущего окна в соответствии со значением аргумента, в единицах ширины нулевого символа. Без аргументов, выводит текущее значение.
Undo   Отменить последнее текстовое изменение или группу изменений.
ZeroxСоздать копию окна, содержащего последний выделенный текст.
<|>   Если обычной команде оболочки предшествуют символы <, |, или > то выделенный текст в теле окна подвергается воздействию ввода-вывода команды. Символ < заменяет выделение стандартным выводом команды; символ > отправляет выделение в качестве стандартного ввода команды; и символ |
выполняет оба действия одновременно, ’передавая’ выделение через команду и заменяя его выводом.
Устоявшееся место для расположения исполняемых команд - в заголовке окна; Более того, acme поддерживает набор команд в заголовке окна слева, в зависимости от состоянием окна.
Если текст, указанный кнопкой 2, не распознаётся как встроенная команда, он выполняется как команда оболочки. Например, указание на date кнопкой мыши 2 выполнит date(1). Стандартные потоки вывода и ошибок команды будут отправлены в окно ошибок ассоциированное с каталогом, где была запущена команда. Окно будет создано при необходимости. Например, исполнение pwd в окне /etc/passwd выведет /etc в (возможно, только что созданном) окне с меткой /etc/+Errors; В окне, содержащем /home/rob/sam/sam.c выполнение mk запустит mk(1) в /home/rob/sam, производящего вывод в окно с меткой /home/rob/sam/+Errors. Среда выполнения этих команд содержит переменную $% и $samfile со значением, соответствующим имени файла в заголовке окна, в котором выполняется команда, и $winid соответствующим индентификатору (id) окна.
(смотри acme(4)).
Переменная окружения $acmeshell определяет, какая оболочка будет использоваться для запуска команд; Оболочка rc(1) Используется по-умолчанию.

Mouse button 3
Pointing at text with button 3 instructs acme to locate or acquire the file, string, etc. described by the indicated text and its context. This description follows the actions taken when button 3 is released after sweeping out some text. In the description, text refers to the text of the original sweep or, if it was null, the result of applying the same expansion rules that apply to button 2 actions.
If the text names an existing window, acme moves the mouse cursor to the selected text in the body of that window. If the text names an existing file with no associated window, acme loads the file into a new window and moves the mouse there. If the text is a file name contained in angle brackets, acme loads the indicated include file from the directory appropriate to the suffix of the file name of the window holding the text. (The Incl command adds directories to the standard list.)
If the text begins with a colon, it is taken to be an address, in the style of sam(1), within the body of the window containing the text. The address is evaluated, the resulting text highlighted, and the mouse moved to it. Thus, in acme, one must type :/regexp or :127 not just /regexp or 127. (There is an easier way to locate literal text; see below.) If shift is held down during the selection or click, any leading regular expression search defaults to searching backward in the text instead of forward.
If the text is a file name followed by a colon and an address, acme loads the file and evaluates the address. For example, clicking button 3 anywhere in the text file.c:27 will open file.c, select line 27, and put the mouse at the beginning of the line. The rules about Error files, directories, and so on all combine to make this an efficient way to investigate errors from compilers, etc.
If the text is not an address or file, it is taken to be literal text, which is then searched for in the body of the window in which button 3 was clicked. If a match is found, it is selected and the mouse is moved there. Thus, to search for occurrences of a word in a file, just click button 3 on the word. Because of the rule of using the selection as the button 3 action, subsequent clicks will find subsequent occurrences without moving the mouse. If shift is held down during the selection or click, the search looks backward in the file.
In all these actions, the mouse motion is not done if the text is a null string within a non-null selected string in the tag, so that (for example) complex regular expressions may be selected and applied repeatedly to the body by just clicking button 3 over them.

Chords of mouse buttons
Several operations are bound to multiple-button actions. After selecting text, with button 1 still down, pressing button 2 executes Cut and button 3 executes Paste. After clicking one button, the other undoes the first; thus (while holding down button 1) 2 followed by 3 is a Snarf that leaves the file undirtied; 3 followed by 2 is a no-op. These actions also apply to text selected by double-clicking because the double-click expansion is made when the second click starts, not when it ends.
Commands may be given extra arguments by a mouse chord with buttons 2 and 1. While holding down button 2 on text to be executed as a command, clicking button 1 appends the text last pointed to by button 1 as a distinct final argument. For example, to search for literal text one may execute Look text with button 2 or instead point at text with button 1 in any window, release button 1, then execute Look, clicking button 1 while 2 is held down.
When an external command (e.g. echo(1)) is executed this way, the extra argument is passed as expected and an environment variable $acmeaddr is created that holds, in the form interpreted by button 3, the fully-qualified address of the extra argument.

Simulated buttons
For systems without a three-button mouse, the keyboard modifier keys can be used to modify the effect of the main mouse button. On Unix systems, the Control key changes the main button to button 2, and the Alt key changes it to button 3. On Mac systems, the Option key changes the main button to button 2, and the Command key changes it to button 3. Pressing the key after the button is held down adds the button to form a chord, so that for example on Macs selecting text with the trackpad button and then typing Option without letting go of the button will cause a 1-2 chord, cutting the selection. On Mac systems, the usual keyboard shortcuts Command-C, -V, -X, and -Z invoke copy, paste, cut, and undo, and Command-Shift-Z invokes redo, as in other programs. Especially on Mac laptops, these keyboard shortcuts are typically much less awkward than the equivalent chords.

Support programs
Win creates a new acme window and runs a command (default $SHELL) in it, turning the window into something analogous to an 9term(1) window. Executing text in a win window with button 2 is similar to using Send. Win windows follow the same scrolling heuristic as in 9term(1): the window scrolls on output only if the window is displaying the end of the buffer.
Awd loads the tag line of its window with the directory in which it’s running, suffixed label (default rc); it is intended to be executed by a cd function for use in win windows. An example definition is
fn cd { builtin cd $1 && awd $sysname }

Applications and guide files
In the directory /acme live several subdirectories, each corresponding to a program or set of related programs that employ acme’s user interface. Each subdirectory includes source, binaries, and a readme file for further information. It also includes a guide, a text file holding sample commands to invoke the programs. The idea is to find an example in the guide that best matches the job at hand, edit it to suit, and execute it.
Whenever a command is executed by acme, the default search path includes the directory of the window containing the command and its subdirectory $cputype. The program directories in /acme contain appropriately labeled subdirectories of binaries, so commands named in the guide files will be found automatically when run. Also, acme binds the directories /acme/bin and /acme/bin/$cputype to the end of /bin when it starts; this is where acme-specific programs such as win and awd reside.

FILES
$HOME/acme.dump   default file for Dump and Load; also where state is written if acme dies or is killed unexpectedly, e.g. by deleting its window.
/acme/*/guide    template files for applications
/acme/*/readme   informal documentation for applications
/acme/*/src      source for applications
/acme/*/mips     MIPS-specific binaries for applications

SOURCE
/usr/local/plan9/src/cmd/acme
/usr/local/plan9/src/cmd/9term/win.c
/usr/local/plan9/bin/awd

SEE ALSO
acme(4)
Rob Pike, Acme: A User Interface for Programmers.

BUGS
With the −l option or Load command, the recreation of windows under control of external programs such as win is just to rerun the command; information may be lost.

Space Glenda