Vim Tips Wiki
Register
Advertisement

Whenever you complete a code block in a curly braces language by typing '}', this mapping automatically indents said block.

imap } }<Esc>=%``a

It works by typing out the '}', indenting with % and then returning to the last cursor position. It then puts vim back in insert mode (with a).

This doesn't work cleanly if the closing curly brace has to be indented outwards (the cursor goes to where it was originally typed). I don't believe there is a clean way to handle this.

Comments

Why is this mapping needed? Don't the Vim defaults automatically indent C programs as you type, with no need to do anything special when } is pressed? JohnBeckett 09:08, 28 March 2009 (UTC)


Perhaps this isn't for C code, in which case 'cindent' would not be set and 'cinkeys' would have no effect? 'indentkeys' would still be the correct way to do this, however, as far as I can tell.

--Fritzophrenic 17:28, 30 March 2009 (UTC)


(Hope I'm adding this comment the right way...) Both the indenting and indentkeys probably cover most people's needs, but I find the feature useful myself. As an example, I was refactoring a bit of code just now, and I put an existing if-statement (consisting of several lines) inside a for loop. The whole body gets indented properly, whereas normally I would have to do it manually. It also helps in editing other people's code.


OK, but each new tip has to make sense to someone who is browsing the tip collection, and has to contain advice that is useful in most cases. In general, one should be using the standard indent procedures, and tips should explain those. I'm not sure if we have a better tip, but Indent a code block is a weak tip that should be enhanced. The above information could possibly be added, if the circumstances where it is helpful could be made clearer (I don't see how the tip would help pasting existing lines, unless you're using a console Vim where the paste is performed by the operating system feeding keys and you have forgotten to set the 'paste' option). My inclination is to merge tips, particularly short ones, to keep related information in one place. JohnBeckett 22:53, 30 March 2009 (UTC)


Advertisement