Debian Codegraph @

markdown/extensions/wikilinks.py

raw
1 # WikiLinks Extension for Python-Markdown
2 # ======================================
3
4 # Converts [[WikiLinks]] to relative links.
5
6 # See https://Python-Markdown.github.io/extensions/wikilinks
7 # for documentation.
8
9 # Original code Copyright [Waylan Limberg](https://github.com/waylan).
10
11 # All changes Copyright The Python Markdown Project
12
13 # License: [BSD](https://opensource.org/licenses/bsd-license.php)
14
15 """
16 Converts `[[WikiLinks]]` to relative links.
17
18 See the [documentation](https://Python-Markdown.github.io/extensions/wikilinks)
19 for details.
20 """
21
22 from __future__ import annotations
23
24 from . import Extension
25 from ..inlinepatterns import InlineProcessor
26 import xml.etree.ElementTree as etree
27 import re
28 from typing import Any
29
30
31 def build_url(label: str, base: str, end: str) -> str:
32 """ Build a URL from the label, a base, and an end. """
33 clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
34 return '{}{}{}'.format(base, clean_label, end)
35
36
37 class WikiLinkExtension(Extension):
38 """ Add inline processor to Markdown. """
39
40 def __init__(self, **kwargs):
41 self.config = {
42 'base_url': ['/', 'String to append to beginning or URL.'],
43 'end_url': ['/', 'String to append to end of URL.'],
44 'html_class': ['wikilink', 'CSS hook. Leave blank for none.'],
45 'build_url': [build_url, 'Callable formats URL from label.'],
46 }
47 """ Default configuration options. """
48 super().__init__(**kwargs)
49
50 def extendMarkdown(self, md):
51 """ Register the processor.
52
53 | Class Instance | Registry | Name | Priority |
54 | --------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------ | :------: |
55 | [`WikiLinksInlineProcessor`][markdown.extensions.wikilinks.WikiLinksInlineProcessor] | [`inlinepatterns`][markdown.inlinepatterns.build_inlinepatterns] | `wikilink` | `75` |
56
57 """
58 # flake8: noqa: E501 53-55
59 self.md = md
60
61 # append to end of inline patterns
62 WIKILINK_RE = r'\[\[([\w0-9_ -]+)\]\]'
63 wikilinkPattern = WikiLinksInlineProcessor(WIKILINK_RE, self.getConfigs())
64 wikilinkPattern.md = md
65 md.inlinePatterns.register(wikilinkPattern, 'wikilink', 75)
66
67
68 class WikiLinksInlineProcessor(InlineProcessor):
69 """ Build link from `wikilink`. """
70
71 def __init__(self, pattern: str, config: dict[str, Any]):
72 super().__init__(pattern)
73 self.config = config
74
75 def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | str, int, int]:
76 if m.group(1).strip():
77 base_url, end_url, html_class = self._getMeta()
78 label = m.group(1).strip()
79 url = self.config['build_url'](label, base_url, end_url)
80 a = etree.Element('a')
81 a.text = label
82 a.set('href', url)
83 if html_class:
84 a.set('class', html_class)
85 else:
86 a = ''
87 return a, m.start(0), m.end(0)
88
89 def _getMeta(self) -> tuple[str, str, str]:
90 """ Return meta data or `config` data. """
91 base_url = self.config['base_url']
92 end_url = self.config['end_url']
93 html_class = self.config['html_class']
94 if hasattr(self.md, 'Meta'):
95 if 'wiki_base_url' in self.md.Meta:
96 base_url = self.md.Meta['wiki_base_url'][0]
97 if 'wiki_end_url' in self.md.Meta:
98 end_url = self.md.Meta['wiki_end_url'][0]
99 if 'wiki_html_class' in self.md.Meta:
100 html_class = self.md.Meta['wiki_html_class'][0]
101 return base_url, end_url, html_class
102
103
104 def makeExtension(**kwargs): # pragma: no cover
105 return WikiLinkExtension(**kwargs)