Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/mdit_py_plugins/anchors/index.py: 84%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

43 statements  

1from collections.abc import Callable 

2import re 

3 

4from markdown_it import MarkdownIt 

5from markdown_it.rules_core import StateCore 

6from markdown_it.token import Token 

7 

8 

9def anchors_plugin( 

10 md: MarkdownIt, 

11 min_level: int = 1, 

12 max_level: int = 2, 

13 slug_func: Callable[[str], str] | None = None, 

14 permalink: bool = False, 

15 permalinkSymbol: str = "¶", 

16 permalinkBefore: bool = False, 

17 permalinkSpace: bool = True, 

18) -> None: 

19 """Plugin for adding header anchors, based on 

20 `markdown-it-anchor <https://github.com/valeriangalliat/markdown-it-anchor>`__ 

21 

22 .. code-block:: md 

23 

24 # Title String 

25 

26 renders as: 

27 

28 .. code-block:: html 

29 

30 <h1 id="title-string">Title String <a class="header-anchor" href="#title-string">¶</a></h1> 

31 

32 Explicit heading IDs (e.g. ``{#id}`` from ``attrs_block_plugin``) are preserved, 

33 at any level, and generated IDs avoid collisions with them. 

34 Explicit IDs are not de-duplicated, and an empty explicit ID counts as no ID. 

35 

36 :param min_level: minimum header level to apply anchors 

37 :param max_level: maximum header level to apply anchors 

38 :param slug_func: function to convert title text to id slug. 

39 :param permalink: Add a permalink next to the title 

40 :param permalinkSymbol: the symbol to show 

41 :param permalinkBefore: Add the permalink before the title, otherwise after 

42 :param permalinkSpace: Add a space between the permalink and the title 

43 

44 Note, the default slug function aims to mimic the GitHub Markdown format, see: 

45 

46 - https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/toc_filter.rb 

47 - https://gist.github.com/asabaylus/3071099 

48 

49 """ 

50 selected_levels = list(range(min_level, max_level + 1)) 

51 md.core.ruler.push( 

52 "anchor", 

53 _make_anchors_func( 

54 selected_levels, 

55 slug_func or slugify, 

56 permalink, 

57 permalinkSymbol, 

58 permalinkBefore, 

59 permalinkSpace, 

60 ), 

61 ) 

62 

63 

64def _make_anchors_func( 

65 selected_levels: list[int], 

66 slug_func: Callable[[str], str], 

67 permalink: bool, 

68 permalinkSymbol: str, 

69 permalinkBefore: bool, 

70 permalinkSpace: bool, 

71) -> Callable[[StateCore], None]: 

72 def _anchor_func(state: StateCore) -> None: 

73 # reserve every explicit heading id (at any level) up front, 

74 # so a generated slug never collides with one, whatever the order; 

75 # an empty id is treated as absent 

76 slugs: set[str] = { 

77 str(heading_id) 

78 for token in state.tokens 

79 if token.type == "heading_open" and (heading_id := token.attrGet("id")) 

80 } 

81 for idx, token in enumerate(state.tokens): 

82 if token.type != "heading_open": 

83 continue 

84 level = int(token.tag[1]) 

85 if level not in selected_levels: 

86 continue 

87 inline_token = state.tokens[idx + 1] 

88 assert inline_token.children is not None 

89 title = "".join( 

90 child.content 

91 for child in inline_token.children 

92 if child.type in ["text", "code_inline"] 

93 ) 

94 slug = token.attrGet("id") 

95 if not slug: 

96 slug = unique_slug(slug_func(title), slugs) 

97 token.attrSet("id", slug) 

98 

99 if permalink: 

100 link_open = Token( 

101 "link_open", 

102 "a", 

103 1, 

104 ) 

105 link_open.attrSet("class", "header-anchor") 

106 link_open.attrSet("href", f"#{slug}") 

107 link_tokens = [ 

108 link_open, 

109 Token("html_block", "", 0, content=permalinkSymbol), 

110 Token("link_close", "a", -1), 

111 ] 

112 if permalinkBefore: 

113 inline_token.children = ( 

114 link_tokens 

115 + ( 

116 [Token("text", "", 0, content=" ")] 

117 if permalinkSpace 

118 else [] 

119 ) 

120 + inline_token.children 

121 ) 

122 else: 

123 inline_token.children.extend( 

124 ([Token("text", "", 0, content=" ")] if permalinkSpace else []) 

125 + link_tokens 

126 ) 

127 

128 return _anchor_func 

129 

130 

131def slugify(title: str) -> str: 

132 return re.sub(r"[^\w\u4e00-\u9fff\- ]", "", title.lower().replace(" ", "-")) 

133 

134 

135def unique_slug(slug: str, slugs: set[str]) -> str: 

136 uniq = slug 

137 i = 1 

138 while uniq in slugs: 

139 uniq = f"{slug}-{i}" 

140 i += 1 

141 slugs.add(uniq) 

142 return uniq