|
| 1 | +import re |
| 2 | +from typing import Callable, List, Optional |
| 3 | + |
| 4 | +from markdown_it import MarkdownIt |
| 5 | +from markdown_it.rules_core import StateCore |
| 6 | +from markdown_it.token import Token |
| 7 | + |
| 8 | + |
| 9 | +def anchors_plugin( |
| 10 | + md: MarkdownIt, |
| 11 | + min_level: int = 1, |
| 12 | + max_level: int = 2, |
| 13 | + slug_func: Optional[Callable[[str], str]] = None, |
| 14 | + permalink: bool = False, |
| 15 | + permalinkSymbol: str = "¶", |
| 16 | + permalinkBefore: bool = False, |
| 17 | + permalinkSpace: bool = True, |
| 18 | +): |
| 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 | + :param min_level: minimum header level to apply anchors |
| 33 | + :param max_level: maximum header level to apply anchors |
| 34 | + :param slug_func: function to convert title text to id slug. |
| 35 | + :param permalink: Add a permalink next to the title |
| 36 | + :param permalinkSymbol: the symbol to show |
| 37 | + :param permalinkBefore: Add the permalink before the title, otherwise after |
| 38 | + :param permalinkSpace: Add a space between the permalink and the title |
| 39 | +
|
| 40 | + Note, the default slug function aims to mimic the GitHub Markdown format, see: |
| 41 | +
|
| 42 | + - https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/toc_filter.rb |
| 43 | + - https://gist.github.com/asabaylus/3071099 |
| 44 | +
|
| 45 | + """ |
| 46 | + selected_levels = list(range(min_level, max_level + 1)) |
| 47 | + md.core.ruler.push( |
| 48 | + "anchor", |
| 49 | + _make_anchors_func( |
| 50 | + selected_levels, |
| 51 | + slug_func or slugify, |
| 52 | + permalink, |
| 53 | + permalinkSymbol, |
| 54 | + permalinkBefore, |
| 55 | + permalinkSpace, |
| 56 | + ), |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +def _make_anchors_func( |
| 61 | + selected_levels: List[int], |
| 62 | + slug_func: Callable[[str], str], |
| 63 | + permalink: bool, |
| 64 | + permalinkSymbol: str, |
| 65 | + permalinkBefore: bool, |
| 66 | + permalinkSpace: bool, |
| 67 | +): |
| 68 | + slugs = set() |
| 69 | + |
| 70 | + def _anchor_func(state: StateCore): |
| 71 | + for (idx, token) in enumerate(state.tokens): |
| 72 | + token: Token |
| 73 | + if token.type != "heading_open": |
| 74 | + continue |
| 75 | + level = int(token.tag[1]) |
| 76 | + if level not in selected_levels: |
| 77 | + continue |
| 78 | + title = "".join( |
| 79 | + [ |
| 80 | + child.content |
| 81 | + for child in state.tokens[idx + 1].children |
| 82 | + if child.type in ["text", "code_inline"] |
| 83 | + ] |
| 84 | + ) |
| 85 | + slug = unique_slug(slug_func(title), slugs) |
| 86 | + token.attrSet("id", slug) |
| 87 | + |
| 88 | + if permalink: |
| 89 | + link_tokens = [ |
| 90 | + Token( |
| 91 | + "link_open", |
| 92 | + "a", |
| 93 | + 1, |
| 94 | + attrs=[["class", "header-anchor"], ["href", f"#{slug}"]], |
| 95 | + ), |
| 96 | + Token("html_block", "", 0, content=permalinkSymbol), |
| 97 | + Token("link_close", "a", -1), |
| 98 | + ] |
| 99 | + if permalinkBefore: |
| 100 | + state.tokens[idx + 1].children = ( |
| 101 | + link_tokens |
| 102 | + + ( |
| 103 | + [Token("text", "", 0, content=" ")] |
| 104 | + if permalinkSpace |
| 105 | + else [] |
| 106 | + ) |
| 107 | + + state.tokens[idx + 1].children |
| 108 | + ) |
| 109 | + else: |
| 110 | + state.tokens[idx + 1].children.extend( |
| 111 | + ([Token("text", "", 0, content=" ")] if permalinkSpace else []) |
| 112 | + + link_tokens |
| 113 | + ) |
| 114 | + |
| 115 | + return _anchor_func |
| 116 | + |
| 117 | + |
| 118 | +def slugify(title: str): |
| 119 | + return re.subn( |
| 120 | + r"[^\w\u4e00-\u9fff\- ]", "", title.strip().lower().replace(" ", "-") |
| 121 | + )[0] |
| 122 | + |
| 123 | + |
| 124 | +def unique_slug(slug: str, slugs: set): |
| 125 | + uniq = slug |
| 126 | + i = 1 |
| 127 | + while uniq in slugs: |
| 128 | + uniq = f"{slug}-{i}" |
| 129 | + i += 1 |
| 130 | + slugs.add(uniq) |
| 131 | + return uniq |
0 commit comments