bash substitutions in vimscript

喜夏-厌秋 提交于 2019-12-13 20:53:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!