Search code examples
vim

How can I swap words that contain special punctuation in Vim?


I have many strings similar to "Edit the file `my-file.conf`" and I want to change them to "Edit the `my-file.conf` file". Note that the file names are in backticks and not single quotes (I couldn't see how to illustrate that in this editor). I've tried numerous alternatives but always seem to get hung up on the backticks. Can anyone help me out? Thanks.


Solution

  • I've been meaning to create some clean functions to do this (maybe someone else will provide them), but for now I have the following (hacky) remaps in my vimrc:

    " use [w and ]w and [W and ]W to exchange a word/WORD under the cursor with
    " the prev/next one
    nnoremap ]w mx$ox<ESC>kJ`xdawhelphmx$"_daw`xh
    nnoremap ]W mx$ox<ESC>kJ`xdaWElphmx$"_daw`xh
    nnoremap [w mx$ox<ESC>kJ`xdawbPhmx$"_daw`xh
    nnoremap [W mx$ox<ESC>kJ`xdaWBPhmx$"_daw`xh
    

    Make them repeatable with tpope's vim-repeat

    " apply the repeat plugin to any mapping
    function! Repeat(mapname, map, command)
        execute 'nnoremap <silent> <Plug>'.a:mapname.' '.a:command.
                    \' :call repeat#set("\<Plug>'.a:mapname.'")<CR>'
        execute 'nmap '.a:map.' <Plug>'.a:mapname
    endfunction
    
    " use [w and ]w and [W and ]W to exchange a word/WORD under the cursor with
    " the prev/next one
    call Repeat('WordForward', ']w', 'mx$ox<ESC>kJ`xdawhelphmx$"_daw`xh')
    call Repeat('WORDForward', ']W', 'mx$ox<ESC>kJ`xdaWElphmx$"_daw`xh')
    call Repeat('WordBackward', '[w', 'mx$ox<ESC>kJ`xdawbPhmx$"_daw`xh')
    call Repeat('WORDBackward', '[W', 'mx$ox<ESC>kJ`xdaWBPhmx$"_daw`xh')