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

Commit

Permalink
Count link repetitions from the hash part, not the title
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mcornella committed Nov 2, 2020
1 parent 74381a1 commit b8d4a2b
Showing 1 changed file with 34 additions and 10 deletions.
44 changes: 34 additions & 10 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,13 +380,7 @@ class MarkdownTocTools {
title = title.replace(/\#/gi, "").trim(); // replace special char
title = title.replace(/\b[_*]|[*_]\b/gi, ""); // replace bold and italic marks

if (!(title in hashMap)) {
hashMap[title] = 0;
} else {
hashMap[title] += 1;
}

let hash = this.getHash(title, this.options.ANCHOR_MODE, hashMap[title]);
let hash = this.getHash(title, this.options.ANCHOR_MODE, hashMap);
headerList.push({
line : index,
depth : depth,
Expand All @@ -401,9 +395,39 @@ class MarkdownTocTools {
return headerList;
}

private getHash(headername : string, mode : string, repetition : number) {
let anchor = require('anchor-markdown-header');
return anchor(headername, mode, repetition);
private getHash(headername : string, mode : string, hashMap: { [key: string]: number }) {
// Get the link format for headername (force repetition = 0)
let link = require('anchor-markdown-header')(headername, mode, 0);

// Decompose the link into its two components
let match = link.match(/^\[([^\]]+)\]\((#[^)]+)\)$/);
if (!match || match.length < 3) return link;
let [title, hash] = match.slice(1, 3);

// Check if the hash is repeated
if (!(hash in hashMap)) {
hashMap[hash] = 0;
} else {
hashMap[hash] += 1;

// Add the repetition number to the hash
switch (mode) {
case "github.com":
hash = `${hash}-${hashMap[hash]}`;
break;
case "bitbucket.org":
hash = `${hash}_${hashMap[hash]}`;
break;
case "ghost.org":
hash = `${hash}-${hashMap[hash]}`;
break;
case "gitlab.com":
hash = `${hash}-${hashMap[hash]}`;
break;
}
}

return `[${title}](${hash})`;
}

private parseValidNumber(value : string) {
Expand Down

0 comments on commit b8d4a2b

Please sign in to comment.