So I made this: outdent.js.

Why?

A pet peeve of mine with browser developer tools is that when using the “Edit as HTML” feature, or even when editing text nodes, there will often be a lot of unnecessary whitespace to the left. My guess is that browsers just use element.outerHTML for “Edit as HTML”. For indented HTML code, this typically results in something like this:

<div>
                Some content here.
            </div>

So I played with the idea of removing extraneous whitespace, such that the editable HTML would look like:

<div>
    Some content here.
</div>

In the end I wrote a script and a demo page to test and showcase it. To be honest, I’m not sure if it could have any practical uses. If applied to, say, the Firefox devtools, I can see it be useful for text nodes, though there are a few gotchas. For outerHTML editing (“Edit as HTML”), I reckon a more complete HTML pretty-printing solution would be much more interesting.

Using the script

The main function in outdent.js is removeExtraIndentation(). Basic usage looks like this:

// Basic usage
var outdentedText = removeExtraIndentation(text);

Briefly, what it does is that it looks at the amount of whitespace at the start of each line, finds the lowest common denominator, and substracts it from each line. Some subtleties include: skipping some lines which are bound to have no leading whitespace, and fixing mixed whitespace (when tabs and spaces are mixed).

The function accepts a second argument: an object with properties overriding default values for some of the function’s inner working.

var defaultOptions = {
    ignoreHead: 1,
    ignoreTail: 0,
    tabWidth: 4
}

// Same output
var test1 = removeExtraIndentation(text);
var test2 = removeExtraIndentation(text, defaultOptions);

// Changing one option
var test3 = removeExtraIndentation(text, {
    ignoreHead: 0
});

The options are:

  • ignoreHead: starting from the top of the string, number of lines to ignore when analyzing leading whitespace. The default is 1, to accomodate the typical results given by element.outerHTML.
  • ignoreTail: starting from the end of the string, number of lines to ignore when analyzing leading whitespace.
  • tabWidth: tab width used when fixing mixed whitespace (and thus converting tabs to spaces or the other way round).

There is also a small utility to restrict the number of consecutive empty lines in a string:

// At most two empty lines consecutively
var modifiedText = removeEmtpyLines(text, 2);

// Only one empty line consecutively
var modifiedText = removeEmtpyLines(text, 1);

// Remove all empty lines
var modifiedText = removeEmtpyLines(text, 0);