« Back to home

Fun with vim and var

A common style guideline in JavaScript is to use a single var declaration at the top of your functions. This is because even if you use multiple var declarations scattered throughout the code, JavaScript’s scoping rules mean that the variables are actually defined at the top of the function that contains them — so why not make your code reflect reality?

So you end up with functions that look like this:

var foo = function (x) {
  var y = document.getElementById(x),
      z = y.checked,
      s = y.style;
 ...
}

Lispers will recognize that JavaScript var is just Scheme’s let*.

Recently discussion has wandered across the net arguing that this is bad practice, because if you want to re-order your variables in the var declaration, it’s too much editing grunt-work. So people have proposed that it’s better to do this:

var foo = function (x) {
  var y = document.getElementById(x);
  var z = y.checked;
  var s = y.style;
 ...
}

I write in single-var style all the time, and frankly I’ve never found myself cursing at the difficulty of reordering the variables. However, for fun I decided to put together a Vim macro to handle it. Here’s my attempt:

map <C-a> :.s#^(s*vars+)(.*)([,;])s*n(s*)(.*)([,;])s*$#153r426<C-m><C-m>

(It should be one line.)

To use it, you put the cursor anywhere on the first of the two lines you want to swap, and hit the keystroke to fire it off; Ctrl-A in the example above. It attempts to preserve whatever indentation you’re using.

So if you find yourself considering having a var explosion in your code just because you find editing too difficult, maybe a macro is in order. I assume it would be just as easy to implement something like this in Emacs.