Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - map shell command

Tags:

dictionary

vim

I have following instruction in my .vimrc:

map t :!../tt <C-R><C-W> <CR><CR>

It works quite fine: vim gets word from file and runs ../t word. But one annoying thing is when the command is run vim returns to shell for a while and then return to file. I don't need to see command output so is it possible to get around this annoying flash?

like image 635
ghi Avatar asked Jun 06 '26 11:06

ghi


1 Answers

You can try either

nnoremap <silent> t :<C-u>silent !../tt <C-r>=shellescape(expand('<cword>'), 1)<CR><CR><C-l>

or

nnoremap <silent> t :<C-u>call system('../tt '.shellescape(expand('<cword>')))<CR>

or even

nnoremap <expr> <silent> t system('../tt '.shellescape(expand('<cword>')))[-1]

. Note some things:

  1. Don’t use map (without n and nore) unless you have a specific reason. I believe you don’t need this mapping for visual and operator-pending modes (leading n restricts mapping to normal mode only) and you also should not want this mapping to be remappable.
  2. Use <C-u> to discard count you can occasionally type unless you do know you need it (third version uses two hacks that turn mapping to no-op with a side-effect and does not need <C-u>).
  3. Never forget to escape shell arguments.
  4. Version with silent ! (do not forget space after silent, this is why @David Pope’s answer does not work) has <C-l> at the end. This is because using ! will always provide access to your terminal and thus redraw is needed after command has run.
  5. Versions with system() won’t work if you add an argument containing newline, it is a documented bug. If you don’t want to do so (expand('<cword>') won’t ever add newline) it is absolutely safe.
  6. t is a very useful motion. It is better to learn to use it then remap it to something. I suggest ,t as a lhs.
like image 196
ZyX Avatar answered Jun 10 '26 20:06

ZyX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!