-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (49 loc) · 1.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
///////////////////////////////////////////////////////////////////////////////
//
// PREDENTATION
//
///////////////////////////////////////////////////////////////////////////////
'use strict';
var cheerio = require('cheerio');
var through = require('through2');
var onlyTag = /^\s*<\/?\w[^>]+>\s*$/;
module.exports = (function () {
return function () {
var data = '';
return through(function (chunk, encoding, callback) {
data += chunk.toString();
var $ = cheerio.load(data, { decodeEntities: false });
$('pre').each(function (index, pre) {
var level = null;
var lines = $(pre).html().split('\n');
// Do not process single line pre elements
if (lines.length === 1) {
return;
}
// Determine the level of indentation
lines.forEach(function (line) {
// Ignore lines with only a markup tag
if (line.match(onlyTag)) {
return;
}
// Ignore lines with only whitespace
if (line.match(/[^\s]+/)) {
var current = (line.match(/^\s+/) !== null) ? line.match(/^\s+/)[0].length : 0;
level = (level === null || level === 0) ? current : (current < level) ? current : level;
}
});
// Remove indentation
lines.forEach(function (line, index, lines) {
// Ignore lines with only a markup tag
if (line.match(onlyTag)) {
return;
}
lines[index] = line.replace(new RegExp('^\\s{' + level + '}'), '');
});
$(pre).text(lines.join('\n'));
});
this.push($.html());
callback();
});
};
}());