/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/parsers/rst/states.py

http://github.com/IronLanguages/main · Python · 2988 lines · 2567 code · 167 blank · 254 comment · 263 complexity · 6ce5880999a37ea5b18a992d37ba39cb MD5 · raw file

Large files are truncated click here to view the full file

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