You may need to insert a line break (newline) before or after each
occurrence of a search pattern. That is useful if the newlines are
needed, or as a temporary change to help understand some text. This tip
shows how to insert newlines before or after specified strings, both
manually and using a script to define a command so, for example,
:%LineBreakAt
would add a newline after
and
Using a script
The following script defines a user command to automate the insertion of line breaks. Save the script in a file called
linebreakat.vim
.
" Insert a newline after each specified string (or before if use '!').
" If no arguments, use previous search.
command! -bang -nargs=* -range LineBreakAt ,call LineBreakAt('', )
function! LineBreakAt(bang, ...) range
let save_search = @/
if empty(a:bang)
let before = ''
let after = '\ze.'
let repl = '&\r'
else
let before = '.\zs'
let after = ''
let repl = '\r&'
endif
let pat_list = map(deepcopy(a:000), "escape(v:val, '/\\.*$^~[')")
let find = empty(pat_list) ? @/ : join(pat_list, '\|')
let find = before . '\%(' . find . '\)' . after
" Example: 10,20s/\%(arg1\|arg2\|arg3\)\ze./&\r/ge
execute a:firstline . ',' . a:lastline . 's/'. find . '/' . repl . '/ge'
let @/ = save_search
endfunction
In Vim, enter the command :so linebreakat.vim
to source the script.
If you want the script sourced
automatically whenever Vim starts, place the file in directory
~/.vim/plugin
(Unix) or $HOME/vimfiles/plugin
(Windows). On Windows, enter the
following command to see the name of the required directory (which you may need to create):