@c This is part of the Emacs manual.@c Copyright (C) 1985,86,87,93,94,95,97,2000,2001,2002,2003,2004@c Free Software Foundation, Inc.@c See file emacs.texi for copying conditions.@node Keyboard Macros, Files, Fixit, Top@chapter Keyboard Macros@cindex defining keyboard macros@cindex keyboard macro In this chapter we describe how a sequence of editing commands canbe recorded and repeated multiple times. A @dfn{keyboard macro} is a command defined by the user to stand foranother sequence of keys. For example, if you discover that you areabout to type @kbd{C-n C-d} forty times, you can speed your work bydefining a keyboard macro to do @kbd{C-n C-d} and calling it with arepeat count of forty. You define a keyboard macro while executing the commands which are thedefinition. Put differently, as you define a keyboard macro, thedefinition is being executed for the first time. This way, you can seewhat the effects of your commands are, so that you don't have to figurethem out in your head. When you are finished, the keyboard macro isdefined and also has been, in effect, executed once. You can then do thewhole thing over again by invoking the macro. Keyboard macros differ from ordinary Emacs commands in that they arewritten in the Emacs command language rather than in Lisp. This makes iteasier for the novice to write them, and makes them more convenient astemporary hacks. However, the Emacs command language is not powerfulenough as a programming language to be useful for writing anythingintelligent or general. For such things, Lisp must be used.@menu* Basic Keyboard Macro:: Defining and running keyboard macros.* Keyboard Macro Ring:: Where previous keyboard macros are saved.* Keyboard Macro Counter:: Inserting incrementing numbers in macros.* Keyboard Macro Query:: Making keyboard macros do different things each time.* Save Keyboard Macro:: Giving keyboard macros names; saving them in files.* Edit Keyboard Macro:: Editing keyboard macros.* Keyboard Macro Step-Edit:: Interactively executing and editing a keyboard macro.@end menu@node Basic Keyboard Macro@section Basic Use@table @kbd@item C-x (Start defining a keyboard macro (@code{kmacro-start-macro}).@item C-x )End the definition of a keyboard macro (@code{kmacro-end-macro}).@item C-x eExecute the most recent keyboard macro (@code{kmacro-end-and-call-macro}).First end the definition of the keyboard macro, if currently defining it.To immediately execute the keyboard macro again, just repeat the @kbd{e}.@item C-u C-x (Re-execute last keyboard macro, then add more keys to its definition.@item C-u C-u C-x (Add more keys to the last keyboard macro without re-executing it.@item C-x qWhen this point is reached during macro execution, ask for confirmation(@code{kbd-macro-query}).@item C-x C-k nGive a command name (for the duration of the session) to the mostrecently defined keyboard macro (@code{kmacro-name-last-macro}).@item C-x C-k bBind the most recently defined keyboard macro to a key sequence (forthe duration of the session) (@code{kmacro-bind-to-key}).@item M-x insert-kbd-macroInsert in the buffer a keyboard macro's definition, as Lisp code.@item C-x C-k eEdit a previously defined keyboard macro (@code{edit-kbd-macro}).@item C-x C-k rRun the last keyboard macro on each line that begins in the region(@code{apply-macro-to-region-lines}).@end table@kindex C-x (@kindex C-x )@kindex C-x e@findex kmacro-start-macro@findex kmacro-end-macro@findex kmacro-end-and-call-macro To start defining a keyboard macro, type the @kbd{C-x (} command(@code{kmacro-start-macro}). From then on, your keys continue to beexecuted, but also become part of the definition of the macro. @samp{Def}appears in the mode line to remind you of what is going on. When you arefinished, the @kbd{C-x )} command (@code{kmacro-end-macro}) terminates thedefinition (without becoming part of it!). For example,@exampleC-x ( M-f foo C-x )@end example@noindentdefines a macro to move forward a word and then insert @samp{foo}. The macro thus defined can be invoked again with the @kbd{C-x e}command (@code{kmacro-end-and-call-macro}), which may be given arepeat count as a numeric argument to execute the macro many times.If you enter @kbd{C-x e} while defining a macro, the macro isterminated and executed immediately. After executing the macro with @kbd{C-x e}, you can use @kbd{e}repeatedly to immediately repeat the macro one or more times. For example,@exampleC-x ( xyz C-x e e e@end example@noindentinserts @samp{xyzxyzxyzxyz} in the current buffer. @kbd{C-x )} can also be given a repeat count as an argument, inwhich case it repeats the macro that many times right after definingit, but defining the macro counts as the first repetition (since it isexecuted as you define it). Therefore, giving @kbd{C-x )} an argumentof 4 executes the macro immediately 3 additional times. An argumentof zero to @kbd{C-x e} or @kbd{C-x )} means repeat the macroindefinitely (until it gets an error or you type @kbd{C-g} or, onMS-DOS, @kbd{C-@key{BREAK}}).@kindex C-x C-k C-s@kindex C-x C-k C-kAlternatively, you can use @kbd{C-x C-k C-s} to start a keyboard macro,and @kbd{C-x C-k C-k...} to end and execute it. If you wish to repeat an operation at regularly spaced places in thetext, define a macro and include as part of the macro the commands to moveto the next place you want to use it. For example, if you want to changeeach line, you should position point at the start of a line, and define amacro to change that line and leave point at the start of the next line.Then repeating the macro will operate on successive lines. When a command reads an argument with the minibuffer, yourminibuffer input becomes part of the macro along with the command. Sowhen you replay the macro, the command gets the same argument aswhen you entered the macro. For example,@exampleC-x ( C-a C-@key{SPC} C-n M-w C-x b f o o @key{RET} C-y C-x b @key{RET} C-x )@end example@noindentdefines a macro that copies the current line into the buffer@samp{foo}, then returns to the original buffer. You can use function keys in a keyboard macro, just like keyboardkeys. You can even use mouse events, but be careful about that: whenthe macro replays the mouse event, it uses the original mouse positionof that event, the position that the mouse had while you were definingthe macro. The effect of this may be hard to predict. (Using thecurrent mouse position would be even less predictable.) One thing that doesn't always work well in a keyboard macro is thecommand @kbd{C-M-c} (@code{exit-recursive-edit}). When this commandexits a recursive edit that started within the macro, it works as you'dexpect. But if it exits a recursive edit that started before youinvoked the keyboard macro, it also necessarily exits the keyboard macroas part of the process. After you have terminated the definition of a keyboard macro, you can addto the end of its definition by typing @kbd{C-u C-x (}. This is equivalentto plain @kbd{C-x (} followed by retyping the whole definition so far. Asa consequence it re-executes the macro as previously defined. You can also add to the end of the definition of the last keyboardmacro without re-executing it by typing @kbd{C-u C-u C-x (}. The variable @code{kmacro-execute-before-append} specifies whethera single @kbd{C-u} prefix causes the existing macro to be re-executedbefore appending to it.@findex apply-macro-to-region-lines@kindex C-x C-k r The command @kbd{C-x C-k r} (@code{apply-macro-to-region-lines})repeats the last defined keyboard macro on each line that begins inthe region. It does this line by line, by moving point to thebeginning of the line and then executing the macro.@node Keyboard Macro Ring@section The Keyboard Macro Ring All defined keyboard macros are recorded in the ``keyboard macro ring'',a list of sequences of keys. There is only one keyboard macro ring,shared by all buffers. All commands which operates on the keyboard macro ring use thesame @kbd{C-x C-k} prefix. Most of these commands can be executed andrepeated immediately after each other without repeating the @kbd{C-xC-k} prefix. For example,@exampleC-x C-k C-p C-p C-k C-k C-k C-n C-n C-k C-p C-k C-d@end example@noindentwill rotate the keyboard macro ring to the ``second previous'' macro,execute the resulting head macro three times, rotate back to theoriginal head macro, execute that once, rotate to the ``previous''macro, execute that, and finally delete it from the macro ring.@findex kmacro-end-or-call-macro-repeat@kindex C-x C-k C-k The command @kbd{C-x C-k C-k} (@code{kmacro-end-or-call-macro-repeat})executes the keyboard macro at the head of the macro ring. You canrepeat the macro immediately by typing another @kbd{C-k}, or you canrotate the macro ring immediately by typing @kbd{C-n} or @kbd{C-p}.@findex kmacro-cycle-ring-next@kindex C-x C-k C-n@findex kmacro-cycle-ring-previous@kindex C-x C-k C-p The commands @kbd{C-x C-k C-n} (@code{kmacro-cycle-ring-next}) and@kbd{C-x C-k C-p} (@code{kmacro-cycle-ring-previous}) rotates themacro ring, bringing the next or previous keyboard macro to the headof the macro ring. The definition of the new head macro is displayedin the echo area. You can continue to rotate the macro ringimmediately by repeating just @kbd{C-n} and @kbd{C-p} until thedesired macro is at the head of the ring. To execute the new macroring head immediately, just type @kbd{C-k}. Note that Emacs treats the head of the macro ring as the ``lastdefined keyboard macro''. For instance, it is the keyboard macro that@kbd{C-x e} will execute.@findex kmacro-view-macro-repeat@kindex C-x C-k C-v The commands @kbd{C-x C-k C-v} (@code{kmacro-view-macro-repeat})displays the last keyboard macro, or when repeated (with @kbd{C-v}),it displays the previous macro on the macro ring, just like @kbd{C-xC-k C-p}, but without actually rotating the macro ring. If you enter@kbd{C-k} immediately after displaying a macro from the ring, thatmacro is executed, but still without altering the macro ring. So while e.g. @kbd{C-x C-k C-p C-p C-k C-k} makes the 3rd previousmacro the current macro and executes it twice, @kbd{C-x C-k C-v C-vC-v C-k C-k} will display and execute the 3rd previous macro once andthen the current macro once.@findex kmacro-delete-ring-head@kindex C-x C-k C-d The commands @kbd{C-x C-k C-d} (@code{kmacro-delete-ring-head})removes and deletes the macro currently at the head of the macroring. You can use this to delete a macro that didn't work asexpected, or which you don't need anymore.@findex kmacro-swap-ring@kindex C-x C-k C-t The commands @kbd{C-x C-k C-t} (@code{kmacro-swap-ring})interchanges the head of the macro ring with the previous element onthe macro ring.@findex kmacro-call-ring-2nd-repeat@kindex C-x C-k C-l The commands @kbd{C-x C-k C-l} (@code{kmacro-call-ring-2nd-repeat})executes the previous (rather than the head) element on the macro ring.@node Keyboard Macro Counter@section The Keyboard Macro Counter Each keyboard macro has an associated counter which is automaticallyincremented on every repetition of the keyboard macro. Normally, themacro counter is initialized to 0 when you start defining the macro,and incremented by 1 after each insertion of the counter value;that is, if you insert the macro counter twice while defining themacro, the counter will increase by 2 on each repetition of the macro.@findex kmacro-insert-counter@kindex C-x C-k C-i The command @kbd{C-x C-k C-i} (@code{kmacro-insert-counter}) insertsthe current value of the keyboard macro counter and increments thecounter by 1. You can use a numeric prefix argument to specify adifferent increment. If you specify a @kbd{C-u} prefix, the lastinserted counter value is repeated and the counter is not incremented.For example, if you enter the following sequence while defining a macro@exampleC-x C-k C-i C-x C-k C-i C-u C-x C-k C-i C-x C-k C-i@end example@noindentthe text @samp{0112} is inserted in the buffer, and for the first andsecond execution of the macro @samp{3445} and @samp{6778} areinserted.@findex kmacro-set-counter@kindex C-x C-k C-c The command @kbd{C-x C-k C-c} (@code{kmacro-set-counter}) promptsfor the initial value of the keyboard macro counter if you use itbefore you define a keyboard macro. If you use it while defining akeyboard macro, you set the macro counter to the same (initial) valueon each repetition of the macro. If you specify a @kbd{C-u} prefix,the counter is reset to the value it had prior to the currentrepetition of the macro (undoing any increments so far in thisrepetition).@findex kmacro-add-counter@kindex C-x C-k C-a The command @kbd{C-x C-k C-a} (@code{kmacro-add-counter}) promptsfor a value to add to the macro counter.@findex kmacro-set-format@kindex C-x C-k C-f The command @kbd{C-x C-k C-f} (@code{kmacro-set-format}) promptsfor the format to use when inserting the macro counter. The defaultformat is @samp{%d}. If you set the counter format before you define amacro, that format is restored before each repetition of the macro.Consequently, any changes you make to the macro counter format whiledefining a macro are only active for the rest of the macro.@node Keyboard Macro Query@section Executing Macros with Variations@kindex C-x q@findex kbd-macro-query Using @kbd{C-x q} (@code{kbd-macro-query}), you can get an effectsimilar to that of @code{query-replace}, where the macro asks you eachtime around whether to make a change. While defining the macro,type @kbd{C-x q} at the point where you want the query to occur. Duringmacro definition, the @kbd{C-x q} does nothing, but when you run themacro later, @kbd{C-x q} asks you interactively whether to continue. The valid responses when @kbd{C-x q} asks are @key{SPC} (or @kbd{y}),@key{DEL} (or @kbd{n}), @key{RET} (or @kbd{q}), @kbd{C-l} and @kbd{C-r}.The answers are the same as in @code{query-replace}, though not all ofthe @code{query-replace} options are meaningful. These responses include @key{SPC} to continue, and @key{DEL} to skipthe remainder of this repetition of the macro and start right away withthe next repetition. @key{RET} means to skip the remainder of thisrepetition and cancel further repetitions. @kbd{C-l} redraws the screenand asks you again for a character to say what to do. @kbd{C-r} enters a recursive editing level, in which you can performediting which is not part of the macro. When you exit the recursiveedit using @kbd{C-M-c}, you are asked again how to continue with thekeyboard macro. If you type a @key{SPC} at this time, the rest of themacro definition is executed. It is up to you to leave point and thetext in a state such that the rest of the macro will do what youwant.@refill @kbd{C-u C-x q}, which is @kbd{C-x q} with a numeric argument,performs a completely different function. It enters a recursive editreading input from the keyboard, both when you type it during thedefinition of the macro, and when it is executed from the macro. Duringdefinition, the editing you do inside the recursive edit does not becomepart of the macro. During macro execution, the recursive edit gives youa chance to do some particularized editing on each repetition.@xref{Recursive Edit}. Another way to vary the behavior of a keyboard macro is to use aregister as a counter, incrementing it on each repetition of the macro.@xref{RegNumbers}.@node Save Keyboard Macro@section Naming and Saving Keyboard Macros@cindex saving keyboard macros@findex kmacro-name-last-macro@kindex C-x C-k n If you wish to save a keyboard macro for later use, you can give ita name using @kbd{C-x C-k n} (@code{kmacro-name-last-macro}).This reads a name as an argument using the minibuffer and defines thatname to execute the last keyboard macro, in its current form. (If youlater add to the definition of this macro, that does not alter thename's definition as a macro.) The macro name is a Lisp symbol, anddefining it in this way makes it a valid command name for calling with@kbd{M-x} or for binding a key to with @code{global-set-key}(@pxref{Keymaps}). If you specify a name that has a prior definitionother than a keyboard macro, an error message is shown and nothing ischanged.@cindex binding keyboard macros@findex kmacro-bind-to-key@kindex C-x C-k b You can also bind the last keyboard macro to a key, using@kbd{C-x C-k b} (@code{kmacro-bind-to-key}) followed by thekey sequence you want the keyboard macro to be bound to. You canbind to any key sequence in the global keymap, but since most keysequences already have other bindings, you should select the keysequence carefully. If you try to bind to a key sequence with anexisting binding (in any keymap), you will be asked if you reallywant to replace the existing binding of that key.To avoid problems caused by overriding existing bindings, the keysequences @kbd{C-x C-k 0} through @kbd{C-x C-k 9} and @kbd{C-x C-k A}through @kbd{C-x C-k Z} are reserved for your own keyboard macrobindings. In fact, to bind to one of these key sequences, you onlyneed to type the digit or letter rather than the whole key sequences.For example,@exampleC-x C-k b 4@end example@noindentwill bind the last keyboard macro to the key sequence @kbd{C-x C-k 4}.@findex insert-kbd-macro Once a macro has a command name, you can save its definition in a file.Then it can be used in another editing session. First, visit the fileyou want to save the definition in. Then use this command:@exampleM-x insert-kbd-macro @key{RET} @var{macroname} @key{RET}@end example@noindentThis inserts some Lisp code that, when executed later, will define thesame macro with the same definition it has now. (You need notunderstand Lisp code to do this, because @code{insert-kbd-macro} writesthe Lisp code for you.) Then save the file. You can load the filelater with @code{load-file} (@pxref{Lisp Libraries}). If the file yousave in is your init file @file{~/.emacs} (@pxref{Init File}) then themacro will be defined each time you run Emacs. If you give @code{insert-kbd-macro} a numeric argument, it makesadditional Lisp code to record the keys (if any) that you have boundto @var{macroname}, so that the macro will be reassigned the same keyswhen you load the file.@node Edit Keyboard Macro@section Editing a Keyboard Macro@findex kmacro-edit-macro@kindex C-x C-k C-e@kindex C-x C-k RET You can edit the last keyboard macro by typing @kbd{C-x C-k C-e} or@kbd{C-x C-k RET} (@code{kmacro-edit-macro}). This formats the macrodefinition in a buffer and enters a specialized major mode for editingit. Type @kbd{C-h m} once in that buffer to display details of how toedit the macro. When you are finished editing, type @kbd{C-c C-c}.@findex edit-kbd-macro@kindex C-x C-k e You can edit a named keyboard macro or a macro bound to a key by typing@kbd{C-x C-k e} (@code{edit-kbd-macro}). Follow that with thekeyboard input that you would use to invoke the macro---@kbd{C-x e} or@kbd{M-x @var{name}} or some other key sequence.@findex kmacro-edit-lossage@kindex C-x C-k l You can edit the last 100 keystrokes as a macro by typing@kbd{C-x C-k l} (@code{kmacro-edit-lossage}).@node Keyboard Macro Step-Edit@section Stepwise Editing a Keyboard Macro@findex kmacro-step-edit-macro@kindex C-x C-k SPC You can interactively and stepwise replay and edit the last keyboardmacro one command at a time by typing @kbd{C-x C-k SPC}(@code{kmacro-step-edit-macro}). Unless you quit the macro using@kbd{q} or @kbd{C-g}, the edited macro replaces the last macro on themacro ring.This shows the last macro in the minibuffer together with the first(or next) command to be executed, and prompts you for an action.You can enter @kbd{?} to get a command summary.The following commands are available in the step-edit mode and relateto the first (or current) command in the keyboard macro:@itemize @bullet{}@item@kbd{SPC} and @kbd{y} execute the current command, and advance to thenext command in the keyboard macro.@item@kbd{n}, @kbd{d}, and @kbd{DEL} skip and delete the current command.@item@kbd{f} skips the current command in this execution of the keyboardmacro, but doesn't delete it from the macro.@item@kbd{TAB} executes the current command, as well as all similarcommands immediately following the current command; for example, TABmay be used to insert a sequence of characters (corresponding to asequence of @code{self-insert-command} commands).@item@kbd{c} continues execution (without further editing) until the end ofthe keyboard macro. If execution terminates normally, the editedmacro replaces the original keyboard macro.@item@kbd{C-k} skips and deletes the rest of the keyboard macro,terminates step-editing, and replaces the original keyboard macrowith the edited macro.@item@kbd{q} and @kbd{C-g} cancels the step-editing of the keyboard macro;discarding any changes made to the keyboard macro.@item@kbd{i KEY... C-j} reads and executes a series of key sequences (notincluding the final @kbd{C-j}), and inserts them before the currentcommand in the keyboard macro, without advancing over the currentcommand.@item@kbd{I KEY...} reads one key sequence, executes it, and inserts itbefore the current command in the keyboard macro, without advancingover the current command.@item@kbd{r KEY... C-j} reads and executes a series of key sequences (notincluding the final @kbd{C-j}), and replaces the current command inthe keyboard macro with them, advancing over the inserted keysequences.@item@kbd{R KEY...} reads one key sequence, executes it, and replaces thecurrent command in the keyboard macro with that key sequence,advancing over the inserted key sequence.@item@kbd{a KEY... C-j} executes the current command, then reads andexecutes a series of key sequences (not including the final@kbd{C-j}), and inserts them after the current command in the keyboardmacro; it then advances over the current command and the inserted keysequences.@item@kbd{A KEY... C-j} executes the rest of the commands in the keyboardmacro, then reads and executes a series of key sequences (notincluding the final @kbd{C-j}), and appends them at the end of thekeyboard macro; it then terminates the step-editing and replaces theoriginal keyboard macro with the edited macro.@end itemize@ignore arch-tag: c1b0dd3b-3159-4c08-928f-52e763953e9c@end ignore