问题
How can I use bash substitutions in mapped commands in vimscript
?
Vim does work well with &&
operator but it does not like bash $(command)
operator and backticks operator.
In my .vimrc
I have such a simplified line:
nnoremap SOME_KEY :!java $(echo % | sed 's/\.java//') <CR>
I would expect running java Test
command on pressing SOME_KEY
if my current file is Test.java
.
Instead it results in the following error E492: Not an editor command: sed 's/\.java//')
What is the correct way to use bash substitutions in commands executed on pressing a key in vim? Is there a better way to do what I try to accomplish?
回答1:
You have to replace |
with <bar>
.
If you insert |
into a mapping vim interprets the characters after |
as a new command.
Hence, in your case vim rightly complains about sed 's/\.java//'
isn't an editor command.
Another way to implement your mapping would be
nnoremap SOME_KEY :call system("java $(echo ". expand('%') ." | sed 's/\.java//')")<CR>
回答2:
Vim is interpreting the |
as a command separator in vim not as a pipe in bash.
To fix this you can either escape the |
with \|
or use <bar>
However this is really no reason to be executing this command in bash. This is the same as the following in viml.
nnoremap SOME_KEY :!java shellescape(expand('%:r'))<CR>
%:r
is the current file name without extension.
This one also has the added benefit of escaping the filename just in case the name has spaces or some other weird characters.
Relevant help pages :h filename-modifiers
, :h :bar
, :h shellescape()
, :h expand()
回答3:
Try:
nnoremap SOME_KEY :exec '!java ' . expand("%:r")<CR>
Vim already has a method to strip the extension expand("%:r")
. Using exec
is a good way to do something based on concatenating strings.
来源:https://stackoverflow.com/questions/17883131/bash-substitutions-in-vimscript