3.5 Vi Macros

Viper supports much enhanced Vi-style macros and also facilitates the use of Emacs-style macros. To define a temporary macro, it is generally more convenient to use Emacs keyboard macro facility. Emacs keyboard macros are usually defined anonymously, and the latest macro can be executed by typing C-x e (or *, if Viper is in Vi state). If you need to use several temporary macros, Viper lets you save them to a register (a lowercase letter); such macros can then be executed by typing @a in Vi state (if a macro was previously saved in register a). See Macros and Registers, for details.

If, however, you need to use a macro regularly, it must be given a permanent name and saved. Emacs manual explains how to do this, but invocation of named Emacs macros is quite different from Vi’s. First, invocation of permanent Emacs macros takes time because it requires typing too many keys (to a Vi user’s taste, anyway). Second, binding such macros to function keys, for fast access, hogs valuable real estate on the keyboard.

Vi-style macros are better in that respect, since Vi lets the user overload the meaning of key sequences: keys typed in fast succession are treated specially, if this key sequence is bound to a macro.

Viper provides Vi-style keyboard macros through the usual Ex commands, :map and :map!. These macros are much more powerful in Viper than they are in the original Vi and in other emulators. This is because Viper implements an enhanced vi-style interface to the powerful Emacs keyboard macro facility.

First, any Emacs command can be executed while defining a macro, not just the Vi commands. In particular, the user can invoke Emacs commands via M-x command-name or by pressing various function keys on the keyboard. One can even use the mouse, although this is usually not useful and is not recommended (and macros defined with the use of the mouse cannot be saved in command history and in the startup file, for future use).

Macros defined by mixing Vi and Emacs commands are represented as vectors. So, don’t be confused when you see one (usually through the history of Ex commands). For instance, if gg is defined by typing l, the up-arrow key and M-x next-line, its definition will look as follows in Emacs:

[l up (meta x) n e x t - l i n e return]

Second, Viper macros are defined in a WYSIWYG style. This means that commands are executed as you type them, so you can see precisely what is being defined. Third, macros can be bound to arbitrary sequences of keys, not just to printable keys. For instance, one can define a macro that will be invoked by hitting f3 then f2 function keys. (The keys delete and backspace are excluded; also, a macro invocation sequence can’t start with ESC. Some other keys, such as f1 and help, can’t be bound to macros under Emacs, since they are bound in key-translation-map, which overrides any other binding the user gives to keys. In general, keys that have a binding in key-translation-map can’t be bound to a macro.)

Fourth, in Viper, one can define macros that are specific to a given buffer, a given major mode, or macros that are defined for all buffers. In fact, the same macro name can have several different definitions: one global, several definitions for various major modes, and definitions for various specific buffers. Buffer-specific definitions override mode-specific definitions, which, in turn, override global definitions.

As if all that is not enough, Viper (through its interface to Emacs macros) lets the user define keyboard macros that ask for confirmation or even prompt the user for input and then continue. To do this, one should type C-x q (for confirmation) or C-u C-x q (for prompt). For details, see Customization in The GNU Emacs Manual.

When the user finishes defining a macro (which is done by typing C-x), a departure from Vi), you will be asked whether you want this macro to be global, mode-specific, or buffer-specific. You will also be given a chance to save the macro in your Viper customization file. This is the easiest way to save a macro and make it permanently available. If you work your startup files with bare hands, here is how Viper saves the above macro so that it will be available in Viper’s Insert state (and Replace state) in buffer my-buf only:

(viper-record-kbd-macro "gg" 'insert-state
       [l up (meta x) n e x t - l i n e return]
       "my-buf")

To do the same for Vi state and all buffers with the major mode cc-mode, use:

