@@ -71,6 +71,7 @@ def markdown
7171 def pre_process_markdown
7272 result = File . read file
7373 result = evaluate_shortlinks result if config . shortlinks
74+ result . gsub! '<!-- TOC -->' , toc ( result ) if config . auto_toc
7475 result
7576 end
7677
@@ -83,7 +84,6 @@ def doc
8384 # 2. Syntax highilghting
8485 # 3. Prepend H1 if needed
8586 def markdown_to_html
86- replace_toc_marker
8787 prepend_h1 if config . auto_h1
8888 add_anchor_ids
8989 html = doc . to_html :UNSAFE
@@ -106,39 +106,35 @@ def add_anchor_ids
106106 end
107107 end
108108
109- # Replace <!-- TOC --> with a Table of Contents for the page
110- def replace_toc_marker
111- toc_marker = doc . find do |node |
112- node . type == :html and node . string_content . include? '<!-- TOC -->'
113- end
114-
115- return unless toc_marker
116-
117- toc_marker . insert_after document_toc
118- toc_marker . insert_after CommonMarker . render_doc ( '## Table of Contents' ) . first_child
119- end
120-
121109 # Replace [[link]] with [link](link)
122110 def evaluate_shortlinks ( raw )
123111 raw . gsub ( /\[ \[ ([^\] ]+)\] \] / ) { "[#{ $1} ](#{ $1. to_href } )" }
124112 end
125113
126- # Returns a UL object containing the document table of contents
127- def document_toc
128- toc = [ ]
129- doc . walk do |node |
130- next unless node . type == :header
114+ def toc_caption
115+ @toc_caption ||= if config . auto_toc . is_a? ( String )
116+ config . auto_toc
117+ else
118+ '## Table of Contents'
119+ end
120+ end
121+
122+ def toc ( input )
123+ result = [ "#{ toc_caption } \n " ]
124+ input . lines ( chomp : true ) . each do |line |
125+ next unless line . start_with? '#'
126+
127+ matches = line . match ( /^(?<level>\# {2,3})\s +(?<text>.+)/ )
128+ next unless matches
131129
132- level = node . header_level
133- next unless level . between? 2 , 3
130+ level = matches [ :level ] . size - 1
131+ text = matches [ :text ]
134132
135- text = node . first_child . string_content
136- spacer = ' ' * ( level - 1 )
137- toc << "#{ spacer } - [#{ text } ](##{ text . to_slug } )"
133+ spacer = ' ' * level
134+ result . push "#{ spacer } - [#{ text } ](##{ text . to_slug } )"
138135 end
139136
140- toc = toc . join "\n "
141- CommonMarker . render_doc ( toc ) . first_child
137+ result . join "\n "
142138 end
143139
144140 # If the document does not start with an H1 tag, add it.
0 commit comments