| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
""" |
| 6 |
This is the ``docutils.parsers.rst.states`` module, the core of |
| 7 |
the reStructuredText parser. It defines the following: |
| 8 |
|
| 9 |
:Classes: |
| 10 |
- `RSTStateMachine`: reStructuredText parser's entry point. |
| 11 |
- `NestedStateMachine`: recursive StateMachine. |
| 12 |
- `RSTState`: reStructuredText State superclass. |
| 13 |
- `Inliner`: For parsing inline markup. |
| 14 |
- `Body`: Generic classifier of the first line of a block. |
| 15 |
- `SpecializedBody`: Superclass for compound element members. |
| 16 |
- `BulletList`: Second and subsequent bullet_list list_items |
| 17 |
- `DefinitionList`: Second+ definition_list_items. |
| 18 |
- `EnumeratedList`: Second+ enumerated_list list_items. |
| 19 |
- `FieldList`: Second+ fields. |
| 20 |
- `OptionList`: Second+ option_list_items. |
| 21 |
- `RFC2822List`: Second+ RFC2822-style fields. |
| 22 |
- `ExtensionOptions`: Parses directive option fields. |
| 23 |
- `Explicit`: Second+ explicit markup constructs. |
| 24 |
- `SubstitutionDef`: For embedded directives in substitution definitions. |
| 25 |
- `Text`: Classifier of second line of a text block. |
| 26 |
- `SpecializedText`: Superclass for continuation lines of Text-variants. |
| 27 |
- `Definition`: Second line of potential definition_list_item. |
| 28 |
- `Line`: Second line of overlined section title or transition marker. |
| 29 |
- `Struct`: obsolete, use `types.SimpleNamespace`. |
| 30 |
|
| 31 |
:Exception classes: |
| 32 |
- `MarkupError` |
| 33 |
- `ParserError` |
| 34 |
- `MarkupMismatch` |
| 35 |
|
| 36 |
:Functions: |
| 37 |
- `escape2null()`: Return a string, escape-backslashes converted to nulls. |
| 38 |
- `unescape()`: Return a string, nulls removed or restored to backslashes. |
| 39 |
|
| 40 |
:Attributes: |
| 41 |
- `state_classes`: set of State classes used with `RSTStateMachine`. |
| 42 |
|
| 43 |
Parser Overview |
| 44 |
=============== |
| 45 |
|
| 46 |
The reStructuredText parser is implemented as a recursive state machine, |
| 47 |
examining its input one line at a time. To understand how the parser works, |
| 48 |
please first become familiar with the `docutils.statemachine` module. In the |
| 49 |
description below, references are made to classes defined in this module; |
| 50 |
please see the individual classes for details. |
| 51 |
|
| 52 |
Parsing proceeds as follows: |
| 53 |
|
| 54 |
1. The state machine examines each line of input, checking each of the |
| 55 |
transition patterns of the state `Body`, in order, looking for a match. |
| 56 |
The implicit transitions (blank lines and indentation) are checked before |
| 57 |
any others. The 'text' transition is a catch-all (matches anything). |
| 58 |
|
| 59 |
2. The method associated with the matched transition pattern is called. |
| 60 |
|
| 61 |
A. Some transition methods are self-contained, appending elements to the |
| 62 |
document tree (`Body.doctest` parses a doctest block). The parser's |
| 63 |
current line index is advanced to the end of the element, and parsing |
| 64 |
continues with step 1. |
| 65 |
|
| 66 |
B. Other transition methods trigger the creation of a nested state machine, |
| 67 |
whose job is to parse a compound construct ('indent' does a block quote, |
| 68 |
'bullet' does a bullet list, 'overline' does a section [first checking |
| 69 |
for a valid section header], etc.). |
| 70 |
|
| 71 |
- In the case of lists and explicit markup, a one-off state machine is |
| 72 |
created and run to parse contents of the first item. |
| 73 |
|
| 74 |
- A new state machine is created and its initial state is set to the |
| 75 |
appropriate specialized state (`BulletList` in the case of the |
| 76 |
'bullet' transition; see `SpecializedBody` for more detail). This |
| 77 |
state machine is run to parse the compound element (or series of |
| 78 |
explicit markup elements), and returns as soon as a non-member element |
| 79 |
is encountered. For example, the `BulletList` state machine ends as |
| 80 |
soon as it encounters an element which is not a list item of that |
| 81 |
bullet list. The optional omission of inter-element blank lines is |
| 82 |
enabled by this nested state machine. |
| 83 |
|
| 84 |
- The current line index is advanced to the end of the elements parsed, |
| 85 |
and parsing continues with step 1. |
| 86 |
|
| 87 |
C. The result of the 'text' transition depends on the next line of text. |
| 88 |
The current state is changed to `Text`, under which the second line is |
| 89 |
examined. If the second line is: |
| 90 |
|
| 91 |
- Indented: The element is a definition list item, and parsing proceeds |
| 92 |
similarly to step 2.B, using the `DefinitionList` state. |
| 93 |
|
| 94 |
- A line of uniform punctuation characters: The element is a section |
| 95 |
header; again, parsing proceeds as in step 2.B, and `Body` is still |
| 96 |
used. |
| 97 |
|
| 98 |
- Anything else: The element is a paragraph, which is examined for |
| 99 |
inline markup and appended to the parent element. Processing |
| 100 |
continues with step 1. |
| 101 |
""" |
| 102 |
|
| 103 |
from __future__ import annotations |
| 104 |
|
| 105 |
__docformat__ = 'reStructuredText' |
| 106 |
|
| 107 |
import re |
| 108 |
from types import FunctionType, MethodType |
| 109 |
from types import SimpleNamespace as Struct |
| 110 |
import warnings |
| 111 |
|
| 112 |
from docutils import nodes, statemachine, utils |
| 113 |
from docutils import ApplicationError, DataError |
| 114 |
from docutils.statemachine import StateMachineWS, StateWS |
| 115 |
from docutils.nodes import fully_normalize_name as normalize_name |
| 116 |
from docutils.nodes import unescape, whitespace_normalize_name |
| 117 |
import docutils.parsers.rst |
| 118 |
from docutils.parsers.rst import directives, languages, tableparser, roles |
| 119 |
from docutils.utils import escape2null, column_width, strip_combining_chars |
| 120 |
from docutils.utils import punctuation_chars, urischemes |
| 121 |
from docutils.utils import split_escaped_whitespace |
| •122 |
from roman_numerals import InvalidRomanNumeralError, RomanNumeral |
| 123 |
|
| 124 |
TYPE_CHECKING = False |
| 125 |
if TYPE_CHECKING: |
| 126 |
from docutils.statemachine import StringList |
| 127 |
|
| 128 |
|
| 129 |
class MarkupError(DataError): pass |
| 130 |
class UnknownInterpretedRoleError(DataError): pass |
| 131 |
class InterpretedRoleNotImplementedError(DataError): pass |
| 132 |
class ParserError(ApplicationError): pass |
| 133 |
class MarkupMismatch(Exception): pass |
| 134 |
|
| 135 |
|
| 136 |
class RSTStateMachine(StateMachineWS): |
| 137 |
|
| 138 |
""" |
| 139 |
reStructuredText's master StateMachine. |
| 140 |
|
| 141 |
The entry point to reStructuredText parsing is the `run()` method. |
| 142 |
""" |
| 143 |
section_level_offset: int = 0 |
| 144 |
"""Correction term for section level determination in nested parsing. |
| 145 |
|
| 146 |
Updated by `RSTState.nested_parse()` and used in |
| 147 |
`RSTState.check_subsection()` to compensate differences when |
| 148 |
nested parsing uses a detached base node with a document-wide |
| 149 |
section title style hierarchy or the current node with a new, |
| 150 |
independent title style hierarchy. |
| 151 |
""" |
| 152 |
|
| 153 |
def run(self, input_lines, document, input_offset=0, match_titles=True, |
| 154 |
inliner=None) -> None: |
| 155 |
""" |
| 156 |
Parse `input_lines` and modify the `document` node in place. |
| 157 |
|
| 158 |
Extend `StateMachineWS.run()`: set up parse-global data and |
| 159 |
run the StateMachine. |
| 160 |
""" |
| 161 |
self.language = languages.get_language( |
| 162 |
document.settings.language_code, document.reporter) |
| 163 |
self.match_titles = match_titles |
| 164 |
if inliner is None: |
| 165 |
inliner = Inliner() |
| 166 |
inliner.init_customizations(document.settings) |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
self.memo = Struct(document=document, |
| 171 |
reporter=document.reporter, |
| 172 |
language=self.language, |
| 173 |
title_styles=[], |
| 174 |
section_level=0, |
| 175 |
section_bubble_up_kludge=False, |
| 176 |
inliner=inliner) |
| 177 |
self.document = document |
| 178 |
self.attach_observer(document.note_source) |
| 179 |
self.reporter = self.document.reporter |
| 180 |
self.node = document |
| 181 |
results = StateMachineWS.run(self, input_lines, input_offset, |
| 182 |
input_source=document['source']) |
| 183 |
assert results == [], 'RSTStateMachine.run() results should be empty!' |
| 184 |
self.node = self.memo = None |
| 185 |
|
| 186 |
|
| 187 |
class NestedStateMachine(RSTStateMachine): |
| 188 |
""" |
| 189 |
StateMachine run from within other StateMachine runs, to parse nested |
| 190 |
document structures. |
| 191 |
""" |
| 192 |
|
| 193 |
def __init__(self, state_classes, initial_state, |
| 194 |
debug=False, parent_state_machine=None) -> None: |
| 195 |
|
| 196 |
self.parent_state_machine = parent_state_machine |
| 197 |
"""The instance of the parent state machine.""" |
| 198 |
|
| 199 |
super().__init__(state_classes, initial_state, debug) |
| 200 |
|
| 201 |
def run(self, input_lines, input_offset, memo, node, match_titles=True): |
| 202 |
""" |
| 203 |
Parse `input_lines` and populate `node`. |
| 204 |
|
| 205 |
Extend `StateMachineWS.run()`: set up document-wide data. |
| 206 |
""" |
| 207 |
self.match_titles = match_titles |
| 208 |
self.memo = memo |
| 209 |
self.document = memo.document |
| 210 |
self.attach_observer(self.document.note_source) |
| 211 |
self.language = memo.language |
| 212 |
self.reporter = self.document.reporter |
| 213 |
self.node = node |
| 214 |
results = StateMachineWS.run(self, input_lines, input_offset) |
| 215 |
assert results == [], ('NestedStateMachine.run() results should be ' |
| 216 |
'empty!') |
| 217 |
return results |
| 218 |
|
| 219 |
|
| 220 |
class RSTState(StateWS): |
| 221 |
|
| 222 |
""" |
| 223 |
reStructuredText State superclass. |
| 224 |
|
| 225 |
Contains methods used by all State subclasses. |
| 226 |
""" |
| 227 |
|
| 228 |
nested_sm = NestedStateMachine |
| 229 |
nested_sm_cache = [] |
| 230 |
|
| 231 |
def __init__(self, state_machine: RSTStateMachine, debug=False) -> None: |
| 232 |
self.nested_sm_kwargs = {'state_classes': state_classes, |
| 233 |
'initial_state': 'Body'} |
| 234 |
StateWS.__init__(self, state_machine, debug) |
| 235 |
|
| 236 |
def runtime_init(self) -> None: |
| 237 |
StateWS.runtime_init(self) |
| 238 |
memo = self.state_machine.memo |
| 239 |
self.memo = memo |
| 240 |
self.document = memo.document |
| 241 |
self.inliner = memo.inliner |
| 242 |
self.reporter = self.document.reporter |
| 243 |
|
| 244 |
if not hasattr(self.reporter, 'get_source_and_line'): |
| 245 |
self.reporter.get_source_and_line = self.state_machine.get_source_and_line |
| 246 |
|
| 247 |
@property |
| 248 |
def parent(self) -> nodes.Element | None: |
| 249 |
return self.state_machine.node |
| 250 |
|
| 251 |
@parent.setter |
| 252 |
def parent(self, value: nodes.Element): |
| 253 |
self.state_machine.node = value |
| 254 |
|
| 255 |
def goto_line(self, abs_line_offset) -> None: |
| 256 |
""" |
| 257 |
Jump to input line `abs_line_offset`, ignoring jumps past the end. |
| 258 |
""" |
| 259 |
try: |
| 260 |
self.state_machine.goto_line(abs_line_offset) |
| 261 |
except EOFError: |
| 262 |
pass |
| 263 |
|
| 264 |
def no_match(self, context, transitions): |
| 265 |
""" |
| 266 |
Override `StateWS.no_match` to generate a system message. |
| 267 |
|
| 268 |
This code should never be run. |
| 269 |
""" |
| 270 |
self.reporter.severe( |
| 271 |
'Internal error: no transition pattern match. State: "%s"; ' |
| 272 |
'transitions: %s; context: %s; current line: %r.' |
| 273 |
% (self.__class__.__name__, transitions, context, |
| 274 |
self.state_machine.line)) |
| 275 |
return context, None, [] |
| 276 |
|
| 277 |
def bof(self, context): |
| 278 |
"""Called at beginning of file.""" |
| 279 |
return [], [] |
| 280 |
|
| 281 |
def nested_parse(self, |
| 282 |
block: StringList, |
| 283 |
input_offset: int, |
| 284 |
node: nodes.Element|None = None, |
| 285 |
match_titles: bool = False, |
| 286 |
state_machine_class: StateMachineWS|None = None, |
| 287 |
state_machine_kwargs: dict|None = None |
| 288 |
) -> int: |
| 289 |
""" |
| 290 |
Parse the input `block` with a nested state-machine rooted at `node`. |
| 291 |
|
| 292 |
:block: |
| 293 |
reStructuredText source extract. |
| 294 |
:input_offset: |
| 295 |
Line number at start of the block. |
| 296 |
:node: |
| 297 |
Base node. Generated nodes will be appended to this node. |
| 298 |
Default: the "current node" (`self.state_machine.node`). |
| 299 |
:match_titles: |
| 300 |
Allow section titles? |
| 301 |
Caution: With a custom base node, this may lead to an invalid |
| 302 |
or mixed up document tree. [#]_ |
| 303 |
:state_machine_class: |
| 304 |
Default: `NestedStateMachine`. |
| 305 |
:state_machine_kwargs: |
| 306 |
Keyword arguments for the state-machine instantiation. |
| 307 |
Default: `self.nested_sm_kwargs`. |
| 308 |
|
| 309 |
Create a new state-machine instance if required. |
| 310 |
Return new offset. |
| 311 |
|
| 312 |
.. [#] See also ``test_parsers/test_rst/test_nested_parsing.py`` |
| 313 |
and Sphinx's `nested_parse_to_nodes()`__. |
| 314 |
|
| 315 |
__ https://www.sphinx-doc.org/en/master/extdev/utils.html |
| 316 |
#sphinx.util.parsing.nested_parse_to_nodes |
| 317 |
""" |
| 318 |
if node is None: |
| 319 |
node = self.state_machine.node |
| 320 |
use_default = 0 |
| 321 |
if state_machine_class is None: |
| 322 |
state_machine_class = self.nested_sm |
| 323 |
use_default += 1 |
| 324 |
if state_machine_kwargs is None: |
| 325 |
state_machine_kwargs = self.nested_sm_kwargs |
| 326 |
use_default += 1 |
| 327 |
my_state_machine = None |
| 328 |
if use_default == 2: |
| 329 |
try: |
| 330 |
|
| 331 |
my_state_machine = self.nested_sm_cache.pop() |
| 332 |
except IndexError: |
| 333 |
pass |
| 334 |
if not my_state_machine: |
| 335 |
my_state_machine = state_machine_class( |
| 336 |
debug=self.debug, |
| 337 |
parent_state_machine=self.state_machine, |
| 338 |
**state_machine_kwargs) |
| 339 |
|
| 340 |
|
| 341 |
if (node == self.state_machine.node |
| 342 |
and not isinstance(node, (nodes.document, nodes.section))): |
| 343 |
match_titles = False |
| 344 |
if match_titles: |
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
l_node = len(node.section_hierarchy()) |
| 350 |
l_start = min(len(self.parent.section_hierarchy()), |
| 351 |
len(self.memo.title_styles)) |
| 352 |
my_state_machine.section_level_offset = l_start - l_node |
| 353 |
|
| 354 |
|
| 355 |
block_length = len(block) |
| 356 |
my_state_machine.run(block, input_offset, self.memo, |
| 357 |
node, match_titles) |
| 358 |
|
| 359 |
if match_titles: |
| 360 |
if node == self.state_machine.node: |
| 361 |
|
| 362 |
sm = self.state_machine |
| 363 |
try: |
| 364 |
while True: |
| 365 |
sm.node = my_state_machine.node |
| 366 |
sm = sm.parent_state_machine |
| 367 |
except AttributeError: |
| 368 |
pass |
| 369 |
|
| 370 |
new_offset = my_state_machine.abs_line_offset() |
| 371 |
if use_default == 2: |
| 372 |
self.nested_sm_cache.append(my_state_machine) |
| 373 |
else: |
| 374 |
my_state_machine.unlink() |
| 375 |
|
| 376 |
if block.parent and (len(block) - block_length) != 0: |
| 377 |
|
| 378 |
self.state_machine.next_line(len(block) - block_length) |
| 379 |
return new_offset |
| 380 |
|
| 381 |
def nested_list_parse(self, block, input_offset, node, initial_state, |
| 382 |
blank_finish, |
| 383 |
blank_finish_state=None, |
| 384 |
extra_settings={}, |
| 385 |
match_titles=False, |
| 386 |
state_machine_class=None, |
| 387 |
state_machine_kwargs=None): |
| 388 |
""" |
| 389 |
Parse the input `block` with a nested state-machine rooted at `node`. |
| 390 |
|
| 391 |
Create a new StateMachine rooted at `node` and run it over the |
| 392 |
input `block` (see also `nested_parse()`). |
| 393 |
Also keep track of optional intermediate blank lines and the |
| 394 |
required final one. |
| 395 |
|
| 396 |
Return new offset and a boolean indicating whether there was a |
| 397 |
blank final line. |
| 398 |
""" |
| 399 |
if match_titles: |
| 400 |
warnings.warn('The "match_titles" argument of ' |
| 401 |
'parsers.rst.states.RSTState.nested_list_parse() ' |
| 402 |
'will be ignored in Docutils 1.0 ' |
| 403 |
'and removed in Docutils 2.0.', |
| 404 |
PendingDeprecationWarning, stacklevel=2) |
| 405 |
if state_machine_class is None: |
| 406 |
state_machine_class = self.nested_sm |
| 407 |
if state_machine_kwargs is None: |
| 408 |
state_machine_kwargs = self.nested_sm_kwargs.copy() |
| 409 |
state_machine_kwargs['initial_state'] = initial_state |
| 410 |
my_state_machine = state_machine_class( |
| 411 |
debug=self.debug, |
| 412 |
parent_state_machine=self.state_machine, |
| 413 |
**state_machine_kwargs) |
| 414 |
if blank_finish_state is None: |
| 415 |
blank_finish_state = initial_state |
| 416 |
my_state_machine.states[blank_finish_state].blank_finish = blank_finish |
| 417 |
for key, value in extra_settings.items(): |
| 418 |
setattr(my_state_machine.states[initial_state], key, value) |
| 419 |
my_state_machine.run(block, input_offset, memo=self.memo, |
| 420 |
node=node, match_titles=match_titles) |
| 421 |
blank_finish = my_state_machine.states[blank_finish_state].blank_finish |
| 422 |
my_state_machine.unlink() |
| 423 |
return my_state_machine.abs_line_offset(), blank_finish |
| 424 |
|
| 425 |
def section(self, title, source, style, lineno, messages) -> None: |
| 426 |
"""Check for a valid subsection and create one if it checks out.""" |
| 427 |
if self.check_subsection(source, style, lineno): |
| 428 |
self.new_subsection(title, lineno, messages) |
| 429 |
|
| 430 |
def check_subsection(self, source, style, lineno) -> bool: |
| 431 |
""" |
| 432 |
Check for a valid subsection header. Update section data in `memo`. |
| 433 |
|
| 434 |
When a new section is reached that isn't a subsection of the current |
| 435 |
section, set `self.parent` to the new section's parent section |
| 436 |
(or the root node if the new section is a top-level section). |
| 437 |
""" |
| 438 |
title_styles = self.memo.title_styles |
| 439 |
parent_sections = self.parent.section_hierarchy() |
| 440 |
|
| 441 |
oldlevel = (len(parent_sections) |
| 442 |
+ self.state_machine.section_level_offset) |
| 443 |
|
| 444 |
try: |
| 445 |
newlevel = title_styles.index(style) + 1 |
| 446 |
except ValueError: |
| 447 |
newlevel = len(title_styles) + 1 |
| 448 |
|
| 449 |
|
| 450 |
if newlevel > oldlevel + 1: |
| 451 |
styles = ' '.join('/'.join(style) for style in title_styles) |
| 452 |
self.parent += self.reporter.error( |
| 453 |
'Inconsistent title style:' |
| 454 |
f' skip from level {oldlevel} to {newlevel}.', |
| 455 |
nodes.literal_block('', source), |
| 456 |
nodes.paragraph('', f'Established title styles: {styles}'), |
| 457 |
line=lineno) |
| 458 |
return False |
| 459 |
if newlevel <= oldlevel: |
| 460 |
|
| 461 |
try: |
| 462 |
new_parent = parent_sections[newlevel-oldlevel-1].parent |
| 463 |
except IndexError: |
| 464 |
styles = ' '.join('/'.join(style) for style in title_styles) |
| 465 |
details = (f'The parent of level {newlevel} sections cannot' |
| 466 |
' be reached. The parser is at section level' |
| 467 |
f' {oldlevel} but the current node has only' |
| 468 |
f' {len(parent_sections)} parent section(s).' |
| 469 |
'\nOne reason may be a high level' |
| 470 |
' section used in a directive that parses its' |
| 471 |
' content into a base node not attached to' |
| 472 |
' the document\n(up to Docutils 0.21,' |
| 473 |
' these sections were silently dropped).') |
| 474 |
self.parent += self.reporter.error( |
| 475 |
f'A level {newlevel} section cannot be used here.', |
| 476 |
nodes.literal_block('', source), |
| 477 |
nodes.paragraph('', f'Established title styles: {styles}'), |
| 478 |
nodes.paragraph('', details), |
| 479 |
line=lineno) |
| 480 |
return False |
| 481 |
self.parent = new_parent |
| 482 |
self.memo.section_level = newlevel - 1 |
| 483 |
if newlevel > len(title_styles): |
| 484 |
title_styles.append(style) |
| 485 |
return True |
| 486 |
|
| 487 |
def title_inconsistent(self, sourcetext, lineno): |
| 488 |
. |
| 489 |
error = self.reporter.error( |
| 490 |
'Title level inconsistent:', nodes.literal_block('', sourcetext), |
| 491 |
line=lineno) |
| 492 |
return error |
| 493 |
|
| 494 |
def new_subsection(self, title, lineno, messages): |
| 495 |
"""Append new subsection to document tree.""" |
| 496 |
section_node = nodes.section() |
| 497 |
self.parent += section_node |
| 498 |
textnodes, title_messages = self.inline_text(title, lineno) |
| 499 |
titlenode = nodes.title(title, '', *textnodes) |
| 500 |
name = normalize_name(titlenode.astext()) |
| 501 |
section_node['names'].append(name) |
| 502 |
section_node += titlenode |
| 503 |
section_node += messages |
| 504 |
section_node += title_messages |
| 505 |
self.document.note_implicit_target(section_node, section_node) |
| 506 |
|
| 507 |
self.parent = section_node |
| 508 |
self.memo.section_level += 1 |
| 509 |
|
| 510 |
def paragraph(self, lines, lineno): |
| 511 |
""" |
| 512 |
Return a list (paragraph & messages) & a boolean: literal_block next? |
| 513 |
""" |
| 514 |
data = '\n'.join(lines).rstrip() |
| 515 |
if re.search(r'(?<!\\)(\\\\)*::$', data): |
| 516 |
if len(data) == 2: |
| 517 |
return [], 1 |
| 518 |
elif data[-3] in ' \n': |
| 519 |
text = data[:-3].rstrip() |
| 520 |
else: |
| 521 |
text = data[:-1] |
| 522 |
literalnext = 1 |
| 523 |
else: |
| 524 |
text = data |
| 525 |
literalnext = 0 |
| 526 |
textnodes, messages = self.inline_text(text, lineno) |
| 527 |
p = nodes.paragraph(data, '', *textnodes) |
| 528 |
p.source, p.line = self.state_machine.get_source_and_line(lineno) |
| 529 |
return [p] + messages, literalnext |
| 530 |
|
| 531 |
def inline_text(self, text, lineno): |
| 532 |
""" |
| 533 |
Return 2 lists: nodes (text and inline elements), and system_messages. |
| 534 |
""" |
| 535 |
nodes, messages = self.inliner.parse(text, lineno, |
| 536 |
self.memo, self.parent) |
| 537 |
return nodes, messages |
| 538 |
|
| 539 |
def unindent_warning(self, node_name): |
| 540 |
|
| 541 |
lineno = self.state_machine.abs_line_number() + 1 |
| 542 |
return self.reporter.warning('%s ends without a blank line; ' |
| 543 |
'unexpected unindent.' % node_name, |
| 544 |
line=lineno) |
| 545 |
|
| 546 |
|
| 547 |
def build_regexp(definition, compile_patterns=True): |
| 548 |
""" |
| 549 |
Build, compile and return a regular expression based on `definition`. |
| 550 |
|
| 551 |
:Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), |
| 552 |
where "parts" is a list of regular expressions and/or regular |
| 553 |
expression definitions to be joined into an or-group. |
| 554 |
""" |
| 555 |
name, prefix, suffix, parts = definition |
| 556 |
part_strings = [] |
| 557 |
for part in parts: |
| 558 |
if isinstance(part, tuple): |
| 559 |
part_strings.append(build_regexp(part, None)) |
| 560 |
else: |
| 561 |
part_strings.append(part) |
| 562 |
or_group = '|'.join(part_strings) |
| 563 |
regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() |
| 564 |
if compile_patterns: |
| 565 |
return re.compile(regexp) |
| 566 |
else: |
| 567 |
return regexp |
| 568 |
|
| 569 |
|
| 570 |
class Inliner: |
| 571 |
|
| 572 |
""" |
| 573 |
Parse inline markup; call the `parse()` method. |
| 574 |
""" |
| 575 |
|
| 576 |
def __init__(self) -> None: |
| 577 |
self.implicit_dispatch = [] |
| 578 |
"""List of (pattern, bound method) tuples, used by |
| 579 |
`self.implicit_inline`.""" |
| 580 |
|
| 581 |
def init_customizations(self, settings) -> None: |
| 582 |
|
| 583 |
if getattr(settings, 'character_level_inline_markup', False): |
| 584 |
start_string_prefix = '(^|(?<!\x00))' |
| 585 |
end_string_suffix = '' |
| 586 |
else: |
| 587 |
start_string_prefix = ('(^|(?<=\\s|[%s%s]))' % |
| 588 |
(punctuation_chars.openers, |
| 589 |
punctuation_chars.delimiters)) |
| 590 |
end_string_suffix = ('($|(?=\\s|[\x00%s%s%s]))' % |
| 591 |
(punctuation_chars.closing_delimiters, |
| 592 |
punctuation_chars.delimiters, |
| 593 |
punctuation_chars.closers)) |
| 594 |
args = locals().copy() |
| 595 |
args.update(vars(self.__class__)) |
| 596 |
|
| 597 |
parts = ('initial_inline', start_string_prefix, '', |
| 598 |
[ |
| 599 |
('start', '', self.non_whitespace_after, |
| 600 |
[r'\*\*', |
| 601 |
r'\*(?!\*)', |
| 602 |
r'``', |
| 603 |
r'_`', |
| 604 |
r'\|(?!\|)'] |
| 605 |
), |
| 606 |
('whole', '', end_string_suffix, |
| 607 |
[ |
| 608 |
r'(?P<refname>%s)(?P<refend>__?)' % self.simplename, |
| 609 |
('footnotelabel', r'\[', r'(?P<fnend>\]_)', |
| 610 |
[r'[0-9]+', |
| 611 |
r'\#(%s)?' % self.simplename, |
| 612 |
r'\*', |
| 613 |
r'(?P<citationlabel>%s)' % self.simplename, |
| 614 |
] |
| 615 |
) |
| 616 |
] |
| 617 |
), |
| 618 |
('backquote', |
| 619 |
'(?P<role>(:%s:)?)' % self.simplename, |
| 620 |
self.non_whitespace_after, |
| 621 |
['`(?!`)'] |
| 622 |
) |
| 623 |
] |
| 624 |
) |
| 625 |
self.start_string_prefix = start_string_prefix |
| 626 |
self.end_string_suffix = end_string_suffix |
| 627 |
self.parts = parts |
| 628 |
|
| 629 |
self.patterns = Struct( |
| 630 |
initial=build_regexp(parts), |
| 631 |
emphasis=re.compile(self.non_whitespace_escape_before |
| 632 |
+ r'(\*)' + end_string_suffix), |
| 633 |
strong=re.compile(self.non_whitespace_escape_before |
| 634 |
+ r'(\*\*)' + end_string_suffix), |
| 635 |
interpreted_or_phrase_ref=re.compile( |
| 636 |
r""" |
| 637 |
%(non_unescaped_whitespace_escape_before)s |
| 638 |
( |
| 639 |
` |
| 640 |
(?P<suffix> |
| 641 |
(?P<role>:%(simplename)s:)? |
| 642 |
(?P<refend>__?)? |
| 643 |
) |
| 644 |
) |
| 645 |
%(end_string_suffix)s |
| 646 |
""" % args, re.VERBOSE), |
| 647 |
embedded_link=re.compile( |
| 648 |
r""" |
| 649 |
( |
| 650 |
(?:[ \n]+|^) # spaces or beginning of line/string |
| 651 |
< # open bracket |
| 652 |
%(non_whitespace_after)s |
| 653 |
(([^<>]|\x00[<>])+) # anything but unescaped angle brackets |
| 654 |
%(non_whitespace_escape_before)s |
| 655 |
> # close bracket |
| 656 |
) |
| 657 |
$ # end of string |
| 658 |
""" % args, re.VERBOSE), |
| 659 |
literal=re.compile(self.non_whitespace_before + '(``)' |
| 660 |
+ end_string_suffix), |
| 661 |
target=re.compile(self.non_whitespace_escape_before |
| 662 |
+ r'(`)' + end_string_suffix), |
| 663 |
substitution_ref=re.compile(self.non_whitespace_escape_before |
| 664 |
+ r'(\|_{0,2})' |
| 665 |
+ end_string_suffix), |
| 666 |
email=re.compile(self.email_pattern % args + '$', |
| 667 |
re.VERBOSE), |
| 668 |
uri=re.compile( |
| 669 |
(r""" |
| 670 |
%(start_string_prefix)s |
| 671 |
(?P<whole> |
| 672 |
(?P<absolute> # absolute URI |
| 673 |
(?P<scheme> # scheme (http, ftp, mailto) |
| 674 |
[a-zA-Z][a-zA-Z0-9.+-]* |
| 675 |
) |
| 676 |
: |
| 677 |
( |
| 678 |
( # either: |
| 679 |
(//?)? # hierarchical URI |
| 680 |
%(uric)s* # URI characters |
| 681 |
%(uri_end)s # final URI char |
| 682 |
) |
| 683 |
( # optional query |
| 684 |
\?%(uric)s* |
| 685 |
%(uri_end)s |
| 686 |
)? |
| 687 |
( # optional fragment |
| 688 |
\#%(uric)s* |
| 689 |
%(uri_end)s |
| 690 |
)? |
| 691 |
) |
| 692 |
) |
| 693 |
| # *OR* |
| 694 |
(?P<email> # email address |
| 695 |
""" + self.email_pattern + r""" |
| 696 |
) |
| 697 |
) |
| 698 |
%(end_string_suffix)s |
| 699 |
""") % args, re.VERBOSE), |
| 700 |
pep=re.compile( |
| 701 |
r""" |
| 702 |
%(start_string_prefix)s |
| 703 |
( |
| 704 |
(pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file |
| 705 |
| |
| 706 |
(PEP\s+(?P<pepnum2>\d+)) # reference by name |
| 707 |
) |
| 708 |
%(end_string_suffix)s""" % args, re.VERBOSE), |
| 709 |
rfc=re.compile( |
| 710 |
r""" |
| 711 |
%(start_string_prefix)s |
| 712 |
(RFC(-|\s+)?(?P<rfcnum>\d+)) |
| 713 |
%(end_string_suffix)s""" % args, re.VERBOSE)) |
| 714 |
|
| 715 |
self.implicit_dispatch.append((self.patterns.uri, |
| 716 |
self.standalone_uri)) |
| 717 |
if settings.pep_references: |
| 718 |
self.implicit_dispatch.append((self.patterns.pep, |
| 719 |
self.pep_reference)) |
| 720 |
if settings.rfc_references: |
| 721 |
self.implicit_dispatch.append((self.patterns.rfc, |
| 722 |
self.rfc_reference)) |
| 723 |
|
| 724 |
def parse(self, text, lineno, memo, parent): |
| 725 |
|
| 726 |
|
| 727 |
""" |
| 728 |
Return 2 lists: nodes (text and inline elements), and system_messages. |
| 729 |
|
| 730 |
Using `self.patterns.initial`, a pattern which matches start-strings |
| 731 |
(emphasis, strong, interpreted, phrase reference, literal, |
| 732 |
substitution reference, and inline target) and complete constructs |
| 733 |
(simple reference, footnote reference), search for a candidate. When |
| 734 |
one is found, check for validity (e.g., not a quoted '*' character). |
| 735 |
If valid, search for the corresponding end string if applicable, and |
| 736 |
check it for validity. If not found or invalid, generate a warning |
| 737 |
and ignore the start-string. Implicit inline markup (e.g. standalone |
| 738 |
URIs) is found last. |
| 739 |
|
| 740 |
:text: source string |
| 741 |
:lineno: absolute line number, cf. `statemachine.get_source_and_line()` |
| 742 |
""" |
| 743 |
self.document = memo.document |
| 744 |
self.language = memo.language |
| 745 |
self.reporter = self.document.reporter |
| 746 |
self.parent = parent |
| 747 |
pattern_search = self.patterns.initial.search |
| 748 |
dispatch = self.dispatch |
| 749 |
remaining = escape2null(text) |
| 750 |
processed = [] |
| 751 |
unprocessed = [] |
| 752 |
messages = [] |
| 753 |
while remaining: |
| 754 |
match = pattern_search(remaining) |
| 755 |
if match: |
| 756 |
groups = match.groupdict() |
| 757 |
method = dispatch[groups['start'] or groups['backquote'] |
| 758 |
or groups['refend'] or groups['fnend']] |
| 759 |
before, inlines, remaining, sysmessages = method(self, match, |
| 760 |
lineno) |
| 761 |
unprocessed.append(before) |
| 762 |
messages += sysmessages |
| 763 |
if inlines: |
| 764 |
processed += self.implicit_inline(''.join(unprocessed), |
| 765 |
lineno) |
| 766 |
processed += inlines |
| 767 |
unprocessed = [] |
| 768 |
else: |
| 769 |
break |
| 770 |
remaining = ''.join(unprocessed) + remaining |
| 771 |
if remaining: |
| 772 |
processed += self.implicit_inline(remaining, lineno) |
| 773 |
return processed, messages |
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
non_whitespace_before = r'(?<!\s)' |
| 779 |
non_whitespace_escape_before = r'(?<![\s\x00])' |
| 780 |
non_unescaped_whitespace_escape_before = r'(?<!(?<!\x00)[\s\x00])' |
| 781 |
non_whitespace_after = r'(?!\s)' |
| 782 |
|
| 783 |
simplename = r'(?:(?!_)\w)+(?:[-._+:](?:(?!_)\w)+)*' |
| 784 |
|
| 785 |
|
| 786 |
uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]""" |
| 787 |
|
| 788 |
uri_end_delim = r"""[>]""" |
| 789 |
|
| 790 |
urilast = r"""[_~*/=+a-zA-Z0-9]""" |
| 791 |
|
| 792 |
|
| 793 |
uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals() |
| 794 |
emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]""" |
| 795 |
email_pattern = r""" |
| 796 |
%(emailc)s+(?:\.%(emailc)s+)* # name |
| 797 |
(?<!\x00)@ # at |
| 798 |
%(emailc)s+(?:\.%(emailc)s*)* # host |
| 799 |
%(uri_end)s # final URI char |
| 800 |
""" |
| 801 |
|
| 802 |
def quoted_start(self, match): |
| 803 |
"""Test if inline markup start-string is 'quoted'. |
| 804 |
|
| 805 |
'Quoted' in this context means the start-string is enclosed in a pair |
| 806 |
of matching opening/closing delimiters (not necessarily quotes) |
| 807 |
or at the end of the match. |
| 808 |
""" |
| 809 |
string = match.string |
| 810 |
start = match.start() |
| 811 |
if start == 0: |
| 812 |
return False |
| 813 |
prestart = string[start - 1] |
| 814 |
try: |
| 815 |
poststart = string[match.end()] |
| 816 |
except IndexError: |
| 817 |
return True |
| 818 |
return punctuation_chars.match_chars(prestart, poststart) |
| 819 |
|
| 820 |
def inline_obj(self, match, lineno, end_pattern, nodeclass, |
| 821 |
restore_backslashes=False): |
| 822 |
string = match.string |
| 823 |
matchstart = match.start('start') |
| 824 |
matchend = match.end('start') |
| 825 |
if self.quoted_start(match): |
| 826 |
return string[:matchend], [], string[matchend:], [], '' |
| 827 |
endmatch = end_pattern.search(string[matchend:]) |
| 828 |
if endmatch and endmatch.start(1): |
| 829 |
text = endmatch.string[:endmatch.start(1)] |
| 830 |
if restore_backslashes: |
| 831 |
text = unescape(text, True) |
| 832 |
textend = matchend + endmatch.end(1) |
| 833 |
rawsource = unescape(string[matchstart:textend], True) |
| 834 |
node = nodeclass(rawsource, text) |
| 835 |
return (string[:matchstart], [node], |
| 836 |
string[textend:], [], endmatch.group(1)) |
| 837 |
msg = self.reporter.warning( |
| 838 |
'Inline %s start-string without end-string.' |
| 839 |
% nodeclass.__name__, line=lineno) |
| 840 |
text = unescape(string[matchstart:matchend], True) |
| 841 |
prb = self.problematic(text, text, msg) |
| 842 |
return string[:matchstart], [prb], string[matchend:], [msg], '' |
| 843 |
|
| 844 |
def problematic(self, text, rawsource, message): |
| 845 |
msgid = self.document.set_id(message, self.parent) |
| 846 |
problematic = nodes.problematic(rawsource, text, refid=msgid) |
| 847 |
prbid = self.document.set_id(problematic) |
| 848 |
message.add_backref(prbid) |
| 849 |
return problematic |
| 850 |
|
| 851 |
def emphasis(self, match, lineno): |
| 852 |
before, inlines, remaining, sysmessages, endstring = self.inline_obj( |
| 853 |
match, lineno, self.patterns.emphasis, nodes.emphasis) |
| 854 |
return before, inlines, remaining, sysmessages |
| 855 |
|
| 856 |
def strong(self, match, lineno): |
| 857 |
before, inlines, remaining, sysmessages, endstring = self.inline_obj( |
| 858 |
match, lineno, self.patterns.strong, nodes.strong) |
| 859 |
return before, inlines, remaining, sysmessages |
| 860 |
|
| 861 |
def interpreted_or_phrase_ref(self, match, lineno): |
| 862 |
end_pattern = self.patterns.interpreted_or_phrase_ref |
| 863 |
string = match.string |
| 864 |
matchstart = match.start('backquote') |
| 865 |
matchend = match.end('backquote') |
| 866 |
rolestart = match.start('role') |
| 867 |
role = match.group('role') |
| 868 |
position = '' |
| 869 |
if role: |
| 870 |
role = role[1:-1] |
| 871 |
position = 'prefix' |
| 872 |
elif self.quoted_start(match): |
| 873 |
return string[:matchend], [], string[matchend:], [] |
| 874 |
endmatch = end_pattern.search(string[matchend:]) |
| 875 |
if endmatch and endmatch.start(1): |
| 876 |
textend = matchend + endmatch.end() |
| 877 |
if endmatch.group('role'): |
| 878 |
if role: |
| 879 |
msg = self.reporter.warning( |
| 880 |
'Multiple roles in interpreted text (both ' |
| 881 |
'prefix and suffix present; only one allowed).', |
| 882 |
line=lineno) |
| 883 |
text = unescape(string[rolestart:textend], True) |
| 884 |
prb = self.problematic(text, text, msg) |
| 885 |
return string[:rolestart], [prb], string[textend:], [msg] |
| 886 |
role = endmatch.group('suffix')[1:-1] |
| 887 |
position = 'suffix' |
| 888 |
escaped = endmatch.string[:endmatch.start(1)] |
| 889 |
rawsource = unescape(string[matchstart:textend], True) |
| 890 |
if rawsource[-1:] == '_': |
| 891 |
if role: |
| 892 |
msg = self.reporter.warning( |
| 893 |
'Mismatch: both interpreted text role %s and ' |
| 894 |
'reference suffix.' % position, line=lineno) |
| 895 |
text = unescape(string[rolestart:textend], True) |
| 896 |
prb = self.problematic(text, text, msg) |
| 897 |
return string[:rolestart], [prb], string[textend:], [msg] |
| 898 |
return self.phrase_ref(string[:matchstart], string[textend:], |
| 899 |
rawsource, escaped) |
| 900 |
else: |
| 901 |
rawsource = unescape(string[rolestart:textend], True) |
| 902 |
nodelist, messages = self.interpreted(rawsource, escaped, role, |
| 903 |
lineno) |
| 904 |
return (string[:rolestart], nodelist, |
| 905 |
string[textend:], messages) |
| 906 |
msg = self.reporter.warning( |
| 907 |
'Inline interpreted text or phrase reference start-string ' |
| 908 |
'without end-string.', line=lineno) |
| 909 |
text = unescape(string[matchstart:matchend], True) |
| 910 |
prb = self.problematic(text, text, msg) |
| 911 |
return string[:matchstart], [prb], string[matchend:], [msg] |
| 912 |
|
| 913 |
def phrase_ref(self, before, after, rawsource, escaped, text=None): |
| 914 |
|
| 915 |
match = self.patterns.embedded_link.search(escaped) |
| 916 |
if match: |
| 917 |
text = escaped[:match.start(0)] |
| 918 |
unescaped = unescape(text) |
| 919 |
rawtext = unescape(text, True) |
| 920 |
aliastext = match.group(2) |
| 921 |
rawaliastext = unescape(aliastext, True) |
| 922 |
underscore_escaped = rawaliastext.endswith(r'\_') |
| 923 |
if (aliastext.endswith('_') |
| 924 |
and not (underscore_escaped |
| 925 |
or self.patterns.uri.match(aliastext))): |
| 926 |
aliastype = 'name' |
| 927 |
alias = normalize_name(unescape(aliastext[:-1])) |
| 928 |
target = nodes.target(match.group(1), refname=alias) |
| 929 |
target.indirect_reference_name = whitespace_normalize_name( |
| 930 |
unescape(aliastext[:-1])) |
| 931 |
else: |
| 932 |
aliastype = 'uri' |
| 933 |
|
| 934 |
alias_parts = split_escaped_whitespace(match.group(2)) |
| 935 |
alias = ' '.join(''.join(part.split()) |
| 936 |
for part in alias_parts) |
| 937 |
alias = self.adjust_uri(unescape(alias)) |
| 938 |
if alias.endswith(r'\_'): |
| 939 |
alias = alias[:-2] + '_' |
| 940 |
target = nodes.target(match.group(1), refuri=alias) |
| 941 |
target.referenced = 1 |
| 942 |
if not aliastext: |
| 943 |
raise ApplicationError('problem with embedded link: %r' |
| 944 |
% aliastext) |
| 945 |
if not text: |
| 946 |
text = alias |
| 947 |
unescaped = unescape(text) |
| 948 |
rawtext = rawaliastext |
| 949 |
else: |
| 950 |
text = escaped |
| 951 |
unescaped = unescape(text) |
| 952 |
target = None |
| 953 |
rawtext = unescape(escaped, True) |
| 954 |
|
| 955 |
refname = normalize_name(unescaped) |
| 956 |
reference = nodes.reference(rawsource, text, |
| 957 |
name=whitespace_normalize_name(unescaped)) |
| 958 |
reference[0].rawsource = rawtext |
| 959 |
|
| 960 |
node_list = [reference] |
| 961 |
|
| 962 |
if rawsource[-2:] == '__': |
| 963 |
if target and (aliastype == 'name'): |
| 964 |
reference['refname'] = alias |
| 965 |
self.document.note_refname(reference) |
| 966 |
|
| 967 |
elif target and (aliastype == 'uri'): |
| 968 |
reference['refuri'] = alias |
| 969 |
else: |
| 970 |
reference['anonymous'] = True |
| 971 |
else: |
| 972 |
if target: |
| 973 |
target['names'].append(refname) |
| 974 |
if aliastype == 'name': |
| 975 |
reference['refname'] = alias |
| 976 |
self.document.note_indirect_target(target) |
| 977 |
self.document.note_refname(reference) |
| 978 |
else: |
| 979 |
reference['refuri'] = alias |
| 980 |
|
| 981 |
self.document.note_implicit_target(target, self.parent) |
| 982 |
node_list.append(target) |
| 983 |
else: |
| 984 |
reference['refname'] = refname |
| 985 |
self.document.note_refname(reference) |
| 986 |
return before, node_list, after, [] |
| 987 |
|
| 988 |
def adjust_uri(self, uri): |
| 989 |
match = self.patterns.email.match(uri) |
| 990 |
if match: |
| 991 |
return 'mailto:' + uri |
| 992 |
else: |
| 993 |
return uri |
| 994 |
|
| 995 |
def interpreted(self, rawsource, text, role, lineno): |
| 996 |
role_fn, messages = roles.role(role, self.language, lineno, |
| 997 |
self.reporter) |
| 998 |
if role_fn: |
| 999 |
nodes, messages2 = role_fn(role, rawsource, text, lineno, self) |
| 1000 |
return nodes, messages + messages2 |
| 1001 |
else: |
| 1002 |
msg = self.reporter.error( |
| 1003 |
'Unknown interpreted text role "%s".' % role, |
| 1004 |
line=lineno) |
| 1005 |
return ([self.problematic(rawsource, rawsource, msg)], |
| 1006 |
messages + [msg]) |
| 1007 |
|
| 1008 |
def literal(self, match, lineno): |
| 1009 |
before, inlines, remaining, sysmessages, endstring = self.inline_obj( |
| 1010 |
match, lineno, self.patterns.literal, nodes.literal, |
| 1011 |
restore_backslashes=True) |
| 1012 |
return before, inlines, remaining, sysmessages |
| 1013 |
|
| 1014 |
def inline_internal_target(self, match, lineno): |
| 1015 |
before, inlines, remaining, sysmessages, endstring = self.inline_obj( |
| 1016 |
match, lineno, self.patterns.target, nodes.target) |
| 1017 |
if inlines and isinstance(inlines[0], nodes.target): |
| 1018 |
assert len(inlines) == 1 |
| 1019 |
target = inlines[0] |
| 1020 |
name = normalize_name(target.astext()) |
| 1021 |
target['names'].append(name) |
| 1022 |
self.document.note_explicit_target(target, self.parent) |
| 1023 |
return before, inlines, remaining, sysmessages |
| 1024 |
|
| 1025 |
def substitution_reference(self, match, lineno): |
| 1026 |
before, inlines, remaining, sysmessages, endstring = self.inline_obj( |
| 1027 |
match, lineno, self.patterns.substitution_ref, |
| 1028 |
nodes.substitution_reference) |
| 1029 |
if len(inlines) == 1: |
| 1030 |
subref_node = inlines[0] |
| 1031 |
if isinstance(subref_node, nodes.substitution_reference): |
| 1032 |
subref_text = subref_node.astext() |
| 1033 |
self.document.note_substitution_ref(subref_node, subref_text) |
| 1034 |
if endstring[-1:] == '_': |
| 1035 |
reference_node = nodes.reference( |
| 1036 |
'|%s%s' % (subref_text, endstring), '') |
| 1037 |
if endstring[-2:] == '__': |
| 1038 |
reference_node['anonymous'] = True |
| 1039 |
else: |
| 1040 |
reference_node['refname'] = normalize_name(subref_text) |
| 1041 |
self.document.note_refname(reference_node) |
| 1042 |
reference_node += subref_node |
| 1043 |
inlines = [reference_node] |
| 1044 |
return before, inlines, remaining, sysmessages |
| 1045 |
|
| 1046 |
def footnote_reference(self, match, lineno): |
| 1047 |
""" |
| 1048 |
Handles `nodes.footnote_reference` and `nodes.citation_reference` |
| 1049 |
elements. |
| 1050 |
""" |
| 1051 |
label = match.group('footnotelabel') |
| 1052 |
refname = normalize_name(label) |
| 1053 |
string = match.string |
| 1054 |
before = string[:match.start('whole')] |
| 1055 |
remaining = string[match.end('whole'):] |
| 1056 |
if match.group('citationlabel'): |
| 1057 |
refnode = nodes.citation_reference('[%s]_' % label, |
| 1058 |
refname=refname) |
| 1059 |
refnode += nodes.Text(label) |
| 1060 |
self.document.note_citation_ref(refnode) |
| 1061 |
else: |
| 1062 |
refnode = nodes.footnote_reference('[%s]_' % label) |
| 1063 |
if refname[0] == '#': |
| 1064 |
refname = refname[1:] |
| 1065 |
refnode['auto'] = 1 |
| 1066 |
self.document.note_autofootnote_ref(refnode) |
| 1067 |
elif refname == '*': |
| 1068 |
refname = '' |
| 1069 |
refnode['auto'] = '*' |
| 1070 |
self.document.note_symbol_footnote_ref( |
| 1071 |
refnode) |
| 1072 |
else: |
| 1073 |
refnode += nodes.Text(label) |
| 1074 |
if refname: |
| 1075 |
refnode['refname'] = refname |
| 1076 |
self.document.note_footnote_ref(refnode) |
| 1077 |
if utils.get_trim_footnote_ref_space(self.document.settings): |
| 1078 |
before = before.rstrip() |
| 1079 |
return before, [refnode], remaining, [] |
| 1080 |
|
| 1081 |
def reference(self, match, lineno, anonymous=False): |
| 1082 |
referencename = match.group('refname') |
| 1083 |
refname = normalize_name(referencename) |
| 1084 |
referencenode = nodes.reference( |
| 1085 |
referencename + match.group('refend'), referencename, |
| 1086 |
name=whitespace_normalize_name(referencename)) |
| 1087 |
referencenode[0].rawsource = referencename |
| 1088 |
if anonymous: |
| 1089 |
referencenode['anonymous'] = True |
| 1090 |
else: |
| 1091 |
referencenode['refname'] = refname |
| 1092 |
self.document.note_refname(referencenode) |
| 1093 |
string = match.string |
| 1094 |
matchstart = match.start('whole') |
| 1095 |
matchend = match.end('whole') |
| 1096 |
return string[:matchstart], [referencenode], string[matchend:], [] |
| 1097 |
|
| 1098 |
def anonymous_reference(self, match, lineno): |
| 1099 |
return self.reference(match, lineno, anonymous=True) |
| 1100 |
|
| 1101 |
def standalone_uri(self, match, lineno): |
| 1102 |
if (not match.group('scheme') |
| 1103 |
or match.group('scheme').lower() in urischemes.schemes): |
| 1104 |
if match.group('email'): |
| 1105 |
addscheme = 'mailto:' |
| 1106 |
else: |
| 1107 |
addscheme = '' |
| 1108 |
text = match.group('whole') |
| 1109 |
refuri = addscheme + unescape(text) |
| 1110 |
reference = nodes.reference(unescape(text, True), text, |
| 1111 |
refuri=refuri) |
| 1112 |
return [reference] |
| 1113 |
else: |
| 1114 |
raise MarkupMismatch |
| 1115 |
|
| 1116 |
def pep_reference(self, match, lineno): |
| 1117 |
text = match.group(0) |
| 1118 |
if text.startswith('pep-'): |
| 1119 |
pepnum = int(unescape(match.group('pepnum1'))) |
| 1120 |
elif text.startswith('PEP'): |
| 1121 |
pepnum = int(unescape(match.group('pepnum2'))) |
| 1122 |
else: |
| 1123 |
raise MarkupMismatch |
| 1124 |
ref = (self.document.settings.pep_base_url |
| 1125 |
+ self.document.settings.pep_file_url_template % pepnum) |
| 1126 |
return [nodes.reference(unescape(text, True), text, refuri=ref)] |
| 1127 |
|
| 1128 |
rfc_url = 'rfc%d.html' |
| 1129 |
|
| 1130 |
def rfc_reference(self, match, lineno): |
| 1131 |
text = match.group(0) |
| 1132 |
if text.startswith('RFC'): |
| 1133 |
rfcnum = int(unescape(match.group('rfcnum'))) |
| 1134 |
ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum |
| 1135 |
else: |
| 1136 |
raise MarkupMismatch |
| 1137 |
return [nodes.reference(unescape(text, True), text, refuri=ref)] |
| 1138 |
|
| 1139 |
def implicit_inline(self, text, lineno): |
| 1140 |
""" |
| 1141 |
Check each of the patterns in `self.implicit_dispatch` for a match, |
| 1142 |
and dispatch to the stored method for the pattern. Recursively check |
| 1143 |
the text before and after the match. Return a list of `nodes.Text` |
| 1144 |
and inline element nodes. |
| 1145 |
""" |
| 1146 |
if not text: |
| 1147 |
return [] |
| 1148 |
for pattern, method in self.implicit_dispatch: |
| 1149 |
match = pattern.search(text) |
| 1150 |
if match: |
| 1151 |
try: |
| 1152 |
|
| 1153 |
|
| 1154 |
return (self.implicit_inline(text[:match.start()], lineno) |
| 1155 |
+ method(match, lineno) |
| 1156 |
+ self.implicit_inline(text[match.end():], lineno)) |
| 1157 |
except MarkupMismatch: |
| 1158 |
pass |
| 1159 |
return [nodes.Text(text)] |
| 1160 |
|
| 1161 |
dispatch = {'*': emphasis, |
| 1162 |
'**': strong, |
| 1163 |
'`': interpreted_or_phrase_ref, |
| 1164 |
'``': literal, |
| 1165 |
'_`': inline_internal_target, |
| 1166 |
']_': footnote_reference, |
| 1167 |
'|': substitution_reference, |
| 1168 |
'_': reference, |
| 1169 |
'__': anonymous_reference} |
| 1170 |
|
| 1171 |
|
| 1172 |
def _loweralpha_to_int(s, _zero=(ord('a')-1)): |
| 1173 |
return ord(s) - _zero |
| 1174 |
|
| 1175 |
|
| 1176 |
def _upperalpha_to_int(s, _zero=(ord('A')-1)): |
| 1177 |
return ord(s) - _zero |
| 1178 |
|
| 1179 |
|
| 1180 |
class Body(RSTState): |
| 1181 |
|
| 1182 |
""" |
| 1183 |
Generic classifier of the first line of a block. |
| 1184 |
""" |
| 1185 |
|
| 1186 |
double_width_pad_char = tableparser.TableParser.double_width_pad_char |
| 1187 |
"""Padding character for East Asian double-width text.""" |
| 1188 |
|
| 1189 |
enum = Struct() |
| 1190 |
"""Enumerated list parsing information.""" |
| 1191 |
|
| 1192 |
enum.formatinfo = { |
| 1193 |
'parens': Struct(prefix='(', suffix=')', start=1, end=-1), |
| 1194 |
'rparen': Struct(prefix='', suffix=')', start=0, end=-1), |
| 1195 |
'period': Struct(prefix='', suffix='.', start=0, end=-1)} |
| 1196 |
enum.formats = enum.formatinfo.keys() |
| 1197 |
enum.sequences = ['arabic', 'loweralpha', 'upperalpha', |
| 1198 |
'lowerroman', 'upperroman'] |
| 1199 |
enum.sequencepats = {'arabic': '[0-9]+', |
| 1200 |
'loweralpha': '[a-z]', |
| 1201 |
'upperalpha': '[A-Z]', |
| 1202 |
'lowerroman': '[ivxlcdm]+', |
| 1203 |
'upperroman': '[IVXLCDM]+'} |
| 1204 |
enum.converters = {'arabic': int, |
| 1205 |
'loweralpha': _loweralpha_to_int, |
| 1206 |
'upperalpha': _upperalpha_to_int, |
| 1207 |
'lowerroman': RomanNumeral.from_string, |
| 1208 |
'upperroman': RomanNumeral.from_string} |
| 1209 |
|
| 1210 |
enum.sequenceregexps = {} |
| 1211 |
for sequence in enum.sequences: |
| 1212 |
enum.sequenceregexps[sequence] = re.compile( |
| 1213 |
enum.sequencepats[sequence] + '$') |
| 1214 |
|
| 1215 |
grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$') |
| 1216 |
"""Matches the top (& bottom) of a full table).""" |
| 1217 |
|
| 1218 |
simple_table_top_pat = re.compile('=+( +=+)+ *$') |
| 1219 |
"""Matches the top of a simple table.""" |
| 1220 |
|
| 1221 |
simple_table_border_pat = re.compile('=+[ =]*$') |
| 1222 |
"""Matches the bottom & header bottom of a simple table.""" |
| 1223 |
|
| 1224 |
pats = {} |
| 1225 |
"""Fragments of patterns used by transitions.""" |
| 1226 |
|
| 1227 |
pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]' |
| 1228 |
pats['alpha'] = '[a-zA-Z]' |
| 1229 |
pats['alphanum'] = '[a-zA-Z0-9]' |
| 1230 |
pats['alphanumplus'] = '[a-zA-Z0-9_-]' |
| 1231 |
pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s' |
| 1232 |
'|%(upperroman)s|#)' % enum.sequencepats) |
| 1233 |
pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats |
| 1234 |
|
| 1235 |
pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats |
| 1236 |
pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats |
| 1237 |
pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats |
| 1238 |
pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats |
| 1239 |
|
| 1240 |
for format in enum.formats: |
| 1241 |
pats[format] = '(?P<%s>%s%s%s)' % ( |
| 1242 |
format, re.escape(enum.formatinfo[format].prefix), |
| 1243 |
pats['enum'], re.escape(enum.formatinfo[format].suffix)) |
| 1244 |
|
| 1245 |
patterns = { |
| 1246 |
'bullet': '[-+*\u2022\u2023\u2043]( +|$)', |
| 1247 |
'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats, |
| 1248 |
'field_marker': r':(?![: ])([^:\\]|\\.|:(?!([ `]|$)))*(?<! ):( +|$)', |
| 1249 |
'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats, |
| 1250 |
'doctest': r'>>>( +|$)', |
| 1251 |
'line_block': r'\|( +|$)', |
| 1252 |
'grid_table_top': grid_table_top_pat, |
| 1253 |
'simple_table_top': simple_table_top_pat, |
| 1254 |
'explicit_markup': r'\.\.( +|$)', |
| 1255 |
'anonymous': r'__( +|$)', |
| 1256 |
'line': r'(%(nonalphanum7bit)s)\1* *$' % pats, |
| 1257 |
'text': r''} |
| 1258 |
initial_transitions = ( |
| 1259 |
'bullet', |
| 1260 |
'enumerator', |
| 1261 |
'field_marker', |
| 1262 |
'option_marker', |
| 1263 |
'doctest', |
| 1264 |
'line_block', |
| 1265 |
'grid_table_top', |
| 1266 |
'simple_table_top', |
| 1267 |
'explicit_markup', |
| 1268 |
'anonymous', |
| 1269 |
'line', |
| 1270 |
'text') |
| 1271 |
|
| 1272 |
def indent(self, match, context, next_state): |
| 1273 |
"""Block quote.""" |
| 1274 |
(indented, indent, line_offset, blank_finish |
| 1275 |
) = self.state_machine.get_indented() |
| 1276 |
elements = self.block_quote(indented, line_offset) |
| 1277 |
self.parent += elements |
| 1278 |
if not blank_finish: |
| 1279 |
self.parent += self.unindent_warning('Block quote') |
| 1280 |
return context, next_state, [] |
| 1281 |
|
| 1282 |
def block_quote(self, indented, line_offset): |
| 1283 |
elements = [] |
| 1284 |
while indented: |
| 1285 |
blockquote = nodes.block_quote(rawsource='\n'.join(indented)) |
| 1286 |
(blockquote.source, blockquote.line |
| 1287 |
) = self.state_machine.get_source_and_line(line_offset+1) |
| 1288 |
(blockquote_lines, |
| 1289 |
attribution_lines, |
| 1290 |
attribution_offset, |
| 1291 |
indented, |
| 1292 |
new_line_offset) = self.split_attribution(indented, line_offset) |
| 1293 |
self.nested_parse(blockquote_lines, line_offset, blockquote) |
| 1294 |
elements.append(blockquote) |
| 1295 |
if attribution_lines: |
| 1296 |
attribution, messages = self.parse_attribution( |
| 1297 |
attribution_lines, line_offset+attribution_offset) |
| 1298 |
blockquote += attribution |
| 1299 |
elements += messages |
| 1300 |
line_offset = new_line_offset |
| 1301 |
while indented and not indented[0]: |
| 1302 |
indented = indented[1:] |
| 1303 |
line_offset += 1 |
| 1304 |
return elements |
| 1305 |
|
| 1306 |
|
| 1307 |
attribution_pattern = re.compile('(---?(?!-)|\u2014) *(?=[^ \\n])') |
| 1308 |
|
| 1309 |
def split_attribution(self, indented, line_offset): |
| 1310 |
""" |
| 1311 |
Check for a block quote attribution and split it off: |
| 1312 |
|
| 1313 |
* First line after a blank line must begin with a dash ("--", "---", |
| 1314 |
em-dash; matches `self.attribution_pattern`). |
| 1315 |
* Every line after that must have consistent indentation. |
| 1316 |
* Attributions must be preceded by block quote content. |
| 1317 |
|
| 1318 |
Return a tuple of: (block quote content lines, attribution lines, |
| 1319 |
attribution offset, remaining indented lines, remaining lines offset). |
| 1320 |
""" |
| 1321 |
blank = None |
| 1322 |
nonblank_seen = False |
| 1323 |
for i in range(len(indented)): |
| 1324 |
line = indented[i].rstrip() |
| 1325 |
if line: |
| 1326 |
if nonblank_seen and blank == i - 1: |
| 1327 |
match = self.attribution_pattern.match(line) |
| 1328 |
if match: |
| 1329 |
attribution_end, indent = self.check_attribution( |
| 1330 |
indented, i) |
| 1331 |
if attribution_end: |
| 1332 |
a_lines = indented[i:attribution_end] |
| 1333 |
a_lines.trim_left(match.end(), end=1) |
| 1334 |
a_lines.trim_left(indent, start=1) |
| 1335 |
return (indented[:i], a_lines, |
| 1336 |
i, indented[attribution_end:], |
| 1337 |
line_offset + attribution_end) |
| 1338 |
nonblank_seen = True |
| 1339 |
else: |
| 1340 |
blank = i |
| 1341 |
else: |
| 1342 |
return indented, None, None, None, None |
| 1343 |
|
| 1344 |
def check_attribution(self, indented, attribution_start): |
| 1345 |
""" |
| 1346 |
Check attribution shape. |
| 1347 |
Return the index past the end of the attribution, and the indent. |
| 1348 |
""" |
| 1349 |
indent = None |
| 1350 |
i = attribution_start + 1 |
| 1351 |
for i in range(attribution_start + 1, len(indented)): |
| 1352 |
line = indented[i].rstrip() |
| 1353 |
if not line: |
| 1354 |
break |
| 1355 |
if indent is None: |
| 1356 |
indent = len(line) - len(line.lstrip()) |
| 1357 |
elif len(line) - len(line.lstrip()) != indent: |
| 1358 |
return None, None |
| 1359 |
else: |
| 1360 |
|
| 1361 |
i += 1 |
| 1362 |
return i, (indent or 0) |
| 1363 |
|
| 1364 |
def parse_attribution(self, indented, line_offset): |
| 1365 |
text = '\n'.join(indented).rstrip() |
| 1366 |
lineno = 1 + line_offset |
| 1367 |
textnodes, messages = self.inline_text(text, lineno) |
| 1368 |
node = nodes.attribution(text, '', *textnodes) |
| 1369 |
node.source, node.line = self.state_machine.get_source_and_line(lineno) |
| 1370 |
return node, messages |
| 1371 |
|
| 1372 |
def bullet(self, match, context, next_state): |
| 1373 |
"""Bullet list item.""" |
| 1374 |
ul = nodes.bullet_list() |
| 1375 |
ul.source, ul.line = self.state_machine.get_source_and_line() |
| 1376 |
self.parent += ul |
| 1377 |
ul['bullet'] = match.string[0] |
| 1378 |
i, blank_finish = self.list_item(match.end()) |
| 1379 |
ul += i |
| 1380 |
offset = self.state_machine.line_offset + 1 |
| 1381 |
new_line_offset, blank_finish = self.nested_list_parse( |
| 1382 |
self.state_machine.input_lines[offset:], |
| 1383 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 1384 |
node=ul, initial_state='BulletList', |
| 1385 |
blank_finish=blank_finish) |
| 1386 |
self.goto_line(new_line_offset) |
| 1387 |
if not blank_finish: |
| 1388 |
self.parent += self.unindent_warning('Bullet list') |
| 1389 |
return [], next_state, [] |
| 1390 |
|
| 1391 |
def list_item(self, indent): |
| 1392 |
src, srcline = self.state_machine.get_source_and_line() |
| 1393 |
if self.state_machine.line[indent:]: |
| 1394 |
indented, line_offset, blank_finish = ( |
| 1395 |
self.state_machine.get_known_indented(indent)) |
| 1396 |
else: |
| 1397 |
indented, indent, line_offset, blank_finish = ( |
| 1398 |
self.state_machine.get_first_known_indented(indent)) |
| 1399 |
listitem = nodes.list_item('\n'.join(indented)) |
| 1400 |
listitem.source, listitem.line = src, srcline |
| 1401 |
if indented: |
| 1402 |
self.nested_parse(indented, input_offset=line_offset, |
| 1403 |
node=listitem) |
| 1404 |
return listitem, blank_finish |
| 1405 |
|
| 1406 |
def enumerator(self, match, context, next_state): |
| 1407 |
"""Enumerated List Item""" |
| 1408 |
format, sequence, text, ordinal = self.parse_enumerator(match) |
| 1409 |
if not self.is_enumerated_list_item(ordinal, sequence, format): |
| 1410 |
raise statemachine.TransitionCorrection('text') |
| 1411 |
enumlist = nodes.enumerated_list() |
| 1412 |
(enumlist.source, |
| 1413 |
enumlist.line) = self.state_machine.get_source_and_line() |
| 1414 |
self.parent += enumlist |
| 1415 |
if sequence == '#': |
| 1416 |
enumlist['enumtype'] = 'arabic' |
| 1417 |
else: |
| 1418 |
enumlist['enumtype'] = sequence |
| 1419 |
enumlist['prefix'] = self.enum.formatinfo[format].prefix |
| 1420 |
enumlist['suffix'] = self.enum.formatinfo[format].suffix |
| 1421 |
if ordinal != 1: |
| 1422 |
enumlist['start'] = ordinal |
| 1423 |
msg = self.reporter.info( |
| 1424 |
'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' |
| 1425 |
% (text, ordinal), base_node=enumlist) |
| 1426 |
self.parent += msg |
| 1427 |
listitem, blank_finish = self.list_item(match.end()) |
| 1428 |
enumlist += listitem |
| 1429 |
offset = self.state_machine.line_offset + 1 |
| 1430 |
newline_offset, blank_finish = self.nested_list_parse( |
| 1431 |
self.state_machine.input_lines[offset:], |
| 1432 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 1433 |
node=enumlist, initial_state='EnumeratedList', |
| 1434 |
blank_finish=blank_finish, |
| 1435 |
extra_settings={'lastordinal': ordinal, |
| 1436 |
'format': format, |
| 1437 |
'auto': sequence == '#'}) |
| 1438 |
self.goto_line(newline_offset) |
| 1439 |
if not blank_finish: |
| 1440 |
self.parent += self.unindent_warning('Enumerated list') |
| 1441 |
return [], next_state, [] |
| 1442 |
|
| 1443 |
def parse_enumerator(self, match, expected_sequence=None): |
| 1444 |
""" |
| 1445 |
Analyze an enumerator and return the results. |
| 1446 |
|
| 1447 |
:Return: |
| 1448 |
- the enumerator format ('period', 'parens', or 'rparen'), |
| 1449 |
- the sequence used ('arabic', 'loweralpha', 'upperroman', etc.), |
| 1450 |
- the text of the enumerator, stripped of formatting, and |
| 1451 |
- the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.; |
| 1452 |
``None`` is returned for invalid enumerator text). |
| 1453 |
|
| 1454 |
The enumerator format has already been determined by the regular |
| 1455 |
expression match. If `expected_sequence` is given, that sequence is |
| 1456 |
tried first. If not, we check for Roman numeral 1. This way, |
| 1457 |
single-character Roman numerals (which are also alphabetical) can be |
| 1458 |
matched. If no sequence has been matched, all sequences are checked in |
| 1459 |
order. |
| 1460 |
""" |
| 1461 |
groupdict = match.groupdict() |
| 1462 |
sequence = '' |
| 1463 |
for format in self.enum.formats: |
| 1464 |
if groupdict[format]: |
| 1465 |
break |
| 1466 |
else: |
| 1467 |
raise ParserError('enumerator format not matched') |
| 1468 |
text = groupdict[format][self.enum.formatinfo[format].start |
| 1469 |
: self.enum.formatinfo[format].end] |
| 1470 |
if text == '#': |
| 1471 |
sequence = '#' |
| 1472 |
elif expected_sequence: |
| 1473 |
try: |
| 1474 |
if self.enum.sequenceregexps[expected_sequence].match(text): |
| 1475 |
sequence = expected_sequence |
| 1476 |
except KeyError: |
| 1477 |
raise ParserError('unknown enumerator sequence: %s' |
| 1478 |
% sequence) |
| 1479 |
elif text == 'i': |
| 1480 |
sequence = 'lowerroman' |
| 1481 |
elif text == 'I': |
| 1482 |
sequence = 'upperroman' |
| 1483 |
if not sequence: |
| 1484 |
for sequence in self.enum.sequences: |
| 1485 |
if self.enum.sequenceregexps[sequence].match(text): |
| 1486 |
break |
| 1487 |
else: |
| 1488 |
raise ParserError('enumerator sequence not matched') |
| 1489 |
if sequence == '#': |
| 1490 |
ordinal = 1 |
| 1491 |
else: |
| 1492 |
try: |
| 1493 |
ordinal = int(self.enum.converters[sequence](text)) |
| 1494 |
except InvalidRomanNumeralError: |
| 1495 |
ordinal = None |
| 1496 |
return format, sequence, text, ordinal |
| 1497 |
|
| 1498 |
def is_enumerated_list_item(self, ordinal, sequence, format): |
| 1499 |
""" |
| 1500 |
Check validity based on the ordinal value and the second line. |
| 1501 |
|
| 1502 |
Return true if the ordinal is valid and the second line is blank, |
| 1503 |
indented, or starts with the next enumerator or an auto-enumerator. |
| 1504 |
""" |
| 1505 |
if ordinal is None: |
| 1506 |
return None |
| 1507 |
try: |
| 1508 |
next_line = self.state_machine.next_line() |
| 1509 |
except EOFError: |
| 1510 |
self.state_machine.previous_line() |
| 1511 |
return 1 |
| 1512 |
else: |
| 1513 |
self.state_machine.previous_line() |
| 1514 |
if not next_line[:1].strip(): |
| 1515 |
return 1 |
| 1516 |
result = self.make_enumerator(ordinal + 1, sequence, format) |
| 1517 |
if result: |
| 1518 |
next_enumerator, auto_enumerator = result |
| 1519 |
try: |
| 1520 |
if next_line.startswith((next_enumerator, auto_enumerator)): |
| 1521 |
return 1 |
| 1522 |
except TypeError: |
| 1523 |
pass |
| 1524 |
return None |
| 1525 |
|
| 1526 |
def make_enumerator(self, ordinal, sequence, format): |
| 1527 |
""" |
| 1528 |
Construct and return the next enumerated list item marker, and an |
| 1529 |
auto-enumerator ("#" instead of the regular enumerator). |
| 1530 |
|
| 1531 |
Return ``None`` for invalid (out of range) ordinals. |
| 1532 |
""" |
| 1533 |
if sequence == '#': |
| 1534 |
enumerator = '#' |
| 1535 |
elif sequence == 'arabic': |
| 1536 |
enumerator = str(ordinal) |
| 1537 |
else: |
| 1538 |
if sequence.endswith('alpha'): |
| 1539 |
if ordinal > 26: |
| 1540 |
return None |
| 1541 |
enumerator = chr(ordinal + ord('a') - 1) |
| 1542 |
elif sequence.endswith('roman'): |
| 1543 |
try: |
| 1544 |
enumerator = RomanNumeral(ordinal).to_uppercase() |
| 1545 |
except TypeError: |
| 1546 |
return None |
| 1547 |
else: |
| 1548 |
raise ParserError('unknown enumerator sequence: "%s"' |
| 1549 |
% sequence) |
| 1550 |
if sequence.startswith('lower'): |
| 1551 |
enumerator = enumerator.lower() |
| 1552 |
elif sequence.startswith('upper'): |
| 1553 |
enumerator = enumerator.upper() |
| 1554 |
else: |
| 1555 |
raise ParserError('unknown enumerator sequence: "%s"' |
| 1556 |
% sequence) |
| 1557 |
formatinfo = self.enum.formatinfo[format] |
| 1558 |
next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix |
| 1559 |
+ ' ') |
| 1560 |
auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' ' |
| 1561 |
return next_enumerator, auto_enumerator |
| 1562 |
|
| 1563 |
def field_marker(self, match, context, next_state): |
| 1564 |
"""Field list item.""" |
| 1565 |
field_list = nodes.field_list() |
| 1566 |
self.parent += field_list |
| 1567 |
field, blank_finish = self.field(match) |
| 1568 |
field_list += field |
| 1569 |
offset = self.state_machine.line_offset + 1 |
| 1570 |
newline_offset, blank_finish = self.nested_list_parse( |
| 1571 |
self.state_machine.input_lines[offset:], |
| 1572 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 1573 |
node=field_list, initial_state='FieldList', |
| 1574 |
blank_finish=blank_finish) |
| 1575 |
self.goto_line(newline_offset) |
| 1576 |
if not blank_finish: |
| 1577 |
self.parent += self.unindent_warning('Field list') |
| 1578 |
return [], next_state, [] |
| 1579 |
|
| 1580 |
def field(self, match): |
| 1581 |
name = self.parse_field_marker(match) |
| 1582 |
src, srcline = self.state_machine.get_source_and_line() |
| 1583 |
lineno = self.state_machine.abs_line_number() |
| 1584 |
(indented, indent, line_offset, blank_finish |
| 1585 |
) = self.state_machine.get_first_known_indented(match.end()) |
| 1586 |
field_node = nodes.field() |
| 1587 |
field_node.source = src |
| 1588 |
field_node.line = srcline |
| 1589 |
name_nodes, name_messages = self.inline_text(name, lineno) |
| 1590 |
field_node += nodes.field_name(name, '', *name_nodes) |
| 1591 |
field_body = nodes.field_body('\n'.join(indented), *name_messages) |
| 1592 |
field_node += field_body |
| 1593 |
if indented: |
| 1594 |
self.parse_field_body(indented, line_offset, field_body) |
| 1595 |
return field_node, blank_finish |
| 1596 |
|
| 1597 |
def parse_field_marker(self, match): |
| 1598 |
"""Extract & return field name from a field marker match.""" |
| 1599 |
field = match.group()[1:] |
| 1600 |
field = field[:field.rfind(':')] |
| 1601 |
return field |
| 1602 |
|
| 1603 |
def parse_field_body(self, indented, offset, node) -> None: |
| 1604 |
self.nested_parse(indented, input_offset=offset, node=node) |
| 1605 |
|
| 1606 |
def option_marker(self, match, context, next_state): |
| 1607 |
"""Option list item.""" |
| 1608 |
optionlist = nodes.option_list() |
| 1609 |
(optionlist.source, optionlist.line |
| 1610 |
) = self.state_machine.get_source_and_line() |
| 1611 |
try: |
| 1612 |
listitem, blank_finish = self.option_list_item(match) |
| 1613 |
except MarkupError as error: |
| 1614 |
|
| 1615 |
msg = self.reporter.error('Invalid option list marker: %s' |
| 1616 |
% error) |
| 1617 |
self.parent += msg |
| 1618 |
(indented, indent, line_offset, blank_finish |
| 1619 |
) = self.state_machine.get_first_known_indented(match.end()) |
| 1620 |
elements = self.block_quote(indented, line_offset) |
| 1621 |
self.parent += elements |
| 1622 |
if not blank_finish: |
| 1623 |
self.parent += self.unindent_warning('Option list') |
| 1624 |
return [], next_state, [] |
| 1625 |
self.parent += optionlist |
| 1626 |
optionlist += listitem |
| 1627 |
offset = self.state_machine.line_offset + 1 |
| 1628 |
newline_offset, blank_finish = self.nested_list_parse( |
| 1629 |
self.state_machine.input_lines[offset:], |
| 1630 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 1631 |
node=optionlist, initial_state='OptionList', |
| 1632 |
blank_finish=blank_finish) |
| 1633 |
self.goto_line(newline_offset) |
| 1634 |
if not blank_finish: |
| 1635 |
self.parent += self.unindent_warning('Option list') |
| 1636 |
return [], next_state, [] |
| 1637 |
|
| 1638 |
def option_list_item(self, match): |
| 1639 |
offset = self.state_machine.abs_line_offset() |
| 1640 |
options = self.parse_option_marker(match) |
| 1641 |
(indented, indent, line_offset, blank_finish |
| 1642 |
) = self.state_machine.get_first_known_indented(match.end()) |
| 1643 |
if not indented: |
| 1644 |
self.goto_line(offset) |
| 1645 |
raise statemachine.TransitionCorrection('text') |
| 1646 |
option_group = nodes.option_group('', *options) |
| 1647 |
description = nodes.description('\n'.join(indented)) |
| 1648 |
option_list_item = nodes.option_list_item('', option_group, |
| 1649 |
description) |
| 1650 |
if indented: |
| 1651 |
self.nested_parse(indented, input_offset=line_offset, |
| 1652 |
node=description) |
| 1653 |
return option_list_item, blank_finish |
| 1654 |
|
| 1655 |
def parse_option_marker(self, match): |
| 1656 |
""" |
| 1657 |
Return a list of `node.option` and `node.option_argument` objects, |
| 1658 |
parsed from an option marker match. |
| 1659 |
|
| 1660 |
:Exception: `MarkupError` for invalid option markers. |
| 1661 |
""" |
| 1662 |
optlist = [] |
| 1663 |
|
| 1664 |
optionstrings = re.split(r', (?![^<]*>)', match.group().rstrip()) |
| 1665 |
for optionstring in optionstrings: |
| 1666 |
tokens = optionstring.split() |
| 1667 |
delimiter = ' ' |
| 1668 |
firstopt = tokens[0].split('=', 1) |
| 1669 |
if len(firstopt) > 1: |
| 1670 |
|
| 1671 |
tokens[:1] = firstopt |
| 1672 |
delimiter = '=' |
| 1673 |
elif (len(tokens[0]) > 2 |
| 1674 |
and ((tokens[0].startswith('-') |
| 1675 |
and not tokens[0].startswith('--')) |
| 1676 |
or tokens[0].startswith('+'))): |
| 1677 |
|
| 1678 |
tokens[:1] = [tokens[0][:2], tokens[0][2:]] |
| 1679 |
delimiter = '' |
| 1680 |
if len(tokens) > 1 and (tokens[1].startswith('<') |
| 1681 |
and tokens[-1].endswith('>')): |
| 1682 |
|
| 1683 |
tokens[1:] = [' '.join(tokens[1:])] |
| 1684 |
if 0 < len(tokens) <= 2: |
| 1685 |
option = nodes.option(optionstring) |
| 1686 |
option += nodes.option_string(tokens[0], tokens[0]) |
| 1687 |
if len(tokens) > 1: |
| 1688 |
option += nodes.option_argument(tokens[1], tokens[1], |
| 1689 |
delimiter=delimiter) |
| 1690 |
optlist.append(option) |
| 1691 |
else: |
| 1692 |
raise MarkupError( |
| 1693 |
'wrong number of option tokens (=%s), should be 1 or 2: ' |
| 1694 |
'"%s"' % (len(tokens), optionstring)) |
| 1695 |
return optlist |
| 1696 |
|
| 1697 |
def doctest(self, match, context, next_state): |
| 1698 |
line = self.document.current_line |
| 1699 |
data = '\n'.join(self.state_machine.get_text_block()) |
| 1700 |
|
| 1701 |
. |
| 1702 |
n = nodes.doctest_block(data, data) |
| 1703 |
n.line = line |
| 1704 |
self.parent += n |
| 1705 |
return [], next_state, [] |
| 1706 |
|
| 1707 |
def line_block(self, match, context, next_state): |
| 1708 |
"""First line of a line block.""" |
| 1709 |
block = nodes.line_block() |
| 1710 |
self.parent += block |
| 1711 |
lineno = self.state_machine.abs_line_number() |
| 1712 |
(block.source, |
| 1713 |
block.line) = self.state_machine.get_source_and_line(lineno) |
| 1714 |
line, messages, blank_finish = self.line_block_line(match, lineno) |
| 1715 |
block += line |
| 1716 |
self.parent += messages |
| 1717 |
if not blank_finish: |
| 1718 |
offset = self.state_machine.line_offset + 1 |
| 1719 |
new_line_offset, blank_finish = self.nested_list_parse( |
| 1720 |
self.state_machine.input_lines[offset:], |
| 1721 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 1722 |
node=block, initial_state='LineBlock', |
| 1723 |
blank_finish=False) |
| 1724 |
self.goto_line(new_line_offset) |
| 1725 |
if not blank_finish: |
| 1726 |
self.parent += self.reporter.warning( |
| 1727 |
'Line block ends without a blank line.', |
| 1728 |
line=lineno+1) |
| 1729 |
if len(block): |
| 1730 |
if block[0].indent is None: |
| 1731 |
block[0].indent = 0 |
| 1732 |
self.nest_line_block_lines(block) |
| 1733 |
return [], next_state, [] |
| 1734 |
|
| 1735 |
def line_block_line(self, match, lineno): |
| 1736 |
"""Return one line element of a line_block.""" |
| 1737 |
(indented, indent, line_offset, blank_finish |
| 1738 |
) = self.state_machine.get_first_known_indented(match.end(), |
| 1739 |
until_blank=True) |
| 1740 |
text = '\n'.join(indented) |
| 1741 |
text_nodes, messages = self.inline_text(text, lineno) |
| 1742 |
line = nodes.line(text, '', *text_nodes) |
| 1743 |
(line.source, |
| 1744 |
line.line) = self.state_machine.get_source_and_line(lineno) |
| 1745 |
if match.string.rstrip() != '|': |
| 1746 |
line.indent = len(match.group(1)) - 1 |
| 1747 |
return line, messages, blank_finish |
| 1748 |
|
| 1749 |
def nest_line_block_lines(self, block) -> None: |
| 1750 |
for index in range(1, len(block)): |
| 1751 |
if block[index].indent is None: |
| 1752 |
block[index].indent = block[index - 1].indent |
| 1753 |
self.nest_line_block_segment(block) |
| 1754 |
|
| 1755 |
def nest_line_block_segment(self, block) -> None: |
| 1756 |
indents = [item.indent for item in block] |
| 1757 |
least = min(indents) |
| 1758 |
new_items = [] |
| 1759 |
new_block = nodes.line_block() |
| 1760 |
for item in block: |
| 1761 |
if item.indent > least: |
| 1762 |
new_block.append(item) |
| 1763 |
else: |
| 1764 |
if len(new_block): |
| 1765 |
self.nest_line_block_segment(new_block) |
| 1766 |
new_items.append(new_block) |
| 1767 |
new_block = nodes.line_block() |
| 1768 |
new_items.append(item) |
| 1769 |
if len(new_block): |
| 1770 |
self.nest_line_block_segment(new_block) |
| 1771 |
new_items.append(new_block) |
| 1772 |
block[:] = new_items |
| 1773 |
|
| 1774 |
def grid_table_top(self, match, context, next_state): |
| 1775 |
"""Top border of a full table.""" |
| 1776 |
return self.table_top(match, context, next_state, |
| 1777 |
self.isolate_grid_table, |
| 1778 |
tableparser.GridTableParser) |
| 1779 |
|
| 1780 |
def simple_table_top(self, match, context, next_state): |
| 1781 |
"""Top border of a simple table.""" |
| 1782 |
return self.table_top(match, context, next_state, |
| 1783 |
self.isolate_simple_table, |
| 1784 |
tableparser.SimpleTableParser) |
| 1785 |
|
| 1786 |
def table_top(self, match, context, next_state, |
| 1787 |
isolate_function, parser_class): |
| 1788 |
"""Top border of a generic table.""" |
| 1789 |
nodelist, blank_finish = self.table(isolate_function, parser_class) |
| 1790 |
self.parent += nodelist |
| 1791 |
if not blank_finish: |
| 1792 |
msg = self.reporter.warning( |
| 1793 |
'Blank line required after table.', |
| 1794 |
line=self.state_machine.abs_line_number()+1) |
| 1795 |
self.parent += msg |
| 1796 |
return [], next_state, [] |
| 1797 |
|
| 1798 |
def table(self, isolate_function, parser_class): |
| 1799 |
"""Parse a table.""" |
| 1800 |
block, messages, blank_finish = isolate_function() |
| 1801 |
if block: |
| 1802 |
try: |
| 1803 |
parser = parser_class() |
| 1804 |
tabledata = parser.parse(block) |
| 1805 |
tableline = (self.state_machine.abs_line_number() - len(block) |
| 1806 |
+ 1) |
| 1807 |
table = self.build_table(tabledata, tableline) |
| 1808 |
nodelist = [table] + messages |
| 1809 |
except tableparser.TableMarkupError as err: |
| 1810 |
nodelist = self.malformed_table(block, ' '.join(err.args), |
| 1811 |
offset=err.offset) + messages |
| 1812 |
else: |
| 1813 |
nodelist = messages |
| 1814 |
return nodelist, blank_finish |
| 1815 |
|
| 1816 |
def isolate_grid_table(self): |
| 1817 |
messages = [] |
| 1818 |
blank_finish = True |
| 1819 |
try: |
| 1820 |
block = self.state_machine.get_text_block(flush_left=True) |
| 1821 |
except statemachine.UnexpectedIndentationError as err: |
| 1822 |
block, src, srcline = err.args |
| 1823 |
messages.append(self.reporter.error('Unexpected indentation.', |
| 1824 |
source=src, line=srcline)) |
| 1825 |
blank_finish = False |
| 1826 |
block.disconnect() |
| 1827 |
|
| 1828 |
block.pad_double_width(self.double_width_pad_char) |
| 1829 |
width = len(block[0].strip()) |
| 1830 |
for i in range(len(block)): |
| 1831 |
block[i] = block[i].strip() |
| 1832 |
if block[i][0] not in '+|': |
| 1833 |
blank_finish = False |
| 1834 |
self.state_machine.previous_line(len(block) - i) |
| 1835 |
del block[i:] |
| 1836 |
break |
| 1837 |
if not self.grid_table_top_pat.match(block[-1]): |
| 1838 |
|
| 1839 |
for i in range(len(block) - 2, 1, -1): |
| 1840 |
if self.grid_table_top_pat.match(block[i]): |
| 1841 |
self.state_machine.previous_line(len(block) - i + 1) |
| 1842 |
del block[i+1:] |
| 1843 |
blank_finish = False |
| 1844 |
break |
| 1845 |
else: |
| 1846 |
detail = 'Bottom border missing or corrupt.' |
| 1847 |
messages.extend(self.malformed_table(block, detail, i)) |
| 1848 |
return [], messages, blank_finish |
| 1849 |
for i in range(len(block)): |
| 1850 |
if len(strip_combining_chars(block[i]) |
| 1851 |
) != width or block[i][-1] not in '+|': |
| 1852 |
detail = 'Right border not aligned or missing.' |
| 1853 |
messages.extend(self.malformed_table(block, detail, i)) |
| 1854 |
return [], messages, blank_finish |
| 1855 |
return block, messages, blank_finish |
| 1856 |
|
| 1857 |
def isolate_simple_table(self): |
| 1858 |
start = self.state_machine.line_offset |
| 1859 |
lines = self.state_machine.input_lines |
| 1860 |
limit = len(lines) - 1 |
| 1861 |
toplen = len(lines[start].strip()) |
| 1862 |
pattern_match = self.simple_table_border_pat.match |
| 1863 |
found = 0 |
| 1864 |
found_at = None |
| 1865 |
i = start + 1 |
| 1866 |
while i <= limit: |
| 1867 |
line = lines[i] |
| 1868 |
match = pattern_match(line) |
| 1869 |
if match: |
| 1870 |
if len(line.strip()) != toplen: |
| 1871 |
self.state_machine.next_line(i - start) |
| 1872 |
messages = self.malformed_table( |
| 1873 |
lines[start:i+1], 'Bottom border or header rule does ' |
| 1874 |
'not match top border.', i-start) |
| 1875 |
return [], messages, i == limit or not lines[i+1].strip() |
| 1876 |
found += 1 |
| 1877 |
found_at = i |
| 1878 |
if found == 2 or i == limit or not lines[i+1].strip(): |
| 1879 |
end = i |
| 1880 |
break |
| 1881 |
i += 1 |
| 1882 |
else: |
| 1883 |
details = 'No bottom table border found' |
| 1884 |
if found: |
| 1885 |
details += ' or no blank line after table bottom' |
| 1886 |
self.state_machine.next_line(found_at - start) |
| 1887 |
block = lines[start:found_at+1] |
| 1888 |
else: |
| 1889 |
self.state_machine.next_line(i - start - 1) |
| 1890 |
block = lines[start:] |
| 1891 |
messages = self.malformed_table(block, details + '.') |
| 1892 |
return [], messages, not found |
| 1893 |
self.state_machine.next_line(end - start) |
| 1894 |
block = lines[start:end+1] |
| 1895 |
|
| 1896 |
block.pad_double_width(self.double_width_pad_char) |
| 1897 |
return block, [], end == limit or not lines[end+1].strip() |
| 1898 |
|
| 1899 |
def malformed_table(self, block, detail='', offset=0): |
| 1900 |
block.replace(self.double_width_pad_char, '') |
| 1901 |
data = '\n'.join(block) |
| 1902 |
message = 'Malformed table.' |
| 1903 |
startline = self.state_machine.abs_line_number() - len(block) + 1 |
| 1904 |
if detail: |
| 1905 |
message += '\n' + detail |
| 1906 |
error = self.reporter.error(message, nodes.literal_block(data, data), |
| 1907 |
line=startline+offset) |
| 1908 |
return [error] |
| 1909 |
|
| 1910 |
def build_table(self, tabledata, tableline, stub_columns=0, widths=None): |
| 1911 |
colwidths, headrows, bodyrows = tabledata |
| 1912 |
table = nodes.table() |
| 1913 |
(table.source, |
| 1914 |
table.line) = self.state_machine.get_source_and_line(tableline) |
| 1915 |
if widths == 'auto': |
| 1916 |
table['classes'] += ['colwidths-auto'] |
| 1917 |
elif widths: |
| 1918 |
table['classes'] += ['colwidths-given'] |
| 1919 |
tgroup = nodes.tgroup(cols=len(colwidths)) |
| 1920 |
table += tgroup |
| 1921 |
for colwidth in colwidths: |
| 1922 |
colspec = nodes.colspec(colwidth=colwidth) |
| 1923 |
if stub_columns: |
| 1924 |
colspec.attributes['stub'] = True |
| 1925 |
stub_columns -= 1 |
| 1926 |
tgroup += colspec |
| 1927 |
if headrows: |
| 1928 |
thead = nodes.thead() |
| 1929 |
tgroup += thead |
| 1930 |
for row in headrows: |
| 1931 |
thead += self.build_table_row(row, tableline) |
| 1932 |
tbody = nodes.tbody() |
| 1933 |
tgroup += tbody |
| 1934 |
for row in bodyrows: |
| 1935 |
tbody += self.build_table_row(row, tableline) |
| 1936 |
return table |
| 1937 |
|
| 1938 |
def build_table_row(self, rowdata, tableline): |
| 1939 |
row = nodes.row() |
| 1940 |
for cell in rowdata: |
| 1941 |
if cell is None: |
| 1942 |
continue |
| 1943 |
morerows, morecols, offset, cellblock = cell |
| 1944 |
attributes = {} |
| 1945 |
if morerows: |
| 1946 |
attributes['morerows'] = morerows |
| 1947 |
if morecols: |
| 1948 |
attributes['morecols'] = morecols |
| 1949 |
entry = nodes.entry(**attributes) |
| 1950 |
row += entry |
| 1951 |
if ''.join(cellblock): |
| 1952 |
self.nested_parse(cellblock, input_offset=tableline+offset-1, |
| 1953 |
node=entry) |
| 1954 |
return row |
| 1955 |
|
| 1956 |
explicit = Struct() |
| 1957 |
"""Patterns and constants used for explicit markup recognition.""" |
| 1958 |
|
| 1959 |
explicit.patterns = Struct( |
| 1960 |
target=re.compile(r""" |
| 1961 |
( |
| 1962 |
_ # anonymous target |
| 1963 |
| # *OR* |
| 1964 |
(?!_) # no underscore at the beginning |
| 1965 |
(?P<quote>`?) # optional open quote |
| 1966 |
(?![ `]) # first char. not space or |
| 1967 |
# backquote |
| 1968 |
(?P<name> # reference name |
| 1969 |
.+? |
| 1970 |
) |
| 1971 |
%(non_whitespace_escape_before)s |
| 1972 |
(?P=quote) # close quote if open quote used |
| 1973 |
) |
| 1974 |
(?<!(?<!\x00):) # no unescaped colon at end |
| 1975 |
%(non_whitespace_escape_before)s |
| 1976 |
[ ]? # optional space |
| 1977 |
: # end of reference name |
| 1978 |
([ ]+|$) # followed by whitespace |
| 1979 |
""" % vars(Inliner), re.VERBOSE), |
| 1980 |
reference=re.compile(r""" |
| 1981 |
( |
| 1982 |
(?P<simple>%(simplename)s)_ |
| 1983 |
| # *OR* |
| 1984 |
` # open backquote |
| 1985 |
(?![ ]) # not space |
| 1986 |
(?P<phrase>.+?) # hyperlink phrase |
| 1987 |
%(non_whitespace_escape_before)s |
| 1988 |
`_ # close backquote, |
| 1989 |
# reference mark |
| 1990 |
) |
| 1991 |
$ # end of string |
| 1992 |
""" % vars(Inliner), re.VERBOSE), |
| 1993 |
substitution=re.compile(r""" |
| 1994 |
( |
| 1995 |
(?![ ]) # first char. not space |
| 1996 |
(?P<name>.+?) # substitution text |
| 1997 |
%(non_whitespace_escape_before)s |
| 1998 |
\| # close delimiter |
| 1999 |
) |
| 2000 |
([ ]+|$) # followed by whitespace |
| 2001 |
""" % vars(Inliner), |
| 2002 |
re.VERBOSE),) |
| 2003 |
|
| 2004 |
def footnote(self, match): |
| 2005 |
src, srcline = self.state_machine.get_source_and_line() |
| 2006 |
(indented, indent, offset, blank_finish |
| 2007 |
) = self.state_machine.get_first_known_indented(match.end()) |
| 2008 |
label = match.group(1) |
| 2009 |
name = normalize_name(label) |
| 2010 |
footnote = nodes.footnote('\n'.join(indented)) |
| 2011 |
footnote.source = src |
| 2012 |
footnote.line = srcline |
| 2013 |
if name[0] == '#': |
| 2014 |
name = name[1:] |
| 2015 |
footnote['auto'] = 1 |
| 2016 |
if name: |
| 2017 |
footnote['names'].append(name) |
| 2018 |
self.document.note_autofootnote(footnote) |
| 2019 |
elif name == '*': |
| 2020 |
name = '' |
| 2021 |
footnote['auto'] = '*' |
| 2022 |
self.document.note_symbol_footnote(footnote) |
| 2023 |
else: |
| 2024 |
footnote += nodes.label('', label) |
| 2025 |
footnote['names'].append(name) |
| 2026 |
self.document.note_footnote(footnote) |
| 2027 |
if name: |
| 2028 |
self.document.note_explicit_target(footnote, footnote) |
| 2029 |
else: |
| 2030 |
self.document.set_id(footnote, footnote) |
| 2031 |
if indented: |
| 2032 |
self.nested_parse(indented, input_offset=offset, node=footnote) |
| 2033 |
else: |
| 2034 |
footnote += self.reporter.warning('Footnote content expected.') |
| 2035 |
return [footnote], blank_finish |
| 2036 |
|
| 2037 |
def citation(self, match): |
| 2038 |
src, srcline = self.state_machine.get_source_and_line() |
| 2039 |
(indented, indent, offset, blank_finish |
| 2040 |
) = self.state_machine.get_first_known_indented(match.end()) |
| 2041 |
label = match.group(1) |
| 2042 |
name = normalize_name(label) |
| 2043 |
citation = nodes.citation('\n'.join(indented)) |
| 2044 |
citation.source = src |
| 2045 |
citation.line = srcline |
| 2046 |
citation += nodes.label('', label) |
| 2047 |
citation['names'].append(name) |
| 2048 |
self.document.note_citation(citation) |
| 2049 |
self.document.note_explicit_target(citation, citation) |
| 2050 |
if indented: |
| 2051 |
self.nested_parse(indented, input_offset=offset, node=citation) |
| 2052 |
else: |
| 2053 |
citation += self.reporter.warning('Citation content expected.') |
| 2054 |
return [citation], blank_finish |
| 2055 |
|
| 2056 |
def hyperlink_target(self, match): |
| 2057 |
pattern = self.explicit.patterns.target |
| 2058 |
lineno = self.state_machine.abs_line_number() |
| 2059 |
(block, indent, offset, blank_finish |
| 2060 |
) = self.state_machine.get_first_known_indented( |
| 2061 |
match.end(), until_blank=True, strip_indent=False) |
| 2062 |
blocktext = match.string[:match.end()] + '\n'.join(block) |
| 2063 |
block = [escape2null(line) for line in block] |
| 2064 |
escaped = block[0] |
| 2065 |
blockindex = 0 |
| 2066 |
while True: |
| 2067 |
targetmatch = pattern.match(escaped) |
| 2068 |
if targetmatch: |
| 2069 |
break |
| 2070 |
blockindex += 1 |
| 2071 |
try: |
| 2072 |
escaped += block[blockindex] |
| 2073 |
except IndexError: |
| 2074 |
raise MarkupError('malformed hyperlink target.') |
| 2075 |
del block[:blockindex] |
| 2076 |
block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() |
| 2077 |
target = self.make_target(block, blocktext, lineno, |
| 2078 |
targetmatch.group('name')) |
| 2079 |
return [target], blank_finish |
| 2080 |
|
| 2081 |
def make_target(self, block, block_text, lineno, target_name): |
| 2082 |
target_type, data = self.parse_target(block, block_text, lineno) |
| 2083 |
if target_type == 'refname': |
| 2084 |
target = nodes.target(block_text, '', refname=normalize_name(data)) |
| 2085 |
target.indirect_reference_name = data |
| 2086 |
self.add_target(target_name, '', target, lineno) |
| 2087 |
self.document.note_indirect_target(target) |
| 2088 |
return target |
| 2089 |
elif target_type == 'refuri': |
| 2090 |
target = nodes.target(block_text, '') |
| 2091 |
self.add_target(target_name, data, target, lineno) |
| 2092 |
return target |
| 2093 |
else: |
| 2094 |
return data |
| 2095 |
|
| 2096 |
def parse_target(self, block, block_text, lineno): |
| 2097 |
""" |
| 2098 |
Determine the type of reference of a target. |
| 2099 |
|
| 2100 |
:Return: A 2-tuple, one of: |
| 2101 |
|
| 2102 |
- 'refname' and the indirect reference name |
| 2103 |
- 'refuri' and the URI |
| 2104 |
- 'malformed' and a system_message node |
| 2105 |
""" |
| 2106 |
if block and block[-1].strip()[-1:] == '_': |
| 2107 |
reference = ' '.join(line.strip() for line in block) |
| 2108 |
refname = self.is_reference(reference) |
| 2109 |
if refname: |
| 2110 |
return 'refname', refname |
| 2111 |
ref_parts = split_escaped_whitespace(' '.join(block)) |
| 2112 |
reference = ' '.join(''.join(unescape(part).split()) |
| 2113 |
for part in ref_parts) |
| 2114 |
return 'refuri', reference |
| 2115 |
|
| 2116 |
def is_reference(self, reference): |
| 2117 |
match = self.explicit.patterns.reference.match( |
| 2118 |
whitespace_normalize_name(reference)) |
| 2119 |
if not match: |
| 2120 |
return None |
| 2121 |
return unescape(match.group('simple') or match.group('phrase')) |
| 2122 |
|
| 2123 |
def add_target(self, targetname, refuri, target, lineno): |
| 2124 |
target.line = lineno |
| 2125 |
if targetname: |
| 2126 |
name = normalize_name(unescape(targetname)) |
| 2127 |
target['names'].append(name) |
| 2128 |
if refuri: |
| 2129 |
uri = self.inliner.adjust_uri(refuri) |
| 2130 |
if uri: |
| 2131 |
target['refuri'] = uri |
| 2132 |
else: |
| 2133 |
raise ApplicationError('problem with URI: %r' % refuri) |
| 2134 |
self.document.note_explicit_target(target, self.parent) |
| 2135 |
else: |
| 2136 |
if refuri: |
| 2137 |
target['refuri'] = refuri |
| 2138 |
target['anonymous'] = True |
| 2139 |
self.document.note_anonymous_target(target) |
| 2140 |
|
| 2141 |
def substitution_def(self, match): |
| 2142 |
pattern = self.explicit.patterns.substitution |
| 2143 |
src, srcline = self.state_machine.get_source_and_line() |
| 2144 |
(block, indent, offset, blank_finish |
| 2145 |
) = self.state_machine.get_first_known_indented(match.end(), |
| 2146 |
strip_indent=False) |
| 2147 |
blocktext = (match.string[:match.end()] + '\n'.join(block)) |
| 2148 |
block.disconnect() |
| 2149 |
escaped = escape2null(block[0].rstrip()) |
| 2150 |
blockindex = 0 |
| 2151 |
while True: |
| 2152 |
subdefmatch = pattern.match(escaped) |
| 2153 |
if subdefmatch: |
| 2154 |
break |
| 2155 |
blockindex += 1 |
| 2156 |
try: |
| 2157 |
escaped = escaped + ' ' + escape2null( |
| 2158 |
block[blockindex].strip()) |
| 2159 |
except IndexError: |
| 2160 |
raise MarkupError('malformed substitution definition.') |
| 2161 |
del block[:blockindex] |
| 2162 |
start = subdefmatch.end()-len(escaped)-1 |
| 2163 |
block[0] = (block[0].strip() + ' ')[start:-1] |
| 2164 |
if not block[0]: |
| 2165 |
del block[0] |
| 2166 |
offset += 1 |
| 2167 |
while block and not block[-1].strip(): |
| 2168 |
block.pop() |
| 2169 |
subname = subdefmatch.group('name') |
| 2170 |
substitution_node = nodes.substitution_definition(blocktext) |
| 2171 |
substitution_node.source = src |
| 2172 |
substitution_node.line = srcline |
| 2173 |
if not block: |
| 2174 |
msg = self.reporter.warning( |
| 2175 |
'Substitution definition "%s" missing contents.' % subname, |
| 2176 |
nodes.literal_block(blocktext, blocktext), |
| 2177 |
source=src, line=srcline) |
| 2178 |
return [msg], blank_finish |
| 2179 |
block[0] = block[0].strip() |
| 2180 |
substitution_node['names'].append( |
| 2181 |
nodes.whitespace_normalize_name(subname)) |
| 2182 |
new_abs_offset, blank_finish = self.nested_list_parse( |
| 2183 |
block, input_offset=offset, node=substitution_node, |
| 2184 |
initial_state='SubstitutionDef', blank_finish=blank_finish) |
| 2185 |
i = 0 |
| 2186 |
for node in substitution_node[:]: |
| 2187 |
if not (isinstance(node, nodes.Inline) |
| 2188 |
or isinstance(node, nodes.Text)): |
| 2189 |
self.parent += substitution_node[i] |
| 2190 |
del substitution_node[i] |
| 2191 |
else: |
| 2192 |
i += 1 |
| 2193 |
for node in substitution_node.findall(nodes.Element, |
| 2194 |
include_self=False): |
| 2195 |
if isinstance(node, nodes.problematic): |
| 2196 |
msg = self.reporter.error( |
| 2197 |
'Problematic content in substitution definition', |
| 2198 |
nodes.literal_block('', blocktext), |
| 2199 |
source=src, line=srcline) |
| 2200 |
msg.append(nodes.block_quote( |
| 2201 |
'', nodes.paragraph('', '', *substitution_node.children))) |
| 2202 |
return [msg], blank_finish |
| 2203 |
illegal = self.disallowed_inside_substitution_definitions(node) |
| 2204 |
if illegal: |
| 2205 |
msg = self.reporter.error(f'{illegal} are not supported in ' |
| 2206 |
'a substitution definition.', |
| 2207 |
nodes.literal_block('', blocktext), |
| 2208 |
source=src, line=srcline) |
| 2209 |
return [msg], blank_finish |
| 2210 |
if len(substitution_node) == 0: |
| 2211 |
msg = self.reporter.warning( |
| 2212 |
'Substitution definition "%s" empty or invalid.' % subname, |
| 2213 |
nodes.literal_block(blocktext, blocktext), |
| 2214 |
source=src, line=srcline) |
| 2215 |
return [msg], blank_finish |
| 2216 |
self.document.note_substitution_def( |
| 2217 |
substitution_node, subname, self.parent) |
| 2218 |
return [substitution_node], blank_finish |
| 2219 |
|
| 2220 |
def disallowed_inside_substitution_definitions(self, node) -> str: |
| 2221 |
if isinstance(node, nodes.reference) and node.get('anonymous'): |
| 2222 |
return 'Anonymous references' |
| 2223 |
if isinstance(node, nodes.footnote_reference) and node.get('auto'): |
| 2224 |
return 'References to auto-numbered and auto-symbol footnotes' |
| 2225 |
if node['names'] or node['ids']: |
| 2226 |
return 'Targets (names and identifiers)' |
| 2227 |
else: |
| 2228 |
return '' |
| 2229 |
|
| 2230 |
def directive(self, match, **option_presets): |
| 2231 |
"""Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" |
| 2232 |
type_name = match.group(1) |
| 2233 |
directive_class, messages = directives.directive( |
| 2234 |
type_name, self.memo.language, self.document) |
| 2235 |
self.parent += messages |
| 2236 |
if directive_class: |
| 2237 |
return self.run_directive( |
| 2238 |
directive_class, match, type_name, option_presets) |
| 2239 |
else: |
| 2240 |
return self.unknown_directive(type_name) |
| 2241 |
|
| 2242 |
def run_directive(self, directive, match, type_name, option_presets): |
| 2243 |
""" |
| 2244 |
Parse a directive then run its directive function. |
| 2245 |
|
| 2246 |
Parameters: |
| 2247 |
|
| 2248 |
- `directive`: The class implementing the directive. Must be |
| 2249 |
a subclass of `rst.Directive`. |
| 2250 |
|
| 2251 |
- `match`: A regular expression match object which matched the first |
| 2252 |
line of the directive. |
| 2253 |
|
| 2254 |
- `type_name`: The directive name, as used in the source text. |
| 2255 |
|
| 2256 |
- `option_presets`: A dictionary of preset options, defaults for the |
| 2257 |
directive options. Currently, only an "alt" option is passed by |
| 2258 |
substitution definitions (value: the substitution name), which may |
| 2259 |
be used by an embedded image directive. |
| 2260 |
|
| 2261 |
Returns a 2-tuple: list of nodes, and a "blank finish" boolean. |
| 2262 |
""" |
| 2263 |
if isinstance(directive, (FunctionType, MethodType)): |
| 2264 |
from docutils.parsers.rst import convert_directive_function |
| 2265 |
directive = convert_directive_function(directive) |
| 2266 |
lineno = self.state_machine.abs_line_number() |
| 2267 |
initial_line_offset = self.state_machine.line_offset |
| 2268 |
(indented, indent, line_offset, blank_finish |
| 2269 |
) = self.state_machine.get_first_known_indented(match.end(), |
| 2270 |
strip_top=0) |
| 2271 |
block_text = '\n'.join(self.state_machine.input_lines[ |
| 2272 |
initial_line_offset : self.state_machine.line_offset + 1]) |
| 2273 |
try: |
| 2274 |
arguments, options, content, content_offset = ( |
| 2275 |
self.parse_directive_block(indented, line_offset, |
| 2276 |
directive, option_presets)) |
| 2277 |
except MarkupError as detail: |
| 2278 |
error = self.reporter.error( |
| 2279 |
'Error in "%s" directive:\n%s.' % (type_name, |
| 2280 |
' '.join(detail.args)), |
| 2281 |
nodes.literal_block(block_text, block_text), line=lineno) |
| 2282 |
return [error], blank_finish |
| 2283 |
directive_instance = directive( |
| 2284 |
type_name, arguments, options, content, lineno, |
| 2285 |
content_offset, block_text, self, self.state_machine) |
| 2286 |
try: |
| 2287 |
result = directive_instance.run() |
| 2288 |
except docutils.parsers.rst.DirectiveError as error: |
| 2289 |
msg_node = self.reporter.system_message(error.level, error.msg, |
| 2290 |
line=lineno) |
| 2291 |
msg_node += nodes.literal_block(block_text, block_text) |
| 2292 |
result = [msg_node] |
| 2293 |
assert isinstance(result, list), \ |
| 2294 |
'Directive "%s" must return a list of nodes.' % type_name |
| 2295 |
for i in range(len(result)): |
| 2296 |
assert isinstance(result[i], nodes.Node), \ |
| 2297 |
('Directive "%s" returned non-Node object (index %s): %r' |
| 2298 |
% (type_name, i, result[i])) |
| 2299 |
return (result, |
| 2300 |
blank_finish or self.state_machine.is_next_line_blank()) |
| 2301 |
|
| 2302 |
def parse_directive_block(self, indented, line_offset, directive, |
| 2303 |
option_presets): |
| 2304 |
option_spec = directive.option_spec |
| 2305 |
has_content = directive.has_content |
| 2306 |
if indented and not indented[0].strip(): |
| 2307 |
indented.trim_start() |
| 2308 |
line_offset += 1 |
| 2309 |
while indented and not indented[-1].strip(): |
| 2310 |
indented.trim_end() |
| 2311 |
if indented and (directive.required_arguments |
| 2312 |
or directive.optional_arguments |
| 2313 |
or option_spec): |
| 2314 |
for i, line in enumerate(indented): |
| 2315 |
if not line.strip(): |
| 2316 |
break |
| 2317 |
else: |
| 2318 |
i += 1 |
| 2319 |
arg_block = indented[:i] |
| 2320 |
content = indented[i+1:] |
| 2321 |
content_offset = line_offset + i + 1 |
| 2322 |
else: |
| 2323 |
content = indented |
| 2324 |
content_offset = line_offset |
| 2325 |
arg_block = [] |
| 2326 |
if option_spec: |
| 2327 |
options, arg_block = self.parse_directive_options( |
| 2328 |
option_presets, option_spec, arg_block) |
| 2329 |
else: |
| 2330 |
options = {} |
| 2331 |
if arg_block and not (directive.required_arguments |
| 2332 |
or directive.optional_arguments): |
| 2333 |
content = arg_block + indented[i:] |
| 2334 |
content_offset = line_offset |
| 2335 |
arg_block = [] |
| 2336 |
while content and not content[0].strip(): |
| 2337 |
content.trim_start() |
| 2338 |
content_offset += 1 |
| 2339 |
if directive.required_arguments or directive.optional_arguments: |
| 2340 |
arguments = self.parse_directive_arguments( |
| 2341 |
directive, arg_block) |
| 2342 |
else: |
| 2343 |
arguments = [] |
| 2344 |
if content and not has_content: |
| 2345 |
raise MarkupError('no content permitted') |
| 2346 |
return arguments, options, content, content_offset |
| 2347 |
|
| 2348 |
def parse_directive_options(self, option_presets, option_spec, arg_block): |
| 2349 |
options = option_presets.copy() |
| 2350 |
for i, line in enumerate(arg_block): |
| 2351 |
if re.match(Body.patterns['field_marker'], line): |
| 2352 |
opt_block = arg_block[i:] |
| 2353 |
arg_block = arg_block[:i] |
| 2354 |
break |
| 2355 |
else: |
| 2356 |
opt_block = [] |
| 2357 |
if opt_block: |
| 2358 |
success, data = self.parse_extension_options(option_spec, |
| 2359 |
opt_block) |
| 2360 |
if success: |
| 2361 |
options.update(data) |
| 2362 |
else: |
| 2363 |
raise MarkupError(data) |
| 2364 |
return options, arg_block |
| 2365 |
|
| 2366 |
def parse_directive_arguments(self, directive, arg_block): |
| 2367 |
required = directive.required_arguments |
| 2368 |
optional = directive.optional_arguments |
| 2369 |
arg_text = '\n'.join(arg_block) |
| 2370 |
arguments = arg_text.split() |
| 2371 |
if len(arguments) < required: |
| 2372 |
raise MarkupError('%s argument(s) required, %s supplied' |
| 2373 |
% (required, len(arguments))) |
| 2374 |
elif len(arguments) > required + optional: |
| 2375 |
if directive.final_argument_whitespace: |
| 2376 |
arguments = arg_text.split(None, required + optional - 1) |
| 2377 |
else: |
| 2378 |
raise MarkupError( |
| 2379 |
'maximum %s argument(s) allowed, %s supplied' |
| 2380 |
% (required + optional, len(arguments))) |
| 2381 |
return arguments |
| 2382 |
|
| 2383 |
def parse_extension_options(self, option_spec, datalines): |
| 2384 |
""" |
| 2385 |
Parse `datalines` for a field list containing extension options |
| 2386 |
matching `option_spec`. |
| 2387 |
|
| 2388 |
:Parameters: |
| 2389 |
- `option_spec`: a mapping of option name to conversion |
| 2390 |
function, which should raise an exception on bad input. |
| 2391 |
- `datalines`: a list of input strings. |
| 2392 |
|
| 2393 |
:Return: |
| 2394 |
- Success value, 1 or 0. |
| 2395 |
- An option dictionary on success, an error string on failure. |
| 2396 |
""" |
| 2397 |
node = nodes.field_list() |
| 2398 |
newline_offset, blank_finish = self.nested_list_parse( |
| 2399 |
datalines, 0, node, initial_state='ExtensionOptions', |
| 2400 |
blank_finish=True) |
| 2401 |
if newline_offset != len(datalines): |
| 2402 |
return 0, 'invalid option block' |
| 2403 |
try: |
| 2404 |
options = utils.extract_extension_options(node, option_spec) |
| 2405 |
except KeyError as detail: |
| 2406 |
return 0, 'unknown option: "%s"' % detail.args[0] |
| 2407 |
except (ValueError, TypeError) as detail: |
| 2408 |
return 0, 'invalid option value: %s' % ' '.join(detail.args) |
| 2409 |
except utils.ExtensionOptionError as detail: |
| 2410 |
return 0, 'invalid option data: %s' % ' '.join(detail.args) |
| 2411 |
if blank_finish: |
| 2412 |
return 1, options |
| 2413 |
else: |
| 2414 |
return 0, 'option data incompletely parsed' |
| 2415 |
|
| 2416 |
def unknown_directive(self, type_name): |
| 2417 |
lineno = self.state_machine.abs_line_number() |
| 2418 |
(indented, indent, offset, blank_finish |
| 2419 |
) = self.state_machine.get_first_known_indented(0, strip_indent=False) |
| 2420 |
text = '\n'.join(indented) |
| 2421 |
error = self.reporter.error('Unknown directive type "%s".' % type_name, |
| 2422 |
nodes.literal_block(text, text), |
| 2423 |
line=lineno) |
| 2424 |
return [error], blank_finish |
| 2425 |
|
| 2426 |
def comment(self, match): |
| 2427 |
if self.state_machine.is_next_line_blank(): |
| 2428 |
first_comment_line = match.string[match.end():] |
| 2429 |
if not first_comment_line.strip(): |
| 2430 |
return [nodes.comment()], True |
| 2431 |
if first_comment_line.startswith('end of inclusion from "'): |
| 2432 |
|
| 2433 |
self.document.include_log.pop() |
| 2434 |
return [], True |
| 2435 |
(indented, indent, offset, blank_finish |
| 2436 |
) = self.state_machine.get_first_known_indented(match.end()) |
| 2437 |
while indented and not indented[-1].strip(): |
| 2438 |
indented.trim_end() |
| 2439 |
text = '\n'.join(indented) |
| 2440 |
return [nodes.comment(text, text)], blank_finish |
| 2441 |
|
| 2442 |
explicit.constructs = [ |
| 2443 |
(footnote, |
| 2444 |
re.compile(r""" |
| 2445 |
\.\.[ ]+ # explicit markup start |
| 2446 |
\[ |
| 2447 |
( # footnote label: |
| 2448 |
[0-9]+ # manually numbered footnote |
| 2449 |
| # *OR* |
| 2450 |
\# # anonymous auto-numbered footnote |
| 2451 |
| # *OR* |
| 2452 |
\#%s # auto-number ed?) footnote label |
| 2453 |
| # *OR* |
| 2454 |
\* # auto-symbol footnote |
| 2455 |
) |
| 2456 |
\] |
| 2457 |
([ ]+|$) # whitespace or end of line |
| 2458 |
""" % Inliner.simplename, re.VERBOSE)), |
| 2459 |
(citation, |
| 2460 |
re.compile(r""" |
| 2461 |
\.\.[ ]+ # explicit markup start |
| 2462 |
\[(%s)\] # citation label |
| 2463 |
([ ]+|$) # whitespace or end of line |
| 2464 |
""" % Inliner.simplename, re.VERBOSE)), |
| 2465 |
(hyperlink_target, |
| 2466 |
re.compile(r""" |
| 2467 |
\.\.[ ]+ # explicit markup start |
| 2468 |
_ # target indicator |
| 2469 |
(?![ ]|$) # first char. not space or EOL |
| 2470 |
""", re.VERBOSE)), |
| 2471 |
(substitution_def, |
| 2472 |
re.compile(r""" |
| 2473 |
\.\.[ ]+ # explicit markup start |
| 2474 |
\| # substitution indicator |
| 2475 |
(?![ ]|$) # first char. not space or EOL |
| 2476 |
""", re.VERBOSE)), |
| 2477 |
(directive, |
| 2478 |
re.compile(r""" |
| 2479 |
\.\.[ ]+ # explicit markup start |
| 2480 |
(%s) # directive name |
| 2481 |
[ ]? # optional space |
| 2482 |
:: # directive delimiter |
| 2483 |
([ ]+|$) # whitespace or end of line |
| 2484 |
""" % Inliner.simplename, re.VERBOSE))] |
| 2485 |
|
| 2486 |
def explicit_markup(self, match, context, next_state): |
| 2487 |
"""Footnotes, hyperlink targets, directives, comments.""" |
| 2488 |
nodelist, blank_finish = self.explicit_construct(match) |
| 2489 |
self.parent += nodelist |
| 2490 |
self.explicit_list(blank_finish) |
| 2491 |
return [], next_state, [] |
| 2492 |
|
| 2493 |
def explicit_construct(self, match): |
| 2494 |
"""Determine which explicit construct this is, parse & return it.""" |
| 2495 |
errors = [] |
| 2496 |
for method, pattern in self.explicit.constructs: |
| 2497 |
expmatch = pattern.match(match.string) |
| 2498 |
if expmatch: |
| 2499 |
try: |
| 2500 |
return method(self, expmatch) |
| 2501 |
except MarkupError as error: |
| 2502 |
lineno = self.state_machine.abs_line_number() |
| 2503 |
message = ' '.join(error.args) |
| 2504 |
errors.append(self.reporter.warning(message, line=lineno)) |
| 2505 |
break |
| 2506 |
nodelist, blank_finish = self.comment(match) |
| 2507 |
return nodelist + errors, blank_finish |
| 2508 |
|
| 2509 |
def explicit_list(self, blank_finish) -> None: |
| 2510 |
""" |
| 2511 |
Create a nested state machine for a series of explicit markup |
| 2512 |
constructs (including anonymous hyperlink targets). |
| 2513 |
""" |
| 2514 |
offset = self.state_machine.line_offset + 1 |
| 2515 |
newline_offset, blank_finish = self.nested_list_parse( |
| 2516 |
self.state_machine.input_lines[offset:], |
| 2517 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 2518 |
node=self.parent, initial_state='Explicit', |
| 2519 |
blank_finish=blank_finish) |
| 2520 |
self.goto_line(newline_offset) |
| 2521 |
if not blank_finish: |
| 2522 |
self.parent += self.unindent_warning('Explicit markup') |
| 2523 |
|
| 2524 |
def anonymous(self, match, context, next_state): |
| 2525 |
"""Anonymous hyperlink targets.""" |
| 2526 |
nodelist, blank_finish = self.anonymous_target(match) |
| 2527 |
self.parent += nodelist |
| 2528 |
self.explicit_list(blank_finish) |
| 2529 |
return [], next_state, [] |
| 2530 |
|
| 2531 |
def anonymous_target(self, match): |
| 2532 |
lineno = self.state_machine.abs_line_number() |
| 2533 |
(block, indent, offset, blank_finish |
| 2534 |
) = self.state_machine.get_first_known_indented(match.end(), |
| 2535 |
until_blank=True) |
| 2536 |
blocktext = match.string[:match.end()] + '\n'.join(block) |
| 2537 |
block = [escape2null(line) for line in block] |
| 2538 |
target = self.make_target(block, blocktext, lineno, '') |
| 2539 |
return [target], blank_finish |
| 2540 |
|
| 2541 |
def line(self, match, context, next_state): |
| 2542 |
"""Section title overline or transition marker.""" |
| 2543 |
if self.state_machine.match_titles: |
| 2544 |
return [match.string], 'Line', [] |
| 2545 |
elif match.string.strip() == '::': |
| 2546 |
raise statemachine.TransitionCorrection('text') |
| 2547 |
elif len(match.string.strip()) < 4: |
| 2548 |
msg = self.reporter.info( |
| 2549 |
'Unexpected possible title overline or transition.\n' |
| 2550 |
"Treating it as ordinary text because it's so short.", |
| 2551 |
line=self.state_machine.abs_line_number()) |
| 2552 |
self.parent += msg |
| 2553 |
raise statemachine.TransitionCorrection('text') |
| 2554 |
else: |
| 2555 |
blocktext = self.state_machine.line |
| 2556 |
msg = self.reporter.error( |
| 2557 |
'Unexpected section title or transition.', |
| 2558 |
nodes.literal_block(blocktext, blocktext), |
| 2559 |
line=self.state_machine.abs_line_number()) |
| 2560 |
self.parent += msg |
| 2561 |
return [], next_state, [] |
| 2562 |
|
| 2563 |
def text(self, match, context, next_state): |
| 2564 |
"""Titles, definition lists, paragraphs.""" |
| 2565 |
return [match.string], 'Text', [] |
| 2566 |
|
| 2567 |
|
| 2568 |
class RFC2822Body(Body): |
| 2569 |
|
| 2570 |
""" |
| 2571 |
RFC2822 headers are only valid as the first constructs in documents. As |
| 2572 |
soon as anything else appears, the `Body` state should take over. |
| 2573 |
""" |
| 2574 |
|
| 2575 |
patterns = Body.patterns.copy() |
| 2576 |
patterns['rfc2822'] = r'[!-9;-~]+:( +|$)' |
| 2577 |
initial_transitions = [(name, 'Body') |
| 2578 |
for name in Body.initial_transitions] |
| 2579 |
initial_transitions.insert(-1, ('rfc2822', 'Body')) |
| 2580 |
|
| 2581 |
def rfc2822(self, match, context, next_state): |
| 2582 |
"""RFC2822-style field list item.""" |
| 2583 |
fieldlist = nodes.field_list(classes=['rfc2822']) |
| 2584 |
self.parent += fieldlist |
| 2585 |
field, blank_finish = self.rfc2822_field(match) |
| 2586 |
fieldlist += field |
| 2587 |
offset = self.state_machine.line_offset + 1 |
| 2588 |
newline_offset, blank_finish = self.nested_list_parse( |
| 2589 |
self.state_machine.input_lines[offset:], |
| 2590 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 2591 |
node=fieldlist, initial_state='RFC2822List', |
| 2592 |
blank_finish=blank_finish) |
| 2593 |
self.goto_line(newline_offset) |
| 2594 |
if not blank_finish: |
| 2595 |
self.parent += self.unindent_warning( |
| 2596 |
'RFC2822-style field list') |
| 2597 |
return [], next_state, [] |
| 2598 |
|
| 2599 |
def rfc2822_field(self, match): |
| 2600 |
name = match.string[:match.string.find(':')] |
| 2601 |
(indented, indent, line_offset, blank_finish |
| 2602 |
) = self.state_machine.get_first_known_indented(match.end(), |
| 2603 |
until_blank=True) |
| 2604 |
fieldnode = nodes.field() |
| 2605 |
fieldnode += nodes.field_name(name, name) |
| 2606 |
fieldbody = nodes.field_body('\n'.join(indented)) |
| 2607 |
fieldnode += fieldbody |
| 2608 |
if indented: |
| 2609 |
self.nested_parse(indented, input_offset=line_offset, |
| 2610 |
node=fieldbody) |
| 2611 |
return fieldnode, blank_finish |
| 2612 |
|
| 2613 |
|
| 2614 |
class SpecializedBody(Body): |
| 2615 |
|
| 2616 |
""" |
| 2617 |
Superclass for second and subsequent compound element members. Compound |
| 2618 |
elements are lists and list-like constructs. |
| 2619 |
|
| 2620 |
All transition methods are disabled (redefined as `invalid_input`). |
| 2621 |
Override individual methods in subclasses to re-enable. |
| 2622 |
|
| 2623 |
For example, once an initial bullet list item, say, is recognized, the |
| 2624 |
`BulletList` subclass takes over, with a "bullet_list" node as its |
| 2625 |
container. Upon encountering the initial bullet list item, `Body.bullet` |
| 2626 |
calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which |
| 2627 |
starts up a nested parsing session with `BulletList` as the initial state. |
| 2628 |
Only the ``bullet`` transition method is enabled in `BulletList`; as long |
| 2629 |
as only bullet list items are encountered, they are parsed and inserted |
| 2630 |
into the container. The first construct which is *not* a bullet list item |
| 2631 |
triggers the `invalid_input` method, which ends the nested parse and |
| 2632 |
closes the container. `BulletList` needs to recognize input that is |
| 2633 |
invalid in the context of a bullet list, which means everything *other |
| 2634 |
than* bullet list items, so it inherits the transition list created in |
| 2635 |
`Body`. |
| 2636 |
""" |
| 2637 |
|
| 2638 |
def invalid_input(self, match=None, context=None, next_state=None): |
| 2639 |
"""Not a compound element member. Abort this state machine.""" |
| 2640 |
self.state_machine.previous_line() |
| 2641 |
raise EOFError |
| 2642 |
|
| 2643 |
indent = invalid_input |
| 2644 |
bullet = invalid_input |
| 2645 |
enumerator = invalid_input |
| 2646 |
field_marker = invalid_input |
| 2647 |
option_marker = invalid_input |
| 2648 |
doctest = invalid_input |
| 2649 |
line_block = invalid_input |
| 2650 |
grid_table_top = invalid_input |
| 2651 |
simple_table_top = invalid_input |
| 2652 |
explicit_markup = invalid_input |
| 2653 |
anonymous = invalid_input |
| 2654 |
line = invalid_input |
| 2655 |
text = invalid_input |
| 2656 |
|
| 2657 |
|
| 2658 |
class BulletList(SpecializedBody): |
| 2659 |
|
| 2660 |
"""Second and subsequent bullet_list list_items.""" |
| 2661 |
|
| 2662 |
def bullet(self, match, context, next_state): |
| 2663 |
"""Bullet list item.""" |
| 2664 |
if match.string[0] != self.parent['bullet']: |
| 2665 |
|
| 2666 |
self.invalid_input() |
| 2667 |
listitem, blank_finish = self.list_item(match.end()) |
| 2668 |
self.parent += listitem |
| 2669 |
self.blank_finish = blank_finish |
| 2670 |
return [], next_state, [] |
| 2671 |
|
| 2672 |
|
| 2673 |
class DefinitionList(SpecializedBody): |
| 2674 |
|
| 2675 |
"""Second and subsequent definition_list_items.""" |
| 2676 |
|
| 2677 |
def text(self, match, context, next_state): |
| 2678 |
"""Definition lists.""" |
| 2679 |
return [match.string], 'Definition', [] |
| 2680 |
|
| 2681 |
|
| 2682 |
class EnumeratedList(SpecializedBody): |
| 2683 |
|
| 2684 |
"""Second and subsequent enumerated_list list_items.""" |
| 2685 |
|
| 2686 |
def enumerator(self, match, context, next_state): |
| 2687 |
"""Enumerated list item.""" |
| 2688 |
format, sequence, text, ordinal = self.parse_enumerator( |
| 2689 |
match, self.parent['enumtype']) |
| 2690 |
if (format != self.format |
| 2691 |
or (sequence != '#' and (sequence != self.parent['enumtype'] |
| 2692 |
or self.auto |
| 2693 |
or ordinal != (self.lastordinal + 1))) |
| 2694 |
or not self.is_enumerated_list_item(ordinal, sequence, format)): |
| 2695 |
|
| 2696 |
self.invalid_input() |
| 2697 |
if sequence == '#': |
| 2698 |
self.auto = 1 |
| 2699 |
listitem, blank_finish = self.list_item(match.end()) |
| 2700 |
self.parent += listitem |
| 2701 |
self.blank_finish = blank_finish |
| 2702 |
self.lastordinal = ordinal |
| 2703 |
return [], next_state, [] |
| 2704 |
|
| 2705 |
|
| 2706 |
class FieldList(SpecializedBody): |
| 2707 |
|
| 2708 |
"""Second and subsequent field_list fields.""" |
| 2709 |
|
| 2710 |
def field_marker(self, match, context, next_state): |
| 2711 |
"""Field list field.""" |
| 2712 |
field, blank_finish = self.field(match) |
| 2713 |
self.parent += field |
| 2714 |
self.blank_finish = blank_finish |
| 2715 |
return [], next_state, [] |
| 2716 |
|
| 2717 |
|
| 2718 |
class OptionList(SpecializedBody): |
| 2719 |
|
| 2720 |
"""Second and subsequent option_list option_list_items.""" |
| 2721 |
|
| 2722 |
def option_marker(self, match, context, next_state): |
| 2723 |
"""Option list item.""" |
| 2724 |
try: |
| 2725 |
option_list_item, blank_finish = self.option_list_item(match) |
| 2726 |
except MarkupError: |
| 2727 |
self.invalid_input() |
| 2728 |
self.parent += option_list_item |
| 2729 |
self.blank_finish = blank_finish |
| 2730 |
return [], next_state, [] |
| 2731 |
|
| 2732 |
|
| 2733 |
class RFC2822List(SpecializedBody, RFC2822Body): |
| 2734 |
|
| 2735 |
"""Second and subsequent RFC2822-style field_list fields.""" |
| 2736 |
|
| 2737 |
patterns = RFC2822Body.patterns |
| 2738 |
initial_transitions = RFC2822Body.initial_transitions |
| 2739 |
|
| 2740 |
def rfc2822(self, match, context, next_state): |
| 2741 |
"""RFC2822-style field list item.""" |
| 2742 |
field, blank_finish = self.rfc2822_field(match) |
| 2743 |
self.parent += field |
| 2744 |
self.blank_finish = blank_finish |
| 2745 |
return [], 'RFC2822List', [] |
| 2746 |
|
| 2747 |
blank = SpecializedBody.invalid_input |
| 2748 |
|
| 2749 |
|
| 2750 |
class ExtensionOptions(FieldList): |
| 2751 |
|
| 2752 |
""" |
| 2753 |
Parse field_list fields for extension options. |
| 2754 |
|
| 2755 |
No nested parsing is done (including inline markup parsing). |
| 2756 |
""" |
| 2757 |
|
| 2758 |
def parse_field_body(self, indented, offset, node) -> None: |
| 2759 |
"""Override `Body.parse_field_body` for simpler parsing.""" |
| 2760 |
lines = [] |
| 2761 |
for line in list(indented) + ['']: |
| 2762 |
if line.strip(): |
| 2763 |
lines.append(line) |
| 2764 |
elif lines: |
| 2765 |
text = '\n'.join(lines) |
| 2766 |
node += nodes.paragraph(text, text) |
| 2767 |
lines = [] |
| 2768 |
|
| 2769 |
|
| 2770 |
class LineBlock(SpecializedBody): |
| 2771 |
|
| 2772 |
"""Second and subsequent lines of a line_block.""" |
| 2773 |
|
| 2774 |
blank = SpecializedBody.invalid_input |
| 2775 |
|
| 2776 |
def line_block(self, match, context, next_state): |
| 2777 |
"""New line of line block.""" |
| 2778 |
lineno = self.state_machine.abs_line_number() |
| 2779 |
line, messages, blank_finish = self.line_block_line(match, lineno) |
| 2780 |
self.parent += line |
| 2781 |
self.parent.parent += messages |
| 2782 |
self.blank_finish = blank_finish |
| 2783 |
return [], next_state, [] |
| 2784 |
|
| 2785 |
|
| 2786 |
class Explicit(SpecializedBody): |
| 2787 |
|
| 2788 |
"""Second and subsequent explicit markup construct.""" |
| 2789 |
|
| 2790 |
def explicit_markup(self, match, context, next_state): |
| 2791 |
"""Footnotes, hyperlink targets, directives, comments.""" |
| 2792 |
nodelist, blank_finish = self.explicit_construct(match) |
| 2793 |
self.parent += nodelist |
| 2794 |
self.blank_finish = blank_finish |
| 2795 |
return [], next_state, [] |
| 2796 |
|
| 2797 |
def anonymous(self, match, context, next_state): |
| 2798 |
"""Anonymous hyperlink targets.""" |
| 2799 |
nodelist, blank_finish = self.anonymous_target(match) |
| 2800 |
self.parent += nodelist |
| 2801 |
self.blank_finish = blank_finish |
| 2802 |
return [], next_state, [] |
| 2803 |
|
| 2804 |
blank = SpecializedBody.invalid_input |
| 2805 |
|
| 2806 |
|
| 2807 |
class SubstitutionDef(Body): |
| 2808 |
|
| 2809 |
""" |
| 2810 |
Parser for the contents of a substitution_definition element. |
| 2811 |
""" |
| 2812 |
|
| 2813 |
patterns = { |
| 2814 |
'embedded_directive': re.compile(r'(%s)::( +|$)' |
| 2815 |
% Inliner.simplename), |
| 2816 |
'text': r''} |
| 2817 |
initial_transitions = ['embedded_directive', 'text'] |
| 2818 |
|
| 2819 |
def embedded_directive(self, match, context, next_state): |
| 2820 |
nodelist, blank_finish = self.directive(match, |
| 2821 |
alt=self.parent['names'][0]) |
| 2822 |
self.parent += nodelist |
| 2823 |
if not self.state_machine.at_eof(): |
| 2824 |
self.blank_finish = blank_finish |
| 2825 |
raise EOFError |
| 2826 |
|
| 2827 |
def text(self, match, context, next_state): |
| 2828 |
if not self.state_machine.at_eof(): |
| 2829 |
self.blank_finish = self.state_machine.is_next_line_blank() |
| 2830 |
raise EOFError |
| 2831 |
|
| 2832 |
|
| 2833 |
class Text(RSTState): |
| 2834 |
|
| 2835 |
""" |
| 2836 |
Classifier of second line of a text block. |
| 2837 |
|
| 2838 |
Could be a paragraph, a definition list item, or a title. |
| 2839 |
""" |
| 2840 |
|
| 2841 |
patterns = {'underline': Body.patterns['line'], |
| 2842 |
'text': r''} |
| 2843 |
initial_transitions = [('underline', 'Body'), ('text', 'Body')] |
| 2844 |
|
| 2845 |
def blank(self, match, context, next_state): |
| 2846 |
"""End of paragraph.""" |
| 2847 |
|
| 2848 |
paragraph, literalnext = self.paragraph( |
| 2849 |
context, self.state_machine.abs_line_number() - 1) |
| 2850 |
self.parent += paragraph |
| 2851 |
if literalnext: |
| 2852 |
self.parent += self.literal_block() |
| 2853 |
return [], 'Body', [] |
| 2854 |
|
| 2855 |
def eof(self, context): |
| 2856 |
if context: |
| 2857 |
self.blank(None, context, None) |
| 2858 |
return [] |
| 2859 |
|
| 2860 |
def indent(self, match, context, next_state): |
| 2861 |
"""Definition list item.""" |
| 2862 |
dl = nodes.definition_list() |
| 2863 |
|
| 2864 |
lineno = self.state_machine.abs_line_number() - 1 |
| 2865 |
dl.source, dl.line = self.state_machine.get_source_and_line(lineno) |
| 2866 |
dl_item, blank_finish = self.definition_list_item(context) |
| 2867 |
dl += dl_item |
| 2868 |
self.parent += dl |
| 2869 |
offset = self.state_machine.line_offset + 1 |
| 2870 |
newline_offset, blank_finish = self.nested_list_parse( |
| 2871 |
self.state_machine.input_lines[offset:], |
| 2872 |
input_offset=self.state_machine.abs_line_offset() + 1, |
| 2873 |
node=dl, initial_state='DefinitionList', |
| 2874 |
blank_finish=blank_finish, blank_finish_state='Definition') |
| 2875 |
self.goto_line(newline_offset) |
| 2876 |
if not blank_finish: |
| 2877 |
self.parent += self.unindent_warning('Definition list') |
| 2878 |
return [], 'Body', [] |
| 2879 |
|
| 2880 |
def underline(self, match, context, next_state): |
| 2881 |
"""Section title.""" |
| 2882 |
lineno = self.state_machine.abs_line_number() |
| 2883 |
title = context[0].rstrip() |
| 2884 |
underline = match.string.rstrip() |
| 2885 |
source = title + '\n' + underline |
| 2886 |
messages = [] |
| 2887 |
if column_width(title) > len(underline): |
| 2888 |
if len(underline) < 4: |
| 2889 |
if self.state_machine.match_titles: |
| 2890 |
msg = self.reporter.info( |
| 2891 |
'Possible title underline, too short for the title.\n' |
| 2892 |
"Treating it as ordinary text because it's so short.", |
| 2893 |
line=lineno) |
| 2894 |
self.parent += msg |
| 2895 |
raise statemachine.TransitionCorrection('text') |
| 2896 |
else: |
| 2897 |
blocktext = context[0] + '\n' + self.state_machine.line |
| 2898 |
msg = self.reporter.warning( |
| 2899 |
'Title underline too short.', |
| 2900 |
nodes.literal_block(blocktext, blocktext), |
| 2901 |
line=lineno) |
| 2902 |
messages.append(msg) |
| 2903 |
if not self.state_machine.match_titles: |
| 2904 |
blocktext = context[0] + '\n' + self.state_machine.line |
| 2905 |
|
| 2906 |
src, srcline = self.state_machine.get_source_and_line() |
| 2907 |
|
| 2908 |
|
| 2909 |
|
| 2910 |
|
| 2911 |
msg = self.reporter.error( |
| 2912 |
'Unexpected section title.', |
| 2913 |
nodes.literal_block(blocktext, blocktext), |
| 2914 |
source=src, line=srcline) |
| 2915 |
self.parent += messages |
| 2916 |
self.parent += msg |
| 2917 |
return [], next_state, [] |
| 2918 |
style = underline[0] |
| 2919 |
context[:] = [] |
| 2920 |
self.section(title, source, style, lineno - 1, messages) |
| 2921 |
return [], next_state, [] |
| 2922 |
|
| 2923 |
def text(self, match, context, next_state): |
| 2924 |
"""Paragraph.""" |
| 2925 |
startline = self.state_machine.abs_line_number() - 1 |
| 2926 |
msg = None |
| 2927 |
try: |
| 2928 |
block = self.state_machine.get_text_block(flush_left=True) |
| 2929 |
except statemachine.UnexpectedIndentationError as err: |
| 2930 |
block, src, srcline = err.args |
| 2931 |
msg = self.reporter.error('Unexpected indentation.', |
| 2932 |
source=src, line=srcline) |
| 2933 |
lines = context + list(block) |
| 2934 |
paragraph, literalnext = self.paragraph(lines, startline) |
| 2935 |
self.parent += paragraph |
| 2936 |
self.parent += msg |
| 2937 |
if literalnext: |
| 2938 |
try: |
| 2939 |
self.state_machine.next_line() |
| 2940 |
except EOFError: |
| 2941 |
pass |
| 2942 |
self.parent += self.literal_block() |
| 2943 |
return [], next_state, [] |
| 2944 |
|
| 2945 |
def literal_block(self): |
| 2946 |
"""Return a list of nodes.""" |
| 2947 |
(indented, indent, offset, blank_finish |
| 2948 |
) = self.state_machine.get_indented() |
| 2949 |
while indented and not indented[-1].strip(): |
| 2950 |
indented.trim_end() |
| 2951 |
if not indented: |
| 2952 |
return self.quoted_literal_block() |
| 2953 |
data = '\n'.join(indented) |
| 2954 |
literal_block = nodes.literal_block(data, data) |
| 2955 |
(literal_block.source, |
| 2956 |
literal_block.line) = self.state_machine.get_source_and_line(offset+1) |
| 2957 |
nodelist = [literal_block] |
| 2958 |
if not blank_finish: |
| 2959 |
nodelist.append(self.unindent_warning('Literal block')) |
| 2960 |
return nodelist |
| 2961 |
|
| 2962 |
def quoted_literal_block(self): |
| 2963 |
abs_line_offset = self.state_machine.abs_line_offset() |
| 2964 |
offset = self.state_machine.line_offset |
| 2965 |
parent_node = nodes.Element() |
| 2966 |
new_abs_offset = self.nested_parse( |
| 2967 |
self.state_machine.input_lines[offset:], |
| 2968 |
input_offset=abs_line_offset, node=parent_node, match_titles=False, |
| 2969 |
state_machine_kwargs={'state_classes': (QuotedLiteralBlock,), |
| 2970 |
'initial_state': 'QuotedLiteralBlock'}) |
| 2971 |
self.goto_line(new_abs_offset) |
| 2972 |
return parent_node.children |
| 2973 |
|
| 2974 |
def definition_list_item(self, termline): |
| 2975 |
|
| 2976 |
dd_lineno = self.state_machine.abs_line_number() |
| 2977 |
dt_lineno = dd_lineno - 1 |
| 2978 |
(indented, indent, line_offset, blank_finish |
| 2979 |
) = self.state_machine.get_indented() |
| 2980 |
dl_item = nodes.definition_list_item( |
| 2981 |
'\n'.join(termline + list(indented))) |
| 2982 |
(dl_item.source, |
| 2983 |
dl_item.line) = self.state_machine.get_source_and_line(dt_lineno) |
| 2984 |
dt_nodes, messages = self.term(termline, dt_lineno) |
| 2985 |
dl_item += dt_nodes |
| 2986 |
dd = nodes.definition('', *messages) |
| 2987 |
dd.source, dd.line = self.state_machine.get_source_and_line(dd_lineno) |
| 2988 |
dl_item += dd |
| 2989 |
if termline[0][-2:] == '::': |
| 2990 |
dd += self.reporter.info( |
| 2991 |
'Blank line missing before literal block (after the "::")? ' |
| 2992 |
'Interpreted as a definition list item.', |
| 2993 |
line=dd_lineno) |
| 2994 |
|
| 2995 |
|
| 2996 |
|
| 2997 |
self.nested_parse(indented, input_offset=line_offset, node=dd) |
| 2998 |
return dl_item, blank_finish |
| 2999 |
|
| 3000 |
classifier_delimiter = re.compile(' +: +') |
| 3001 |
|
| 3002 |
def term(self, lines, lineno): |
| 3003 |
"""Return a definition_list's term and optional classifiers.""" |
| 3004 |
assert len(lines) == 1 |
| 3005 |
text_nodes, messages = self.inline_text(lines[0], lineno) |
| 3006 |
dt = nodes.term(lines[0]) |
| 3007 |
dt.source, dt.line = self.state_machine.get_source_and_line(lineno) |
| 3008 |
node_list = [dt] |
| 3009 |
for i in range(len(text_nodes)): |
| 3010 |
node = text_nodes[i] |
| 3011 |
if isinstance(node, nodes.Text): |
| 3012 |
parts = self.classifier_delimiter.split(node) |
| 3013 |
if len(parts) == 1: |
| 3014 |
node_list[-1] += node |
| 3015 |
else: |
| 3016 |
text = parts[0].rstrip() |
| 3017 |
textnode = nodes.Text(text) |
| 3018 |
node_list[-1] += textnode |
| 3019 |
node_list += [nodes.classifier(unescape(part, True), part) |
| 3020 |
for part in parts[1:]] |
| 3021 |
else: |
| 3022 |
node_list[-1] += node |
| 3023 |
return node_list, messages |
| 3024 |
|
| 3025 |
|
| 3026 |
class SpecializedText(Text): |
| 3027 |
|
| 3028 |
""" |
| 3029 |
Superclass for second and subsequent lines of Text-variants. |
| 3030 |
|
| 3031 |
All transition methods are disabled. Override individual methods in |
| 3032 |
subclasses to re-enable. |
| 3033 |
""" |
| 3034 |
|
| 3035 |
def eof(self, context): |
| 3036 |
"""Incomplete construct.""" |
| 3037 |
return [] |
| 3038 |
|
| 3039 |
def invalid_input(self, match=None, context=None, next_state=None): |
| 3040 |
"""Not a compound element member. Abort this state machine.""" |
| 3041 |
raise EOFError |
| 3042 |
|
| 3043 |
blank = invalid_input |
| 3044 |
indent = invalid_input |
| 3045 |
underline = invalid_input |
| 3046 |
text = invalid_input |
| 3047 |
|
| 3048 |
|
| 3049 |
class Definition(SpecializedText): |
| 3050 |
|
| 3051 |
"""Second line of potential definition_list_item.""" |
| 3052 |
|
| 3053 |
def eof(self, context): |
| 3054 |
"""Not a definition.""" |
| 3055 |
self.state_machine.previous_line(2) |
| 3056 |
return [] |
| 3057 |
|
| 3058 |
def indent(self, match, context, next_state): |
| 3059 |
"""Definition list item.""" |
| 3060 |
dl_item, blank_finish = self.definition_list_item(context) |
| 3061 |
self.parent += dl_item |
| 3062 |
self.blank_finish = blank_finish |
| 3063 |
return [], 'DefinitionList', [] |
| 3064 |
|
| 3065 |
|
| 3066 |
class Line(SpecializedText): |
| 3067 |
|
| 3068 |
""" |
| 3069 |
Second line of over- & underlined section title or transition marker. |
| 3070 |
""" |
| 3071 |
|
| 3072 |
eofcheck = 1 . |
| 3073 |
|
| 3074 |
def eof(self, context): |
| 3075 |
"""Transition marker at end of section or document.""" |
| 3076 |
marker = context[0].strip() |
| 3077 |
if len(marker) < 4: |
| 3078 |
self.state_correction(context) |
| 3079 |
src, srcline = self.state_machine.get_source_and_line() |
| 3080 |
|
| 3081 |
transition = nodes.transition(rawsource=context[0]) |
| 3082 |
transition.source = src |
| 3083 |
transition.line = srcline - 1 |
| 3084 |
|
| 3085 |
self.parent += transition |
| 3086 |
return [] |
| 3087 |
|
| 3088 |
def blank(self, match, context, next_state): |
| 3089 |
"""Transition marker.""" |
| 3090 |
src, srcline = self.state_machine.get_source_and_line() |
| 3091 |
marker = context[0].strip() |
| 3092 |
if len(marker) < 4: |
| 3093 |
self.state_correction(context) |
| 3094 |
transition = nodes.transition(rawsource=marker) |
| 3095 |
transition.source = src |
| 3096 |
transition.line = srcline - 1 |
| 3097 |
self.parent += transition |
| 3098 |
return [], 'Body', [] |
| 3099 |
|
| 3100 |
def text(self, match, context, next_state): |
| 3101 |
"""Potential over- & underlined title.""" |
| 3102 |
lineno = self.state_machine.abs_line_number() - 1 |
| 3103 |
overline = context[0] |
| 3104 |
title = match.string |
| 3105 |
underline = '' |
| 3106 |
try: |
| 3107 |
underline = self.state_machine.next_line() |
| 3108 |
except EOFError: |
| 3109 |
blocktext = overline + '\n' + title |
| 3110 |
if len(overline.rstrip()) < 4: |
| 3111 |
self.short_overline(context, blocktext, lineno, 2) |
| 3112 |
else: |
| 3113 |
msg = self.reporter.error( |
| 3114 |
'Incomplete section title.', |
| 3115 |
nodes.literal_block(blocktext, blocktext), |
| 3116 |
line=lineno) |
| 3117 |
self.parent += msg |
| 3118 |
return [], 'Body', [] |
| 3119 |
source = '%s\n%s\n%s' % (overline, title, underline) |
| 3120 |
overline = overline.rstrip() |
| 3121 |
underline = underline.rstrip() |
| 3122 |
if not self.transitions['underline'][0].match(underline): |
| 3123 |
blocktext = overline + '\n' + title + '\n' + underline |
| 3124 |
if len(overline.rstrip()) < 4: |
| 3125 |
self.short_overline(context, blocktext, lineno, 2) |
| 3126 |
else: |
| 3127 |
msg = self.reporter.error( |
| 3128 |
'Missing matching underline for section title overline.', |
| 3129 |
nodes.literal_block(source, source), |
| 3130 |
line=lineno) |
| 3131 |
self.parent += msg |
| 3132 |
return [], 'Body', [] |
| 3133 |
elif overline != underline: |
| 3134 |
blocktext = overline + '\n' + title + '\n' + underline |
| 3135 |
if len(overline.rstrip()) < 4: |
| 3136 |
self.short_overline(context, blocktext, lineno, 2) |
| 3137 |
else: |
| 3138 |
msg = self.reporter.error( |
| 3139 |
'Title overline & underline mismatch.', |
| 3140 |
nodes.literal_block(source, source), |
| 3141 |
line=lineno) |
| 3142 |
self.parent += msg |
| 3143 |
return [], 'Body', [] |
| 3144 |
title = title.rstrip() |
| 3145 |
messages = [] |
| 3146 |
if column_width(title) > len(overline): |
| 3147 |
blocktext = overline + '\n' + title + '\n' + underline |
| 3148 |
if len(overline.rstrip()) < 4: |
| 3149 |
self.short_overline(context, blocktext, lineno, 2) |
| 3150 |
else: |
| 3151 |
msg = self.reporter.warning( |
| 3152 |
'Title overline too short.', |
| 3153 |
nodes.literal_block(source, source), |
| 3154 |
line=lineno) |
| 3155 |
messages.append(msg) |
| 3156 |
style = (overline[0], underline[0]) |
| 3157 |
self.section(title.lstrip(), source, style, lineno + 1, messages) |
| 3158 |
return [], 'Body', [] |
| 3159 |
|
| 3160 |
indent = text |
| 3161 |
|
| 3162 |
def underline(self, match, context, next_state): |
| 3163 |
overline = context[0] |
| 3164 |
blocktext = overline + '\n' + self.state_machine.line |
| 3165 |
lineno = self.state_machine.abs_line_number() - 1 |
| 3166 |
if len(overline.rstrip()) < 4: |
| 3167 |
self.short_overline(context, blocktext, lineno, 1) |
| 3168 |
msg = self.reporter.error( |
| 3169 |
'Invalid section title or transition marker.', |
| 3170 |
nodes.literal_block(blocktext, blocktext), |
| 3171 |
line=lineno) |
| 3172 |
self.parent += msg |
| 3173 |
return [], 'Body', [] |
| 3174 |
|
| 3175 |
def short_overline(self, context, blocktext, lineno, lines=1) -> None: |
| 3176 |
msg = self.reporter.info( |
| 3177 |
'Possible incomplete section title.\nTreating the overline as ' |
| 3178 |
"ordinary text because it's so short.", |
| 3179 |
line=lineno) |
| 3180 |
self.parent += msg |
| 3181 |
self.state_correction(context, lines) |
| 3182 |
|
| 3183 |
def state_correction(self, context, lines=1): |
| 3184 |
self.state_machine.previous_line(lines) |
| 3185 |
context[:] = [] |
| 3186 |
raise statemachine.StateCorrection('Body', 'text') |
| 3187 |
|
| 3188 |
|
| 3189 |
class QuotedLiteralBlock(RSTState): |
| 3190 |
|
| 3191 |
""" |
| 3192 |
Nested parse handler for quoted (unindented) literal blocks. |
| 3193 |
|
| 3194 |
Special-purpose. Not for inclusion in `state_classes`. |
| 3195 |
""" |
| 3196 |
|
| 3197 |
patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats, |
| 3198 |
'text': r''} |
| 3199 |
initial_transitions = ('initial_quoted', 'text') |
| 3200 |
|
| 3201 |
def __init__(self, state_machine, debug=False) -> None: |
| 3202 |
RSTState.__init__(self, state_machine, debug) |
| 3203 |
self.messages = [] |
| 3204 |
self.initial_lineno = None |
| 3205 |
|
| 3206 |
def blank(self, match, context, next_state): |
| 3207 |
if context: |
| 3208 |
raise EOFError |
| 3209 |
else: |
| 3210 |
return context, next_state, [] |
| 3211 |
|
| 3212 |
def eof(self, context): |
| 3213 |
if context: |
| 3214 |
src, srcline = self.state_machine.get_source_and_line( |
| 3215 |
self.initial_lineno) |
| 3216 |
text = '\n'.join(context) |
| 3217 |
literal_block = nodes.literal_block(text, text) |
| 3218 |
literal_block.source = src |
| 3219 |
literal_block.line = srcline |
| 3220 |
self.parent += literal_block |
| 3221 |
else: |
| 3222 |
self.parent += self.reporter.warning( |
| 3223 |
'Literal block expected; none found.', |
| 3224 |
line=self.state_machine.abs_line_number() |
| 3225 |
) |
| 3226 |
self.state_machine.previous_line() |
| 3227 |
self.parent += self.messages |
| 3228 |
return [] |
| 3229 |
|
| 3230 |
def indent(self, match, context, next_state): |
| 3231 |
assert context, ('QuotedLiteralBlock.indent: context should not ' |
| 3232 |
'be empty!') |
| 3233 |
self.messages.append( |
| 3234 |
self.reporter.error('Unexpected indentation.', |
| 3235 |
line=self.state_machine.abs_line_number())) |
| 3236 |
self.state_machine.previous_line() |
| 3237 |
raise EOFError |
| 3238 |
|
| 3239 |
def initial_quoted(self, match, context, next_state): |
| 3240 |
"""Match arbitrary quote character on the first line only.""" |
| 3241 |
self.remove_transition('initial_quoted') |
| 3242 |
quote = match.string[0] |
| 3243 |
pattern = re.compile(re.escape(quote)) |
| 3244 |
|
| 3245 |
self.add_transition('quoted', |
| 3246 |
(pattern, self.quoted, self.__class__.__name__)) |
| 3247 |
self.initial_lineno = self.state_machine.abs_line_number() |
| 3248 |
return [match.string], next_state, [] |
| 3249 |
|
| 3250 |
def quoted(self, match, context, next_state): |
| 3251 |
"""Match consistent quotes on subsequent lines.""" |
| 3252 |
context.append(match.string) |
| 3253 |
return context, next_state, [] |
| 3254 |
|
| 3255 |
def text(self, match, context, next_state): |
| 3256 |
if context: |
| 3257 |
self.messages.append( |
| 3258 |
self.reporter.error('Inconsistent literal block quoting.', |
| 3259 |
line=self.state_machine.abs_line_number())) |
| 3260 |
self.state_machine.previous_line() |
| 3261 |
raise EOFError |
| 3262 |
|
| 3263 |
|
| 3264 |
state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList, |
| 3265 |
OptionList, LineBlock, ExtensionOptions, Explicit, Text, |
| 3266 |
Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List) |
| 3267 |
"""Standard set of State classes used to start `RSTStateMachine`.""" |