I've been trying to find something that will let me run multiple commands on the same line in Vim, akin to using semicolons to separate commands in *nix systems or & in Windows. Is there a way to do this?
8 Answers
A bar | will allow you to do this. From :help :bar
'|'can be used to separate commands, so you can give multiple commands in one line. If you want to use'|'in an argument, precede it with'\'.
Example:
:echo "hello" | echo "goodbye"
Output:
hello
goodbye
NB: You may find that your ~/.vimrc doesn't support mapping |, or \|. In these cases, try using <bar> instead.
9 Comments
|!map statement (and believe me, you will), check out :help map_bar..vimrc doesn't support an escaped bar (\|) for mappings. I learned I have to actually type out <bar>.:help bar shows motion.txt though and nothing about multiple commands.:help <bar>Put <CR> (Carriage Return/Enter) between and after commands. For example:
map <F5> :w<CR>:!make && ./run<CR>
Don't use | because:
Some commands have problems if you use
|after them|does not work consistently in configuration files, see:help map_bar
1 Comment
:h map_bar I got that it was ok to use <bar>. But you're right, it is complicated. Reading :h map_bar is the way to go here.You could define a function that executes your commands.
function Func()
:command
:command2
endfunction
And place this in, for example, your vimrc. Run the function with
exec Func()
4 Comments
:call Func() because :execute Func() means something more. It means to perform the return value of the function as a command. The function described here will not usually have a command that starts with :return, so its return value will be the number zero. Performing that as a command will move the cursor to the first line of the current buffer, which is not always what you had in mind.call works; exec produces unexpected results. Thank you!Thought this might help someone trying to do substitutions in a chain and one fails
from a comment
%s/word/newword/ge | %s/word2/newword2/ge
You can use the e flag to ignore the error when the string is not found.
1 Comment
I've always used ^J to separate multiple commands by pressing Ctrl+v, Ctrl+j.
5 Comments
^J as command separator in a string because it is inserting the NULL character terminating the string. however you can use <CR> = "\n".exe "echo 'foo' \n echo 'bar'"exe "echo 'foo'" . nr2char(0x0a) . "echo 'bar'"map aa :echo 'foo' <C-V><C-J> echo 'bar'<CR>
;instead of&&to separate Unix shell commands too!&&is 'boolean and' in shell commands so if you havecommand1 && command2,command2will only execute ifcommand1executed successfully. with;you're just manually specifying the end of that line and starting a new one. It's the same as writing each command on a different line in a shell script.