showdown/src/subParsers/headers.js

80 lines
2.5 KiB
JavaScript
Raw Normal View History

2015-01-16 05:21:33 +08:00
/**
* Created by Estevao on 11-01-2015.
*/
showdown.subParser('headers', function (text, options, globals) {
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
var prefixHeader = options.prefixHeaderId;
2015-01-19 19:37:21 +08:00
// Set text-style headers:
// Header 1
// ========
//
// Header 2
// --------
//
text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm, function (wholeMatch, m1) {
return showdown.subParser('hashBlock')('<h1 id="' + headerId(m1) + '">' + showdown.subParser('spanGamut')(m1,
options,
globals) + '</h1>',
options, globals);
});
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, function (matchFound, m1) {
return showdown.subParser('hashBlock')('<h2 id="' + headerId(m1) + '">' + showdown.subParser('spanGamut')(m1,
options,
globals) + '</h2>',
options, globals);
});
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// atx-style headers:
// # Header 1
// ## Header 2
// ## Header 2 with closing hashes ##
// ...
// ###### Header 6
//
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
/*
text = text.replace(/
^(\#{1,6}) // $1 = string of #'s
[ \t]*
(.+?) // $2 = Header text
[ \t]*
\#* // optional closing #'s (not counted)
\n+
/gm, function() {...});
*/
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, function (wholeMatch, m1, m2) {
var span = showdown.subParser('spanGamut')(m2, options,
globals), header = '<h' + m1.length + ' id="' + headerId(m2) + '">' + span + '</h' + m1.length + '>';
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
return showdown.subParser('hashBlock')(header, options, globals);
});
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
function headerId(m) {
var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
2015-01-19 19:37:21 +08:00
if (globals.hashLinkCounts[escapedId]) {
title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
} else {
title = escapedId;
globals.hashLinkCounts[escapedId] = 1;
}
2015-01-19 19:37:21 +08:00
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (prefixHeader === true) {
prefixHeader = 'section';
}
2015-01-19 19:37:21 +08:00
if (showdown.helper.isString(prefixHeader)) {
return prefixHeader + title;
2015-01-16 05:21:33 +08:00
}
2015-01-19 19:37:21 +08:00
return title;
}
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
});