How to “copy to clipboard” in vim of Bash on Windows?

前端 未结 9 1032
执念已碎
执念已碎 2020-12-13 00:38

I used to use \"+y to copy text to system\'s clipboard, but it doesn\'t work in vim of Bash on Windows.

9条回答
  •  没有蜡笔的小新
    2020-12-13 01:22

    If you don't want to set up an X server, this method will allow you to copy selected text to your clipboard using the clip.exe program which comes shipped with Windows.

    The code snippets below can be placed in your .vimrc file.

    First create a helper function which will return the currently selected text as a string. We can use this function to pipe highlighted text into clip.exe:

    func! GetSelectedText()
        normal gv"xy
        let result = getreg("x")
        return result
    endfunc
    

    The system function will allow us to call native programs and pipe parameters into them. The snippet below sets up two key mappings; the first line will allow Ctrl+C to be used for copying text and the second will allow Ctrl+X for cutting text:

    noremap  :call system('clip.exe', GetSelectedText())
    noremap  :call system('clip.exe', GetSelectedText())gvx
    

    After saving the changes to your .vimrc file you should be good to go.

    If you are going to be using your .vimrc on multiple systems, I suggest wrapping these mappings in an if statement to check if clip.exe actually exists:

    if !has("clipboard") && executable("clip.exe")
        noremap  :call system('clip.exe', GetSelectedText())
        noremap  :call system('clip.exe', GetSelectedText())gvx
    endif
    

    The above will also allow Vim to ignore those key bindings if it has direct access to the system clipboard.

    You might also want to add keybindings for when vim does have access to the clipboard, like so:

    if has("clipboard")
        vnoremap  "+x
        vnoremap  "+x
    
        vnoremap  "+y
        vnoremap  "+y
    
        map        "+gP
        map       "+gP
    
        cmap       +
        cmap      +
    endif
    

    Which will come in handy if you are using Vim natively on Windows or are using vim-gtk on a Linux system.

提交回复
热议问题