Skip to content

mdfilters

Class info

🛈 DocStrings

autoref_link(
    text: str | None = None, link: str | ModuleType | Callable[..., Any] | None = None
) -> str

Create a markdown autorefs-style link (used by MkDocs / MkDocStrings).

If link is empty string or None, just the text will get returned.

Parameters:

Name Type Description Default
text str | None

Text to show for the link

None
link str | ModuleType | Callable[..., Any] | None

Target url

None
Source code in src/jinjarope/mdfilters.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def autoref_link(
    text: str | None = None,
    link: str | types.ModuleType | Callable[..., Any] | None = None,
) -> str:
    """Create a markdown autorefs-style link (used by MkDocs / MkDocStrings).

    If link is empty string or None, just the text will get returned.

    Args:
        text: Text to show for the link
        link: Target url
    """
    if not link:
        return text or ""
    match link:
        case types.ModuleType():
            link = link.__name__
        case _ if callable(link):
            if (mod := link.__module__) != "builtins":
                link = f"{mod}.{link.__qualname__}"
            else:
                link = link.__qualname__

    return f"[{text or link}][{link}]"

extract_header_section

extract_header_section(markdown: str, section_name: str) -> str | None

Extract block with given header from markdown.

Parameters:

Name Type Description Default
markdown str

The markdown to extract a section from

required
section_name str

The header of the section to extract

required
Source code in src/jinjarope/mdfilters.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def extract_header_section(markdown: str, section_name: str) -> str | None:
    """Extract block with given header from markdown.

    Args:
        markdown: The markdown to extract a section from
        section_name: The header of the section to extract
    """
    header_pattern = re.compile(f"^(#+) {section_name}$", re.MULTILINE)
    md = str(markdown or "")
    header_match = header_pattern.search(md)
    if header_match is None:
        return None
    section_level = len(header_match[1])
    start_index = header_match.span()[1] + 1
    end_pattern = re.compile(f"^#{{1,{section_level}}} ", re.MULTILINE)
    end_match = end_pattern.search(md[start_index:])
    if end_match is None:
        return md[start_index:]
    end_index = end_match.span()[0]
    return md[start_index : end_index + start_index]

md_escape

md_escape(text: str, entity_type: str | None = None) -> str

Helper function to escape markup.

Parameters:

Name Type Description Default
text str

The text.

required
entity_type str | None

For the entity types PRE, CODE and the link part of TEXT_LINKS, only certain characters need to be escaped.

None
Source code in src/jinjarope/mdfilters.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def md_escape(text: str, entity_type: str | None = None) -> str:
    """Helper function to escape markup.

    Args:
        text: The text.
        entity_type: For the entity types ``PRE``, ``CODE`` and the link
                     part of ``TEXT_LINKS``, only certain characters need to be escaped.
    """
    if entity_type in ["pre", "code"]:
        escape_chars = r"\`"
    elif entity_type == "text_link":
        escape_chars = r"\)"
    else:
        escape_chars = r"_*[]()~`>#+-=|{}.!"

    return re.sub(f"([{re.escape(escape_chars)}])", r"\\\1", text)
md_link(
    text: str | None = None, link: str | None = None, tooltip: str | None = None
) -> str

Create a markdown link.

If link is empty string or None, just the text will get returned.

Parameters:

Name Type Description Default
text str | None

Text to show for the link

None
link str | None

Target url

None
tooltip str | None

Optional tooltip

None
Source code in src/jinjarope/mdfilters.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def md_link(
    text: str | None = None,
    link: str | None = None,
    tooltip: str | None = None,
) -> str:
    """Create a markdown link.

    If link is empty string or None, just the text will get returned.

    Args:
        text: Text to show for the link
        link: Target url
        tooltip: Optional tooltip
    """
    if not link:
        return text or ""
    tt = f" '{tooltip}'" if tooltip else ""
    return f"[{text or link}]({link}{tt})"

md_style

md_style(
    text: str,
    *,
    size: int | None = None,
    bold: bool = False,
    italic: bool = False,
    code: bool = False,
    align: Literal["left", "right", "center"] | None = None
) -> str

Apply styling to given markdown.

Parameters:

Name Type Description Default
text str

Text to style

required
size int | None

Optional text size

None
bold bool

Whether styled text should be bold

False
italic bool

Whether styled text should be italic

False
code bool

Whether styled text should styled as (inline) code

False
align Literal['left', 'right', 'center'] | None

Optional text alignment

None
Source code in src/jinjarope/mdfilters.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def md_style(
    text: str,
    *,
    size: int | None = None,
    bold: bool = False,
    italic: bool = False,
    code: bool = False,
    align: Literal["left", "right", "center"] | None = None,
) -> str:
    """Apply styling to given markdown.

    Args:
        text: Text to style
        size: Optional text size
        bold: Whether styled text should be bold
        italic: Whether styled text should be italic
        code: Whether styled text should styled as (inline) code
        align: Optional text alignment
    """
    if not text:
        return text or ""
    if size:
        text = f"<font size='{size}'>{text}</font>"
    if bold:
        text = f"**{text}**"
    if italic:
        text = f"*{text}*"
    if code:
        text = f"`{text}`"
    if align:
        text = f"<p style='text-align: {align};'>{text}</p>"
    return text

shift_header_levels

shift_header_levels(text: str, level_shift: int) -> str

Shift the level of all headers of given text.

Parameters:

Name Type Description Default
text str

The Text to shift the header levels from

required
level_shift int

Level delta. (1 means "increase level by 1")

required
Source code in src/jinjarope/mdfilters.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def shift_header_levels(text: str, level_shift: int) -> str:
    """Shift the level of all headers of given text.

    Args:
        text: The Text to shift the header levels from
        level_shift: Level delta. (1 means "increase level by 1")
    """
    if not level_shift:
        return text

    def mod_header(match: re.Match[str], levels: int) -> str:
        header_str = match[1]
        if levels > 0:
            header_str += levels * "#"
        else:
            header_str = header_str[:levels]
        return f"{header_str} {match[2]}"

    return re.sub(HEADER_REGEX, lambda x: mod_header(x, level_shift), str(text or ""))