From 5cea9e413c60d8dd772f08183e7ce8ab90fa88a1 Mon Sep 17 00:00:00 2001 From: Emil Bay Date: Sun, 20 Sep 2015 20:14:23 +0200 Subject: [PATCH] Append identical header ids with counter This ensures unique HTML id's in line with the HTML spec, and allows anchors to always reference the intended header. Fixes #27 --- lib/renderer.js | 19 ++++++++++++++++++- test/new/identical_header_1.html | 2 ++ test/new/identical_header_1.text | 3 +++ test/new/identical_header_2.html | 2 ++ test/new/identical_header_2.text | 3 +++ 5 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 test/new/identical_header_1.html create mode 100644 test/new/identical_header_1.text create mode 100644 test/new/identical_header_2.html create mode 100644 test/new/identical_header_2.text diff --git a/lib/renderer.js b/lib/renderer.js index 89f2db2..6c2d41f 100644 --- a/lib/renderer.js +++ b/lib/renderer.js @@ -15,6 +15,8 @@ var defaultOptions = { function Renderer(options) { this.options = options || defaultOptions; + + this._idCounter = {} } Renderer.prototype.code = function(code, lang, escaped) { @@ -56,7 +58,22 @@ Renderer.prototype._createId = function(str) { } catch (e) { str = str.replace(/[^\w]+/g, '-'); } - return str.replace(/-$/, ''); + str = str.replace(/-$/, ''); + + // make sure internal id has the current id registered. If not, initialize it + // at 0 + if (this._idCounter[str] === undefined) { + this._idCounter[str] = 0; + } + + // Increment the internal counter for the current id, and save new count + var cnt = ++this._idCounter[str]; + + if (cnt > 1) { + str = str + '-' + cnt + } + + return str; }; Renderer.prototype.heading = function(text, level, raw) { diff --git a/test/new/identical_header_1.html b/test/new/identical_header_1.html new file mode 100644 index 0000000..948d697 --- /dev/null +++ b/test/new/identical_header_1.html @@ -0,0 +1,2 @@ +

Identical IDs

+

Identical IDs

diff --git a/test/new/identical_header_1.text b/test/new/identical_header_1.text new file mode 100644 index 0000000..4659a36 --- /dev/null +++ b/test/new/identical_header_1.text @@ -0,0 +1,3 @@ +# identical ids + +# identical ids diff --git a/test/new/identical_header_2.html b/test/new/identical_header_2.html new file mode 100644 index 0000000..948d697 --- /dev/null +++ b/test/new/identical_header_2.html @@ -0,0 +1,2 @@ +

Identical IDs

+

Identical IDs

diff --git a/test/new/identical_header_2.text b/test/new/identical_header_2.text new file mode 100644 index 0000000..4659a36 --- /dev/null +++ b/test/new/identical_header_2.text @@ -0,0 +1,3 @@ +# identical ids + +# identical ids