Showing posts with label vim. Show all posts
Showing posts with label vim. Show all posts

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.


Friday, March 10, 2017

vim - how to re-format the assignment or equation in the code and log file

From time to time, we find ourselves in the situation where  we have some code or log files that have the following format

a=10
bb=20
ccc=30
dddd=40
eeeee=50
ffffffff=60

and we want to have a cleaner format like :

a                              = 10
bb                             = 20
ccc                            = 30
dddd                           = 40
eeeee                          = 50
ffffffff                       = 60



Here are the steps how to do it quickly in vim.

step 1: add empty space before and after = sign. we can achieve this by substitue command

    '<,'>s/=/ = /

step 2: re-format each line using printf

'<,'>!xargs printf "\%-20s \%s \%s"


Explanation

'<,'> is the previous selection (type ge)
! calls the external command
xargs will pass each line to printf.
\% is to escape the % sign. In vim, % represent the current file name
-20 means the minimum size of the string is 20 and it is left-adjusted
\%-20s \%s \%s correspond to left side, = sign and right side respectively.