File tree Expand file tree Collapse file tree 1 file changed +26
-5
lines changed Expand file tree Collapse file tree 1 file changed +26
-5
lines changed Original file line number Diff line number Diff line change @@ -33,20 +33,38 @@ class MarkdownToc {
33
33
const menus = [ "# Table of contents" , "" ] ;
34
34
let isCodeBlock = false ;
35
35
let topLevel = NaN ;
36
+ let previous = null ;
36
37
37
38
for ( let line of input . split ( "\n" ) ) {
38
39
39
- if ( line . startsWith ( "```" ) ) {
40
+ const trimmed = line . trim ( ) ;
41
+
42
+ if ( trimmed . startsWith ( "```" ) ) {
40
43
isCodeBlock = ! isCodeBlock ;
41
44
}
42
45
43
46
if ( isCodeBlock ) {
44
47
continue ;
45
48
}
46
49
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 ) {
50
68
if ( isNaN ( topLevel ) ) {
51
69
topLevel = level ;
52
70
}
@@ -55,12 +73,15 @@ class MarkdownToc {
55
73
continue ;
56
74
}
57
75
58
- const title = match [ 2 ] . trim ( ) ;
59
76
const link = title . toLocaleLowerCase ( )
60
77
. replace ( / \s / g, "-" )
61
78
. replace ( / [ ^ A - Z a - z 0 - 9 - ] / g, "" ) ;
62
79
const menu = `${ " " . repeat ( level - topLevel ) } - [${ title } ](#${ link } )` ;
63
80
menus . push ( menu ) ;
81
+
82
+ previous = null ;
83
+ } else {
84
+ previous = trimmed ;
64
85
}
65
86
}
66
87
You can’t perform that action at this time.
0 commit comments