History Report a problem
Article Edit this page Discussion

Add a newline after given patterns

From Vim Tips Wiki

Jump to: navigation, search

Tip 671 Previous TipNext Tip

Created: March 5, 2004 Complexity: basic Author: parv Minimum version: 6.0 Karma: 4/1 Imported from: Tip#671


After having gone numb when trying to de-parse HTML source code with very long lines, I created the following function with a macro and command. It takes a list of one or more patterns/strings, and adds a newline after each. (Wrapping/indentation is controlled by your own settings).

"Intentionally left incomplete to be complete as needed
nnoremap ,nl :NewLine

"Add line breaks in after given strings/regex
com! -nargs=+ -range -bar NewLine <line1>,<line2>call AddNewLine(<f-args>)

function! AddNewLine(...) range
  let str_no = 1
  while str_no <= a:0
    exec 'let var = a:' . str_no
    " ` (backquote) is used as delimiters for s///, which is hard
    "  to distinguish but also is much rarer than delimiters.
    "  And, "No Match found" messages are suppressed (s///e)
    exec a:firstline . "," . a:lastline . 's`\(' . var . '\)\($\)\@!`\1\r`ge'
    let str_no = str_no +1
  endwhile
  unlet! var
  unlet str_no
endfunction

Note: The substitution is done on a pattern which is NOT ALREADY AT THE END of the line. The default range is limited to current line; specify other range just like any other Vim command.

[edit] Comments

Why not just use the 's'ubstitution command and ^V^M (ctrl-v, ctrl-m) (or ^Q^M)?

To put a new line after each <br /> tag in your html try something like:

:%s/<br \/>/<br \/>^V^M/g

I wrote the function mainly because to get the effect of giving OR'd pattern, in LHS of s///, simply separated by spaces w/o having to escape the darned "|"; also, to not having to remember to put "\($\)\@!" -- zero width negative look ahead assertion for end-of-line -- on each invocation of s///. \@! is used to limit the number of useless blank lines.

As to using ^V^M, instead of \r I suppose, ... I tried using \<CR> , <CR> , ^V^M and ^M in a normal macro, which was not including a new line. (I had not tried ^Q^M.) Instead, search for 'g' was being initiated, given macro's RHS was ":%s/\(>\)\($\)\@!/\1^M/g" (where ^M is one of \<CR> , <CR> , ^V^M, ^M).

The same exact macro works as desired when manually executed. After wasting time w/ above four character sequences, I used \r.


Rate this article:

Share this article:

Hubs Highlights International Sites Wikia messages
Entertainment
Gaming
Cartoons & Comics
Science Fiction
Hobbies
Sports
See all...
Grand Theft Auto
Pushing Daisies
Legend of Zelda Wiki
Terminator Wiki
Everquest II Wiki
Astronomy Wiki
German
Spanish
Chinese
Japanese
More...
Wikia is hiring for several open positions


Vote for featured Wikia!

Send this article to a friend
"Add a newline after given patterns"
 
 
Hi!

I thought you'd like this page from Wikia!

http://vim.wikia.com

Come check it out!
Send confirmation