(viper-record-kbd-macro "gg" 'vi-state
       [l up (meta x) n e x t - l i n e return]
       'cc-mode)

Both macro names and macro definitions are vectors of symbols that denote keys on the keyboard. Some keys, like \, , or digit-keys must be escaped with a backslash. Modified keys are represented as lists. For instance, holding Meta and Control and pressing f4 is represented as (control meta f4). If all members of a vectors are printable characters (or sequences, such as \e, \t, for ESC and TAB), then they can also be represented as strings:

(viper-record-kbd-macro "aa" 'vi-state  "aaa\e"  "my-buffer")

Thus, typing aa fast in Vi state will switch Viper to Insert state (due to the first a), insert aa, and then it will switch back to Vi state. All this will take effect only in the buffer named my-buffer.

Note that the last argument to viper-record-kbd-macro must be either a string (a buffer name), a symbol representing a major mode, or t; the latter says that the macro is to be defined for all buffers (which is how macros are defined in original Vi).

For convenience, Viper also lets you define Vi-style macros in its Emacs state. There is no Ex command, like :map and :map! for doing this, but the user can include such a macro in the Viper customization file. The only thing is that the viper-record-kbd-macro command should specify emacs-state instead of vi-state or insert-state.

The user can get rid of a macro either by using the Ex commands :unmap and :unmap! or by issuing a call to viper-unrecord-kbd-macro. The latter is more powerful, since it can delete macros even in emacs-state. However, viper-unrecord-kbd-macro is usually needed only when the user needs to get rid of the macros that are already predefined in Viper. The syntax is:

(viper-unrecord-kbd-macro macro state)

The second argument must be vi-state, insert-state, or emacs-state. The first argument is a name of a macro. To avoid mistakes in specifying names of existing macros, type M-x viper-describe-kbd-macros and use a name from the list displayed by this command.

If an error occurs during macro definition, Emacs aborts the process, and it must be repeated. This is analogous to Vi, except that in Vi the user doesn’t know there is an error until the macro is actually run. All that means that in order for a definition to be successful, the user must do some simple planning of the process in advance, to avoid errors. For instance, if you want to map gg to llll in Vi state, you must make sure that there is enough room on the current line. Since l moves the cursor forward, it may signal an error on reaching the end of line, which will abort the definition.

These precautions are necessary only when defining macros; they will help avoid the need to redo the job. When macros are actually run, an error during the execution will simply terminate the current execution (but the macro will remain mapped).

A macro name can be a string of characters or a vector of keys. The latter makes it possible to define macros bound to, say, double-hits on a function key, such as up or f13. This is very useful if you run out of function keys on your keyboard; it makes Viper macro facility a keyboard doubler, so to speak.

Elsewhere (See Key Bindings, for details), we review the standard Emacs mechanism for binding function keys to commands. For instance,

(global-set-key [f13] 'repeat-complex-command)

binds the key f13 to the Emacs function that repeats the last minibuffer command. Under Viper, however, you may still use this key for additional purposes, if you bind, say, a double-hitting action for that key to some other function. Emacs doesn’t allow the user to do that, but Viper does this through its keyboard macro facility. To do this, type :map first. When you are asked to enter a macro name, hit f13 twice, followed by RET or SPC.

Emacs will now start the mapping process by actually executing Vi and Emacs commands, so that you could see what will happen each time the macro is executed. Suppose now we wanted to bind the key sequence f13 f13 to the command eval-last-sexp. To accomplish this, we can type M-x eval-last-sexp followed by C-x ). If you answer positively to Viper’s offer to save this macro in your Viper customization file for future uses, the following will be inserted in that file:

(viper-record-kbd-macro [f16 f16] 'vi-state
         [(meta x) e v a l - l a s t - s e x p]
         'lisp-interaction-mode)

To illustrate the above point, Viper provides two canned macros, which, by default, are bound to [f12 \1] and [f12 \2] (invoked by typing f12 then 1 and 2, respectively). These macros are useful shortcuts to Viper’s command ring history. The first macro will execute the second-last destructive command (the last one is executed by ., as usual). The second macro executes the third-last command.

If you need to go deeper into the command history, you will have to use other commands, as described earlier in this section; or you can bind, say, f12 \3 like this:

(viper-record-kbd-macro [f12 \3] 'vi-state
                      [(meta x) r e p e a t - f r o m - h i s t o r y]
                      t)

Note that even though the macro uses the function key f12, the key is actually free and can still be bound to some Emacs function via define-key or global-set-key.

Viper allows the user to define macro names that are prefixes of other macros. For instance, one can define [[ and [[[[ to be macros. If you type the exact sequence of such keys and then pause, Viper will execute the right macro. However, if you don’t pause and, say, type [[[[text then the conflict is resolved as follows. If only one of the key sequences, [[ or [[[[ has a definition applicable to the current buffer, then, in fact, there is no conflict and the right macro will be chosen. If both have applicable definitions, then the first one found will be executed. Usually this is the macro with a shorter name. So, in our case, [[[[text will cause the macro [[ to be executed twice and then the remaining keys, t e x t, will be processed.

When defining macros using :map or :map!, the user enters the actually keys to be used to invoke the macro. For instance, you should hit the actual key f6 if it is to be part of a macro name; you do not write f 6. When entering keys, Viper displays them as strings or vectors (e.g., "abc" or [f6 f7 a]). The same holds for unmapping. Hitting TAB while typing a macro name in the :unmap or :unmap! command will cause name completion. Completions are displayed as strings or vectors. However, as before, you don’t actually type ‘"’, ‘[’, or ‘]’ that appear in the completions. These are meta-symbols that indicate whether the corresponding macro name is a vector or a string.

One last difference from Vi: Vi-style keyboard macros cannot be defined in terms of other Vi-style keyboard macros (but named Emacs macros are OK). More precisely, while defining or executing a macro, the special meaning of key sequences (as Vi macros) is ignored. This is because it is all too easy to create an infinite loop in this way. Since Viper macros are much more powerful than Vi’s it is impossible to detect such loops. In practice, this is not really a limitation but, rather, a feature.

We should also note that Vi macros are disabled in the minibuffer, which helps keep some potential troubles away.

The rate at which the user must type keys in order for them to be recognized as a timeout macro is controlled by the variable viper-fast-keyseq-timeout, which defaults to 200 milliseconds.

For the most part, Viper macros defined in the Viper customization file can be shared between X and TTY modes. The problem with TTY may be that the function keys there generate sequences of events instead of a single event (as under a window system). Emacs maps some of these sequences back to the logical keys (e.g., the sequences generated by the arrow keys are mapped to up, left, etc.). However, not all function keys are mapped in this way. Macros that are bound to key sequences that contain such unmapped function keys have to be redefined for TTY’s (and possibly for every type of TTY you may be using). To do this, start Emacs on an appropriate TTY device and define the macro using :map, as usual.

Finally, Viper provides a function that conveniently displays all macros currently defined. To see all macros along with their definitions, type M-x viper-describe-kbd-macros.