@@ -17,7 +17,7 @@ module MarkdownHelper
1717 section
1818 ] . freeze
1919
20- ALLOWED_ATTRIBUTES = %w[ id class lang href src alt title width target rel type start checked disabled open aria-label aria-haspopup aria-expanded data-line data-line-text data-action data-mention-username data-sourcepos data-reference-type data-footnotes data-footnote-ref data-footnote-backref data-footnote-backref-idx data-math-style ] . freeze
20+ ALLOWED_ATTRIBUTES = %w[ id class lang href src alt title width target rel type start checked disabled open aria-label aria-haspopup aria-expanded data-line data-line-text data-action data-mention-username data-sourcepos data-reference-type data-heading-alias data- footnotes data-footnote-ref data-footnote-backref data-footnote-backref-idx data-math-style ] . freeze
2121
2222 # Commonmarker extensions beyond the gem defaults (tables, tasklist,
2323 # strikethrough, autolink stay on). Footnotes: `[^1]` in text plus a
@@ -142,6 +142,8 @@ def transform_mention_anchors(html)
142142 # so previews require no duplicate citation data or network request.
143143 def transform_reference_anchors ( html , numbered_sections : true )
144144 doc = Nokogiri ::HTML ::DocumentFragment . parse ( html )
145+ # Only server-created aliases can redirect a reference to their heading.
146+ doc . css ( "[data-heading-alias]" ) . remove_attr ( "data-heading-alias" )
145147 used_ids = doc . css ( "[id]" ) . filter_map { |node | node [ "id" ] . presence } . to_set
146148 section_ids = Set . new
147149
@@ -162,9 +164,17 @@ def transform_reference_anchors(html, numbered_sections: true)
162164 section_number = heading . text . squish [ /\A (\d +(?:\. \d +)*)\b / , 1 ]
163165 next unless section_number
164166
165- heading [ "id" ] ||= unique_dom_id ( "section-#{ section_number . tr ( '.' , '-' ) } " , used_ids )
166- used_ids << heading [ "id" ]
167- section_ids << heading [ "id" ]
167+ section_id = "section-#{ section_number . tr ( '.' , '-' ) } "
168+ if heading [ "id" ] != section_id
169+ section_id = unique_dom_id ( section_id , used_ids )
170+ if heading [ "id" ] . present?
171+ add_heading_alias ( heading , section_id )
172+ else
173+ heading [ "id" ] = section_id
174+ end
175+ end
176+ used_ids << section_id
177+ section_ids << section_id << heading [ "id" ]
168178 end
169179 end
170180
@@ -216,6 +226,13 @@ def unique_dom_id(base, used_ids)
216226 "#{ base } -#{ suffix } "
217227 end
218228
229+ def add_heading_alias ( heading , id )
230+ anchor = Nokogiri ::XML ::Node . new ( "span" , heading . document )
231+ anchor [ "id" ] = id
232+ anchor [ "data-heading-alias" ] = ""
233+ heading . prepend_child ( anchor )
234+ end
235+
219236 def enhance_reference_anchor ( anchor , type :)
220237 anchor . add_class ( "reference-anchor" )
221238 anchor . add_class ( "reference-anchor--#{ type } " )
0 commit comments