简体   繁体   中英

How to do automatic code alignment for all the code or a block of code in vi/vim?

I want to know what's the quickest way to do automatic code alignment in vi/vim or a method to add something in ~/.vimrc and then press a shortcut in vi/vim for making the code aligned/neat? Like I am using :set cindent in a .c code but it doesn't indent the code.

To enable automatic indenting — particularly for a C file — you can use something like this in your ~/.vimrc :

set cindent
set autoindent

For more on those options, run :help cindent and :help autoindent .

To indent existing code in a file, you can use = , which will indent a selection (or indeed a whole file). One way to indent all the code in an entire file is to run

gg=G

or

1G=G

either of which will jump to the top of the file ( gg , or 1G ), and then indent the code ( = ) from there to the end of the file ( G ). If you'd like to indent a particular block of code, you can visually select it and then run = ; for example, to indent eight particular lines (including the one that the cursor is on), you could run

V7j=

which would enter linewise visual mode ( V ), selecting the current line, move down seven lines ( 7j ), selecting those too, and then indent the selection ( = ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM