Skip to content

Commit ecfa3c5

Browse files
authored
Support setext-style headers
1 parent 1a19ce6 commit ecfa3c5

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

index.js

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,38 @@ class MarkdownToc {
3333
const menus = ["# Table of contents", ""];
3434
let isCodeBlock = false;
3535
let topLevel = NaN;
36+
let previous = null;
3637

3738
for (let line of input.split("\n")) {
3839

39-
if (line.startsWith("```")) {
40+
const trimmed = line.trim();
41+
42+
if (trimmed.startsWith("```")) {
4043
isCodeBlock = !isCodeBlock;
4144
}
4245

4346
if (isCodeBlock) {
4447
continue;
4548
}
4649

47-
if (line.startsWith("#")) {
48-
const match = line.match(/(#+)\s*(.*?)#*\s*$/);
49-
const level = match[1].length;
50+
let level = NaN;
51+
let title = null;
52+
53+
if (trimmed.startsWith("#")) {
54+
const match = trimmed.match(/(#+)\s*(.*?)#*\s*$/);
55+
level = match[1].length;
56+
title = match[2].trim();
57+
} else if (previous != null && previous.length > 0 && trimmed.length > 0) {
58+
if (trimmed.match(/[^=]/g) == null) {
59+
level = 1;
60+
title = previous;
61+
} else if (trimmed.match(/[^-]/g) == null && previous.match(/[^-]/g) != null) {
62+
level = 2;
63+
title = previous;
64+
}
65+
}
66+
67+
if (level != NaN && title != null) {
5068
if (isNaN(topLevel)) {
5169
topLevel = level;
5270
}
@@ -55,12 +73,15 @@ class MarkdownToc {
5573
continue;
5674
}
5775

58-
const title = match[2].trim();
5976
const link = title.toLocaleLowerCase()
6077
.replace(/\s/g, "-")
6178
.replace(/[^A-Za-z0-9-]/g, "");
6279
const menu = `${" ".repeat(level - topLevel)}- [${title}](#${link})`;
6380
menus.push(menu);
81+
82+
previous = null;
83+
} else {
84+
previous = trimmed;
6485
}
6586
}
6687

0 commit comments

Comments
 (0)