Vim Indenting C/C++ Code
Posted on In Linux, ProgrammingVim provides some basic formatting commands. A combination of these commands with the editing commands will make the programmer happy.
A list of basic text formatting commands in Vim:
- = is an operator that formats/indents text.
- i{ is a text object that specifies the surrounding code block. It should be used together with v, =, etc.
Some basic but useful operation that are combination of the two basic ones above:
- vi{ visually selects the inner code block around the cursor.
- =i{ formats the code block.
- =2i{ formats the current block and the block around it.
- == formats current line.
The method to format a block of C/C++ or Java code:
- First, go to the start point of codes to be formatted, then press v to start selection.
- Second, go to the end point.
- Third, press = to format the codes that have been selected. All braces and indentations will be aligned.
A short way to format the whole buffer:
- gg=G
= is an operator that does indentation only. It doesn’t format.
If you want formatting use `gq`. Type `help gq` for more info.
Installing this plugin: https://github.com/Chiel92/vim-autoformat might help for getting the right formatprg settings for using `gq`.