gvim: passing the visually-selected text to the command line

后端 未结 2 2181
长发绾君心
长发绾君心 2021-02-10 02:05

I use gvim to store recipes of commands that I will execute, depending on output. Currently, I select the text in gvim and paste the commands into a terminal console, but I bet

相关标签:
2条回答
  • 2021-02-10 02:10

    Assuming you mean the Vim command line:

    (if you mean the OS command line, see below).

    For parts of lines (i.e. no end of line character), you could do something like this:

    " Visually select lines, then:
    y:<C-R>"<ENTER>
    

    where <C-R> means press Ctrl+R. The y 'yanks' the selected text, the : enters command mode, <C-R>" pulls the contents of the " (last yanked text) register onto the command line and <ENTER> (obviously) runs the command.


    If you want to do line-wise stuff, it's a bit more complicated (as the command line doesn't like ^Ms in the command). I'd recommend something like this in your vimrc:

    function! RunCommands()
        exe getline('.')
    endfunction
    command -range RunCommands <line1>,<line2>call RunCommands()
    vmap ,r :RunCommands<CR>
    

    Select the lines (after restarting vim) and press ,r.


    Another way that you may find useful is to copy the lines you want, hit q: to open the command line window and paste the lines you want into there and then move the cursor over the line you want and press ENTER. This has the advantage that you can edit the command before pressing ENTER. It'll only run one command at a time.

    If you mean an (e.g.) Windows or Linux command line:

    Use the function I listed above, but instead of:

    exe getline('.')
    

    use

    call system(getline('.'))
    

    or, if you want to see the result:

    echo system(getline('.'))
    

    or

    echomsg system(getline('.'))
    

    For more information:

    :help :echo
    :help :echomsg
    :help :messages
    
    :help :vmap
    :help :command-range
    :help :command
    :help :function
    
    :help c_CTRL-R
    :help :exe
    :help getline()
    :help system()
    
    0 讨论(0)
  • 2021-02-10 02:18

    If you are using the vim GUI, you can do set guioptions+=a. This way, any highlighted text inside gvim in visual mode gets pasted to a clipboard.

    0 讨论(0)
提交回复
热议问题