PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/documentor/libraries/docutils-0.9.1-py3.2/docutils/parsers/rst/states.py

https://github.com/tictactatic/Superdesk
Python | 3049 lines | 2953 code | 21 blank | 75 comment | 48 complexity | 14748e446acf36c12334059de74259fe MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. # $Id: states.py 7363 2012-02-20 21:31:48Z goodger $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. This is the ``docutils.parsers.rst.states`` module, the core of
  6. the reStructuredText parser. It defines the following:
  7. :Classes:
  8. - `RSTStateMachine`: reStructuredText parser's entry point.
  9. - `NestedStateMachine`: recursive StateMachine.
  10. - `RSTState`: reStructuredText State superclass.
  11. - `Inliner`: For parsing inline markup.
  12. - `Body`: Generic classifier of the first line of a block.
  13. - `SpecializedBody`: Superclass for compound element members.
  14. - `BulletList`: Second and subsequent bullet_list list_items
  15. - `DefinitionList`: Second+ definition_list_items.
  16. - `EnumeratedList`: Second+ enumerated_list list_items.
  17. - `FieldList`: Second+ fields.
  18. - `OptionList`: Second+ option_list_items.
  19. - `RFC2822List`: Second+ RFC2822-style fields.
  20. - `ExtensionOptions`: Parses directive option fields.
  21. - `Explicit`: Second+ explicit markup constructs.
  22. - `SubstitutionDef`: For embedded directives in substitution definitions.
  23. - `Text`: Classifier of second line of a text block.
  24. - `SpecializedText`: Superclass for continuation lines of Text-variants.
  25. - `Definition`: Second line of potential definition_list_item.
  26. - `Line`: Second line of overlined section title or transition marker.
  27. - `Struct`: An auxiliary collection class.
  28. :Exception classes:
  29. - `MarkupError`
  30. - `ParserError`
  31. - `MarkupMismatch`
  32. :Functions:
  33. - `escape2null()`: Return a string, escape-backslashes converted to nulls.
  34. - `unescape()`: Return a string, nulls removed or restored to backslashes.
  35. :Attributes:
  36. - `state_classes`: set of State classes used with `RSTStateMachine`.
  37. Parser Overview
  38. ===============
  39. The reStructuredText parser is implemented as a recursive state machine,
  40. examining its input one line at a time. To understand how the parser works,
  41. please first become familiar with the `docutils.statemachine` module. In the
  42. description below, references are made to classes defined in this module;
  43. please see the individual classes for details.
  44. Parsing proceeds as follows:
  45. 1. The state machine examines each line of input, checking each of the
  46. transition patterns of the state `Body`, in order, looking for a match.
  47. The implicit transitions (blank lines and indentation) are checked before
  48. any others. The 'text' transition is a catch-all (matches anything).
  49. 2. The method associated with the matched transition pattern is called.
  50. A. Some transition methods are self-contained, appending elements to the
  51. document tree (`Body.doctest` parses a doctest block). The parser's
  52. current line index is advanced to the end of the element, and parsing
  53. continues with step 1.
  54. B. Other transition methods trigger the creation of a nested state machine,
  55. whose job is to parse a compound construct ('indent' does a block quote,
  56. 'bullet' does a bullet list, 'overline' does a section [first checking
  57. for a valid section header], etc.).
  58. - In the case of lists and explicit markup, a one-off state machine is
  59. created and run to parse contents of the first item.
  60. - A new state machine is created and its initial state is set to the
  61. appropriate specialized state (`BulletList` in the case of the
  62. 'bullet' transition; see `SpecializedBody` for more detail). This
  63. state machine is run to parse the compound element (or series of
  64. explicit markup elements), and returns as soon as a non-member element
  65. is encountered. For example, the `BulletList` state machine ends as
  66. soon as it encounters an element which is not a list item of that
  67. bullet list. The optional omission of inter-element blank lines is
  68. enabled by this nested state machine.
  69. - The current line index is advanced to the end of the elements parsed,
  70. and parsing continues with step 1.
  71. C. The result of the 'text' transition depends on the next line of text.
  72. The current state is changed to `Text`, under which the second line is
  73. examined. If the second line is:
  74. - Indented: The element is a definition list item, and parsing proceeds
  75. similarly to step 2.B, using the `DefinitionList` state.
  76. - A line of uniform punctuation characters: The element is a section
  77. header; again, parsing proceeds as in step 2.B, and `Body` is still
  78. used.
  79. - Anything else: The element is a paragraph, which is examined for
  80. inline markup and appended to the parent element. Processing
  81. continues with step 1.
  82. """
  83. __docformat__ = 'reStructuredText'
  84. import sys
  85. import re
  86. try:
  87. import roman
  88. except ImportError:
  89. import docutils.utils.roman as roman
  90. from types import FunctionType, MethodType
  91. from docutils import nodes, statemachine, utils, urischemes
  92. from docutils import ApplicationError, DataError
  93. from docutils.statemachine import StateMachineWS, StateWS
  94. from docutils.nodes import fully_normalize_name as normalize_name
  95. from docutils.nodes import whitespace_normalize_name
  96. import docutils.parsers.rst
  97. from docutils.parsers.rst import directives, languages, tableparser, roles
  98. from docutils.parsers.rst.languages import en as _fallback_language_module
  99. from docutils.utils import escape2null, unescape, column_width
  100. from docutils.utils import punctuation_chars
  101. class MarkupError(DataError): pass
  102. class UnknownInterpretedRoleError(DataError): pass
  103. class InterpretedRoleNotImplementedError(DataError): pass
  104. class ParserError(ApplicationError): pass
  105. class MarkupMismatch(Exception): pass
  106. class Struct:
  107. """Stores data attributes for dotted-attribute access."""
  108. def __init__(self, **keywordargs):
  109. self.__dict__.update(keywordargs)
  110. class RSTStateMachine(StateMachineWS):
  111. """
  112. reStructuredText's master StateMachine.
  113. The entry point to reStructuredText parsing is the `run()` method.
  114. """
  115. def run(self, input_lines, document, input_offset=0, match_titles=True,
  116. inliner=None):
  117. """
  118. Parse `input_lines` and modify the `document` node in place.
  119. Extend `StateMachineWS.run()`: set up parse-global data and
  120. run the StateMachine.
  121. """
  122. self.language = languages.get_language(
  123. document.settings.language_code)
  124. self.match_titles = match_titles
  125. if inliner is None:
  126. inliner = Inliner()
  127. inliner.init_customizations(document.settings)
  128. self.memo = Struct(document=document,
  129. reporter=document.reporter,
  130. language=self.language,
  131. title_styles=[],
  132. section_level=0,
  133. section_bubble_up_kludge=False,
  134. inliner=inliner)
  135. self.document = document
  136. self.attach_observer(document.note_source)
  137. self.reporter = self.memo.reporter
  138. self.node = document
  139. results = StateMachineWS.run(self, input_lines, input_offset,
  140. input_source=document['source'])
  141. assert results == [], 'RSTStateMachine.run() results should be empty!'
  142. self.node = self.memo = None # remove unneeded references
  143. class NestedStateMachine(StateMachineWS):
  144. """
  145. StateMachine run from within other StateMachine runs, to parse nested
  146. document structures.
  147. """
  148. def run(self, input_lines, input_offset, memo, node, match_titles=True):
  149. """
  150. Parse `input_lines` and populate a `docutils.nodes.document` instance.
  151. Extend `StateMachineWS.run()`: set up document-wide data.
  152. """
  153. self.match_titles = match_titles
  154. self.memo = memo
  155. self.document = memo.document
  156. self.attach_observer(self.document.note_source)
  157. self.reporter = memo.reporter
  158. self.language = memo.language
  159. self.node = node
  160. results = StateMachineWS.run(self, input_lines, input_offset)
  161. assert results == [], ('NestedStateMachine.run() results should be '
  162. 'empty!')
  163. return results
  164. class RSTState(StateWS):
  165. """
  166. reStructuredText State superclass.
  167. Contains methods used by all State subclasses.
  168. """
  169. nested_sm = NestedStateMachine
  170. nested_sm_cache = []
  171. def __init__(self, state_machine, debug=False):
  172. self.nested_sm_kwargs = {'state_classes': state_classes,
  173. 'initial_state': 'Body'}
  174. StateWS.__init__(self, state_machine, debug)
  175. def runtime_init(self):
  176. StateWS.runtime_init(self)
  177. memo = self.state_machine.memo
  178. self.memo = memo
  179. self.reporter = memo.reporter
  180. self.inliner = memo.inliner
  181. self.document = memo.document
  182. self.parent = self.state_machine.node
  183. # enable the reporter to determine source and source-line
  184. if not hasattr(self.reporter, 'get_source_and_line'):
  185. self.reporter.get_source_and_line = self.state_machine.get_source_and_line
  186. # print "adding get_source_and_line to reporter", self.state_machine.input_offset
  187. def goto_line(self, abs_line_offset):
  188. """
  189. Jump to input line `abs_line_offset`, ignoring jumps past the end.
  190. """
  191. try:
  192. self.state_machine.goto_line(abs_line_offset)
  193. except EOFError:
  194. pass
  195. def no_match(self, context, transitions):
  196. """
  197. Override `StateWS.no_match` to generate a system message.
  198. This code should never be run.
  199. """
  200. self.reporter.severe(
  201. 'Internal error: no transition pattern match. State: "%s"; '
  202. 'transitions: %s; context: %s; current line: %r.'
  203. % (self.__class__.__name__, transitions, context,
  204. self.state_machine.line))
  205. return context, None, []
  206. def bof(self, context):
  207. """Called at beginning of file."""
  208. return [], []
  209. def nested_parse(self, block, input_offset, node, match_titles=False,
  210. state_machine_class=None, state_machine_kwargs=None):
  211. """
  212. Create a new StateMachine rooted at `node` and run it over the input
  213. `block`.
  214. """
  215. use_default = 0
  216. if state_machine_class is None:
  217. state_machine_class = self.nested_sm
  218. use_default += 1
  219. if state_machine_kwargs is None:
  220. state_machine_kwargs = self.nested_sm_kwargs
  221. use_default += 1
  222. block_length = len(block)
  223. state_machine = None
  224. if use_default == 2:
  225. try:
  226. state_machine = self.nested_sm_cache.pop()
  227. except IndexError:
  228. pass
  229. if not state_machine:
  230. state_machine = state_machine_class(debug=self.debug,
  231. **state_machine_kwargs)
  232. state_machine.run(block, input_offset, memo=self.memo,
  233. node=node, match_titles=match_titles)
  234. if use_default == 2:
  235. self.nested_sm_cache.append(state_machine)
  236. else:
  237. state_machine.unlink()
  238. new_offset = state_machine.abs_line_offset()
  239. # No `block.parent` implies disconnected -- lines aren't in sync:
  240. if block.parent and (len(block) - block_length) != 0:
  241. # Adjustment for block if modified in nested parse:
  242. self.state_machine.next_line(len(block) - block_length)
  243. return new_offset
  244. def nested_list_parse(self, block, input_offset, node, initial_state,
  245. blank_finish,
  246. blank_finish_state=None,
  247. extra_settings={},
  248. match_titles=False,
  249. state_machine_class=None,
  250. state_machine_kwargs=None):
  251. """
  252. Create a new StateMachine rooted at `node` and run it over the input
  253. `block`. Also keep track of optional intermediate blank lines and the
  254. required final one.
  255. """
  256. if state_machine_class is None:
  257. state_machine_class = self.nested_sm
  258. if state_machine_kwargs is None:
  259. state_machine_kwargs = self.nested_sm_kwargs.copy()
  260. state_machine_kwargs['initial_state'] = initial_state
  261. state_machine = state_machine_class(debug=self.debug,
  262. **state_machine_kwargs)
  263. if blank_finish_state is None:
  264. blank_finish_state = initial_state
  265. state_machine.states[blank_finish_state].blank_finish = blank_finish
  266. for key, value in list(extra_settings.items()):
  267. setattr(state_machine.states[initial_state], key, value)
  268. state_machine.run(block, input_offset, memo=self.memo,
  269. node=node, match_titles=match_titles)
  270. blank_finish = state_machine.states[blank_finish_state].blank_finish
  271. state_machine.unlink()
  272. return state_machine.abs_line_offset(), blank_finish
  273. def section(self, title, source, style, lineno, messages):
  274. """Check for a valid subsection and create one if it checks out."""
  275. if self.check_subsection(source, style, lineno):
  276. self.new_subsection(title, lineno, messages)
  277. def check_subsection(self, source, style, lineno):
  278. """
  279. Check for a valid subsection header. Return 1 (true) or None (false).
  280. When a new section is reached that isn't a subsection of the current
  281. section, back up the line count (use ``previous_line(-x)``), then
  282. ``raise EOFError``. The current StateMachine will finish, then the
  283. calling StateMachine can re-examine the title. This will work its way
  284. back up the calling chain until the correct section level isreached.
  285. @@@ Alternative: Evaluate the title, store the title info & level, and
  286. back up the chain until that level is reached. Store in memo? Or
  287. return in results?
  288. :Exception: `EOFError` when a sibling or supersection encountered.
  289. """
  290. memo = self.memo
  291. title_styles = memo.title_styles
  292. mylevel = memo.section_level
  293. try: # check for existing title style
  294. level = title_styles.index(style) + 1
  295. except ValueError: # new title style
  296. if len(title_styles) == memo.section_level: # new subsection
  297. title_styles.append(style)
  298. return 1
  299. else: # not at lowest level
  300. self.parent += self.title_inconsistent(source, lineno)
  301. return None
  302. if level <= mylevel: # sibling or supersection
  303. memo.section_level = level # bubble up to parent section
  304. if len(style) == 2:
  305. memo.section_bubble_up_kludge = True
  306. # back up 2 lines for underline title, 3 for overline title
  307. self.state_machine.previous_line(len(style) + 1)
  308. raise EOFError # let parent section re-evaluate
  309. if level == mylevel + 1: # immediate subsection
  310. return 1
  311. else: # invalid subsection
  312. self.parent += self.title_inconsistent(source, lineno)
  313. return None
  314. def title_inconsistent(self, sourcetext, lineno):
  315. error = self.reporter.severe(
  316. 'Title level inconsistent:', nodes.literal_block('', sourcetext),
  317. line=lineno)
  318. return error
  319. def new_subsection(self, title, lineno, messages):
  320. """Append new subsection to document tree. On return, check level."""
  321. memo = self.memo
  322. mylevel = memo.section_level
  323. memo.section_level += 1
  324. section_node = nodes.section()
  325. self.parent += section_node
  326. textnodes, title_messages = self.inline_text(title, lineno)
  327. titlenode = nodes.title(title, '', *textnodes)
  328. name = normalize_name(titlenode.astext())
  329. section_node['names'].append(name)
  330. section_node += titlenode
  331. section_node += messages
  332. section_node += title_messages
  333. self.document.note_implicit_target(section_node, section_node)
  334. offset = self.state_machine.line_offset + 1
  335. absoffset = self.state_machine.abs_line_offset() + 1
  336. newabsoffset = self.nested_parse(
  337. self.state_machine.input_lines[offset:], input_offset=absoffset,
  338. node=section_node, match_titles=True)
  339. self.goto_line(newabsoffset)
  340. if memo.section_level <= mylevel: # can't handle next section?
  341. raise EOFError # bubble up to supersection
  342. # reset section_level; next pass will detect it properly
  343. memo.section_level = mylevel
  344. def paragraph(self, lines, lineno):
  345. """
  346. Return a list (paragraph & messages) & a boolean: literal_block next?
  347. """
  348. data = '\n'.join(lines).rstrip()
  349. if re.search(r'(?<!\\)(\\\\)*::$', data):
  350. if len(data) == 2:
  351. return [], 1
  352. elif data[-3] in ' \n':
  353. text = data[:-3].rstrip()
  354. else:
  355. text = data[:-1]
  356. literalnext = 1
  357. else:
  358. text = data
  359. literalnext = 0
  360. textnodes, messages = self.inline_text(text, lineno)
  361. p = nodes.paragraph(data, '', *textnodes)
  362. p.source, p.line = self.state_machine.get_source_and_line(lineno)
  363. return [p] + messages, literalnext
  364. def inline_text(self, text, lineno):
  365. """
  366. Return 2 lists: nodes (text and inline elements), and system_messages.
  367. """
  368. return self.inliner.parse(text, lineno, self.memo, self.parent)
  369. def unindent_warning(self, node_name):
  370. # the actual problem is one line below the current line
  371. lineno = self.state_machine.abs_line_number()+1
  372. return self.reporter.warning('%s ends without a blank line; '
  373. 'unexpected unindent.' % node_name,
  374. line=lineno)
  375. def build_regexp(definition, compile=True):
  376. """
  377. Build, compile and return a regular expression based on `definition`.
  378. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts),
  379. where "parts" is a list of regular expressions and/or regular
  380. expression definitions to be joined into an or-group.
  381. """
  382. name, prefix, suffix, parts = definition
  383. part_strings = []
  384. for part in parts:
  385. if type(part) is tuple:
  386. part_strings.append(build_regexp(part, None))
  387. else:
  388. part_strings.append(part)
  389. or_group = '|'.join(part_strings)
  390. regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals()
  391. if compile:
  392. return re.compile(regexp, re.UNICODE)
  393. else:
  394. return regexp
  395. class Inliner:
  396. """
  397. Parse inline markup; call the `parse()` method.
  398. """
  399. def __init__(self):
  400. self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),]
  401. """List of (pattern, bound method) tuples, used by
  402. `self.implicit_inline`."""
  403. def init_customizations(self, settings):
  404. """Setting-based customizations; run when parsing begins."""
  405. if settings.pep_references:
  406. self.implicit_dispatch.append((self.patterns.pep,
  407. self.pep_reference))
  408. if settings.rfc_references:
  409. self.implicit_dispatch.append((self.patterns.rfc,
  410. self.rfc_reference))
  411. def parse(self, text, lineno, memo, parent):
  412. # Needs to be refactored for nested inline markup.
  413. # Add nested_parse() method?
  414. """
  415. Return 2 lists: nodes (text and inline elements), and system_messages.
  416. Using `self.patterns.initial`, a pattern which matches start-strings
  417. (emphasis, strong, interpreted, phrase reference, literal,
  418. substitution reference, and inline target) and complete constructs
  419. (simple reference, footnote reference), search for a candidate. When
  420. one is found, check for validity (e.g., not a quoted '*' character).
  421. If valid, search for the corresponding end string if applicable, and
  422. check it for validity. If not found or invalid, generate a warning
  423. and ignore the start-string. Implicit inline markup (e.g. standalone
  424. URIs) is found last.
  425. """
  426. self.reporter = memo.reporter
  427. self.document = memo.document
  428. self.language = memo.language
  429. self.parent = parent
  430. pattern_search = self.patterns.initial.search
  431. dispatch = self.dispatch
  432. remaining = escape2null(text)
  433. processed = []
  434. unprocessed = []
  435. messages = []
  436. while remaining:
  437. match = pattern_search(remaining)
  438. if match:
  439. groups = match.groupdict()
  440. method = dispatch[groups['start'] or groups['backquote']
  441. or groups['refend'] or groups['fnend']]
  442. before, inlines, remaining, sysmessages = method(self, match,
  443. lineno)
  444. unprocessed.append(before)
  445. messages += sysmessages
  446. if inlines:
  447. processed += self.implicit_inline(''.join(unprocessed),
  448. lineno)
  449. processed += inlines
  450. unprocessed = []
  451. else:
  452. break
  453. remaining = ''.join(unprocessed) + remaining
  454. if remaining:
  455. processed += self.implicit_inline(remaining, lineno)
  456. return processed, messages
  457. # Inline object recognition
  458. # -------------------------
  459. # lookahead and look-behind expressions for inline markup rules
  460. start_string_prefix = ('(^|(?<=\\s|[%s%s]))' %
  461. (punctuation_chars.openers,
  462. punctuation_chars.delimiters))
  463. end_string_suffix = ('($|(?=\\s|[\x00%s%s%s]))' %
  464. (punctuation_chars.closing_delimiters,
  465. punctuation_chars.delimiters,
  466. punctuation_chars.closers))
  467. # print start_string_prefix.encode('utf8')
  468. # TODO: support non-ASCII whitespace in the following 4 patterns?
  469. non_whitespace_before = r'(?<![ \n])'
  470. non_whitespace_escape_before = r'(?<![ \n\x00])'
  471. non_unescaped_whitespace_escape_before = r'(?<!(?<!\x00)[ \n\x00])'
  472. non_whitespace_after = r'(?![ \n])'
  473. # Alphanumerics with isolated internal [-._+:] chars (i.e. not 2 together):
  474. simplename = r'(?:(?!_)\w)+(?:[-._+:](?:(?!_)\w)+)*'
  475. # Valid URI characters (see RFC 2396 & RFC 2732);
  476. # final \x00 allows backslash escapes in URIs:
  477. uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]"""
  478. # Delimiter indicating the end of a URI (not part of the URI):
  479. uri_end_delim = r"""[>]"""
  480. # Last URI character; same as uric but no punctuation:
  481. urilast = r"""[_~*/=+a-zA-Z0-9]"""
  482. # End of a URI (either 'urilast' or 'uric followed by a
  483. # uri_end_delim'):
  484. uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals()
  485. emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]"""
  486. email_pattern = r"""
  487. %(emailc)s+(?:\.%(emailc)s+)* # name
  488. (?<!\x00)@ # at
  489. %(emailc)s+(?:\.%(emailc)s*)* # host
  490. %(uri_end)s # final URI char
  491. """
  492. parts = ('initial_inline', start_string_prefix, '',
  493. [('start', '', non_whitespace_after, # simple start-strings
  494. [r'\*\*', # strong
  495. r'\*(?!\*)', # emphasis but not strong
  496. r'``', # literal
  497. r'_`', # inline internal target
  498. r'\|(?!\|)'] # substitution reference
  499. ),
  500. ('whole', '', end_string_suffix, # whole constructs
  501. [# reference name & end-string
  502. r'(?P<refname>%s)(?P<refend>__?)' % simplename,
  503. ('footnotelabel', r'\[', r'(?P<fnend>\]_)',
  504. [r'[0-9]+', # manually numbered
  505. r'\#(%s)?' % simplename, # auto-numbered (w/ label?)
  506. r'\*', # auto-symbol
  507. r'(?P<citationlabel>%s)' % simplename] # citation reference
  508. )
  509. ]
  510. ),
  511. ('backquote', # interpreted text or phrase reference
  512. '(?P<role>(:%s:)?)' % simplename, # optional role
  513. non_whitespace_after,
  514. ['`(?!`)'] # but not literal
  515. )
  516. ]
  517. )
  518. patterns = Struct(
  519. initial=build_regexp(parts),
  520. emphasis=re.compile(non_whitespace_escape_before
  521. + r'(\*)' + end_string_suffix, re.UNICODE),
  522. strong=re.compile(non_whitespace_escape_before
  523. + r'(\*\*)' + end_string_suffix, re.UNICODE),
  524. interpreted_or_phrase_ref=re.compile(
  525. r"""
  526. %(non_unescaped_whitespace_escape_before)s
  527. (
  528. `
  529. (?P<suffix>
  530. (?P<role>:%(simplename)s:)?
  531. (?P<refend>__?)?
  532. )
  533. )
  534. %(end_string_suffix)s
  535. """ % locals(), re.VERBOSE | re.UNICODE),
  536. embedded_uri=re.compile(
  537. r"""
  538. (
  539. (?:[ \n]+|^) # spaces or beginning of line/string
  540. < # open bracket
  541. %(non_whitespace_after)s
  542. ([^<>\x00]+) # anything but angle brackets & nulls
  543. %(non_whitespace_before)s
  544. > # close bracket w/o whitespace before
  545. )
  546. $ # end of string
  547. """ % locals(), re.VERBOSE | re.UNICODE),
  548. literal=re.compile(non_whitespace_before + '(``)'
  549. + end_string_suffix),
  550. target=re.compile(non_whitespace_escape_before
  551. + r'(`)' + end_string_suffix),
  552. substitution_ref=re.compile(non_whitespace_escape_before
  553. + r'(\|_{0,2})'
  554. + end_string_suffix),
  555. email=re.compile(email_pattern % locals() + '$',
  556. re.VERBOSE | re.UNICODE),
  557. uri=re.compile(
  558. (r"""
  559. %(start_string_prefix)s
  560. (?P<whole>
  561. (?P<absolute> # absolute URI
  562. (?P<scheme> # scheme (http, ftp, mailto)
  563. [a-zA-Z][a-zA-Z0-9.+-]*
  564. )
  565. :
  566. (
  567. ( # either:
  568. (//?)? # hierarchical URI
  569. %(uric)s* # URI characters
  570. %(uri_end)s # final URI char
  571. )
  572. ( # optional query
  573. \?%(uric)s*
  574. %(uri_end)s
  575. )?
  576. ( # optional fragment
  577. \#%(uric)s*
  578. %(uri_end)s
  579. )?
  580. )
  581. )
  582. | # *OR*
  583. (?P<email> # email address
  584. """ + email_pattern + r"""
  585. )
  586. )
  587. %(end_string_suffix)s
  588. """) % locals(), re.VERBOSE | re.UNICODE),
  589. pep=re.compile(
  590. r"""
  591. %(start_string_prefix)s
  592. (
  593. (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file
  594. |
  595. (PEP\s+(?P<pepnum2>\d+)) # reference by name
  596. )
  597. %(end_string_suffix)s""" % locals(), re.VERBOSE | re.UNICODE),
  598. rfc=re.compile(
  599. r"""
  600. %(start_string_prefix)s
  601. (RFC(-|\s+)?(?P<rfcnum>\d+))
  602. %(end_string_suffix)s""" % locals(), re.VERBOSE | re.UNICODE))
  603. def quoted_start(self, match):
  604. """Test if inline markup start-string is 'quoted'.
  605. 'Quoted' in this context means the start-string is enclosed in a pair
  606. of matching opening/closing delimiters (not necessarily quotes)
  607. or at the end of the match.
  608. """
  609. string = match.string
  610. start = match.start()
  611. if start == 0: # start-string at beginning of text
  612. return False
  613. prestart = string[start - 1]
  614. try:
  615. poststart = string[match.end()]
  616. except IndexError: # start-string at end of text
  617. return True # not "quoted" but no markup start-string either
  618. return punctuation_chars.match_chars(prestart, poststart)
  619. def inline_obj(self, match, lineno, end_pattern, nodeclass,
  620. restore_backslashes=False):
  621. string = match.string
  622. matchstart = match.start('start')
  623. matchend = match.end('start')
  624. if self.quoted_start(match):
  625. return (string[:matchend], [], string[matchend:], [], '')
  626. endmatch = end_pattern.search(string[matchend:])
  627. if endmatch and endmatch.start(1): # 1 or more chars
  628. text = unescape(endmatch.string[:endmatch.start(1)],
  629. restore_backslashes)
  630. textend = matchend + endmatch.end(1)
  631. rawsource = unescape(string[matchstart:textend], 1)
  632. return (string[:matchstart], [nodeclass(rawsource, text)],
  633. string[textend:], [], endmatch.group(1))
  634. msg = self.reporter.warning(
  635. 'Inline %s start-string without end-string.'
  636. % nodeclass.__name__, line=lineno)
  637. text = unescape(string[matchstart:matchend], 1)
  638. rawsource = unescape(string[matchstart:matchend], 1)
  639. prb = self.problematic(text, rawsource, msg)
  640. return string[:matchstart], [prb], string[matchend:], [msg], ''
  641. def problematic(self, text, rawsource, message):
  642. msgid = self.document.set_id(message, self.parent)
  643. problematic = nodes.problematic(rawsource, text, refid=msgid)
  644. prbid = self.document.set_id(problematic)
  645. message.add_backref(prbid)
  646. return problematic
  647. def emphasis(self, match, lineno):
  648. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  649. match, lineno, self.patterns.emphasis, nodes.emphasis)
  650. return before, inlines, remaining, sysmessages
  651. def strong(self, match, lineno):
  652. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  653. match, lineno, self.patterns.strong, nodes.strong)
  654. return before, inlines, remaining, sysmessages
  655. def interpreted_or_phrase_ref(self, match, lineno):
  656. end_pattern = self.patterns.interpreted_or_phrase_ref
  657. string = match.string
  658. matchstart = match.start('backquote')
  659. matchend = match.end('backquote')
  660. rolestart = match.start('role')
  661. role = match.group('role')
  662. position = ''
  663. if role:
  664. role = role[1:-1]
  665. position = 'prefix'
  666. elif self.quoted_start(match):
  667. return (string[:matchend], [], string[matchend:], [])
  668. endmatch = end_pattern.search(string[matchend:])
  669. if endmatch and endmatch.start(1): # 1 or more chars
  670. textend = matchend + endmatch.end()
  671. if endmatch.group('role'):
  672. if role:
  673. msg = self.reporter.warning(
  674. 'Multiple roles in interpreted text (both '
  675. 'prefix and suffix present; only one allowed).',
  676. line=lineno)
  677. text = unescape(string[rolestart:textend], 1)
  678. prb = self.problematic(text, text, msg)
  679. return string[:rolestart], [prb], string[textend:], [msg]
  680. role = endmatch.group('suffix')[1:-1]
  681. position = 'suffix'
  682. escaped = endmatch.string[:endmatch.start(1)]
  683. rawsource = unescape(string[matchstart:textend], 1)
  684. if rawsource[-1:] == '_':
  685. if role:
  686. msg = self.reporter.warning(
  687. 'Mismatch: both interpreted text role %s and '
  688. 'reference suffix.' % position, line=lineno)
  689. text = unescape(string[rolestart:textend], 1)
  690. prb = self.problematic(text, text, msg)
  691. return string[:rolestart], [prb], string[textend:], [msg]
  692. return self.phrase_ref(string[:matchstart], string[textend:],
  693. rawsource, escaped, unescape(escaped))
  694. else:
  695. rawsource = unescape(string[rolestart:textend], 1)
  696. nodelist, messages = self.interpreted(rawsource, escaped, role,
  697. lineno)
  698. return (string[:rolestart], nodelist,
  699. string[textend:], messages)
  700. msg = self.reporter.warning(
  701. 'Inline interpreted text or phrase reference start-string '
  702. 'without end-string.', line=lineno)
  703. text = unescape(string[matchstart:matchend], 1)
  704. prb = self.problematic(text, text, msg)
  705. return string[:matchstart], [prb], string[matchend:], [msg]
  706. def phrase_ref(self, before, after, rawsource, escaped, text):
  707. match = self.patterns.embedded_uri.search(escaped)
  708. if match:
  709. text = unescape(escaped[:match.start(0)])
  710. uri_text = match.group(2)
  711. uri = ''.join(uri_text.split())
  712. uri = self.adjust_uri(uri)
  713. if uri:
  714. target = nodes.target(match.group(1), refuri=uri)
  715. target.referenced = 1
  716. else:
  717. raise ApplicationError('problem with URI: %r' % uri_text)
  718. if not text:
  719. text = uri
  720. else:
  721. target = None
  722. refname = normalize_name(text)
  723. reference = nodes.reference(rawsource, text,
  724. name=whitespace_normalize_name(text))
  725. node_list = [reference]
  726. if rawsource[-2:] == '__':
  727. if target:
  728. reference['refuri'] = uri
  729. else:
  730. reference['anonymous'] = 1
  731. else:
  732. if target:
  733. reference['refuri'] = uri
  734. target['names'].append(refname)
  735. self.document.note_explicit_target(target, self.parent)
  736. node_list.append(target)
  737. else:
  738. reference['refname'] = refname
  739. self.document.note_refname(reference)
  740. return before, node_list, after, []
  741. def adjust_uri(self, uri):
  742. match = self.patterns.email.match(uri)
  743. if match:
  744. return 'mailto:' + uri
  745. else:
  746. return uri
  747. def interpreted(self, rawsource, text, role, lineno):
  748. role_fn, messages = roles.role(role, self.language, lineno,
  749. self.reporter)
  750. if role_fn:
  751. nodes, messages2 = role_fn(role, rawsource, text, lineno, self)
  752. return nodes, messages + messages2
  753. else:
  754. msg = self.reporter.error(
  755. 'Unknown interpreted text role "%s".' % role,
  756. line=lineno)
  757. return ([self.problematic(rawsource, rawsource, msg)],
  758. messages + [msg])
  759. def literal(self, match, lineno):
  760. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  761. match, lineno, self.patterns.literal, nodes.literal,
  762. restore_backslashes=True)
  763. return before, inlines, remaining, sysmessages
  764. def inline_internal_target(self, match, lineno):
  765. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  766. match, lineno, self.patterns.target, nodes.target)
  767. if inlines and isinstance(inlines[0], nodes.target):
  768. assert len(inlines) == 1
  769. target = inlines[0]
  770. name = normalize_name(target.astext())
  771. target['names'].append(name)
  772. self.document.note_explicit_target(target, self.parent)
  773. return before, inlines, remaining, sysmessages
  774. def substitution_reference(self, match, lineno):
  775. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  776. match, lineno, self.patterns.substitution_ref,
  777. nodes.substitution_reference)
  778. if len(inlines) == 1:
  779. subref_node = inlines[0]
  780. if isinstance(subref_node, nodes.substitution_reference):
  781. subref_text = subref_node.astext()
  782. self.document.note_substitution_ref(subref_node, subref_text)
  783. if endstring[-1:] == '_':
  784. reference_node = nodes.reference(
  785. '|%s%s' % (subref_text, endstring), '')
  786. if endstring[-2:] == '__':
  787. reference_node['anonymous'] = 1
  788. else:
  789. reference_node['refname'] = normalize_name(subref_text)
  790. self.document.note_refname(reference_node)
  791. reference_node += subref_node
  792. inlines = [reference_node]
  793. return before, inlines, remaining, sysmessages
  794. def footnote_reference(self, match, lineno):
  795. """
  796. Handles `nodes.footnote_reference` and `nodes.citation_reference`
  797. elements.
  798. """
  799. label = match.group('footnotelabel')
  800. refname = normalize_name(label)
  801. string = match.string
  802. before = string[:match.start('whole')]
  803. remaining = string[match.end('whole'):]
  804. if match.group('citationlabel'):
  805. refnode = nodes.citation_reference('[%s]_' % label,
  806. refname=refname)
  807. refnode += nodes.Text(label)
  808. self.document.note_citation_ref(refnode)
  809. else:
  810. refnode = nodes.footnote_reference('[%s]_' % label)
  811. if refname[0] == '#':
  812. refname = refname[1:]
  813. refnode['auto'] = 1
  814. self.document.note_autofootnote_ref(refnode)
  815. elif refname == '*':
  816. refname = ''
  817. refnode['auto'] = '*'
  818. self.document.note_symbol_footnote_ref(
  819. refnode)
  820. else:
  821. refnode += nodes.Text(label)
  822. if refname:
  823. refnode['refname'] = refname
  824. self.document.note_footnote_ref(refnode)
  825. if utils.get_trim_footnote_ref_space(self.document.settings):
  826. before = before.rstrip()
  827. return (before, [refnode], remaining, [])
  828. def reference(self, match, lineno, anonymous=False):
  829. referencename = match.group('refname')
  830. refname = normalize_name(referencename)
  831. referencenode = nodes.reference(
  832. referencename + match.group('refend'), referencename,
  833. name=whitespace_normalize_name(referencename))
  834. if anonymous:
  835. referencenode['anonymous'] = 1
  836. else:
  837. referencenode['refname'] = refname
  838. self.document.note_refname(referencenode)
  839. string = match.string
  840. matchstart = match.start('whole')
  841. matchend = match.end('whole')
  842. return (string[:matchstart], [referencenode], string[matchend:], [])
  843. def anonymous_reference(self, match, lineno):
  844. return self.reference(match, lineno, anonymous=1)
  845. def standalone_uri(self, match, lineno):
  846. if (not match.group('scheme')
  847. or match.group('scheme').lower() in urischemes.schemes):
  848. if match.group('email'):
  849. addscheme = 'mailto:'
  850. else:
  851. addscheme = ''
  852. text = match.group('whole')
  853. unescaped = unescape(text, 0)
  854. return [nodes.reference(unescape(text, 1), unescaped,
  855. refuri=addscheme + unescaped)]
  856. else: # not a valid scheme
  857. raise MarkupMismatch
  858. def pep_reference(self, match, lineno):
  859. text = match.group(0)
  860. if text.startswith('pep-'):
  861. pepnum = int(match.group('pepnum1'))
  862. elif text.startswith('PEP'):
  863. pepnum = int(match.group('pepnum2'))
  864. else:
  865. raise MarkupMismatch
  866. ref = (self.document.settings.pep_base_url
  867. + self.document.settings.pep_file_url_template % pepnum)
  868. unescaped = unescape(text, 0)
  869. return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)]
  870. rfc_url = 'rfc%d.html'
  871. def rfc_reference(self, match, lineno):
  872. text = match.group(0)
  873. if text.startswith('RFC'):
  874. rfcnum = int(match.group('rfcnum'))
  875. ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum
  876. else:
  877. raise MarkupMismatch
  878. unescaped = unescape(text, 0)
  879. return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)]
  880. def implicit_inline(self, text, lineno):
  881. """
  882. Check each of the patterns in `self.implicit_dispatch` for a match,
  883. and dispatch to the stored method for the pattern. Recursively check
  884. the text before and after the match. Return a list of `nodes.Text`
  885. and inline element nodes.
  886. """
  887. if not text:
  888. return []
  889. for pattern, method in self.implicit_dispatch:
  890. match = pattern.search(text)
  891. if match:
  892. try:
  893. # Must recurse on strings before *and* after the match;
  894. # there may be multiple patterns.
  895. return (self.implicit_inline(text[:match.start()], lineno)
  896. + method(match, lineno) +
  897. self.implicit_inline(text[match.end():], lineno))
  898. except MarkupMismatch:
  899. pass
  900. return [nodes.Text(unescape(text), rawsource=unescape(text, 1))]
  901. dispatch = {'*': emphasis,
  902. '**': strong,
  903. '`': interpreted_or_phrase_ref,
  904. '``': literal,
  905. '_`': inline_internal_target,
  906. ']_': footnote_reference,
  907. '|': substitution_reference,
  908. '_': reference,
  909. '__': anonymous_reference}
  910. def _loweralpha_to_int(s, _zero=(ord('a')-1)):
  911. return ord(s) - _zero
  912. def _upperalpha_to_int(s, _zero=(ord('A')-1)):
  913. return ord(s) - _zero
  914. def _lowerroman_to_int(s):
  915. return roman.fromRoman(s.upper())
  916. class Body(RSTState):
  917. """
  918. Generic classifier of the first line of a block.
  919. """
  920. double_width_pad_char = tableparser.TableParser.double_width_pad_char
  921. """Padding character for East Asian double-width text."""
  922. enum = Struct()
  923. """Enumerated list parsing information."""
  924. enum.formatinfo = {
  925. 'parens': Struct(prefix='(', suffix=')', start=1, end=-1),
  926. 'rparen': Struct(prefix='', suffix=')', start=0, end=-1),
  927. 'period': Struct(prefix='', suffix='.', start=0, end=-1)}
  928. enum.formats = list(enum.formatinfo.keys())
  929. enum.sequences = ['arabic', 'loweralpha', 'upperalpha',
  930. 'lowerroman', 'upperroman'] # ORDERED!
  931. enum.sequencepats = {'arabic': '[0-9]+',
  932. 'loweralpha': '[a-z]',
  933. 'upperalpha': '[A-Z]',
  934. 'lowerroman': '[ivxlcdm]+',
  935. 'upperroman': '[IVXLCDM]+',}
  936. enum.converters = {'arabic': int,
  937. 'loweralpha': _loweralpha_to_int,
  938. 'upperalpha': _upperalpha_to_int,
  939. 'lowerroman': _lowerroman_to_int,
  940. 'upperroman': roman.fromRoman}
  941. enum.sequenceregexps = {}
  942. for sequence in enum.sequences:
  943. enum.sequenceregexps[sequence] = re.compile(
  944. enum.sequencepats[sequence] + '$', re.UNICODE)
  945. grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$')
  946. """Matches the top (& bottom) of a full table)."""
  947. simple_table_top_pat = re.compile('=+( +=+)+ *$')
  948. """Matches the top of a simple table."""
  949. simple_table_border_pat = re.compile('=+[ =]*$')
  950. """Matches the bottom & header bottom of a simple table."""
  951. pats = {}
  952. """Fragments of patterns used by transitions."""
  953. pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]'
  954. pats['alpha'] = '[a-zA-Z]'
  955. pats['alphanum'] = '[a-zA-Z0-9]'
  956. pats['alphanumplus'] = '[a-zA-Z0-9_-]'
  957. pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s'
  958. '|%(upperroman)s|#)' % enum.sequencepats)
  959. pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats
  960. # @@@ Loosen up the pattern? Allow Unicode?
  961. pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats
  962. pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats
  963. pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats
  964. pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats
  965. for format in enum.formats:
  966. pats[format] = '(?P<%s>%s%s%s)' % (
  967. format, re.escape(enum.formatinfo[format].prefix),
  968. pats['enum'], re.escape(enum.formatinfo[format].suffix))
  969. patterns = {
  970. 'bullet': '[-+*\u2022\u2023\u2043]( +|$)',
  971. 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats,
  972. 'field_marker': r':(?![: ])([^:\\]|\\.)*(?<! ):( +|$)',
  973. 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats,
  974. 'doctest': r'>>>( +|$)',
  975. 'line_block': r'\|( +|$)',
  976. 'grid_table_top': grid_table_top_pat,
  977. 'simple_table_top': simple_table_top_pat,
  978. 'explicit_markup': r'\.\.( +|$)',
  979. 'anonymous': r'__( +|$)',
  980. 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats,
  981. 'text': r''}
  982. initial_transitions = (
  983. 'bullet',
  984. 'enumerator',
  985. 'field_marker',
  986. 'option_marker',
  987. 'doctest',
  988. 'line_block',
  989. 'grid_table_top',
  990. 'simple_table_top',
  991. 'explicit_markup',
  992. 'anonymous',
  993. 'line',
  994. 'text')
  995. def indent(self, match, context, next_state):
  996. """Block quote."""
  997. indented, indent, line_offset, blank_finish = \
  998. self.state_machine.get_indented()
  999. elements = self.block_quote(indented, line_offset)
  1000. self.parent += elements
  1001. if not blank_finish:
  1002. self.parent += self.unindent_warning('Block quote')
  1003. return context, next_state, []
  1004. def block_quote(self, indented, line_offset):
  1005. elements = []
  1006. while indented:
  1007. (blockquote_lines,
  1008. attribution_lines,
  1009. attribution_offset,
  1010. indented,
  1011. new_line_offset) = self.split_attribution(indented, line_offset)
  1012. blockquote = nodes.block_quote()
  1013. self.nested_parse(blockquote_lines, line_offset, blockquote)
  1014. elements.append(blockquote)
  1015. if attribution_lines:
  1016. attribution, messages = self.parse_attribution(
  1017. attribution_lines, attribution_offset)
  1018. blockquote += attribution
  1019. elements += messages
  1020. line_offset = new_line_offset
  1021. while indented and not indented[0]:
  1022. indented = indented[1:]
  1023. line_offset += 1
  1024. return elements
  1025. # U+2014 is an em-dash:
  1026. attribution_pattern = re.compile('(---?(?!-)|\u2014) *(?=[^ \\n])',
  1027. re.UNICODE)
  1028. def split_attribution(self, indented, line_offset):
  1029. """
  1030. Check for a block quote attribution and split it off:
  1031. * First line after a blank line must begin with a dash ("--", "---",
  1032. em-dash; matches `self.attribution_pattern`).
  1033. * Every line after that must have consistent indentation.
  1034. * Attributions must be preceded by block quote content.
  1035. Return a tuple of: (block quote content lines, content offset,
  1036. attribution lines, attribution offset, remaining indented lines).
  1037. """
  1038. blank = None
  1039. nonblank_seen = False
  1040. for i in range(len(indented)):
  1041. line = indented[i].rstrip()
  1042. if line:
  1043. if nonblank_seen and blank == i - 1: # last line blank
  1044. match = self.attribution_pattern.match(line)
  1045. if match:
  1046. attribution_end, indent = self.check_attribution(
  1047. indented, i)
  1048. if attribution_end:
  1049. a_lines = indented[i:attribution_end]
  1050. a_lines.trim_left(match.end(), end=1)
  1051. a_lines.trim_left(indent, start=1)
  1052. return (indented[:i], a_lines,
  1053. i, indented[attribution_end:],
  1054. line_offset + attribution_end)
  1055. nonblank_seen = True
  1056. else:

Large files files are truncated, but you can click here to view the full file