Skip to content
This repository was archived by the owner on May 27, 2021. It is now read-only.

Commit b8d4a2b

Browse files
committed
Count link repetitions from the hash part, not the title
This fixes the case where different titles get the same hash. In the old version, the repetition number was tracked with the title; since they didn't match, the repetition number wasn't incremented. Now, the repetition number is tracked from the hash (#title), so they get the correct repetition. Fixes #93
1 parent 74381a1 commit b8d4a2b

File tree

1 file changed

+34
-10
lines changed

1 file changed

+34
-10
lines changed

src/extension.ts

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -380,13 +380,7 @@ class MarkdownTocTools {
380380
title = title.replace(/\#/gi, "").trim(); // replace special char
381381
title = title.replace(/\b[_*]|[*_]\b/gi, ""); // replace bold and italic marks
382382

383-
if (!(title in hashMap)) {
384-
hashMap[title] = 0;
385-
} else {
386-
hashMap[title] += 1;
387-
}
388-
389-
let hash = this.getHash(title, this.options.ANCHOR_MODE, hashMap[title]);
383+
let hash = this.getHash(title, this.options.ANCHOR_MODE, hashMap);
390384
headerList.push({
391385
line : index,
392386
depth : depth,
@@ -401,9 +395,39 @@ class MarkdownTocTools {
401395
return headerList;
402396
}
403397

404-
private getHash(headername : string, mode : string, repetition : number) {
405-
let anchor = require('anchor-markdown-header');
406-
return anchor(headername, mode, repetition);
398+
private getHash(headername : string, mode : string, hashMap: { [key: string]: number }) {
399+
// Get the link format for headername (force repetition = 0)
400+
let link = require('anchor-markdown-header')(headername, mode, 0);
401+
402+
// Decompose the link into its two components
403+
let match = link.match(/^\[([^\]]+)\]\((#[^)]+)\)$/);
404+
if (!match || match.length < 3) return link;
405+
let [title, hash] = match.slice(1, 3);
406+
407+
// Check if the hash is repeated
408+
if (!(hash in hashMap)) {
409+
hashMap[hash] = 0;
410+
} else {
411+
hashMap[hash] += 1;
412+
413+
// Add the repetition number to the hash
414+
switch (mode) {
415+
case "github.com":
416+
hash = `${hash}-${hashMap[hash]}`;
417+
break;
418+
case "bitbucket.org":
419+
hash = `${hash}_${hashMap[hash]}`;
420+
break;
421+
case "ghost.org":
422+
hash = `${hash}-${hashMap[hash]}`;
423+
break;
424+
case "gitlab.com":
425+
hash = `${hash}-${hashMap[hash]}`;
426+
break;
427+
}
428+
}
429+
430+
return `[${title}](${hash})`;
407431
}
408432

409433
private parseValidNumber(value : string) {

0 commit comments

Comments
 (0)