2013-02-14

Simple trick for managing JavaScript brackets in Vim

There are many ways to handle JavaScript brackets and braces in Vim, including autoclosing using plugins. In some cases, though, that is simply not enough. I will show you a few snippets you can insert into your ~/.vimrc to make things a bit easier in some situations.

Bracket followed by semi-colon

This is one of the annoying problems that, so far, no editor I've seen could solve in any sane way. Namely, when you have to open round brackets to enter function arguments you also have to close the bracket and add a semi colon. Here's the example:

myFunc(...);

If you have bracket auto-closing, it would automatically close the bracket and put your cursor inside them, so you don't have the chance to also add the semi-colon:

myFunc(|)

In that case, you'd have to type the arguments, and then go to the end of the line to enter the semi-colon. Tedious...

On the other hand, if you don't have bracket auto-closing, you have to type everything. Again, tedious...

Here is a snippet that you can add to your ~/.vimrc to make things easier:

autocmd FileType javascript inoremap (; ();<Esc>hi

With the above snippet, if you type ( and then ;, it will close the bracket, add the semi-colon, and put the cursor into the brackets.

myFunc(|);

Open blocks with curly braces

Another common pattern is opening blocks of code within curly braces. For example:

if (condition) {
  ...
}

or:

function (foo) {
  ...
}

As with brackets, if the braces are auto-completed, you have to add the newline between them, and then either move back up, or use the S-o shortcut to enter another newline between them and indent the line. Tedious...

Better solution is this:

autocmd FileType javascript inoremap {<CR> {<CR>}<Esc><S-o>

With the above snippet, when you type the opening brace and hit Enter, the other brace will be closed, and a new indented line created between the braces.

function (foo) {
  |
}

Combined with the other autocommand, you can enter functions as arguments. If you type $(;function() {<CR>, Vim will insert:

$(function() {
  |
});

Conclusion

The two autocommands are a rather simple fix, but they demonstrate a powerful principle. In the insert mode, you can map series of keystrokes to a whole bunch of keystrokes and/or commands. For example, you can map a series of keystrokes to the :w! command, and not even leave the insert mode in order to save a file:

inoremap ``w <Esc>:w!<CR>i

With the above setup, whenver you type ``w Vim will simply ignore the text you typed and instead save the file. But if you type, say, ``<Space>, it would insert `` as usual.