home *** CD-ROM | disk | FTP | other *** search
/ ftp.cse.unsw.edu.au / 2014.06.ftp.cse.unsw.edu.au.tar / ftp.cse.unsw.edu.au / pub / doc / editors / macro-guide next >
Encoding:
Text File  |  1992-10-18  |  33.6 KB  |  737 lines

  1. Vi Macros, Abbreviations, and Buffers
  2. Copyright (C) 1988 by Fred Buck; all rights reserved.
  3. Thanks to: Jean-Pierre Radley <jpradley!root@uunet.uu.net>
  4. Contributions:
  5.     1989 Maarten Litmaath <maart@cs.vu.nl>
  6.     1989 Eamonn McManus <emcmanus@cs.tcd.ie>
  7. Patchlevel: 1
  8.  
  9. Heading summary:
  10. =================
  11.  
  12.    Introduction
  13.    
  14.    Non-macro stuff you really should know about when writing macros
  15.    
  16.        Text markers
  17.        Text buffers
  18.        The escape filter
  19.    
  20.    Simple description of the various 'vi' macro mechanisms
  21.    
  22.        Text abbreviation
  23.        Keystroke remapping: text mode ("map!")
  24.        Keystroke remapping: command mode ("map")
  25.        Text-buffer execution
  26.    
  27.    More detail about 'vi' macro operation
  28.    
  29.        Mode-bouncing
  30.        Chained macros
  31.        Recursive macros
  32.        Terminating a recursive macro
  33.    
  34.    Peculiar limitations and restrictions on 'vi' macros
  35.    
  36.        Size
  37.        Putting and yanking to/from named buffers
  38.        Which keys to remap?
  39.    
  40.    Conclusion
  41.  
  42. Introduction 
  43. =============
  44.  
  45. 'Vi' offers a variety of "macro" facilities; a "macro" in this context is a
  46. mechanism whereby a small number of keystrokes, usually a single keystroke,
  47. is made to represent another set of keystrokes, so that typing the first set
  48. of keystrokes is equivalent to typing the second set.  Applications for
  49. macros fall into three major classes:
  50.  
  51.         (a) during text entry, allowing a long, often-repeated
  52.     string of text to be represented by a short abbreviation; for
  53.     instance, in your biography of Ramaswamy Gopalikrishnan, you
  54.     might assign "rgn" as a macro for the name of your subject;
  55.  
  56.         (b) existing 'vi' commands can be made invokable by
  57.     keys other than the traditional ones, so that for instance if
  58.     your terminal has function keys, you can remap the sequences
  59.     generated by the function keys to existing 'vi' commands, and
  60.     thereafter use the function keys instead of the standard 'vi'
  61.     command keys;
  62.  
  63.         (c) complex operations that would take many keystrokes,
  64.     or that would take a hard-to-remember sequence of keystrokes,
  65.     can be tied to an easy-to-remember sequence of keystrokes, and
  66.     be executed quickly and easily.
  67.  
  68. If your primary interest lies in category (c), then 'vi' macros should be the
  69. LAST topic you take up when learning about 'vi', because you can't write
  70. macros to accomplish things you couldn't do yourself if you were typing
  71. everything in at the keyboard: your macros are only as good as your overall
  72. skill at using 'vi'.  If you're not familiar with using the named and unnamed
  73. 'vi' text buffers, or with the use of text markers, or with the shell-escape
  74. ("!") filtration mechanism, the next section contains a bare-bones
  75. introduction to these things, but you should really play with them at some
  76. length yourself in order to see their full possibilities.
  77.  
  78.  
  79. Non-macro stuff you really should know about when writing macros
  80. =================================================================
  81.  
  82. The following is only a very cursory summary of some basic 'vi' mechanisms
  83. that are essential to be familiar with when writing complex 'vi' macros.
  84. These summaries are intended to make at least intelligible the discussion
  85. that is to follow them.  If you don't know about these mechanisms, and if
  86. you want to write complex 'vi' macros, you'd be well-advised to seek out
  87. a text on 'vi' read up on these things.
  88.  
  89. Text Markers:
  90. --------------
  91.  
  92. 'Vi' has 26 available text markers, corresponding to the 26 lowercase letters
  93. of the alphabet.  A marker can be emplaced by moving the cursor to the place
  94. you want to mark, and typing "m" followed by the marker name you want to use,
  95. from "a" to "z".  Typing "ma" marks that location with marker "a".  To return
  96. to this location from somewhere else in the text, type "`a", where "`" is a
  97. backquote sign, or grave accent.  The backquote moves the cursor to the
  98. precise location you were at when you emplaced the mark.  If instead you're
  99. satisfied merely to go to the beginning of the line you were on when you
  100. emplaced the mark, type "'a", where "'" is a standard single-quote sign.
  101.  
  102.     A text region can often be defined by a cursor-movement command, and
  103. the single-quote and back-quote commands are cursor-movement commands. 
  104. Placing text markers makes it much more easy to yank text into a buffer.
  105.  
  106. Text buffers:
  107. --------------
  108.  
  109. 'Vi' has a remarkable total of 36 user-reachable text buffers.  26 of these
  110. are static buffers, meaning that they don't change until the user tells them
  111. to change, and these are called the "named" text buffers, with names
  112. corresponding to the 26 letters of the alphabet.  Don't confuse these "named"
  113. buffers with the 26 text-marker names; the two are entirely separate and
  114. independent.  The text markers must always be in lowercase; the text-buffer
  115. names can be either uppercase or lowercase, although whether a text-buffer
  116. name is in uppercase or in lowercase changes the way text gets loaded into
  117. the buffer.
  118.  
  119.     To put text into a named buffer, type a double-quotation mark, then
  120. the name of the buffer, and then a cursor-movement command, like this:
  121.  
  122.         "ay`b
  123.  
  124. which yanks into named text buffer "a" the text between your current cursor
  125. position and the exact location of text marker "b", which we assume you've
  126. previously set.  The "yank" will end JUST BEFORE the exact location of text
  127. marker "b", if that is after the cursor; if it is before the cursor the
  128. "yank" happens as if cursor and marker were interchanged.  To yank simply an
  129. entire line, use "yy" (or "Y") instead of "y" and the cursor-movement
  130. command; to yank N number of lines from your current cursor position, use
  131.  
  132.         "aNyy
  133.  
  134. The double-quote mark, '"', is the 'vi' command character that indicates that
  135. you want to manipulate a text buffer.
  136.  
  137.     If you use an uppercase rather than a lowercase letter for the name
  138. of the text buffer, then whatever you yank into the buffer will be appended
  139. to the buffer, rather than over-writing the buffer's previous contents.
  140.  
  141.     To re-insert text from a text buffer, position the cursor where you
  142. want to make the insertion, and type a double-quote sign, then the name of
  143. the buffer (case doesn't matter for re-insertion), and then either "p" or
  144. "P":
  145.  
  146.         "ap
  147.  
  148. If you use a lowercase "p", then the text is re-inserted after your current
  149. cursor position; if you use an uppercase "P", then the text is re-inserted
  150. before your current cursor position.
  151.  
  152.     In addition to the 26 named text buffers, 'vi' stacks deleted LINES
  153. in a set of 9 volatile buffers.  By "volatile" I mean that the contents of
  154. these buffers change without the user's explicit direction.  Another volatile
  155. buffer is called the "unnamed" buffer, in which the most-recently-deleted text
  156. resides, and from which the bare "p" and "P" commands work.  This is the only
  157. buffer in which every piece of deleted text is put, the other nine buffers
  158. deal with complete lines only.  They are reachable with the names "1" through
  159. "9", and hence are known as the numbered buffers.  So if you delete some text
  160. in 'vi', the text you've just deleted is in the "unnamed" delete buffer and
  161. can be recovered with "p" or "P".  If that text contains at least one line,
  162. it is placed into buffer "1" as well, whose previous contents are shifted into
  163. buffer "2" and so forth.  Keep deleting text, and the text you deleted the
  164. first time will advance from buffer "1" to buffer "9".  If you delete still
  165. more text, whatever is in buffer "9" is thrown away, and can no longer be
  166. recovered via the buffer mechanism.  However, it can be recovered if you
  167. haven't written the file since you deleted the text:
  168.  
  169.         :w temp
  170.         :e!
  171.  
  172. The first command writes the current (modified) contents of the file you're
  173. editing to a temporary file called 'temp', the second command tells 'vi' to
  174. reload the original file WITHOUT saving the modifications you've made.
  175. They are, however, still available in 'temp'.
  176.  
  177.     The syntax for working with the numbered buffers is the same as that
  178. for the named buffers: to extract text from, say, delete buffer "1", you'd
  179. say
  180.  
  181.         "1p
  182.  
  183. The "unnamed" delete buffer, in which the most-recently-deleted text is
  184. stored, is recoverable simply by typing a "p" or a "P".
  185.  
  186. The escape filter
  187. ------------------
  188.  
  189. An arbitrary set of text lines can be sent through a Unix or Xenix command
  190. and the result substituted for these lines in place.  This is done within
  191. 'vi' by the command
  192.  
  193.         !<cursor-movement-command><Unix/Xenix command>
  194.  
  195. which has the effect of sending the text lines beginning with the current
  196. line and ending with the line your cursor-movement-command has taken you to. 
  197. If in 'vi' the cursor were placed at the beginning of this paragraph, "An
  198. arbitrary", and then the command
  199.  
  200.         !/has the effect/<RETURN>tr '[a-z]' '[A-Z]<RETURN>
  201.  
  202. were entered, every alphabetic character from the cursor position to the end
  203. of the line containing the string "has the effect" would be forced to
  204. uppercase.  Note that most versions of 'vi' operate only in whole-line
  205. increments when using the shell-escape filter; some versions of 'vi' allow
  206. the shell-escape filter to work on text areas that don't correspond exactly
  207. to line boundaries.
  208.  
  209. Simple description of the various 'vi' macro mechanisms
  210. ========================================================
  211.  
  212.     (1) text abbreviation, which operates only in text-entry mode (the
  213.         "abbr" ex-escape command); once set, an abbreviation works
  214.         only in "vi" text-entry mode;
  215.  
  216.     (2) keystroke remapping, which can operate either in text-entry
  217.         or in command mode (the "map!" and "map" ex-escape commands);
  218.         once set, a "map!"'ed sequence is triggered only in text-entry
  219.         mode, and a "map"'ed sequence is triggered only in "vi"
  220.         command mode;
  221.  
  222.     (3) text-buffer execution, which operates only in command mode:
  223.         once text has been placed in any of the named text buffers,
  224.         that text can be executed as if it were a sequence of 'vi'
  225.         commands.
  226.  
  227. Text abbreviation
  228. ------------------
  229.  
  230. Using macros during text-entry is almost always motivated by the goal of just
  231. saving keystrokes.  The text-abbreviation macro in 'vi' is set up by going to
  232. "ex-escape" mode by typing a colon, and has the form
  233.  
  234.         abbr <abbreviation> <expansion>
  235.  
  236. where an example might be
  237.  
  238.         abbr gatt General Agreement on Tariffs and Trade
  239.  
  240. [Note that the name of the text abbreviation cannot contain an embedded
  241. space.  This is a limitation of all the 'vi' macro mechanisms except for text-
  242. buffer execution, which uses the names of the named text buffers to define
  243. which macro to execute; a buffer name is a single alphabetic letter.]
  244.  
  245.     Once this is done, then while in text-entry mode, whenever you type
  246. a non-alphanumeric character followed by the string "gatt", 'vi' will examine
  247. the next character you type to see if it's non-alphanumeric, and if so, then
  248. "gatt" will be erased and "General Agreement on Tariffs and Trade" will be
  249. substituted for it.  (Typing "gatt" at the very top of your text qualifies as
  250. a non-alphanumeric character followed by "gatt".)
  251.  
  252.     If you don't want a particular instance of "gatt" to get converted,
  253. even though it's preceded and followed by a non-alphanumeric character, you
  254. have to escape the first character following "gatt" by typing
  255.  
  256.         ^V
  257.  
  258. (that is control-V), so if you want "gatt!" to appear, you type
  259.  
  260.         gatt^V!
  261.  
  262.     With text abbreviations, your text appears as you type it, and no
  263. transformation is performed on your specified abbreviation until you follow
  264. it with a non-alphabetic character (which includes an immediate exit from
  265. text-entry mode).  This differentiates text abbreviation from text-mode
  266. keystroke-remapping using the "map!" command, which will be discussed soon.
  267.  
  268.     Text abbreviations can be canceled with the ex-escape "unabbr"
  269. command,
  270.  
  271.         unabbr gatt
  272.  
  273. Most simple abbreviations can be unabbreviated via a simple ex-escape
  274. command, the kind you introduce by typing a colon from 'vi' command mode. 
  275. But many cannot, especially mode-bouncing abbreviations, to be discussed
  276. later.  For these, you must enter genuine "ex" mode by typing a capital Q
  277. ("Q") from 'vi' command mode.  Then do your "unabbr gatt".  To return to "vi"
  278. mode, enter "vi" or "visual" at the "ex" colon prompt.
  279.  
  280. You can get a list of your currently active abbreviations by entering simply
  281. "abbr" in ex-escape mode.
  282.  
  283. Keystroke remapping: text mode ("map!")
  284. ----------------------------------------
  285.  
  286. As previously mentioned, the text abbreviation mechanism won't make a
  287. substitution on text that you type until you type a character AFTER the
  288. abbreviation that persuades 'vi' that you want 'vi' to expand the
  289. abbreviation.  Also, 'vi' echoes each character of the abbreviation as you
  290. type it, just in case you really want the "abbreviation" to be a literal
  291. sequence of characters in your text.  So with the previous example, if you're
  292. typing away and enter
  293.  
  294.         "I also want to introduce a new word, 'gattblather'..."
  295.  
  296. then if you have "gatt" abbreviated for "General Agreement on Tariffs and
  297. Trade", your text line will remain as-is, with no substitution for the string
  298. "gatt" in "gattblather".  Furthermore, an abbreviated sequence must be preceded
  299. as well as followed by a non-alphanumeric character for the substitution to be
  300. triggered.
  301.  
  302.     Keystroke-remapping works a bit differently.  Keystroke-remapping is
  303. handled by the ex-escape "map" command, which takes two forms: "map" operates
  304. on characters that are typed in command mode, and "map!" operates on
  305. characters that are typed in text-entry mode.  (Some versions of 'vi' may
  306. reverse this.)
  307.  
  308.     Staying with the previous example, the ex-escape command
  309.  
  310.         map! gatt General Agreement on Tariffs and Trade
  311.  
  312. causes the key-sequence "gatt" to be instantly replaced by "General Agreement
  313. on Tariffs and Trade" wherever it's typed.  The abbreviation mechanism waits
  314. to see what the NEXT character after the abbreviation is going to be, before
  315. deciding whether to make a substitution, and if the sequence wasn't preceded
  316. by a non-alphanumeric character (or by the top of the file), the abbreviation
  317. mechanism doesn't start working at all.
  318.  
  319. By contrast, the keystroke-remapping mechanism instead starts a per-character
  320. timer that begins whenever you type the first character of a remapped
  321. sequence.  When you type "g", nothing will be echoed to your screen unless
  322. you type some character other than "a", or unless you type nothing at all
  323. within a timeout period, typically about two seconds long.  In short, 'vi'
  324. watches to see if you've typed the beginning of a remapped sequence, and if
  325. the sequence is longer than a single character, 'vi' waits to see if you'll
  326. type the complete sequence, in which case 'vi' will supply whatever remapping
  327. you've specified for the sequence you've just typed.  This will happen
  328. regardless of what follows the remapped sequence.  So if you've remapped
  329. "gatt" to "General Agreement on Tariffs and Trade", then entering
  330.  
  331.         "I also want to introduce a new word, 'gattblather'..."
  332.  
  333. in text mode will yield
  334.  
  335.         "I also want to introduce a new word, 'General Agreement
  336.         on Tariffs and Tradeblather'..."
  337.  
  338. As with abbreviations "^V" will let you escape the mapping, but this time
  339. the macro has to be preceded rather than followed by it.  The following will
  340. get you a plain "gatt", regardless of how fast you type it:
  341.  
  342.         ^Vgatt
  343.  
  344. To un-map! a previously map!'ed text-mode sequence like "gatt", use the ex-
  345. escape command
  346.  
  347.         unmap! gatt
  348.  
  349. Most simple map!'ings can be un-map!'ed via a simple ex-escape command, the
  350. kind you introduce by typing a colon from 'vi' command mode.  But many
  351. cannot, especially mode-bouncing map!'ings, to be discussed later.  For
  352. these, you must enter genuine "ex" mode by typing a capital Q ("Q") from 'vi'
  353. command mode.  Then do your "unmap! gatt".  To return to "vi" mode, enter
  354. "vi" or "visual" at the "ex" colon prompt.
  355.  
  356. You can get a list of your currently active text-mode remapped sequences by
  357. entering merely "map!" in ex-escape mode.
  358.  
  359. NEVER MAKE A map!'ed DEFINITION RECURSIVE!  More on this later.
  360.  
  361.  
  362. Keystroke remapping: command mode ("map")
  363. ------------------------------------------
  364.  
  365. Sequences that you've made into text abbreviations, or that you've remapped
  366. using "map!", are triggered only when you're in text-entry mode, and are not
  367. triggered in command mode.  (Note, however, that an ex-escape command line is
  368. considered by 'vi' to constitute text-entry mode.)  Command-mode remapping is
  369. done with the "map" ex-escape command -- note the missing exclamation point
  370. -- and works identically with text-entry remapping except that "map"'ed
  371. sequences are triggered only in command mode and are not triggered in text-
  372. entry mode.
  373.  
  374.     Command-mode keystroke remappings can be canceled the same way text-
  375. entry mode keystroke remappings can, except without the exclamation point:
  376.  
  377.         unmap ;
  378.  
  379. Some 'vi' command keys simply cannot be remapped in command mode; the set of
  380. these keys varies according to the implementation of 'vi'.  The most common
  381. unremappable keys are ":" and "u".
  382.  
  383. You can get a list of your currently active command-mode remapped sequences
  384. by entering merely "map" in ex-escape mode.
  385.  
  386.  
  387. Text-buffer execution
  388. ----------------------
  389.  
  390. This topic, which is often glossed over or omitted entirely in most
  391. proprietary 'vi' documentation, can be stated very simply: any named text
  392. buffer can be treated as a 'vi' command-mode macro by typing the at-sign
  393. character ("@") followed by the name of the buffer.  If named buffer "a"
  394. contains 
  395.  
  396.             H!Lsort
  397.  
  398. then "@a" from 'vi' command mode will sort the lines now on the terminal
  399. screen.  The same would of course be true of a "map" that said the same
  400. thing; this example is for illustration.  
  401.  
  402.     The ability to execute a named text buffer as if the buffer were a
  403. sequence of commands allows 'vi' macros sometimes to operate in a self-
  404. modifying way, because a macro can load a text buffer from text in the
  405. current file and then invoke that text buffer as a command macro, without
  406. having to know in advance what the text is that will be loaded into the
  407. buffer.
  408.  
  409. More detail about 'vi' macro operation
  410. =======================================
  411.  
  412. Mode-bouncing
  413. --------------
  414.  
  415. The various 'vi' macro facilities differ in whether they're triggered in text-
  416. entry or in command mode.  Text-abbreviation is triggered only in text-entry
  417. mode; the "map!" command creates macros that are triggered only in text-entry
  418. mode; the "map" command creates macros that are triggered only in command
  419. mode; and the "@" command works only in command mode.
  420.  
  421.     But all this just means that the >trigger< for the macro must come
  422. within the mode that the macro corresponds to.  Any macro, regardless of
  423. type, can switch between the invocation mode and other modes and back again. 
  424. This is what's meant by a "mode-bouncing" macro.  Any 'vi' macro can go
  425. from text-entry to command mode, to ex-escape mode, or to vi-mode.  You just
  426. define the macro with the exact keystroke sequence that you yourself would
  427. use if you were changing modes.  I refer to macros that shift from one mode
  428. to another as "mode-bouncing" macros.
  429.  
  430.     Control characters are entered into macro definitions by preceding
  431. them with a control-V.  The result, after the control character is typed,
  432. appears as something like "^M" for a carriage return, or "^[" for an ESCAPE. 
  433. Say for the sake of argument you've abbreviated "dater" this way:
  434.  
  435.     abbr dater ^M^[:.!date +\%D^MkJA 
  436.  
  437. where "^M" stands for the keystroke sequence "control-V" followed by "control-
  438. M", and "^[" stands for "control-V" "<ESCAPE>".  Try jotting this down on a
  439. piece of paper, or printing it, and then trying the definition out by typing
  440. each keystroke manually.  Then try defining the abbreviation with the ex-
  441. escape "abbr" command, going into text entry mode, and typing text that
  442. contains the string "dater" preceded and followed by a non-alphanumeric
  443. character, say,
  444.  
  445.     I wonder if today is dater?
  446.  
  447. Note that strange things might happen if instead of an abbreviation, you
  448. used "map!" to make this macro, and then made a minor spelling error in
  449. the middle of some other sentence and said "validater".  This difference
  450. is the reason that 'vi' retains both "abbr" and "map!".  Even with
  451. "abbr", it's possible to collide with some valid use of "dater", as in
  452. "Please take this form and run it through the dater;" the lesson here is,
  453. the main problem with 'vi' text macros is pilot error, the failure to
  454. anticipate future collisions that will have unintended effects.
  455.  
  456. [Sidenote: the reason that '%' is preceded by a backslash in the above
  457. example is that on the "ex" command line, '%' is a magic character standing
  458. for the name of the file currently being edited, and therefore must be
  459. escaped to avoid this special meaning.  The two most common other
  460. characters that have special significance on the "ex" command line are
  461. "#", which stands for the last file previously edited, and "!", which
  462. stands either for the shell-escape, shell-filter, or command-history
  463. mechanisms depending on its position within the line.  All of these
  464. characters should be escaped on the "ex" command line when you don't
  465. want "ex" to see them specially.]
  466.  
  467. Text-entry macros that bounce between modes are notoriously difficult to
  468. cancel ("unabbr" or "unmap!") with a simple ex-escape command, the kind you
  469. introduce by typing a colon in 'vi' command mode.  This is because 'vi'
  470. believes that a simple ex-escape command line is being typed in text-entry
  471. mode, therefore it expands the name of the abbreviation or remap!'ing as you
  472. enter it.  The only effective way to get rid of such macros (and probably you
  473. should make it your habit to use this method to unmap ALL macros, just so you
  474. don't have to risk making a mistake evaluating which macro should be erased
  475. this way and which should not) is to type a capital Q ("Q") in 'vi' command
  476. mode, which puts you into genuine "ex" mode.  From now on, 'vi' can't see
  477. you.  Do your "unabbr" or "unmap!", then enter "vi" or "visual" at the next
  478. colon prompt to return to 'vi'.
  479.  
  480. Chained macros
  481. ---------------
  482.  
  483. Macros, being merely pre-defined sequences of keystrokes, can invoke other
  484. macros, anywhere in their definition.  Such "sub-macros" operate like
  485. subroutines in a computer program.  Take the following example:
  486.  
  487.     map = :set wm=3^M
  488.     map ; ^[=oThe End^[O
  489.  
  490. What this does is to first enter 'vi' command mode, in case we're not already
  491. there; invoke the "=" macro to set word-wrap with a hotzone of 3 characters,
  492. open text for entry, insert the words "The End" on a line by themselves, exit
  493. text-entry mode, open a new line above "The End", and let the user start
  494. typing in whatever text is to be ended by "The End".
  495.  
  496. This can be done at any number of levels; the "=" macro could itself call
  497. other macros, and so forth.
  498.  
  499.  
  500. Recursive macros
  501. -----------------
  502.  
  503. A macro that invokes itself is called a "recursive" macro.  'Vi' tries to
  504. limit the creation of recursive macros by prohibiting macros that embody
  505. "tail recursion", which is to say, a macro that ends by invoking itself. 
  506. This policing system is only partial.  Nothing stops you from imbedding a
  507. recursive macro call INSIDE (as opposed to at the end of) a macro definition.
  508. Although 'vi' will object to a definition like
  509.  
  510.         map! $ 123456$
  511.  
  512. it'll accept
  513.  
  514.         map! $ 123$456
  515.  
  516. THIS IS AN ABSOLUTE DISASTER.  You probably wouldn't make this mistake
  517. yourself, but you MIGHT define a text-entry macro as something like
  518.  
  519.         map! usr /usr/group
  520.  
  521. and this is just as disastrous.  The sequence that you use to define a
  522. remapped text-entry macro MUST NOT also appear in the macro text, because
  523. with the "map!" mechanism, the sequence in the macro text will be infinitely
  524. expanded.  This sort of thing is especially pernicious for "map!"; it's very
  525. rare with "abbr", but can happen there, too, provided that the sequence
  526. constituting the abbreviation name appears in the macro text and is bracketed
  527. by non-alphanumeric characters.
  528.  
  529. A macro is just like a computer program, and can be induced to execute
  530. endless loops that either do nothing or else wreak great damage on your text.
  531.  
  532.     However, there is nevertheless a place for a recursive macro call,
  533. almost exclusively in the realm of command-mode macros.  Most often, such
  534. useful recursive macros require just the sort of tail-recursion that 'vi'
  535. resentfully guards against.  'Vi' won't let you end a macro definition with
  536. the same character that you use to name the macro, so that
  537.  
  538.         map ; 123456;
  539.  
  540. won't work; but if you say, instead,
  541.  
  542.         map = ;
  543.         map ; 123456=
  544.  
  545. you're set.  If you invoke the remapped macro key ";" from command mode, then
  546. 'vi' will substitute "123456", and then find that "=" has been remapped to
  547. ";", that ";" has been remapped to "123456=", and repeat itself.  This is
  548. obviously a useless macro, of course; but unlike the text-entry mode macros,
  549. for reasons explained below, it isn't disastrous; it's merely useless.  Useful
  550. tail-recursive macros exist.
  551.  
  552. Sidenote: in this regard, note the "remap" option, which is controlled by the
  553. ex-escape commands "set remap" and "set noremap".  When the remap option is
  554. set (and this is usually the default case) then remapped characters are tried
  555. repeatedly until they are unchanged.  If "o" is mapped to "O" and if "O" is
  556. mapped to "I", then if the remap option is set, "o" will be mapped to "I". 
  557. If the remap option is not set, or to put it another way, if the "noremap"
  558. option is set, then "o" will only be remapped to "O".  Controlling the state
  559. of the remap switch can be used in very sophisticated recursive or chained
  560. macros to control macro termination and macro flow, because since macros can
  561. bounce among modes, it's quite possible, and sometimes useful, to include as
  562. part of the text of a macro,
  563.  
  564.         "...:set noremap^M...:set remap^M"
  565.  
  566. This allows the macro to toggle the remap switch transparently to the way the
  567. option is set outside the context of the macro.
  568.  
  569.  
  570. Terminating a recursive macro
  571. ------------------------------
  572.  
  573. Recursive macros aren't necessary very often -- the ex-escape "g" command
  574. serves pretty well -- but when they are necessary, you might wonder just how
  575. they ever stop.  The first answer is that ordinarily a macro can be
  576. terminated by hitting a keyboard interrupt -- the BREAK or DELETE key, or
  577. sometimes control-C.  The second answer is that a 'vi' macro will terminate
  578. if somewhere in the middle of the macro it finds a command that it can't
  579. execute successfully. 
  580.  
  581. Let's say that you want to count the times a given word or phrase occurs in
  582. your text between your cursor position and the end of text.  The macro
  583.  
  584.         map ; /Monty zuma/^M:!echo>>somefile^M^M=
  585.  
  586. if followed by
  587.  
  588.         map = ;
  589.         set nowrapscan
  590.  
  591. when invoked with the single keystroke ";" will recursively echo a blank line
  592. into "somefile" each time the string "Monty zuma" is encountered in the
  593. current text file.  When the scan reaches the end of the file, the "/"
  594. command will fail because "nowrapscan" is set, and the macro will terminate. 
  595. Such a macro differs from merely counting the lines on which the string
  596. "Monty zuma" occurs, because "Monty zuma" might occur more than once on a
  597. single line.  When it's done, and assuming that "somefile" was nonexistent or
  598. empty when the macro began, then the number of instances of "Monty zuma" from
  599. your cursor position when you invoked the macro to the end of your text file
  600. will correspond to the result of ":!wc -l somefile".  
  601.  
  602. In the above example, note the double "^M" after the shell-escape "echo"
  603. command.  Remember that a 'vi' macro merely duplicates a set of keystrokes. 
  604. Had you typed the command manually at the keyboard, the shell-escape "echo"
  605. command would have ended with a "Press return to continue" banner from 'vi'. 
  606. You'd have had to hit RETURN after typing the "echo" command, then hit RETURN
  607. again after the "echo" command completed, before doing anything else with
  608. 'vi', and the same principle applies to your macro.
  609.  
  610. On the other hand, remember also that some kinds of ex-escape commands do NOT
  611. require an extra RETURN after the command completes.  Most common are the
  612. filtering commands, like the ":.!date^M" command in the "dater" abbreviation
  613. discussed earlier.  You must always keep in mind that the macro is merely
  614. doing keystrokes for you, and that deciding upon the correct sequence of
  615. keystrokes is up to you.  The best approach to writing complex 'vi' macros is
  616. to take a pad and pencil and step through your projected macro keystroke by
  617. keystroke to make sure your logic is correct.  Only after you're sure that it
  618. is, should you actually enter the macro itself.
  619.  
  620. There are some peculiarities and limitations on just how well a macro can
  621. mimic your own keystrokes, and that will be discussed next.
  622.  
  623. Peculiar limitations and restrictions on 'vi' macros
  624. =====================================================
  625.  
  626. Size
  627. -----
  628.  
  629. This is probably the most exasperating restriction.  In most implementations
  630. of 'vi' for microcomputers, the total text of "abbr", "map!", or "map" cannot
  631. exceed some small fixed limit, often the size of a single disk block. 
  632. Moreover, the text of any given abbreviated or remapped sequence, and the
  633. content of any named text buffer used as a macro, cannot be longer than some
  634. even smaller fixed limit, often something like 128 characters.
  635.  
  636. Getting around these restrictions takes some ingenuity.
  637.  
  638. For getting around the size of an individual macro definition, chain macros
  639. together.
  640.  
  641. For getting around the overall limit on macro text, there's really no answer
  642. except to use different sets of macros depending on the job you're doing at
  643. the moment.  An excellent suggestion is to keep a file of every complex macro
  644. you've ever composed, where "complex" here means "hard to remember."  Place
  645. these macros in a text file, and put comments above each one to tell you what
  646. it does and why it works.  Something like
  647.  
  648.     # This macro opens a window in a Compuserve Forum capture
  649.     # file to allow entry of a reply for automatic upload
  650.     # later on.  It assumes that control-A has previously been
  651.     # mapped to the sequence ":set wrapmargin=3^M".  Text marker
  652.     # "a" is set to the top of the block, and marker "b" is
  653.     # set to the bottom of the block, so later, the block from
  654.     # "a" to "b" can be sent to an upload file.
  655.     ?^#: [0-9][0-9]* ?^M/[0-9]/^MdwP/^$/^MP0irep ^[ma^Ao/post^[mbkO
  656.  
  657.     # This macro takes the text between text markers "a" and "b",
  658.     # inclusive, and appends it to the text file "tangen" for later
  659.     # upload to the Compuserve Tangent Forum.
  660.     :'a,'b!cat >>tangen
  661.  
  662. In these examples, the control characters are all printable ascii, so that
  663. RETURN is represented by a caret and then an "M".  In your own "macro
  664. notebook" file, you should have the control characters made explicit, so
  665. that, say, "^M" is a REAL carriage return rather than a caret and an M.  You
  666. insert such characters with the control-V prefix, as discussed earlier.
  667.  
  668. You'll never use such a file directly.  Instead, you'll use the lines in it
  669. to select macros either to place into named text buffers -- you might want to
  670. put the first of the above macros into named buffer "x", and the second into
  671. named buffer "t", so that if you were reading your capture file and wanted to
  672. compose a reply, you'd hit "@x", compose your reply, and then hit "@t" to
  673. save it.
  674.  
  675. Another approach is to use the lines in the file to generate "map", or "abbr"
  676. or "map!" commands to place into the EXINIT environment variable later on. 
  677. You do this by bringing up your macro notebook file in 'vi', prefixing each
  678. line you want to, say, map, with "map soandso ", yanking that line into a
  679. named buffer with a capital-letter name; then saying ":e! new_vi" and using
  680. the "put" command to stick your accumulated text into the "new_vi" file. 
  681. Make sure that you don't re-save the notebook file; one of the nice things
  682. about 'vi' is that it's a non-destructive editor.  Now, in "new_vi", massage
  683. the text so that it's all a massive EXINIT initialization string.  At the
  684. bottom of the file, add "export EXINIT", and then "vi $*".  Write the file,
  685. exit, and enter "sh new_vi", and you'll have a custom-remapped 'vi' for the
  686. present purpose.  Often you'll find that only a very few such different
  687. customized 'vi's are needed.  Only rarely, using this method, does it become
  688. irritating to be limited to, say, a 512-byte block of total macro text.
  689.  
  690. A third approach is to customize a file called '.exrc' in the current
  691. directory: if different kinds of editing jobs are kept in different
  692. directories, each '.exrc' file will contain macros suitable for the job
  693. you're working on.  The format of a '.exrc' file:
  694.  
  695.     ab gatt General Agreement on Tariffs and Trade
  696.     map = :!date^M
  697.     map! qq rot E + dB/dt = 0
  698.     set ai
  699.  
  700. Putting and yanking to/from named buffers
  701. ------------------------------------------
  702.  
  703. Sometimes you'll have inside a macro a directive to yank text into a named
  704. text buffer, and 'vi' will tell you that you can't yank from inside a macro. 
  705. Or put inside a macro.  This is usually a lie: when this error message comes
  706. up, it's probably because of a fault in 'vi's program logic.  You will
  707. probably be able to get around it by making the yank the first thing that
  708. happens in the macro; sometimes, with particularly boneheaded implementations
  709. of 'vi', this will require that you split a single logical macro into two
  710. separate keystrokes.
  711.  
  712. Which keys to remap?
  713. ---------------------
  714.  
  715. As previously mentioned, some keys you can't remap at all in command mode. 
  716. Not much you can do about this.  There are only a limited set of keys that
  717. don't correspond to existing 'vi' commands, so unless you stick with that
  718. limited set, you're eventually going to redefine an existing command key. 
  719. When you do, make sure it's not a command key that you have any pressing
  720. immediate need for.  You can avoid the command-key-name crunch to some extent
  721. by using the named buffers for your macros; very few applications really
  722. require 26 active non-volatile text buffers, so that leaves quite a few of
  723. the named buffers from a-z available for use as macros.
  724.  
  725.  
  726. Conclusion
  727. ===========
  728.  
  729. Writing and using 'vi' macros is roughly equivalent to writing shell scripts,
  730. or other computer programs.  The functionality is limited only by your skill
  731. in using 'vi's own capabilities, the tools available from Unix, and your
  732. imagination.  If you can program in C, don't be afraid of writing a short C
  733. filter that you can tie into a 'vi' macro to do things with text that you
  734. can't see any other easy way to do.  If you can't program in C, there are a
  735. multitude of tools available anyway.  How to use 'vi' in general, and how to
  736. use the multifarious Unix tools, is beyond my scope here.  Have fun.
  737.