I do all my coding in vim and am quite happy with it (so, please, no "use a different editor" responses), but have an ongoing annoyance in that the smartindent feature wants to not indent comments beginning with # at all. e.g., I want
# Do something $x = $x + 1; if ($y) { # Do something else $y = $y + $z; }
instead of vim's preferred
# Do something $x = $x + 1; if ($y) { # Do something else $y = $y + $z; }
The only ways I have been able to prevent comments from being sent to the start of the line are to either insert and delete a character on the line before hitting # (a nuisance to have to remember to do every time) or turn off smartindent entirely (losing automatic indentation increase/decrease as I open/close braces).
How can I set vim to maintain my indentation for comments instead of sending them to the start of the line?
To indent the current line, or a visual block: ctrl-t, ctrl-d - indent current line forward, backwards (insert mode) visual > or < - indent block by sw (repeat with . ) then try hitting the F5 key while in insert mode (or just :set paste ).
Vim has four methods of indentation, namely: Autoindent – this method uses indent from the previous line for the file type you are editing. smartindent – smartindent works similarly to autoindent but recognizes the syntax for some languages such as C language.
It looks like you're coding in Perl. Ensure that the following are set in your .vimrc:
filetype plugin indent on syntax enable
These will tell Vim to set the filetype when opening a buffer and configure the indentation and syntax highlighting. No need to explicitly set smartindent since Vim's included Perl syntax file will set it (and any other Perl-specific customizations) automatically.
Note: having either set smartindent
and/or set autoindent
in ~/.vimrc
may prevent the solution from working. If you're having problems, look for them.
If you are using the "smartindent" indenting option, a fix for your problem is explained in the ":help smartindent" VIM documentation:
When typing '#' as the first character in a new line, the indent for that line is removed, the '#' is put in the first column. The indent is restored for the next line. If you don't want this, use this mapping: ":inoremap # X^H#", where ^H is entered with CTRL-V CTRL-H. When using the ">>" command, lines starting with '#' are not shifted right.
I use "smartindent" and can confirm that the fix described works for me. It tricks VIM by replacing the keystroke for "#" with typing "X", then hitting backspace, then typing "#" again. You can try this yourself manually and see that it does not trigger the auto-outdenting.
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