I'm had some trouble defining a mapping in my .vimrc. I want <leader>sv
to source my .vimrc, but first I want to write, if I'm currently editing it.
Goal
The intention of the code is this:
if expand('%:p') ==? expand($MYVIMRC)
write
endif
source $MYVIMRC<cr>
Attempt 1
I tried writing my commands inline with pipes:
nnoremap <leader>sv :if expand('%:p') ==? expand($MYVIMRC) | write | endif | source $MYVIMRC<cr>
But I get this error when I load it:
Error detected while processing /Users/jack/.vimrc:
E580: :endif without :if: endif
Attempt 2
I also tried:
let s:source_vimrc='if expand('%:p') ==? expand($MYVIMRC) | write | endif | source $MYVIMRC'
nnoremap <leader>sv :exec(s:source_vimrc)<cr>
which got me:
E15: Invalid expression: 'if expand('%:p') ==? expand($MYVIMRC) | write | endif | source $MYVIMRC'
Attempt 3 (working)
The only way I can get it to work is using <cr>
to simulate typing the whole thing out across multiple lines:
nnoremap <leader>sv :if expand('%:p') ==? expand($MYVIMRC) <cr> :write <cr> :endif <cr> :source $MYVIMRC<cr>
Attempt 4 (sort of?)
nnoremap <leader>sv :if expand('%:p') ==? expand($MYVIMRC) <bar> write <bar> endif <bar> source $MYVIMRC<cr>
That does it, but leaves me with Press Enter or type command to continue
instead of returning to normal mode.
Questions
Do mappings not support pipes for multiple commands? Or do if
s not? Why didn't the first one work like I expected?
A: Because the pipes are interpreted as new commands in the file. Use <bar>
to get them written to the command line.
Why doesn't #4 return me to normal mode? When I type in the command (with |
s), it does.
Note: I'm open to suggestions for better ways to accomplish this, too.
Press Enter or type command to continue
, make your mapping a<silent>
one. You can also increase yourcmdheight
. See:h hit-enter
.