feat(uniqueHeaderId): add unique id prefix and suffix to headers

If two headers have similar texts, the generated id could be equal. In order to prevent id clash:
  - A unique suffix is added if a header id already exists
  - Option to add a prefix to header id
  - Update of correspondent tests
  - (credits to nicovalencia)

Closes #81, closes #82
This commit is contained in:
Estevão Soares dos Santos 2015-01-18 02:12:32 +00:00
parent c9de4b6b1f
commit c367a4b9a1
8 changed files with 43 additions and 4 deletions

BIN
dist/showdown.js vendored

Binary file not shown.

BIN
dist/showdown.js.map vendored

Binary file not shown.

BIN
dist/showdown.min.js vendored

Binary file not shown.

Binary file not shown.

View File

@ -6,7 +6,8 @@
var showdown = {},
parsers = {},
globalOptions = {
omitExtraWLInCodeBlocks: false
omitExtraWLInCodeBlocks: false,
prefixHeaderId: false
};
///////////////////////////////////////////////////////////////////////////
@ -29,10 +30,17 @@ showdown.extensions = {};
//Public methods
showdown.setOption = function (key, value) {
globalOptions[key] = value;
return this;
};
showdown.getOption = function (key) {
return globalOptions[key];
};
showdown.getOptions = function () {
return globalOptions;
};
/**
* Static Method
*
@ -97,7 +105,8 @@ showdown.Converter = function (converterOptions) {
gHtmlBlocks: [],
gUrls: {},
gTitles: {},
gListLevel: 0
gListLevel: 0,
hashLinkCounts: {}
};
// attacklab: Replace ~ with ~T

View File

@ -5,6 +5,8 @@
showdown.subParser('headers', function (text, options, globals) {
'use strict';
var prefixHeader = options.prefixHeaderId;
// Set text-style headers:
// Header 1
// ========
@ -52,7 +54,25 @@ showdown.subParser('headers', function (text, options, globals) {
});
function headerId(m) {
return m.replace(/[^\w]/g, '').toLowerCase();
var title,
escapedId = m.replace(/[^\w]/g, '').toLowerCase();
if (globals.hashLinkCounts[escapedId]) {
title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
} else {
title = escapedId;
globals.hashLinkCounts[escapedId] = 1;
}
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (prefixHeader === true) {
prefixHeader = 'section';
}
if (showdown.helper.isString(prefixHeader)) {
return prefixHeader + title;
}
return title;
}
return text;

View File

@ -0,0 +1,5 @@
<h1 id="sametitle">Same Title</h1>
<p>some text</p>
<h1 id="sametitle-1">Same Title</h1>

View File

@ -0,0 +1,5 @@
# Same Title
some text
# Same Title