-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexpand.js
More file actions
42 lines (39 loc) · 1.17 KB
/
expand.js
File metadata and controls
42 lines (39 loc) · 1.17 KB
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
/**
transforms tabs to an equivalent number of spaces.
*/
// TODO special case for \r if it ever matters
exports.expand = function (str, tabLength) {
str = String(str);
tabLength = tabLength || 4;
var output = [],
tabLf = /[\t\n]/g,
lastLastIndex = 0,
lastLfIndex = 0,
charsAddedThisLine = 0,
tabOffset, match;
while (match = tabLf.exec(str)) {
if (match[0] == "\t") {
tabOffset = (
tabLength - 1 -
(
(match.index - lastLfIndex) +
charsAddedThisLine
) % tabLength
);
charsAddedThisLine += tabOffset;
output.push(
str.slice(lastLastIndex, match.index) +
spaces(tabOffset + 1)
);
} else if (match[0] === "\n") {
output.push(str.slice(lastLastIndex, tabLf.lastIndex));
lastLfIndex = tabLf.lastIndex;
charsAddedThisLine = 0;
}
lastLastIndex = tabLf.lastIndex;
}
return output.join("") + str.slice(lastLastIndex);
};
var spaces = function (n) {
return Array(n + 1).join(" ");
};