Sunday, June 4, 2017

Vim - C/C++ style indent

When edit C/C++ file with vim, sometime we have the problem that the close brace "}" cannot be indent correctly.

One solution is to use "=" utility in vim. In the normal mode, we can type gg=G. This will correct the indent issues in the current file. One of the inconvenience of this method is that you need to exit the insert mode and the edit process is interrupted.

Here is another solution. We still leverage the "=" utility in vim. In addition to that, we also need the command gi. it will send the cursor to the position where you were in the insert mode last time.

The full command is something looks like this:

    inoremap } <esc>a } ^]<s-v>=gi^]f}a

The goal is to map } in the insert mode and correct the possible indent issue and then back to the insert mode.

Initially, we are in the insert mode, <esc> let us exit the insert mode. (a }^] is to add an empty space before "}". It is not necessary for the purpose of correcting the indent issue.) <s-v> let us enter the visual mode, = will correct the indent issue of the current line. gi^] send us back to the position where the last edit occurs. f}a find the "}" and put the cursor after "}" and enter the insert mode.


No comments:

Post a Comment