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

后端 未结 2 2180
长发绾君心
长发绾君心 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:"
    

    where means press Ctrl+R. The y 'yanks' the selected text, the : enters command mode, " pulls the contents of the " (last yanked text) register onto the command line and (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 ,call RunCommands()
    vmap ,r :RunCommands
    

    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()
    

提交回复
热议问题