Removing leading whitespace from indented HTML source in pre/code tags

I really like Homam's idea, but I had to change it to deal with this:

<pre><code><!-- There's nothing on this line, so the script thinks the indentation is zero -->
    foo = bar
</code></pre>

To fix it, I just take out the first line if it's empty:

[].forEach.call(document.querySelectorAll('code'), function($code) {
    var lines = $code.textContent.split('\n');

    if (lines[0] === '')
    {
        lines.shift()
    }

    var matches;
    var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
    if (!!indentation) {
        lines = lines.map(function(line) {
            line = line.replace(indentation, '')
            return line.replace(/\t/g, '    ')
        });

        $code.textContent = lines.join('\n').trim();
    }
});

(I'm also processing <code> tags instead of <pre> tags.)


You may want to just change how it is output, but it is fairly simple to do with JavaScript

var p = document.querySelector(".prettyprint");
p.textContent = p.textContent.replace(/^\s+/mg, "");

http://jsfiddle.net/a4gfZ/


The question asks if there's a JavaScript solution or a simpler method for removing leading whitespace. There's a simpler method:

CSS

pre, code {
    white-space: pre-line;
}

DEMO

white-space

The white-space property is used to describe how whitespace inside the element is handled.

pre-line

Sequences of whitespace are collapsed.

To preserve existing whitespace or indentation, each line can be wrapped in a child tag with white-space reset to pre at the line level:

HTML

<pre>
    <code>
        <i>fn main() {</i>
        <i>    println!("hello world!");</i>
        <i>}</i>
    </code>
</pre>

CSS

pre, code {
    white-space: pre-line;
}

pre > code > i {
    white-space: pre;
}