简体   繁体   English

vim:发送文本选择到bash

[英]vim: send text-selection to bash

How can I send the currently selected (in visual mode) text content to a bash command? 如何将当前选择的文本内容(以可视模式)发送到bash命令?

I know, bash commands can be called with :! 我知道,bash命令可以用:!来调用:! , but for the rest I don't find documentation. ,但其余的我都找不到文档。

First, you can get visually selected text by a function. 首先,您可以通过函数获得直观选择的文本。 I brought this from https://stackoverflow.com/a/6271254/3108885 : 我从https://stackoverflow.com/a/6271254/3108885带来了这个:

function! s:GetVisualSelection()
  let [lnum1, col1] = getpos("'<")[1:2]
  let [lnum2, col2] = getpos("'>")[1:2]
  let lines = getline(lnum1, lnum2)
  let lines[-1] = lines[-1][:col2 - (&selection == 'inclusive' ? 1 : 2)]
  let lines[0] = lines[0][col1 - 1:]
  return join(lines, "\n")
endfunction

Then add a map for Visual mode: 然后为可视模式添加地图:

vnoremap <buffer> <F5> :<C-U>exec '!python -c' shellescape(<SID>GetVisualSelection(), 1)<CR>

If you press F5 , visually selected python code will be executed. 如果按F5键,将执行视觉选择的python代码。 You may define this map only for Python code, by prepending autocmd FileType python before vnoremap . 您可以通过在vnoremap之前添加autocmd FileType python仅为Python代码定义此映射。 So multiple file types can be handled. 因此可以处理多种文件类型。

autocmd FileType python vnoremap <buffer> <F5> :<C-U>exec '!python -c' shellescape(<SID>GetVisualSelection(), 1)<CR>
autocmd FileType ruby vnoremap <buffer> <F5> :<C-U>exec '!ruby -e' shellescape(<SID>GetVisualSelection(), 1)<CR>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM