How do you prettify / align / format code in vi? What is the command?
I have pasted in a hunk of code and I need to have it all formatted/aligned... obviously I am a vi neophyte.
x
Steps. Press “<SHIFT> + v” to enter VISUAL LINE mode. Select the text you wish to indent but using either the cursor keys or the “j” and “k” keys. To indent press “<SHIFT> + dot” (> character).
These commands in my answer work in vim. Most people who think they're using vi are using vim. To find out if your 'vi' is really 'vim', open vi and type :version
-- if it's vim, it will say so. Otherwise you might just see a version number without the name of the program. Also, when you open vim for the first time you will usually see a splash screen of some sort that says "VIM - VI iMproved"...
Automatic Indentation
To turn auto-indentation on, make sure vim knows the file type you're editing (it usually automatically detects this from the file name extension, but might not figure it out with some file types). You can tell it the filetype using the menus for syntax highlighting. Then, do this:
:filetype indent on
You can disable auto-indentation with
:filetype indent off
Automatically adjusting/correcting indentation
In general, ={motion} will align code to an indentation level.
==
align the current line=i{
align the inner block=%
align to the matching parenthesis/bracket under the cursor=14j
or 14==
align the next 14 lines=G
align to the end of the file vG=
same thing, align to the end of the file (but using visual mode) vjjj=
align four lines (using visual mode)Manual indentation
If vim is not guessing the indentation level correctly, there are two ways to change it:
<<
to shift a line left, or >>
to shift it right by one tab. You can do this with several lines by using the same movement commands I showed above (eg, >i{
indents the current inner code block).Aligning equals signs, etc
If you want to align equals signs in a list of declarations, you should consider using this vim script: http://www.vim.org/scripts/script.php?script_id=294
Adjusting indentation/tab sizes
If you want vim to use spaces instead of tabs when it indents, run this command (or consider adding it to your vimrc file)
:set expandtab
To set how many spaces equal a tab, I usually do this:
:set expandtab softtabstop=3 tabstop=3 shiftwidth=3
But if you have to work with different amounts of tabs a lot, you could also use this function and keybinding:
function! Ktabs(tabsize) execute "set softtabstop=" . a:tabsize . " tabstop=" . a:tabsize . " expandtab shiftwidth=" . a:tabsize "set softtabstop=a:tabsize tabstop=a:tabsize expandtab shiftwidth=a:tabsize endfunction noremap <leader><Tab> :call Ktabs(3)<Left>
If you are editing a file with a mix of tabs and spaces, you may want to use this command after setting tab size:
:retab
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With