showdown/src/subParsers/detab.js

33 lines
779 B
JavaScript
Raw Normal View History

2015-01-16 05:21:33 +08:00
/**
* Convert all tabs to spaces
*/
showdown.subParser('detab', function (text) {
2015-01-19 19:37:21 +08:00
'use strict';
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// expand first n-1 tabs
text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// replace the nth with two sentinels
text = text.replace(/\t/g, '¨A¨B');
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// use the sentinel to anchor our regex so it doesn't explode
text = text.replace(/¨B(.+?)¨A/g, function (wholeMatch, m1) {
var leadingText = m1,
numSpaces = 4 - leadingText.length % 4; // g_tab_width
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// there *must* be a better way to do this:
for (var i = 0; i < numSpaces; i++) {
leadingText += ' ';
}
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
return leadingText;
});
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// clean up sentinels
text = text.replace(/¨A/g, ' '); // g_tab_width
text = text.replace(/¨B/g, '');
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
return text;
2015-01-16 05:21:33 +08:00
});