| 1 |
|
| 2 |
e |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
""" |
| 7 |
Transforms needed by most or all documents: |
| 8 |
|
| 9 |
- `Decorations`: Generate a document's header & footer. |
| 10 |
- `ExposeInternals`: Expose internal attributes. |
| 11 |
- `Messages`: Placement of system messages generated after parsing. |
| 12 |
- `FilterMessages`: Remove system messages below verbosity threshold. |
| 13 |
- `TestMessages`: Like `Messages`, used on test runs. |
| 14 |
- `StripComments`: Remove comment elements from the document tree. |
| 15 |
- `StripClassesAndElements`: Remove elements with classes |
| 16 |
in `self.document.settings.strip_elements_with_classes` |
| 17 |
and class values in `self.document.settings.strip_classes`. |
| 18 |
- `SmartQuotes`: Replace ASCII quotation marks with typographic form. |
| 19 |
- `Validate`: Validate the document tree, report violations as warning. |
| 20 |
""" |
| 21 |
|
| 22 |
from __future__ import annotations |
| 23 |
|
| 24 |
__docformat__ = 'reStructuredText' |
| 25 |
|
| •26 |
import os |
| 27 |
import re |
| 28 |
import time |
| 29 |
from docutils import nodes, utils |
| 30 |
from docutils.transforms import Transform |
| 31 |
from docutils.utils import smartquotes |
| 32 |
|
| 33 |
|
| 34 |
class Decorations(Transform): |
| 35 |
|
| 36 |
""" |
| 37 |
Populate a document's decoration element (header, footer). |
| 38 |
""" |
| 39 |
|
| 40 |
default_priority = 820 |
| 41 |
|
| 42 |
def apply(self) -> None: |
| 43 |
header_nodes = self.generate_header() |
| 44 |
if header_nodes: |
| 45 |
decoration = self.document.get_decoration() |
| 46 |
header = decoration.get_header() |
| 47 |
header.extend(header_nodes) |
| 48 |
footer_nodes = self.generate_footer() |
| 49 |
if footer_nodes: |
| 50 |
decoration = self.document.get_decoration() |
| 51 |
footer = decoration.get_footer() |
| 52 |
footer.extend(footer_nodes) |
| 53 |
|
| 54 |
def generate_header(self): |
| 55 |
return None |
| 56 |
|
| 57 |
def generate_footer(self): |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
settings = self.document.settings |
| 65 |
if (settings.generator or settings.datestamp |
| 66 |
or settings.source_link or settings.source_url): |
| 67 |
text = [] |
| 68 |
if (settings.source_link and settings._source |
| 69 |
or settings.source_url): |
| 70 |
if settings.source_url: |
| 71 |
source = settings.source_url |
| 72 |
else: |
| 73 |
source = utils.relative_path(settings.output_path, |
| 74 |
settings._source) |
| 75 |
text.extend([ |
| 76 |
nodes.reference('', 'View document source', |
| 77 |
refuri=source), |
| 78 |
nodes.Text('.\n')]) |
| 79 |
if settings.datestamp: |
| •80 |
source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH') |
| 81 |
if source_date_epoch: |
| 82 |
datestamp = time.strftime(settings.datestamp, |
| 83 |
time.gmtime(int(source_date_epoch))) |
| 84 |
else: |
| 85 |
datestamp = time.strftime(settings.datestamp, time.gmtime()) |
| 86 |
text.append(nodes.Text('Generated on: ' + datestamp + '.\n')) |
| 87 |
if settings.generator: |
| 88 |
text.extend([ |
| 89 |
nodes.Text('Generated by '), |
| 90 |
nodes.reference('', 'Docutils', |
| 91 |
refuri='https://docutils.sourceforge.io/'), |
| 92 |
nodes.Text(' from '), |
| 93 |
nodes.reference('', 'reStructuredText', |
| 94 |
refuri='https://docutils.sourceforge.io/' |
| 95 |
'rst.html'), |
| 96 |
nodes.Text(' source.\n')]) |
| 97 |
return [nodes.paragraph('', '', *text)] |
| 98 |
else: |
| 99 |
return None |
| 100 |
|
| 101 |
|
| 102 |
class ExposeInternals(Transform): |
| 103 |
|
| 104 |
""" |
| 105 |
Expose internal attributes if ``expose_internals`` setting is set. |
| 106 |
""" |
| 107 |
|
| 108 |
default_priority = 840 |
| 109 |
|
| 110 |
def not_Text(self, node) -> bool: |
| 111 |
return not isinstance(node, nodes.Text) |
| 112 |
|
| 113 |
def apply(self) -> None: |
| 114 |
if self.document.settings.expose_internals: |
| 115 |
for node in self.document.findall(self.not_Text): |
| 116 |
for att in self.document.settings.expose_internals: |
| 117 |
value = getattr(node, att, None) |
| 118 |
if value is not None: |
| 119 |
node['internal:' + att] = value |
| 120 |
|
| 121 |
|
| 122 |
class Messages(Transform): |
| 123 |
|
| 124 |
"""Handle "loose" messages. |
| 125 |
|
| 126 |
Place system messages generated by parsing or transforms that are not |
| 127 |
attached to the document tree into a dedicated section of the document. |
| 128 |
""" |
| 129 |
|
| 130 |
default_priority = 860 |
| 131 |
|
| 132 |
def apply(self) -> None: |
| 133 |
messages = [*self.document.parse_messages, |
| 134 |
*self.document.transform_messages] |
| 135 |
loose_messages = [msg for msg in messages if not msg.parent] |
| 136 |
if loose_messages: |
| 137 |
section = nodes.section(classes=['system-messages']) |
| 138 |
|
| 139 |
section += nodes.title('', 'Docutils System Messages') |
| 140 |
section += loose_messages |
| 141 |
self.document.transform_messages[:] = [] |
| 142 |
self.document += section |
| 143 |
|
| 144 |
|
| 145 |
class FilterMessages(Transform): |
| 146 |
|
| 147 |
""" |
| 148 |
Remove system messages below verbosity threshold. |
| 149 |
|
| 150 |
Also convert <problematic> nodes referencing removed messages |
| 151 |
to <Text> nodes and remove "System Messages" section if empty. |
| 152 |
""" |
| 153 |
|
| 154 |
default_priority = 870 |
| 155 |
|
| 156 |
def apply(self) -> None: |
| 157 |
removed_ids = [] |
| 158 |
for node in tuple(self.document.findall(nodes.system_message)): |
| 159 |
if node['level'] < self.document.reporter.report_level: |
| 160 |
node.parent.remove(node) |
| 161 |
for _id in node['ids']: |
| 162 |
self.document.ids.pop(_id, None) |
| 163 |
removed_ids.append(_id) |
| 164 |
for node in tuple(self.document.findall(nodes.problematic)): |
| 165 |
if 'refid' in node and node['refid'] in removed_ids: |
| 166 |
node.parent.replace(node, nodes.Text(node.astext())) |
| 167 |
for node in self.document.findall(nodes.section): |
| 168 |
if "system-messages" in node['classes'] and len(node) == 1: |
| 169 |
node.parent.remove(node) |
| 170 |
|
| 171 |
|
| 172 |
class TestMessages(Transform): |
| 173 |
|
| 174 |
""" |
| 175 |
Append all post-parse system messages to the end of the document. |
| 176 |
|
| 177 |
Used for testing purposes. |
| 178 |
""" |
| 179 |
|
| 180 |
|
| 181 |
__test__ = False |
| 182 |
|
| 183 |
default_priority = 880 |
| 184 |
|
| 185 |
def apply(self) -> None: |
| 186 |
for msg in self.document.transform_messages: |
| 187 |
if not msg.parent: |
| 188 |
self.document += msg |
| 189 |
|
| 190 |
|
| 191 |
class StripComments(Transform): |
| 192 |
|
| 193 |
""" |
| 194 |
Remove comment elements from the document tree (only if the |
| 195 |
``strip_comments`` setting is enabled). |
| 196 |
""" |
| 197 |
|
| 198 |
default_priority = 740 |
| 199 |
|
| 200 |
def apply(self) -> None: |
| 201 |
if self.document.settings.strip_comments: |
| 202 |
for node in tuple(self.document.findall(nodes.comment)): |
| 203 |
node.parent.remove(node) |
| 204 |
|
| 205 |
|
| 206 |
class StripClassesAndElements(Transform): |
| 207 |
|
| 208 |
""" |
| 209 |
Remove from the document tree all elements with classes in |
| 210 |
`self.document.settings.strip_elements_with_classes` and all "classes" |
| 211 |
attribute values in `self.document.settings.strip_classes`. |
| 212 |
""" |
| 213 |
|
| 214 |
default_priority = 420 |
| 215 |
|
| 216 |
def apply(self) -> None: |
| 217 |
if self.document.settings.strip_elements_with_classes: |
| 218 |
self.strip_elements = {*self.document.settings |
| 219 |
.strip_elements_with_classes} |
| 220 |
|
| 221 |
|
| 222 |
for node in tuple(self.document.findall(self.check_classes)): |
| 223 |
node.parent.remove(node) |
| 224 |
|
| 225 |
if not self.document.settings.strip_classes: |
| 226 |
return |
| 227 |
strip_classes = self.document.settings.strip_classes |
| 228 |
for node in self.document.findall(nodes.Element): |
| 229 |
for class_value in strip_classes: |
| 230 |
try: |
| 231 |
node['classes'].remove(class_value) |
| 232 |
except ValueError: |
| 233 |
pass |
| 234 |
|
| 235 |
def check_classes(self, node) -> bool: |
| 236 |
if not isinstance(node, nodes.Element): |
| 237 |
return False |
| 238 |
for class_value in node['classes'][:]: |
| 239 |
if class_value in self.strip_elements: |
| 240 |
return True |
| 241 |
return False |
| 242 |
|
| 243 |
|
| 244 |
class SmartQuotes(Transform): |
| 245 |
|
| 246 |
""" |
| 247 |
Replace ASCII quotation marks with typographic form. |
| 248 |
|
| 249 |
Also replace multiple dashes with em-dash/en-dash characters. |
| 250 |
""" |
| 251 |
|
| 252 |
default_priority = 855 |
| 253 |
|
| 254 |
nodes_to_skip = (nodes.FixedTextElement, nodes.Special) |
| 255 |
"""Do not apply "smartquotes" to instances of these block-level nodes.""" |
| 256 |
|
| 257 |
literal_nodes = (nodes.FixedTextElement, nodes.Special, |
| 258 |
nodes.image, nodes.literal, nodes.math, |
| 259 |
nodes.raw, nodes.problematic) |
| 260 |
"""Do not apply smartquotes to instances of these inline nodes.""" |
| 261 |
|
| 262 |
smartquotes_action = 'qDe' |
| 263 |
"""Setting to select smartquote transformations. |
| 264 |
|
| 265 |
The default 'qDe' educates normal quote characters: (", '), |
| 266 |
em- and en-dashes (---, --) and ellipses (...). |
| 267 |
""" |
| 268 |
|
| 269 |
def __init__(self, document, startnode) -> None: |
| 270 |
Transform.__init__(self, document, startnode=startnode) |
| 271 |
self.unsupported_languages = set() |
| 272 |
|
| 273 |
def get_tokens(self, txtnodes): |
| 274 |
|
| 275 |
|
| 276 |
for node in txtnodes: |
| 277 |
if (isinstance(node.parent, self.literal_nodes) |
| 278 |
or isinstance(node.parent.parent, self.literal_nodes)): |
| 279 |
yield 'literal', str(node) |
| 280 |
else: |
| 281 |
|
| 282 |
|
| 283 |
txt = re.sub('(?<=\x00)([-\\\'".`])', r'\\\1', str(node)) |
| 284 |
yield 'plain', txt |
| 285 |
|
| 286 |
def apply(self) -> None: |
| 287 |
smart_quotes = self.document.settings.setdefault('smart_quotes', |
| 288 |
False) |
| 289 |
if not smart_quotes: |
| 290 |
return |
| 291 |
try: |
| 292 |
alternative = smart_quotes.startswith('alt') |
| 293 |
except AttributeError: |
| 294 |
alternative = False |
| 295 |
|
| 296 |
document_language = self.document.settings.language_code |
| 297 |
lc_smartquotes = self.document.settings.smartquotes_locales |
| 298 |
if lc_smartquotes: |
| 299 |
smartquotes.smartchars.quotes.update(dict(lc_smartquotes)) |
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
for node in self.document.findall(nodes.TextElement): |
| 304 |
|
| 305 |
if isinstance(node, self.nodes_to_skip): |
| 306 |
continue |
| 307 |
|
| 308 |
if isinstance(node.parent, nodes.TextElement): |
| 309 |
continue |
| 310 |
|
| 311 |
|
| 312 |
txtnodes = [txtnode for txtnode in node.findall(nodes.Text) |
| 313 |
if not isinstance(txtnode.parent, |
| 314 |
nodes.option_string)] |
| 315 |
|
| 316 |
|
| 317 |
lang = node.get_language_code(document_language) |
| 318 |
|
| 319 |
if alternative: |
| 320 |
if '-x-altquot' in lang: |
| 321 |
lang = lang.replace('-x-altquot', '') |
| 322 |
else: |
| 323 |
lang += '-x-altquot' |
| 324 |
|
| 325 |
for tag in utils.normalize_language_tag(lang): |
| 326 |
if tag in smartquotes.smartchars.quotes: |
| 327 |
lang = tag |
| 328 |
break |
| 329 |
else: |
| 330 |
if lang not in self.unsupported_languages: |
| 331 |
self.document.reporter.warning( |
| 332 |
'No smart quotes defined for language "%s".' % lang, |
| 333 |
base_node=node) |
| 334 |
self.unsupported_languages.add(lang) |
| 335 |
lang = '' |
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
teacher = smartquotes.educate_tokens( |
| 340 |
self.get_tokens(txtnodes), |
| 341 |
attr=self.smartquotes_action, language=lang) |
| 342 |
|
| 343 |
for txtnode, newtext in zip(txtnodes, teacher): |
| 344 |
txtnode.parent.replace(txtnode, nodes.Text(newtext)) |
| 345 |
|
| 346 |
self.unsupported_languages.clear() |
| 347 |
|
| 348 |
|
| 349 |
class Validate(Transform): |
| 350 |
|
| 351 |
""" |
| 352 |
Validate the document tree, report violations as warning. |
| 353 |
""" |
| 354 |
|
| 355 |
default_priority = 835 |
| 356 |
|
| 357 |
def apply(self) -> None: |
| 358 |
if not getattr(self.document.settings, 'validate', False): |
| 359 |
return |
| 360 |
for node in self.document.findall(): |
| 361 |
try: |
| 362 |
node.validate(recursive=False) |
| 363 |
except nodes.ValidationError as e: |
| 364 |
self.document.reporter.warning( |
| 365 |
str(e), base_node=e.problematic_element or node) |
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|