« Back to Index

Vim: Tips

View original Gist on GitHub

Tags: #vim #tips #tricks

Vim Tips.md

Make two windows scroll together

:windo set scrollbind and :windo set cursorbind

Go to file and line number

gf takes you to the file referenced (e.g. [Makefile](../Makefile)) but if you add a : followed by a line number to the link (e.g. [Makefile](../Makefile:123)) then pressing gF will take you to the specific line number as well.

Delete line above or below the current line

:-d and :+d delete the line above or below the current line, unlike dj or dk which would also delete the current line.

Copy line to another location

:copy allows you to copy a line to another location

e.g. :10 copy 20 copies the range, in this case line 10, to below line 20), where I had always :10y then moved to the destination.

Paste a register

:<range>put <register> allows you to paste a register to a specific line.

QuickFix Window Filtering

:packadd cfilter enables filtering results from quickfix window (e.g. :Cfilter /pattern/, also has negated version Cfilter!).

Append to multiple lines

To ‘append’ to multiple lines: Ctrl+v and select multiple lines, then $, then Shift+a and start typing (this is the opposite of ‘insert’ with Ctrl+v and Shift+i).

Format text width

To autoformat text to a specific width (e.g. set textwidth=80), first select the text and then execute gq. This is super useful for when you have a code comment that you need to tweak/edit, and then it messes up the line breaks. You can just select the entire text and gq to have it fixed!

Format JSON with jq

:%!jq will format the entire file

Modelines

https://vimhelp.org/options.txt.html#modeline

Edit files via terminal

vim -E -s config.txt <<-EOF
:%s/foo/bar/
:update
:quit
EOF

Sort All Arrays

This uses :g/regex1/,/regex2/command syntax.

:g/\[/+1,/\]/-1sort

It will operate on all lines between the lines matching /regex1/ and /regex2/

We use this to sort a bunch of arrays in a file that looked like:

some_var = [
  one,
  two,
  three,
]

another_var = [
  pineapple,
  banana,
  apple,
]