Skip to content

Instantly share code, notes, and snippets.

@habamax
Last active May 15, 2021 18:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save habamax/8990424953c1b6ba314229d0da4fb4d9 to your computer and use it in GitHub Desktop.
Save habamax/8990424953c1b6ba314229d0da4fb4d9 to your computer and use it in GitHub Desktop.

"Swap words" in vim

Quite a common task to swap words on a single line might be really cumbersome.

Consider following text transormation:

def hello(world, is, on, fire) → def hello(is, world, on, fire)

This one is fairly simple:

  1. put your cursor on world

  2. dWWP — swap it with is

117535854 5fe0f900 b000 11eb 84aa 6abe32715e10

The next one would have more keypresses:

def hello(world, is, on, fire) → def hello(world, is, fire, on)
  1. put your cursor on on

  2. dw — delete it

  3. w — go to fire

  4. vep — select and paste over it (yanking prev selected text)

  5. bbP — back to where on was, paste fire yanked previously

117535915 d847ba00 b000 11eb 9dab 8d49b87246bd

Or the next one:

def hello(world, is, on, fire) → def hello(fire, is, on, world)
  1. put your cursor on world

  2. diw — delete it

  3. /fi<CR> — go to fire

  4. vep — select and paste over it (yanking prev selected text)

  5. ``P — back to where world was, paste fire yanked previously

117283676 b0c0e800 ae6e 11eb 93cd f5031120dd15

There is a way to simplify it:

With mentioned plugins it looks way more convenient:

117285023 2da09180 ae70 11eb 88d9 fb3913c92ef1

There is customization in vim-swap you can use to swap markdown table cells:

117285645 ebc41b00 ae70 11eb 9443 5a98125f062a

vim-swap settings for the markdown cells swaps:

let g:swap_no_default_key_mappings = 1
nmap g< <Plug>(swap-prev)
nmap g> <Plug>(swap-next)
nmap g. <Plug>(swap-interactive)

let g:swap#rules = deepcopy(g:swap#default_rules)
let g:swap#rules += [
            \   {
            \     'mode': 'n',
            \     'description': 'Reorder the | bar | delimited | things |.',
            \     'body': '|\%([^|]\+|\)\+',
            \     'delimiter': ['\s*|\s*'],
            \     'priority': -40
            \   }
            \ ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment