29 September 2010

Fun with regex: shrinking indentation

Sometimes you get source code from people who believe in 4 spaces. Or 8, imagine! Or tabs ... well that's just *so* 20th century ...


    function($) {
        $("#blah").toto(function(event) {
            $(this).click(function(event2) {
               $(this).goes(WAY.off(2, the("right")));
            });
        });
    };

Too much indentation! 2 is enough! Let's suppose that for whatever reason, you can't or won't use your text editor's re-indent or reformat function, or you just really dig regular expressions ... here's what to do: replace ^( +)\1 with $1.

^( +)\1 means "any nonzero-length sequence of spaces at the start of the line, followed by the same sequence of spaces. The \1 in the pattern, and the $1 in the replacement, are both back-references to the initial sequence of spaces. Result: indentation halved.


  function($) {
    $("#blah").toto(function(event) {
      $(this).click(function(event2) {
        $(this).goes(WAY.off(2, the("right"))); // Not.
      });
    });
  };

There you go. Readable code.

Don't tell anyone I said this, but if you want to do the opposite (increase indentation), replace ^( +) with $1$1 ...

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.