Debian Codegraph @

docutils/parsers/recommonmark_wrapper.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # :Copyright: © 2020 Günter Milde.
3 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
4 #
5 # Copying and distribution of this file, with or without modification,
6 # are permitted in any medium without royalty provided the copyright
7 # notice and this notice are preserved.
8 # This file is offered as-is, without any warranty.
9 #
10 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
11 #
12 # Revision: $Revision: 10136 $
13 # Date: $Date: 2025-05-20 17:48:27 +0200 (Di, 20. Mai 2025) $
14 """
15 A parser for CommonMark Markdown text using `recommonmark`__.
16
17 __ https://pypi.org/project/recommonmark/
18
19 .. important:: This module is deprecated.
20
21 * The "recommonmark" package is unmaintained and deprecated.
22 This wrapper module will be removed in Docutils 1.0.
23
24 * The API is not settled and may change with any minor Docutils version.
25 """
26
27 from __future__ import annotations
28
29 __docformat__ = 'reStructuredText'
30
31 from docutils import Component
32 from docutils import nodes
33
34 try:
35 # If possible, import Sphinx's 'addnodes'
36 from sphinx import addnodes
37 except ImportError:
38 # stub to prevent errors if Sphinx isn't installed
39 import sys
40 import types
41
42 class pending_xref(nodes.Inline, nodes.Element):
43 ...
44
45 sys.modules['sphinx'] = sphinx = types.ModuleType('sphinx')
46 sphinx.addnodes = addnodes = types.SimpleNamespace()
47 addnodes.pending_xref = pending_xref
48 try:
49 import recommonmark
50 from recommonmark.parser import CommonMarkParser
51 except ImportError as err:
52 raise ImportError(
53 'Parsing "recommonmark" Markdown flavour requires the\n'
54 ' package https://pypi.org/project/recommonmark.'
55 ) from err
56 else:
57 if recommonmark.__version__ < '0.6.0':
58 raise ImportError('The installed version of "recommonmark" is too old.'
59 ' Update with "pip install -U recommonmark".')
60
61
62 # auxiliary function for `document.findall()`
63 def is_literal(node):
64 return isinstance(node, (nodes.literal, nodes.literal_block))
65
66
67 class Parser(CommonMarkParser):
68 """MarkDown parser based on recommonmark.
69
70 This parser is provisional:
71 the API is not settled and may change with any minor Docutils version.
72 """
73 supported = ('recommonmark', 'commonmark', 'markdown', 'md')
74 """Formats this parser supports."""
75
76 config_section = 'recommonmark parser'
77 config_section_dependencies = ('parsers',)
78
79 def get_transforms(self):
80 return Component.get_transforms(self) # + [AutoStructify]
81
82 def parse(self, inputstring, document):
83 """Wrapper of upstream method.
84
85 Ensure "line-length-limt". Report errors with `document.reporter`.
86 """
87 # check for exorbitantly long lines
88 for i, line in enumerate(inputstring.split('\n')):
89 if len(line) > document.settings.line_length_limit:
90 error = document.reporter.error(
91 'Line %d exceeds the line-length-limit.'%(i+1))
92 document.append(error)
93 return
94
95 # pass to upstream parser
96 try:
97 CommonMarkParser.parse(self, inputstring, document)
98 except Exception as err:
99 if document.settings.traceback:
100 raise err
101 error = document.reporter.error('Parsing with "recommonmark" '
102 'returned the error:\n%s'%err)
103 document.append(error)
104
105 # Post-Processing
106 # ---------------
107
108 def finish_parse(self) -> None:
109 """Finalize parse details. Call at end of `self.parse()`."""
110
111 document = self.document
112
113 # merge adjoining Text nodes:
114 for node in document.findall(nodes.TextElement):
115 children = node.children
116 i = 0
117 while i+1 < len(children):
118 if (isinstance(children[i], nodes.Text)
119 and isinstance(children[i+1], nodes.Text)):
120 children[i] = nodes.Text(children[i]+children.pop(i+1))
121 children[i].parent = node
122 else:
123 i += 1
124
125 # remove empty Text nodes:
126 for node in document.findall(nodes.Text):
127 if not len(node):
128 node.parent.remove(node)
129
130 # add "code" class argument to literal elements (inline and block)
131 for node in document.findall(is_literal):
132 if 'code' not in node['classes']:
133 node['classes'].append('code')
134 # move "language" argument to classes
135 for node in document.findall(nodes.literal_block):
136 if 'language' in node.attributes:
137 node['classes'].append(node['language'])
138 del node['language']
139
140 # replace raw nodes if raw is not allowed
141 if not document.settings.raw_enabled:
142 for node in document.findall(nodes.raw):
143 message = document.reporter.warning('Raw content disabled.')
144 if isinstance(node.parent, nodes.TextElement):
145 msgid = document.set_id(message)
146 problematic = nodes.problematic('', node.astext(),
147 refid=msgid)
148 node.parent.replace(node, problematic)
149 prbid = document.set_id(problematic)
150 message.add_backref(prbid)
151 document.append(message)
152 else:
153 node.parent.replace(node, message)
154
155 # drop pending_xref (Sphinx cross reference extension)
156 for node in document.findall(addnodes.pending_xref):
157 reference = node.children[0]
158 if 'name' not in reference:
159 reference['name'] = nodes.fully_normalize_name(
160 reference.astext())
161 node.parent.replace(node, reference)
162 # now we are ready to call the upstream function:
163 super().finish_parse()
164
165 def visit_document(self, node) -> None:
166 """Dummy function to prevent spurious warnings.
167
168 cf. https://github.com/readthedocs/recommonmark/issues/177
169 """
170
171 # Overwrite parent method with version that
172 # doesn't pass deprecated `rawsource` argument to nodes.Text:
173 def visit_text(self, mdnode) -> None:
174 self.current_node.append(nodes.Text(mdnode.literal))