Reputation: 24555
I have 2 commands that work all right to add line numbers to whole file or selection and to change those line numbers to create 1]
format:
command -range=% Addln2 <line1>,<line2>!cat -n
command -range=% Addln3 <line1>,<line2>s/\v\s+(\d+)\s+/\1] /g
However, I am not able to combine them to one command. I tried:
command -range=% Addln2 <line1>,<line2>!cat -n | s/\v\s+(\d+)\s+/\1] /g
but it produces error.
Using sed also does not work:
command -range=% Addln2 <line1>,<line2>!cat -n | sed 's/\v\s+(\d+)\s+/\1] /g'
I also tried to put them together in a function:
function Addlnfn() range
a:firstline,a:lastline !cat -n
a:lastline,a:firstline s/\v\s+(\d+)\s+/\1] /g
endfunction
command -range=% Addlnfn <line1>,<line2>call Addlnfn()
But this also produces an error: Missing endfunction
Where is the problem and how can this be solved? Thanks.
Upvotes: 2
Views: 80
Reputation: 172598
In general, |
can be used to separate commands, but there are exceptions, and :!
is one of them, as :help :bar
explains. The reason here is that the external shell command invoked by :!
may be a pipeline (e.g. cmd1 | grep foo
), so the |
character needs to be part of the arguments, and cannot separate Vim commands.
One workaround is to surround the first command with :execute
:
command -range=% Addln2 execute '<line1>,<line2>!cat -n' | s/\v\s+(\d+)\s+/\1] /g
Moving the commands into a function is another good approach. What you've missed is that the evaluation of the a:firstline,a:lastline
function arguments doesn't happen automatically in Vimscript. Again :execute
comes to the rescue:
function Addlnfn() range
execute a:firstline . ',' . a:lastline . '!cat -n'
execute a:lastline . ',' . a:firstline . 's/\v\s+(\d+)\s+/\1] /g'
endfunction
command -range=% Addlnfn <line1>,<line2>call Addlnfn()
You don't need an external command to number the lines; this can be done purely inside Vim. Looking at your other recent question, it seems you've already discovered that.
Upvotes: 2