GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Saturday 3 March 2007
vim insert multiple lines

The question was: "In olden times, vi would allow you to insert multiple lines with a ":g/pattern/i..." command. How does one do this in vim?

My first answer was actually an answer to a question not quite asked: "How does one do something like this in vim?" And that answer was

  :g/pattern/s/^/one-new-line^V^Manother^V^M/

But naturally, the question as actually asked gnawed at my brain, and I tried a few things, including even (gasp!) vim's :help command!

So, let me count the ways that ended up working for me:

  :g/pattern/i|only-one-inserted-line-can-be-typed-here

Hmm, that worked at work, but not here at home. (See below.)

:help :g helped me find this one -- I had never heard of the "normal" command before:

  :g/^buz/normal ifirst-inserted-line^Msecond-one^M^[

I finally found the key here, under :help :insert

  These two commands will keep on asking for lines, until you type a line
  containing only a ".".  Watch out for lines starting with a backslash, see
  |line-continuation|.
  When these commands are used with |:global| or |:vglobal| then the lines are
  obtained from the text following the command.  Separate lines with a NL
  escaped with a backslash: >
        :global/abc/insert\
        one line\
        another line
  The final "." is not needed then.

Without that, It would have taken a lot longer to think of using the backslash, or the actual control-J instead of control-M.

Soooo, the oh-so-user-friendly escaping required, to get as close as is reasonable to the old vi behavior, is approximately the least intuitive thing that could possibly work:

    :g/pattern/i\^v^jone-line\^v^janother

And, oh, by the way, the doubly-escaped newline displays as "^@".

Dang, that again did not work at home. "Trailing characters." Aha, this appears to be something fixed between vim version 6.2 and vim version 7.0. (Mac OS X, in case that matters.)

(Edit: I hadn't noticed that the backslashes disappeared upon publication.)
11:33:44 PM   comment/     



Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/4/1; 15:25:05 .
Click here to send an email to the editor of this weblog.

March 2007
Sun Mon Tue Wed Thu Fri Sat
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Feb   Apr

Previous/Next