brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: gg=G in Vim fixes the indentation of the whole file

Vim
~/tips/tip-vim-reindent-file

gg=G

Re-indents a file using Vim's indent rules for the language.

Code pasted from a web page or a chat often loses its indentation. Vim can redo it for the whole file with four keys.

gg=G

= is the indent operator. gg goes to the top and G is the motion to the last line, so this re-indents everything. On a smaller part, use =ip for a paragraph or = on a visual selection.

Vim uses the indent rules for the file type, so it needs them switched on. Put this in your vimrc if it isn’t there yet:

filetype plugin indent on

The size of each step comes from shiftwidth, and whether tabs or spaces are used from expandtab. Set those to what the project uses before you press =, or the result is consistent but not what your colleagues expect.

After the cursor jumped to the end, Ctrl-o takes you back to where you were.

The result is only as good as the indent rules. For C-like languages, HTML and shell scripts it works well. For Python and YAML, where indentation carries meaning, Vim can’t know what you meant, and it may change the structure of your code. I’d leave those to a formatter like black, or check the diff carefully.

Further reading: Vim help: = operator, Vim help: :filetype indent on

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link