PageRenderTime 80ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/cpython-doc/tools/docutils/parsers/rst/states.py

https://bitbucket.org/csenger/benchmarks
Python | 3008 lines | 2912 code | 21 blank | 75 comment | 48 complexity | 494a8d8114df0149de8ee8fef642e535 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-2.0
  1. # $Id: states.py 78909 2010-03-13 10:49:23Z georg.brandl $
  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 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. nested_sm_cache = []
  167. def __init__(self, state_machine, debug=0):
  168. self.nested_sm_kwargs = {'state_classes': state_classes,
  169. 'initial_state': 'Body'}
  170. StateWS.__init__(self, state_machine, debug)
  171. def runtime_init(self):
  172. StateWS.runtime_init(self)
  173. memo = self.state_machine.memo
  174. self.memo = memo
  175. self.reporter = memo.reporter
  176. self.inliner = memo.inliner
  177. self.document = memo.document
  178. self.parent = self.state_machine.node
  179. def goto_line(self, abs_line_offset):
  180. """
  181. Jump to input line `abs_line_offset`, ignoring jumps past the end.
  182. """
  183. try:
  184. self.state_machine.goto_line(abs_line_offset)
  185. except EOFError:
  186. pass
  187. def no_match(self, context, transitions):
  188. """
  189. Override `StateWS.no_match` to generate a system message.
  190. This code should never be run.
  191. """
  192. self.reporter.severe(
  193. 'Internal error: no transition pattern match. State: "%s"; '
  194. 'transitions: %s; context: %s; current line: %r.'
  195. % (self.__class__.__name__, transitions, context,
  196. self.state_machine.line),
  197. line=self.state_machine.abs_line_number())
  198. return context, None, []
  199. def bof(self, context):
  200. """Called at beginning of file."""
  201. return [], []
  202. def nested_parse(self, block, input_offset, node, match_titles=0,
  203. state_machine_class=None, state_machine_kwargs=None):
  204. """
  205. Create a new StateMachine rooted at `node` and run it over the input
  206. `block`.
  207. """
  208. use_default = 0
  209. if state_machine_class is None:
  210. state_machine_class = self.nested_sm
  211. use_default += 1
  212. if state_machine_kwargs is None:
  213. state_machine_kwargs = self.nested_sm_kwargs
  214. use_default += 1
  215. block_length = len(block)
  216. state_machine = None
  217. if use_default == 2:
  218. try:
  219. state_machine = self.nested_sm_cache.pop()
  220. except IndexError:
  221. pass
  222. if not state_machine:
  223. state_machine = state_machine_class(debug=self.debug,
  224. **state_machine_kwargs)
  225. state_machine.run(block, input_offset, memo=self.memo,
  226. node=node, match_titles=match_titles)
  227. if use_default == 2:
  228. self.nested_sm_cache.append(state_machine)
  229. else:
  230. state_machine.unlink()
  231. new_offset = state_machine.abs_line_offset()
  232. # No `block.parent` implies disconnected -- lines aren't in sync:
  233. if block.parent and (len(block) - block_length) != 0:
  234. # Adjustment for block if modified in nested parse:
  235. self.state_machine.next_line(len(block) - block_length)
  236. return new_offset
  237. def nested_list_parse(self, block, input_offset, node, initial_state,
  238. blank_finish,
  239. blank_finish_state=None,
  240. extra_settings={},
  241. match_titles=0,
  242. state_machine_class=None,
  243. state_machine_kwargs=None):
  244. """
  245. Create a new StateMachine rooted at `node` and run it over the input
  246. `block`. Also keep track of optional intermediate blank lines and the
  247. required final one.
  248. """
  249. if state_machine_class is None:
  250. state_machine_class = self.nested_sm
  251. if state_machine_kwargs is None:
  252. state_machine_kwargs = self.nested_sm_kwargs.copy()
  253. state_machine_kwargs['initial_state'] = initial_state
  254. state_machine = state_machine_class(debug=self.debug,
  255. **state_machine_kwargs)
  256. if blank_finish_state is None:
  257. blank_finish_state = initial_state
  258. state_machine.states[blank_finish_state].blank_finish = blank_finish
  259. for key, value in extra_settings.items():
  260. setattr(state_machine.states[initial_state], key, value)
  261. state_machine.run(block, input_offset, memo=self.memo,
  262. node=node, match_titles=match_titles)
  263. blank_finish = state_machine.states[blank_finish_state].blank_finish
  264. state_machine.unlink()
  265. return state_machine.abs_line_offset(), blank_finish
  266. def section(self, title, source, style, lineno, messages):
  267. """Check for a valid subsection and create one if it checks out."""
  268. if self.check_subsection(source, style, lineno):
  269. self.new_subsection(title, lineno, messages)
  270. def check_subsection(self, source, style, lineno):
  271. """
  272. Check for a valid subsection header. Return 1 (true) or None (false).
  273. When a new section is reached that isn't a subsection of the current
  274. section, back up the line count (use ``previous_line(-x)``), then
  275. ``raise EOFError``. The current StateMachine will finish, then the
  276. calling StateMachine can re-examine the title. This will work its way
  277. back up the calling chain until the correct section level isreached.
  278. @@@ Alternative: Evaluate the title, store the title info & level, and
  279. back up the chain until that level is reached. Store in memo? Or
  280. return in results?
  281. :Exception: `EOFError` when a sibling or supersection encountered.
  282. """
  283. memo = self.memo
  284. title_styles = memo.title_styles
  285. mylevel = memo.section_level
  286. try: # check for existing title style
  287. level = title_styles.index(style) + 1
  288. except ValueError: # new title style
  289. if len(title_styles) == memo.section_level: # new subsection
  290. title_styles.append(style)
  291. return 1
  292. else: # not at lowest level
  293. self.parent += self.title_inconsistent(source, lineno)
  294. return None
  295. if level <= mylevel: # sibling or supersection
  296. memo.section_level = level # bubble up to parent section
  297. if len(style) == 2:
  298. memo.section_bubble_up_kludge = 1
  299. # back up 2 lines for underline title, 3 for overline title
  300. self.state_machine.previous_line(len(style) + 1)
  301. raise EOFError # let parent section re-evaluate
  302. if level == mylevel + 1: # immediate subsection
  303. return 1
  304. else: # invalid subsection
  305. self.parent += self.title_inconsistent(source, lineno)
  306. return None
  307. def title_inconsistent(self, sourcetext, lineno):
  308. error = self.reporter.severe(
  309. 'Title level inconsistent:', nodes.literal_block('', sourcetext),
  310. line=lineno)
  311. return error
  312. def new_subsection(self, title, lineno, messages):
  313. """Append new subsection to document tree. On return, check level."""
  314. memo = self.memo
  315. mylevel = memo.section_level
  316. memo.section_level += 1
  317. section_node = nodes.section()
  318. self.parent += section_node
  319. textnodes, title_messages = self.inline_text(title, lineno)
  320. titlenode = nodes.title(title, '', *textnodes)
  321. name = normalize_name(titlenode.astext())
  322. section_node['names'].append(name)
  323. section_node += titlenode
  324. section_node += messages
  325. section_node += title_messages
  326. self.document.note_implicit_target(section_node, section_node)
  327. offset = self.state_machine.line_offset + 1
  328. absoffset = self.state_machine.abs_line_offset() + 1
  329. newabsoffset = self.nested_parse(
  330. self.state_machine.input_lines[offset:], input_offset=absoffset,
  331. node=section_node, match_titles=1)
  332. self.goto_line(newabsoffset)
  333. if memo.section_level <= mylevel: # can't handle next section?
  334. raise EOFError # bubble up to supersection
  335. # reset section_level; next pass will detect it properly
  336. memo.section_level = mylevel
  337. def paragraph(self, lines, lineno):
  338. """
  339. Return a list (paragraph & messages) & a boolean: literal_block next?
  340. """
  341. data = '\n'.join(lines).rstrip()
  342. if re.search(r'(?<!\\)(\\\\)*::$', data):
  343. if len(data) == 2:
  344. return [], 1
  345. elif data[-3] in ' \n':
  346. text = data[:-3].rstrip()
  347. else:
  348. text = data[:-1]
  349. literalnext = 1
  350. else:
  351. text = data
  352. literalnext = 0
  353. textnodes, messages = self.inline_text(text, lineno)
  354. p = nodes.paragraph(data, '', *textnodes)
  355. p.line = lineno
  356. return [p] + messages, literalnext
  357. def inline_text(self, text, lineno):
  358. """
  359. Return 2 lists: nodes (text and inline elements), and system_messages.
  360. """
  361. return self.inliner.parse(text, lineno, self.memo, self.parent)
  362. def unindent_warning(self, node_name):
  363. return self.reporter.warning(
  364. '%s ends without a blank line; unexpected unindent.' % node_name,
  365. line=(self.state_machine.abs_line_number() + 1))
  366. def build_regexp(definition, compile=1):
  367. """
  368. Build, compile and return a regular expression based on `definition`.
  369. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts),
  370. where "parts" is a list of regular expressions and/or regular
  371. expression definitions to be joined into an or-group.
  372. """
  373. name, prefix, suffix, parts = definition
  374. part_strings = []
  375. for part in parts:
  376. if type(part) is tuple:
  377. part_strings.append(build_regexp(part, None))
  378. else:
  379. part_strings.append(part)
  380. or_group = '|'.join(part_strings)
  381. regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals()
  382. if compile:
  383. return re.compile(regexp, re.UNICODE)
  384. else:
  385. return regexp
  386. class Inliner:
  387. """
  388. Parse inline markup; call the `parse()` method.
  389. """
  390. def __init__(self):
  391. self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),]
  392. """List of (pattern, bound method) tuples, used by
  393. `self.implicit_inline`."""
  394. def init_customizations(self, settings):
  395. """Setting-based customizations; run when parsing begins."""
  396. if settings.pep_references:
  397. self.implicit_dispatch.append((self.patterns.pep,
  398. self.pep_reference))
  399. if settings.rfc_references:
  400. self.implicit_dispatch.append((self.patterns.rfc,
  401. self.rfc_reference))
  402. def parse(self, text, lineno, memo, parent):
  403. # Needs to be refactored for nested inline markup.
  404. # Add nested_parse() method?
  405. """
  406. Return 2 lists: nodes (text and inline elements), and system_messages.
  407. Using `self.patterns.initial`, a pattern which matches start-strings
  408. (emphasis, strong, interpreted, phrase reference, literal,
  409. substitution reference, and inline target) and complete constructs
  410. (simple reference, footnote reference), search for a candidate. When
  411. one is found, check for validity (e.g., not a quoted '*' character).
  412. If valid, search for the corresponding end string if applicable, and
  413. check it for validity. If not found or invalid, generate a warning
  414. and ignore the start-string. Implicit inline markup (e.g. standalone
  415. URIs) is found last.
  416. """
  417. self.reporter = memo.reporter
  418. self.document = memo.document
  419. self.language = memo.language
  420. self.parent = parent
  421. pattern_search = self.patterns.initial.search
  422. dispatch = self.dispatch
  423. remaining = escape2null(text)
  424. processed = []
  425. unprocessed = []
  426. messages = []
  427. while remaining:
  428. match = pattern_search(remaining)
  429. if match:
  430. groups = match.groupdict()
  431. method = dispatch[groups['start'] or groups['backquote']
  432. or groups['refend'] or groups['fnend']]
  433. before, inlines, remaining, sysmessages = method(self, match,
  434. lineno)
  435. unprocessed.append(before)
  436. messages += sysmessages
  437. if inlines:
  438. processed += self.implicit_inline(''.join(unprocessed),
  439. lineno)
  440. processed += inlines
  441. unprocessed = []
  442. else:
  443. break
  444. remaining = ''.join(unprocessed) + remaining
  445. if remaining:
  446. processed += self.implicit_inline(remaining, lineno)
  447. return processed, messages
  448. openers = u'\'"([{<\u2018\u201c\xab\u00a1\u00bf' # see quoted_start below
  449. closers = u'\'")]}>\u2019\u201d\xbb!?'
  450. unicode_delimiters = u'\u2010\u2011\u2012\u2013\u2014\u00a0'
  451. start_string_prefix = (u'((?<=^)|(?<=[-/: \\n\u2019%s%s]))'
  452. % (re.escape(unicode_delimiters),
  453. re.escape(openers)))
  454. end_string_suffix = (r'((?=$)|(?=[-/:.,; \n\x00%s%s]))'
  455. % (re.escape(unicode_delimiters),
  456. re.escape(closers)))
  457. non_whitespace_before = r'(?<![ \n])'
  458. non_whitespace_escape_before = r'(?<![ \n\x00])'
  459. non_whitespace_after = r'(?![ \n])'
  460. # Alphanumerics with isolated internal [-._+:] chars (i.e. not 2 together):
  461. simplename = r'(?:(?!_)\w)+(?:[-._+:](?:(?!_)\w)+)*'
  462. # Valid URI characters (see RFC 2396 & RFC 2732);
  463. # final \x00 allows backslash escapes in URIs:
  464. uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]"""
  465. # Delimiter indicating the end of a URI (not part of the URI):
  466. uri_end_delim = r"""[>]"""
  467. # Last URI character; same as uric but no punctuation:
  468. urilast = r"""[_~*/=+a-zA-Z0-9]"""
  469. # End of a URI (either 'urilast' or 'uric followed by a
  470. # uri_end_delim'):
  471. uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals()
  472. emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]"""
  473. email_pattern = r"""
  474. %(emailc)s+(?:\.%(emailc)s+)* # name
  475. (?<!\x00)@ # at
  476. %(emailc)s+(?:\.%(emailc)s*)* # host
  477. %(uri_end)s # final URI char
  478. """
  479. parts = ('initial_inline', start_string_prefix, '',
  480. [('start', '', non_whitespace_after, # simple start-strings
  481. [r'\*\*', # strong
  482. r'\*(?!\*)', # emphasis but not strong
  483. r'``', # literal
  484. r'_`', # inline internal target
  485. r'\|(?!\|)'] # substitution reference
  486. ),
  487. ('whole', '', end_string_suffix, # whole constructs
  488. [# reference name & end-string
  489. r'(?P<refname>%s)(?P<refend>__?)' % simplename,
  490. ('footnotelabel', r'\[', r'(?P<fnend>\]_)',
  491. [r'[0-9]+', # manually numbered
  492. r'\#(%s)?' % simplename, # auto-numbered (w/ label?)
  493. r'\*', # auto-symbol
  494. r'(?P<citationlabel>%s)' % simplename] # citation reference
  495. )
  496. ]
  497. ),
  498. ('backquote', # interpreted text or phrase reference
  499. '(?P<role>(:%s:)?)' % simplename, # optional role
  500. non_whitespace_after,
  501. ['`(?!`)'] # but not literal
  502. )
  503. ]
  504. )
  505. patterns = Struct(
  506. initial=build_regexp(parts),
  507. emphasis=re.compile(non_whitespace_escape_before
  508. + r'(\*)' + end_string_suffix),
  509. strong=re.compile(non_whitespace_escape_before
  510. + r'(\*\*)' + end_string_suffix),
  511. interpreted_or_phrase_ref=re.compile(
  512. r"""
  513. %(non_whitespace_escape_before)s
  514. (
  515. `
  516. (?P<suffix>
  517. (?P<role>:%(simplename)s:)?
  518. (?P<refend>__?)?
  519. )
  520. )
  521. %(end_string_suffix)s
  522. """ % locals(), re.VERBOSE | re.UNICODE),
  523. embedded_uri=re.compile(
  524. r"""
  525. (
  526. (?:[ \n]+|^) # spaces or beginning of line/string
  527. < # open bracket
  528. %(non_whitespace_after)s
  529. ([^<>\x00]+) # anything but angle brackets & nulls
  530. %(non_whitespace_before)s
  531. > # close bracket w/o whitespace before
  532. )
  533. $ # end of string
  534. """ % locals(), re.VERBOSE),
  535. literal=re.compile(non_whitespace_before + '(``)'
  536. + end_string_suffix),
  537. target=re.compile(non_whitespace_escape_before
  538. + r'(`)' + end_string_suffix),
  539. substitution_ref=re.compile(non_whitespace_escape_before
  540. + r'(\|_{0,2})'
  541. + end_string_suffix),
  542. email=re.compile(email_pattern % locals() + '$', re.VERBOSE),
  543. uri=re.compile(
  544. (r"""
  545. %(start_string_prefix)s
  546. (?P<whole>
  547. (?P<absolute> # absolute URI
  548. (?P<scheme> # scheme (http, ftp, mailto)
  549. [a-zA-Z][a-zA-Z0-9.+-]*
  550. )
  551. :
  552. (
  553. ( # either:
  554. (//?)? # hierarchical URI
  555. %(uric)s* # URI characters
  556. %(uri_end)s # final URI char
  557. )
  558. ( # optional query
  559. \?%(uric)s*
  560. %(uri_end)s
  561. )?
  562. ( # optional fragment
  563. \#%(uric)s*
  564. %(uri_end)s
  565. )?
  566. )
  567. )
  568. | # *OR*
  569. (?P<email> # email address
  570. """ + email_pattern + r"""
  571. )
  572. )
  573. %(end_string_suffix)s
  574. """) % locals(), re.VERBOSE),
  575. pep=re.compile(
  576. r"""
  577. %(start_string_prefix)s
  578. (
  579. (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file
  580. |
  581. (PEP\s+(?P<pepnum2>\d+)) # reference by name
  582. )
  583. %(end_string_suffix)s""" % locals(), re.VERBOSE),
  584. rfc=re.compile(
  585. r"""
  586. %(start_string_prefix)s
  587. (RFC(-|\s+)?(?P<rfcnum>\d+))
  588. %(end_string_suffix)s""" % locals(), re.VERBOSE))
  589. def quoted_start(self, match):
  590. """Return 1 if inline markup start-string is 'quoted', 0 if not."""
  591. string = match.string
  592. start = match.start()
  593. end = match.end()
  594. if start == 0: # start-string at beginning of text
  595. return 0
  596. prestart = string[start - 1]
  597. try:
  598. poststart = string[end]
  599. if self.openers.index(prestart) \
  600. == self.closers.index(poststart): # quoted
  601. return 1
  602. except IndexError: # start-string at end of text
  603. return 1
  604. except ValueError: # not quoted
  605. pass
  606. return 0
  607. def inline_obj(self, match, lineno, end_pattern, nodeclass,
  608. restore_backslashes=0):
  609. string = match.string
  610. matchstart = match.start('start')
  611. matchend = match.end('start')
  612. if self.quoted_start(match):
  613. return (string[:matchend], [], string[matchend:], [], '')
  614. endmatch = end_pattern.search(string[matchend:])
  615. if endmatch and endmatch.start(1): # 1 or more chars
  616. text = unescape(endmatch.string[:endmatch.start(1)],
  617. restore_backslashes)
  618. textend = matchend + endmatch.end(1)
  619. rawsource = unescape(string[matchstart:textend], 1)
  620. return (string[:matchstart], [nodeclass(rawsource, text)],
  621. string[textend:], [], endmatch.group(1))
  622. msg = self.reporter.warning(
  623. 'Inline %s start-string without end-string.'
  624. % nodeclass.__name__, line=lineno)
  625. text = unescape(string[matchstart:matchend], 1)
  626. rawsource = unescape(string[matchstart:matchend], 1)
  627. prb = self.problematic(text, rawsource, msg)
  628. return string[:matchstart], [prb], string[matchend:], [msg], ''
  629. def problematic(self, text, rawsource, message):
  630. msgid = self.document.set_id(message, self.parent)
  631. problematic = nodes.problematic(rawsource, text, refid=msgid)
  632. prbid = self.document.set_id(problematic)
  633. message.add_backref(prbid)
  634. return problematic
  635. def emphasis(self, match, lineno):
  636. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  637. match, lineno, self.patterns.emphasis, nodes.emphasis)
  638. return before, inlines, remaining, sysmessages
  639. def strong(self, match, lineno):
  640. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  641. match, lineno, self.patterns.strong, nodes.strong)
  642. return before, inlines, remaining, sysmessages
  643. def interpreted_or_phrase_ref(self, match, lineno):
  644. end_pattern = self.patterns.interpreted_or_phrase_ref
  645. string = match.string
  646. matchstart = match.start('backquote')
  647. matchend = match.end('backquote')
  648. rolestart = match.start('role')
  649. role = match.group('role')
  650. position = ''
  651. if role:
  652. role = role[1:-1]
  653. position = 'prefix'
  654. elif self.quoted_start(match):
  655. return (string[:matchend], [], string[matchend:], [])
  656. endmatch = end_pattern.search(string[matchend:])
  657. if endmatch and endmatch.start(1): # 1 or more chars
  658. textend = matchend + endmatch.end()
  659. if endmatch.group('role'):
  660. if role:
  661. msg = self.reporter.warning(
  662. 'Multiple roles in interpreted text (both '
  663. 'prefix and suffix present; only one allowed).',
  664. line=lineno)
  665. text = unescape(string[rolestart:textend], 1)
  666. prb = self.problematic(text, text, msg)
  667. return string[:rolestart], [prb], string[textend:], [msg]
  668. role = endmatch.group('suffix')[1:-1]
  669. position = 'suffix'
  670. escaped = endmatch.string[:endmatch.start(1)]
  671. rawsource = unescape(string[matchstart:textend], 1)
  672. if rawsource[-1:] == '_':
  673. if role:
  674. msg = self.reporter.warning(
  675. 'Mismatch: both interpreted text role %s and '
  676. 'reference suffix.' % position, 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. return self.phrase_ref(string[:matchstart], string[textend:],
  681. rawsource, escaped, unescape(escaped))
  682. else:
  683. rawsource = unescape(string[rolestart:textend], 1)
  684. nodelist, messages = self.interpreted(rawsource, escaped, role,
  685. lineno)
  686. return (string[:rolestart], nodelist,
  687. string[textend:], messages)
  688. msg = self.reporter.warning(
  689. 'Inline interpreted text or phrase reference start-string '
  690. 'without end-string.', line=lineno)
  691. text = unescape(string[matchstart:matchend], 1)
  692. prb = self.problematic(text, text, msg)
  693. return string[:matchstart], [prb], string[matchend:], [msg]
  694. def phrase_ref(self, before, after, rawsource, escaped, text):
  695. match = self.patterns.embedded_uri.search(escaped)
  696. if match:
  697. text = unescape(escaped[:match.start(0)])
  698. uri_text = match.group(2)
  699. uri = ''.join(uri_text.split())
  700. uri = self.adjust_uri(uri)
  701. if uri:
  702. target = nodes.target(match.group(1), refuri=uri)
  703. else:
  704. raise ApplicationError('problem with URI: %r' % uri_text)
  705. if not text:
  706. text = uri
  707. else:
  708. target = None
  709. refname = normalize_name(text)
  710. reference = nodes.reference(rawsource, text,
  711. name=whitespace_normalize_name(text))
  712. node_list = [reference]
  713. if rawsource[-2:] == '__':
  714. if target:
  715. reference['refuri'] = uri
  716. else:
  717. reference['anonymous'] = 1
  718. else:
  719. if target:
  720. reference['refuri'] = uri
  721. target['names'].append(refname)
  722. self.document.note_explicit_target(target, self.parent)
  723. node_list.append(target)
  724. else:
  725. reference['refname'] = refname
  726. self.document.note_refname(reference)
  727. return before, node_list, after, []
  728. def adjust_uri(self, uri):
  729. match = self.patterns.email.match(uri)
  730. if match:
  731. return 'mailto:' + uri
  732. else:
  733. return uri
  734. def interpreted(self, rawsource, text, role, lineno):
  735. role_fn, messages = roles.role(role, self.language, lineno,
  736. self.reporter)
  737. if role_fn:
  738. nodes, messages2 = role_fn(role, rawsource, text, lineno, self)
  739. return nodes, messages + messages2
  740. else:
  741. msg = self.reporter.error(
  742. 'Unknown interpreted text role "%s".' % role,
  743. line=lineno)
  744. return ([self.problematic(rawsource, rawsource, msg)],
  745. messages + [msg])
  746. def literal(self, match, lineno):
  747. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  748. match, lineno, self.patterns.literal, nodes.literal,
  749. restore_backslashes=1)
  750. return before, inlines, remaining, sysmessages
  751. def inline_internal_target(self, match, lineno):
  752. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  753. match, lineno, self.patterns.target, nodes.target)
  754. if inlines and isinstance(inlines[0], nodes.target):
  755. assert len(inlines) == 1
  756. target = inlines[0]
  757. name = normalize_name(target.astext())
  758. target['names'].append(name)
  759. self.document.note_explicit_target(target, self.parent)
  760. return before, inlines, remaining, sysmessages
  761. def substitution_reference(self, match, lineno):
  762. before, inlines, remaining, sysmessages, endstring = self.inline_obj(
  763. match, lineno, self.patterns.substitution_ref,
  764. nodes.substitution_reference)
  765. if len(inlines) == 1:
  766. subref_node = inlines[0]
  767. if isinstance(subref_node, nodes.substitution_reference):
  768. subref_text = subref_node.astext()
  769. self.document.note_substitution_ref(subref_node, subref_text)
  770. if endstring[-1:] == '_':
  771. reference_node = nodes.reference(
  772. '|%s%s' % (subref_text, endstring), '')
  773. if endstring[-2:] == '__':
  774. reference_node['anonymous'] = 1
  775. else:
  776. reference_node['refname'] = normalize_name(subref_text)
  777. self.document.note_refname(reference_node)
  778. reference_node += subref_node
  779. inlines = [reference_node]
  780. return before, inlines, remaining, sysmessages
  781. def footnote_reference(self, match, lineno):
  782. """
  783. Handles `nodes.footnote_reference` and `nodes.citation_reference`
  784. elements.
  785. """
  786. label = match.group('footnotelabel')
  787. refname = normalize_name(label)
  788. string = match.string
  789. before = string[:match.start('whole')]
  790. remaining = string[match.end('whole'):]
  791. if match.group('citationlabel'):
  792. refnode = nodes.citation_reference('[%s]_' % label,
  793. refname=refname)
  794. refnode += nodes.Text(label)
  795. self.document.note_citation_ref(refnode)
  796. else:
  797. refnode = nodes.footnote_reference('[%s]_' % label)
  798. if refname[0] == '#':
  799. refname = refname[1:]
  800. refnode['auto'] = 1
  801. self.document.note_autofootnote_ref(refnode)
  802. elif refname == '*':
  803. refname = ''
  804. refnode['auto'] = '*'
  805. self.document.note_symbol_footnote_ref(
  806. refnode)
  807. else:
  808. refnode += nodes.Text(label)
  809. if refname:
  810. refnode['refname'] = refname
  811. self.document.note_footnote_ref(refnode)
  812. if utils.get_trim_footnote_ref_space(self.document.settings):
  813. before = before.rstrip()
  814. return (before, [refnode], remaining, [])
  815. def reference(self, match, lineno, anonymous=None):
  816. referencename = match.group('refname')
  817. refname = normalize_name(referencename)
  818. referencenode = nodes.reference(
  819. referencename + match.group('refend'), referencename,
  820. name=whitespace_normalize_name(referencename))
  821. if anonymous:
  822. referencenode['anonymous'] = 1
  823. else:
  824. referencenode['refname'] = refname
  825. self.document.note_refname(referencenode)
  826. string = match.string
  827. matchstart = match.start('whole')
  828. matchend = match.end('whole')
  829. return (string[:matchstart], [referencenode], string[matchend:], [])
  830. def anonymous_reference(self, match, lineno):
  831. return self.reference(match, lineno, anonymous=1)
  832. def standalone_uri(self, match, lineno):
  833. if (not match.group('scheme')
  834. or match.group('scheme').lower() in urischemes.schemes):
  835. if match.group('email'):
  836. addscheme = 'mailto:'
  837. else:
  838. addscheme = ''
  839. text = match.group('whole')
  840. unescaped = unescape(text, 0)
  841. return [nodes.reference(unescape(text, 1), unescaped,
  842. refuri=addscheme + unescaped)]
  843. else: # not a valid scheme
  844. raise MarkupMismatch
  845. def pep_reference(self, match, lineno):
  846. text = match.group(0)
  847. if text.startswith('pep-'):
  848. pepnum = int(match.group('pepnum1'))
  849. elif text.startswith('PEP'):
  850. pepnum = int(match.group('pepnum2'))
  851. else:
  852. raise MarkupMismatch
  853. ref = (self.document.settings.pep_base_url
  854. + self.document.settings.pep_file_url_template % pepnum)
  855. unescaped = unescape(text, 0)
  856. return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)]
  857. rfc_url = 'rfc%d.html'
  858. def rfc_reference(self, match, lineno):
  859. text = match.group(0)
  860. if text.startswith('RFC'):
  861. rfcnum = int(match.group('rfcnum'))
  862. ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum
  863. else:
  864. raise MarkupMismatch
  865. unescaped = unescape(text, 0)
  866. return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)]
  867. def implicit_inline(self, text, lineno):
  868. """
  869. Check each of the patterns in `self.implicit_dispatch` for a match,
  870. and dispatch to the stored method for the pattern. Recursively check
  871. the text before and after the match. Return a list of `nodes.Text`
  872. and inline element nodes.
  873. """
  874. if not text:
  875. return []
  876. for pattern, method in self.implicit_dispatch:
  877. match = pattern.search(text)
  878. if match:
  879. try:
  880. # Must recurse on strings before *and* after the match;
  881. # there may be multiple patterns.
  882. return (self.implicit_inline(text[:match.start()], lineno)
  883. + method(match, lineno) +
  884. self.implicit_inline(text[match.end():], lineno))
  885. except MarkupMismatch:
  886. pass
  887. return [nodes.Text(unescape(text), rawsource=unescape(text, 1))]
  888. dispatch = {'*': emphasis,
  889. '**': strong,
  890. '`': interpreted_or_phrase_ref,
  891. '``': literal,
  892. '_`': inline_internal_target,
  893. ']_': footnote_reference,
  894. '|': substitution_reference,
  895. '_': reference,
  896. '__': anonymous_reference}
  897. def _loweralpha_to_int(s, _zero=(ord('a')-1)):
  898. return ord(s) - _zero
  899. def _upperalpha_to_int(s, _zero=(ord('A')-1)):
  900. return ord(s) - _zero
  901. def _lowerroman_to_int(s):
  902. return roman.fromRoman(s.upper())
  903. class Body(RSTState):
  904. """
  905. Generic classifier of the first line of a block.
  906. """
  907. double_width_pad_char = tableparser.TableParser.double_width_pad_char
  908. """Padding character for East Asian double-width text."""
  909. enum = Struct()
  910. """Enumerated list parsing information."""
  911. enum.formatinfo = {
  912. 'parens': Struct(prefix='(', suffix=')', start=1, end=-1),
  913. 'rparen': Struct(prefix='', suffix=')', start=0, end=-1),
  914. 'period': Struct(prefix='', suffix='.', start=0, end=-1)}
  915. enum.formats = enum.formatinfo.keys()
  916. enum.sequences = ['arabic', 'loweralpha', 'upperalpha',
  917. 'lowerroman', 'upperroman'] # ORDERED!
  918. enum.sequencepats = {'arabic': '[0-9]+',
  919. 'loweralpha': '[a-z]',
  920. 'upperalpha': '[A-Z]',
  921. 'lowerroman': '[ivxlcdm]+',
  922. 'upperroman': '[IVXLCDM]+',}
  923. enum.converters = {'arabic': int,
  924. 'loweralpha': _loweralpha_to_int,
  925. 'upperalpha': _upperalpha_to_int,
  926. 'lowerroman': _lowerroman_to_int,
  927. 'upperroman': roman.fromRoman}
  928. enum.sequenceregexps = {}
  929. for sequence in enum.sequences:
  930. enum.sequenceregexps[sequence] = re.compile(
  931. enum.sequencepats[sequence] + '$')
  932. grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$')
  933. """Matches the top (& bottom) of a full table)."""
  934. simple_table_top_pat = re.compile('=+( +=+)+ *$')
  935. """Matches the top of a simple table."""
  936. simple_table_border_pat = re.compile('=+[ =]*$')
  937. """Matches the bottom & header bottom of a simple table."""
  938. pats = {}
  939. """Fragments of patterns used by transitions."""
  940. pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]'
  941. pats['alpha'] = '[a-zA-Z]'
  942. pats['alphanum'] = '[a-zA-Z0-9]'
  943. pats['alphanumplus'] = '[a-zA-Z0-9_-]'
  944. pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s'
  945. '|%(upperroman)s|#)' % enum.sequencepats)
  946. pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats
  947. # @@@ Loosen up the pattern? Allow Unicode?
  948. pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats
  949. pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats
  950. pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats
  951. pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats
  952. for format in enum.formats:
  953. pats[format] = '(?P<%s>%s%s%s)' % (
  954. format, re.escape(enum.formatinfo[format].prefix),
  955. pats['enum'], re.escape(enum.formatinfo[format].suffix))
  956. patterns = {
  957. 'bullet': u'[-+*\u2022\u2023\u2043]( +|$)',
  958. 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats,
  959. 'field_marker': r':(?![: ])([^:\\]|\\.)*(?<! ):( +|$)',
  960. 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats,
  961. 'doctest': r'>>>( +|$)',
  962. 'line_block': r'\|( +|$)',
  963. 'grid_table_top': grid_table_top_pat,
  964. 'simple_table_top': simple_table_top_pat,
  965. 'explicit_markup': r'\.\.( +|$)',
  966. 'anonymous': r'__( +|$)',
  967. 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats,
  968. 'text': r''}
  969. initial_transitions = (
  970. 'bullet',
  971. 'enumerator',
  972. 'field_marker',
  973. 'option_marker',
  974. 'doctest',
  975. 'line_block',
  976. 'grid_table_top',
  977. 'simple_table_top',
  978. 'explicit_markup',
  979. 'anonymous',
  980. 'line',
  981. 'text')
  982. def indent(self, match, context, next_state):
  983. """Block quote."""
  984. indented, indent, line_offset, blank_finish = \
  985. self.state_machine.get_indented()
  986. elements = self.block_quote(indented, line_offset)
  987. self.parent += elements
  988. if not blank_finish:
  989. self.parent += self.unindent_warning('Block quote')
  990. return context, next_state, []
  991. def block_quote(self, indented, line_offset):
  992. elements = []
  993. while indented:
  994. (blockquote_lines,
  995. attribution_lines,
  996. attribution_offset,
  997. indented,
  998. new_line_offset) = self.split_attribution(indented, line_offset)
  999. blockquote = nodes.block_quote()
  1000. self.nested_parse(blockquote_lines, line_offset, blockquote)
  1001. elements.append(blockquote)
  1002. if attribution_lines:
  1003. attribution, messages = self.parse_attribution(
  1004. attribution_lines, attribution_offset)
  1005. blockquote += attribution
  1006. elements += messages
  1007. line_offset = new_line_offset
  1008. while indented and not indented[0]:
  1009. indented = indented[1:]
  1010. line_offset += 1
  1011. return elements
  1012. # U+2014 is an em-dash:
  1013. attribution_pattern = re.compile(u'(---?(?!-)|\u2014) *(?=[^ \\n])')
  1014. def split_attribution(self, indented, line_offset):
  1015. """
  1016. Check for a block quote attribution and split it off:
  1017. * First line after a blank line must begin with a dash ("--", "---",
  1018. em-dash; matches `self.attribution_pattern`).
  1019. * Every line after that must have consistent indentation.
  1020. * Attributions must be preceded by block quote content.
  1021. Return a tuple of: (block quote content lines, content offset,
  1022. attribution lines, attribution offset, remaining indented lines).
  1023. """
  1024. blank = None
  1025. nonblank_seen = False
  1026. for i in range(len(indented)):
  1027. line = indented[i].rstrip()
  1028. if line:
  1029. if nonblank_seen and blank == i - 1: # last line blank
  1030. match = self.attribution_pattern.match(line)
  1031. if match:
  1032. attribution_end, indent = self.check_attribution(
  1033. indented, i)
  1034. if attribution_end:
  1035. a_lines = indented[i:attribution_end]
  1036. a_lines.trim_left(match.end(), end=1)
  1037. a_lines.trim_left(indent, start=1)
  1038. return (indented[:i], a_lines,
  1039. i, indented[attribution_end:],
  1040. line_offset + attribution_end)
  1041. nonblank_seen = True
  1042. else:
  1043. blank = i
  1044. else:
  1045. return (indented, None, None, None, None)
  1046. def check_attribution(self, indented, attribution_start):
  1047. """
  1048. Check attribution shape.
  1049. Return the index past the end of the attribution, and the indent.
  1050. """
  1051. indent = None
  1052. i = attribution_start + 1
  1053. for i in range(attribution_start + 1, len(indented)):
  1054. line = indented[i].rstrip()
  1055. if not line:
  1056. break
  1057. if indent is None:
  1058. indent = len(line) - len(line.lstrip())
  1059. elif len(line) - len(line.lstrip()) != indent:
  1060. return None, None # bad shape; not an attribution
  1061. else:
  1062. # return index of line after last attribution line:
  1063. i += 1
  1064. return i, (indent or 0)
  1065. def parse_attribution(self, indented, line_offset):
  1066. text = '\n'.join(indented).rstrip()
  1067. lineno = self.state_machine.abs_line_number() + line_offset
  1068. textnodes, messages = self.inline_text(text, lineno)
  1069. node = nodes.attribution(text, '', *textnodes)
  1070. node.line = lineno
  1071. return node, messages
  1072. def bullet(self, match, context, next_state):
  1073. """Bullet list item."""
  1074. bulletlist = nodes.bullet_list()
  1075. self.parent += bulletlist
  1076. bulletlist['bullet'] = match.string[0]
  1077. i, blank_finish = self.list_item(match.end())
  1078. bulletlist += i
  1079. offset = self.state_machine.line_offset + 1 # next line
  1080. new_line_offset, blank_finish = self.nested_list_parse(
  1081. self.state_machine.input_lines[offset:],
  1082. input_offset=self.state_machine.abs_line_offset() + 1,
  1083. node=bulletlist, initial_state='BulletList',
  1084. blank_finish=blank_finish)
  1085. self.goto_line(new_line_offset)
  1086. if not blank_finish:
  1087. self.parent += self.unindent_warning('Bullet list')
  1088. return [], next_state, []
  1089. def list_item(self, indent):
  1090. if self.state_machine.line[indent:]:
  1091. indented, line_offset, blank_finish = (
  1092. self.state_machine.get_known_indented(indent))
  1093. else:
  1094. indented, indent, line_offset, blank_finish = (
  1095. self.state_machine.get_first_known_indented(indent))
  1096. listitem = nodes.list_item('\n'.join(indented))
  1097. if indented:
  1098. self.nested_parse(indented, input_offset=line_offset,
  1099. node=listitem)
  1100. return listitem, blank_finish
  1101. def enumerator(self, match, context, next_state):
  1102. """Enumerated List Item"""
  1103. format, sequence, text, ordinal = self.parse_enumerator(match)
  1104. if not self.is_enumerated_list_item(ordinal, sequence, format):
  1105. raise statemachine.TransitionCorrection('text')
  1106. enumlist = nodes.enumerated_list()
  1107. self.parent += enumlist
  1108. if sequence == '#':
  1109. enumlist['enumtype'] = 'arabic'
  1110. else:
  1111. enumlist['enumtype'] = sequence
  1112. enumlist['prefix'] = self.enum.formatinfo[format].prefix
  1113. enumlist['suffix'] = self.enum.formatinfo[format].suffix
  1114. if ordinal != 1:
  1115. enumlist['start'] = ordinal
  1116. msg = self.reporter.info(
  1117. 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)'
  1118. % (text, ordinal), line=self.state_machine.abs_line_number())
  1119. self.parent += msg
  1120. listitem, blank_finish = self.list_item(match.end())
  1121. enumlist += listitem
  1122. offset = self.state_machine.line_offset + 1 # next line
  1123. newline_offset, blank_finish = self.nested_list_parse(
  1124. self.state_machine.input_lines[offset:],
  1125. input_offset=self.state_machine.abs_line_offset() + 1,
  1126. node=enumlist, initial_state='EnumeratedList',
  1127. blank_finish=blank_finish,
  1128. extra_settings={'lastordinal': ordinal,
  1129. 'format': format,
  1130. 'auto': sequence == '#'})
  1131. self.goto_line(newline_offset)
  1132. if not blank_finish:
  1133. self.parent += self.unindent_warning('Enumerated list')
  1134. return [], next_state, []
  1135. def parse_enumerator(self, match, expected_sequence=None):
  1136. """
  1137. Analyze an enumerator and return the results.
  1138. :Return:
  1139. - the enumerator format ('period', 'parens', or 'rparen'),
  1140. - the sequence used ('arabic', 'loweralpha', 'upperroman', etc.),
  1141. - the text of the enumerator, stripped of formatting, and
  1142. - the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.;
  1143. ``None`` is returned for invalid enumerator text).
  1144. The enumerator format has already been determined by the regular
  1145. expression match. If `expected_sequence` is given, that sequence is
  1146. tried first. If not, we check for Roman numeral 1. This way,
  1147. single-character Roman numerals (which are also alphabetical) can be
  1148. matched. If no sequence has been matched, all sequences are checked in
  1149. order.
  1150. """
  1151. groupdict = match.groupdict()
  1152. sequence = ''
  1153. for format in self.enum.formats:
  1154. if groupdict[format]: # was this the format matched?
  1155. break # yes; keep `format`
  1156. else: # shouldn't happen
  1157. raise ParserError('enumerator format not matched')
  1158. text = groupdict[format][self.enum.formatinfo[format].start
  1159. :self.enum.formatinfo[format].end]
  1160. if text == '#':
  1161. sequence = '#'
  1162. elif expected_sequence:
  1163. try:
  1164. if self.enum.sequenceregexps[expected_sequence].match(text):
  1165. sequence = expected_sequence
  1166. except KeyError: # shouldn't happen
  1167. raise ParserError('unknown enumerator sequence: %s'
  1168. % sequence)
  1169. elif text == 'i':
  1170. sequence = 'lowerroman'
  1171. elif text == 'I':
  1172. sequence = 'upperroman'
  1173. if not sequence:
  1174. for sequence in self.enum.sequences:
  1175. if self.enum.sequenceregexps[sequence].match(text):
  1176. break
  1177. else: # shouldn't happen
  1178. raise ParserError('enumerator sequence not matched')
  1179. if sequence == '#':
  1180. ordinal = 1
  1181. else:
  1182. try:
  1183. ordinal = self.enum.converters[sequence](text)
  1184. except roman.InvalidRomanNumeralError:
  1185. ordinal = None
  1186. return format, sequence, text, ordinal
  1187. def is_enumerated_list_item(self, ordinal, sequence, format):
  1188. """
  1189. Check validity based on the ordinal value and the second line.
  1190. Return true if the ordinal is valid and the second line is blank,
  1191. indented, or starts with the next enumerator or an auto-enumerator.
  1192. """
  1193. if ordinal is None:
  1194. return None
  1195. try:
  1196. next_line = self.state_machine.next_line()
  1197. except EOFError: # end of input lines
  1198. self.state_machine.previous_line()
  1199. return 1
  1200. else:
  1201. self.state_machine.previous_line()
  1202. if not next_line[:1].strip(): # blank or indented
  1203. return 1
  1204. result = self.make_enumerator(ordinal + 1, sequence, format)
  1205. if result:
  1206. next_enumerator, auto_enumerator = result
  1207. try:
  1208. if ( next_line.startswith(next_enumerator) or
  1209. next_line.startswith(auto_enumerator) ):
  1210. return 1
  1211. except TypeError:
  1212. pass
  1213. return None
  1214. def make_enumerator(self, ordinal, sequence, format):
  1215. """
  1216. Construct and return the next enumerated list item marker, and an
  1217. auto-enumerator ("#" instead of the regular enumerator).
  1218. Return ``None`` for invalid (out of range) ordinals.
  1219. """ #"
  1220. if sequence == '#':
  1221. enumerator = '#'
  1222. elif sequence == 'arabic':
  1223. enumerator = str(ordinal)
  1224. else:
  1225. if sequence.endswith('alpha'):
  1226. if ordinal > 26:
  1227. return None
  1228. enumerator = chr(ordinal + ord('a') - 1)
  1229. elif sequence.endswith('roman'):
  1230. try:
  1231. enumerator = roman.toRoman(ordinal)
  1232. except roman.RomanError:
  1233. return None
  1234. else: # shouldn't happen
  1235. raise ParserError('unknown enumerator sequence: "%s"'
  1236. % sequence)
  1237. if sequence.startswith('lower'):
  1238. enumerator = enumerator.lower()
  1239. elif sequence.startswith('upper'):
  1240. enumerator = enumerator.upper()
  1241. else: # shouldn't happen
  1242. raise ParserError('unknown enumerator sequence: "%s"'
  1243. % sequence)
  1244. formatinfo = self.enum.formatinfo[format]
  1245. next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix
  1246. + ' ')
  1247. auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' '
  1248. return next_enumerator, auto_enumerator
  1249. def field_marker(self, match, context, next_state):
  1250. """Field list item."""
  1251. field_list = nodes.field_list()
  1252. self.parent += field_list
  1253. field, blank_finish = self.field(match)
  1254. field_list += field
  1255. offset = self.state_machine.line_offset + 1 # next line
  1256. newline_offset, blank_finish = self.nested_list_parse(
  1257. self.state_machine.input_lines[offset:],
  1258. input_offset=self.state_machine.abs_line_offset() + 1,
  1259. node=field_list, initial_state='FieldList',
  1260. blank_finish=blank_finish)
  1261. self.goto_line(newline_offset)
  1262. if not blank_finish:
  1263. self.parent += self.unindent_warning('Field list')
  1264. return [], next_state, []
  1265. def field(self, match):
  1266. name = self.parse_field_marker(match)
  1267. lineno = self.state_machine.abs_line_number()
  1268. indented, indent, line_offset, blank_finish = \
  1269. self.state_machine.get_first_known_indented(match.end())
  1270. field_node = nodes.field()
  1271. field_node.line = lineno
  1272. name_nodes, name_messages = self.inline_text(name, lineno)
  1273. field_node += nodes.field_name(name, '', *name_nodes)
  1274. field_body = nodes.field_body('\n'.join(indented), *name_messages)
  1275. field_node += field_body
  1276. if indented:
  1277. self.parse_field_body(indented, line_offset, field_body)
  1278. return field_node, blank_finish
  1279. def parse_field_marker(self, match):
  1280. """Extract & return field name from a field marker match."""
  1281. field = match.group()[1:] # strip off leading ':'
  1282. field = field[:field.rfind(':')] # strip off trailing ':' etc.
  1283. return field
  1284. def parse_field_body(self, indented, offset, node):
  1285. self.nested_parse(indented, input_offset=offset, node=node)
  1286. def option_marker(self, match, context, next_state):
  1287. """Option list item."""
  1288. optionlist = nodes.option_list()
  1289. try:
  1290. listitem, blank_finish = self.option_list_item(match)
  1291. except MarkupError, (message, lineno):
  1292. # This shouldn't happen; pattern won't match.
  1293. msg = self.reporter.error(
  1294. 'Invalid option list marker: %s' % message, line=lineno)
  1295. self.parent += msg
  1296. indented, indent, line_offset, blank_finish = \
  1297. self.state_machine.get_first_known_indented(match.end())
  1298. elements = self.block_quote(indented, line_offset)
  1299. self.parent += elements
  1300. if not blank_finish:
  1301. self.parent += self.unindent_warning('Option list')
  1302. return [], next_state, []
  1303. self.parent += optionlist
  1304. optionlist += listitem
  1305. offset = self.state_machine.line_offset + 1 # next line
  1306. newline_offset, blank_finish = self.nested_list_parse(
  1307. self.state_machine.input_lines[offset:],
  1308. input_offset=self.state_machine.abs_line_offset() + 1,
  1309. node=optionlist, initial_state='OptionList',
  1310. blank_finish=blank_finish)
  1311. self.goto_line(newline_offset)
  1312. if not blank_finish:
  1313. self.parent += self.unindent_warning('Option list')
  1314. return [], next_state, []
  1315. def option_list_item(self, match):
  1316. offset = self.state_machine.abs_line_offset()
  1317. options = self.parse_option_marker(match)
  1318. indented, indent, line_offset, blank_finish = \
  1319. self.state_machine.get_first_known_indented(match.end())
  1320. if not indented: # not an option list item
  1321. self.goto_line(offset)
  1322. raise statemachine.TransitionCorrection('text')
  1323. option_group = nodes.option_group('', *options)
  1324. description = nodes.description('\n'.join(indented))
  1325. option_list_item = nodes.option_list_item('', option_group,
  1326. description)
  1327. if indented:
  1328. self.nested_parse(indented, input_offset=line_offset,
  1329. node=description)
  1330. return option_list_item, blank_finish
  1331. def parse_option_marker(self, match):
  1332. """
  1333. Return a list of `node.option` and `node.option_argument` objects,
  1334. parsed from an option marker match.
  1335. :Exception: `MarkupError` for invalid option markers.
  1336. """
  1337. optlist = []
  1338. optionstrings = match.group().rstrip().split(', ')
  1339. for optionstring in optionstrings:
  1340. tokens = optionstring.split()
  1341. delimiter = ' '
  1342. firstopt = tokens[0].split('=')
  1343. if len(firstopt) > 1:
  1344. # "--opt=value" form
  1345. tokens[:1] = firstopt
  1346. delimiter = '='
  1347. elif (len(tokens[0]) > 2
  1348. and ((tokens[0].startswith('-')
  1349. and not tokens[0].startswith('--'))
  1350. or tokens[0].startswith('+'))):
  1351. # "-ovalue" form
  1352. tokens[:1] = [tokens[0][:2], tokens[0][2:]]
  1353. delimiter = ''
  1354. if len(tokens) > 1 and (tokens[1].startswith('<')
  1355. and tokens[-1].endswith('>')):
  1356. # "-o <value1 value2>" form; join all values into one token
  1357. tokens[1:] = [' '.join(tokens[1:])]
  1358. if 0 < len(tokens) <= 2:
  1359. option = nodes.option(optionstring)
  1360. option += nodes.option_string(tokens[0], tokens[0])
  1361. if len(tokens) > 1:
  1362. option += nodes.option_argument(tokens[1], tokens[1],
  1363. delimiter=delimiter)
  1364. optlist.append(option)
  1365. else:
  1366. raise MarkupError(
  1367. 'wrong number of option tokens (=%s), should be 1 or 2: '
  1368. '"%s"' % (len(tokens), optionstring),
  1369. self.state_machine.abs_line_number() + 1)
  1370. return optlist
  1371. def doctest(self, match, context, next_state):
  1372. data = '\n'.join(self.state_machine.get_text_block())
  1373. self.parent += nodes.doctest_block(data, data)
  1374. return [], next_state, []
  1375. def line_block(self, match, context, next_state):
  1376. """First line of a line block."""
  1377. block = nodes.line_block()
  1378. self.parent += block
  1379. lineno = self.state_machine.abs_line_number()
  1380. line, messages, blank_finish = self.line_block_line(match, lineno)
  1381. block += line
  1382. self.parent += messages
  1383. if not blank_finish:
  1384. offset = self.state_machine.line_offset + 1 # next line
  1385. new_line_offset, blank_finish = self.nested_list_parse(
  1386. self.state_machine.input_lines[offset:],
  1387. input_offset=self.state_machine.abs_line_offset() + 1,
  1388. node=block, initial_state='LineBlock',
  1389. blank_finish=0)
  1390. self.goto_line(new_line_offset)
  1391. if not blank_finish:
  1392. self.parent += self.reporter.warning(
  1393. 'Line block ends without a blank line.',
  1394. line=(self.state_machine.abs_line_number() + 1))
  1395. if len(block):
  1396. if block[0].indent is None:
  1397. block[0].indent = 0
  1398. self.nest_line_block_lines(block)
  1399. return [], next_state, []
  1400. def line_block_line(self, match, lineno):
  1401. """Return one line element of a line_block."""
  1402. indented, indent, line_offset, blank_finish = \
  1403. self.state_machine.get_first_known_indented(match.end(),
  1404. until_blank=1)
  1405. text = u'\n'.join(indented)
  1406. text_nodes, messages = self.inline_text(text, lineno)
  1407. line = nodes.line(text, '', *text_nodes)
  1408. if match.string.rstrip() != '|': # not empty
  1409. line.indent = len(match.group(1)) - 1
  1410. return line, messages, blank_finish
  1411. def nest_line_block_lines(self, block):
  1412. for index in range(1, len(block)):
  1413. if block[index].indent is None:
  1414. block[index].indent = block[index - 1].indent
  1415. self.nest_line_block_segment(block)
  1416. def nest_line_block_segment(self, block):
  1417. indents = [item.indent for item in block]
  1418. least = min(indents)
  1419. new_items = []
  1420. new_block = nodes.line_block()
  1421. for item in block:
  1422. if item.indent > least:
  1423. new_block.append(item)
  1424. else:
  1425. if len(new_block):
  1426. self.nest_line_block_segment(new_block)
  1427. new_items.append(new_block)
  1428. new_block = nodes.line_block()
  1429. new_items.append(item)
  1430. if len(new_block):
  1431. self.nest_line_block_segment(new_block)
  1432. new_items.append(new_block)
  1433. block[:] = new_items
  1434. def grid_table_top(self, match, context, next_state):
  1435. """Top border of a full table."""
  1436. return self.table_top(match, context, next_state,
  1437. self.isolate_grid_table,
  1438. tableparser.GridTableParser)
  1439. def simple_table_top(self, match, context, next_state):
  1440. """Top border of a simple table."""
  1441. return self.table_top(match, context, next_state,
  1442. self.isolate_simple_table,
  1443. tableparser.SimpleTableParser)
  1444. def table_top(self, match, context, next_state,
  1445. isolate_function, parser_class):
  1446. """Top border of a generic table."""
  1447. nodelist, blank_finish = self.table(isolate_function, parser_class)
  1448. self.parent += nodelist
  1449. if not blank_finish:
  1450. msg = self.reporter.warning(
  1451. 'Blank line required after table.',
  1452. line=self.state_machine.abs_line_number() + 1)
  1453. self.parent += msg
  1454. return [], next_state, []
  1455. def table(self, isolate_function, parser_class):
  1456. """Parse a table."""
  1457. block, messages, blank_finish = isolate_function()
  1458. if block:
  1459. try:
  1460. parser = parser_class()
  1461. tabledata = parser.parse(block)
  1462. tableline = (self.state_machine.abs_line_number() - len(block)
  1463. + 1)
  1464. table = self.build_table(tabledata, tableline)
  1465. nodelist = [table] + messages
  1466. except tableparser.TableMarkupError, detail:
  1467. nodelist = self.malformed_table(
  1468. block, ' '.join(detail.args)) + messages
  1469. else:
  1470. nodelist = messages
  1471. return nodelist, blank_finish
  1472. def isolate_grid_table(self):
  1473. messages = []
  1474. blank_finish = 1
  1475. try:
  1476. block = self.state_machine.get_text_block(flush_left=1)
  1477. except statemachine.UnexpectedIndentationError, instance:
  1478. block, source, lineno = instance.args
  1479. messages.append(self.reporter.error('Unexpected indentation.',
  1480. source=source, line=lineno))
  1481. blank_finish = 0
  1482. block.disconnect()
  1483. # for East Asian chars:
  1484. block.pad_double_width(self.double_width_pad_char)
  1485. width = len(block[0].strip())
  1486. for i in range(len(block)):
  1487. block[i] = block[i].strip()
  1488. if block[i][0] not in '+|': # check left edge
  1489. blank_finish = 0
  1490. self.state_machine.previous_line(len(block) - i)
  1491. del block[i:]
  1492. break
  1493. if not self.grid_table_top_pat.match(block[-1]): # find bottom
  1494. blank_finish = 0
  1495. # from second-last to third line of table:
  1496. for i in range(len(block) - 2, 1, -1):
  1497. if self.grid_table_top_pat.match(block[i]):
  1498. self.state_machine.previous_line(len(block) - i + 1)
  1499. del block[i+1:]
  1500. break
  1501. else:
  1502. messages.extend(self.malformed_table(block))
  1503. return [], messages, blank_finish
  1504. for i in range(len(block)): # check right edge
  1505. if len(block[i]) != width or block[i][-1] not in '+|':
  1506. messages.extend(self.malformed_table(block))
  1507. return [], messages, blank_finish
  1508. return block, messages, blank_finish
  1509. def isolate_simple_table(self):
  1510. start = self.state_machine.line_offset
  1511. lines = self.state_machine.input_lines
  1512. limit = len(lines) - 1
  1513. toplen = len(lines[start].strip())
  1514. pattern_match = self.simple_table_border_pat.match
  1515. found = 0
  1516. found_at = None
  1517. i = start + 1
  1518. while i <= limit:
  1519. line = lines[i]
  1520. match = pattern_match(line)
  1521. if match:
  1522. if len(line.strip()) != toplen:
  1523. self.state_machine.next_line(i - start)
  1524. messages = self.malformed_table(
  1525. lines[start:i+1], 'Bottom/header table border does '
  1526. 'not match top border.')
  1527. return [], messages, i == limit or not lines[i+1].strip()
  1528. found += 1
  1529. found_at = i
  1530. if found == 2 or i == limit or not lines[i+1].strip():
  1531. end = i
  1532. break
  1533. i += 1
  1534. else: # reached end of input_lines
  1535. if found:
  1536. extra = ' or no blank line after table bottom'
  1537. self.state_machine.next_line(found_at - start)
  1538. block = lines[start:found_at+1]
  1539. else:
  1540. extra = ''
  1541. self.state_machine.next_line(i - start - 1)
  1542. block = lines[start:]
  1543. messages = self.malformed_table(
  1544. block, 'No bottom table border found%s.' % extra)
  1545. return [], messages, not extra
  1546. self.state_machine.next_line(end - start)
  1547. block = lines[start:end+1]
  1548. # for East Asian chars:
  1549. block.pad_double_width(self.double_width_pad_char)
  1550. return block, [], end == limit or not lines[end+1].strip()
  1551. def malformed_table(self, block, detail=''):
  1552. block.replace(self.double_width_pad_char, '')
  1553. data = '\n'.join(block)
  1554. message = 'Malformed table.'
  1555. lineno = self.state_machine.abs_line_number() - len(block) + 1
  1556. if detail:
  1557. message += '\n' + detail
  1558. error = self.reporter.error(message, nodes.literal_block(data, data),
  1559. line=lineno)
  1560. return [error]
  1561. def build_table(self, tabledata, tableline, stub_columns=0):
  1562. colwidths, headrows, bodyrows = tabledata
  1563. table = nodes.table()
  1564. tgroup = nodes.tgroup(cols=len(colwidths))
  1565. table += tgroup
  1566. for colwidth in colwidths:
  1567. colspec = nodes.colspec(colwidth=colwidth)
  1568. if stub_columns:
  1569. colspec.attributes['stub'] = 1
  1570. stub_columns -= 1
  1571. tgroup += colspec
  1572. if headrows:
  1573. thead = nodes.thead()
  1574. tgroup += thead
  1575. for row in headrows:
  1576. thead += self.build_table_row(row, tableline)
  1577. tbody = nodes.tbody()
  1578. tgroup += tbody
  1579. for row in bodyrows:
  1580. tbody += self.build_table_row(row, tableline)
  1581. return table
  1582. def build_table_row(self, rowdata, tableline):
  1583. row = nodes.row()
  1584. for cell in rowdata:
  1585. if cell is None:
  1586. continue
  1587. morerows, morecols, offset, cellblock = cell
  1588. attributes = {}
  1589. if morerows:
  1590. attributes['morerows'] = morerows
  1591. if morecols:
  1592. attributes['morecols'] = morecols
  1593. entry = nodes.entry(**attributes)
  1594. row += entry
  1595. if ''.join(cellblock):
  1596. self.nested_parse(cellblock, input_offset=tableline+offset,
  1597. node=entry)
  1598. return row
  1599. explicit = Struct()
  1600. """Patterns and constants used for explicit markup recognition."""
  1601. explicit.patterns = Struct(
  1602. target=re.compile(r"""
  1603. (
  1604. _ # anonymous target
  1605. | # *OR*
  1606. (?!_) # no underscore at the beginning
  1607. (?P<quote>`?) # optional open quote
  1608. (?![ `]) # first char. not space or
  1609. # backquote
  1610. (?P<name> # reference name
  1611. .+?
  1612. )
  1613. %(non_whitespace_escape_before)s
  1614. (?P=quote) # close quote if open quote used
  1615. )
  1616. (?<!(?<!\x00):) # no unescaped colon at end
  1617. %(non_whitespace_escape_before)s
  1618. [ ]? # optional space
  1619. : # end of reference name
  1620. ([ ]+|$) # followed by whitespace
  1621. """ % vars(Inliner), re.VERBOSE),
  1622. reference=re.compile(r"""
  1623. (
  1624. (?P<simple>%(simplename)s)_
  1625. | # *OR*
  1626. ` # open backquote
  1627. (?![ ]) # not space
  1628. (?P<phrase>.+?) # hyperlink phrase
  1629. %(non_whitespace_escape_before)s
  1630. `_ # close backquote,
  1631. # reference mark
  1632. )
  1633. $ # end of string
  1634. """ % vars(Inliner), re.VERBOSE | re.UNICODE),
  1635. substitution=re.compile(r"""
  1636. (
  1637. (?![ ]) # first char. not space
  1638. (?P<name>.+?) # substitution text
  1639. %(non_whitespace_escape_before)s
  1640. \| # close delimiter
  1641. )
  1642. ([ ]+|$) # followed by whitespace
  1643. """ % vars(Inliner), re.VERBOSE),)
  1644. def footnote(self, match):
  1645. lineno = self.state_machine.abs_line_number()
  1646. indented, indent, offset, blank_finish = \
  1647. self.state_machine.get_first_known_indented(match.end())
  1648. label = match.group(1)
  1649. name = normalize_name(label)
  1650. footnote = nodes.footnote('\n'.join(indented))
  1651. footnote.line = lineno
  1652. if name[0] == '#': # auto-numbered
  1653. name = name[1:] # autonumber label
  1654. footnote['auto'] = 1
  1655. if name:
  1656. footnote['names'].append(name)
  1657. self.document.note_autofootnote(footnote)
  1658. elif name == '*': # auto-symbol
  1659. name = ''
  1660. footnote['auto'] = '*'
  1661. self.document.note_symbol_footnote(footnote)
  1662. else: # manually numbered
  1663. footnote += nodes.label('', label)
  1664. footnote['names'].append(name)
  1665. self.document.note_footnote(footnote)
  1666. if name:
  1667. self.document.note_explicit_target(footnote, footnote)
  1668. else:
  1669. self.document.set_id(footnote, footnote)
  1670. if indented:
  1671. self.nested_parse(indented, input_offset=offset, node=footnote)
  1672. return [footnote], blank_finish
  1673. def citation(self, match):
  1674. lineno = self.state_machine.abs_line_number()
  1675. indented, indent, offset, blank_finish = \
  1676. self.state_machine.get_first_known_indented(match.end())
  1677. label = match.group(1)
  1678. name = normalize_name(label)
  1679. citation = nodes.citation('\n'.join(indented))
  1680. citation.line = lineno
  1681. citation += nodes.label('', label)
  1682. citation['names'].append(name)
  1683. self.document.note_citation(citation)
  1684. self.document.note_explicit_target(citation, citation)
  1685. if indented:
  1686. self.nested_parse(indented, input_offset=offset, node=citation)
  1687. return [citation], blank_finish
  1688. def hyperlink_target(self, match):
  1689. pattern = self.explicit.patterns.target
  1690. lineno = self.state_machine.abs_line_number()
  1691. block, indent, offset, blank_finish = \
  1692. self.state_machine.get_first_known_indented(
  1693. match.end(), until_blank=1, strip_indent=0)
  1694. blocktext = match.string[:match.end()] + '\n'.join(block)
  1695. block = [escape2null(line) for line in block]
  1696. escaped = block[0]
  1697. blockindex = 0
  1698. while 1:
  1699. targetmatch = pattern.match(escaped)
  1700. if targetmatch:
  1701. break
  1702. blockindex += 1
  1703. try:
  1704. escaped += block[blockindex]
  1705. except IndexError:
  1706. raise MarkupError('malformed hyperlink target.', lineno)
  1707. del block[:blockindex]
  1708. block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip()
  1709. target = self.make_target(block, blocktext, lineno,
  1710. targetmatch.group('name'))
  1711. return [target], blank_finish
  1712. def make_target(self, block, block_text, lineno, target_name):
  1713. target_type, data = self.parse_target(block, block_text, lineno)
  1714. if target_type == 'refname':
  1715. target = nodes.target(block_text, '', refname=normalize_name(data))
  1716. target.indirect_reference_name = data
  1717. self.add_target(target_name, '', target, lineno)
  1718. self.document.note_indirect_target(target)
  1719. return target
  1720. elif target_type == 'refuri':
  1721. target = nodes.target(block_text, '')
  1722. self.add_target(target_name, data, target, lineno)
  1723. return target
  1724. else:
  1725. return data
  1726. def parse_target(self, block, block_text, lineno):
  1727. """
  1728. Determine the type of reference of a target.
  1729. :Return: A 2-tuple, one of:
  1730. - 'refname' and the indirect reference name
  1731. - 'refuri' and the URI
  1732. - 'malformed' and a system_message node
  1733. """
  1734. if block and block[-1].strip()[-1:] == '_': # possible indirect target
  1735. reference = ' '.join([line.strip() for line in block])
  1736. refname = self.is_reference(reference)
  1737. if refname:
  1738. return 'refname', refname
  1739. reference = ''.join([''.join(line.split()) for line in block])
  1740. return 'refuri', unescape(reference)
  1741. def is_reference(self, reference):
  1742. match = self.explicit.patterns.reference.match(
  1743. whitespace_normalize_name(reference))
  1744. if not match:
  1745. return None
  1746. return unescape(match.group('simple') or match.group('phrase'))
  1747. def add_target(self, targetname, refuri, target, lineno):
  1748. target.line = lineno
  1749. if targetname:
  1750. name = normalize_name(unescape(targetname))
  1751. target['names'].append(name)
  1752. if refuri:
  1753. uri = self.inliner.adjust_uri(refuri)
  1754. if uri:
  1755. target['refuri'] = uri
  1756. else:
  1757. raise ApplicationError('problem with URI: %r' % refuri)
  1758. self.document.note_explicit_target(target, self.parent)
  1759. else: # anonymous target
  1760. if refuri:
  1761. target['refuri'] = refuri
  1762. target['anonymous'] = 1
  1763. self.document.note_anonymous_target(target)
  1764. def substitution_def(self, match):
  1765. pattern = self.explicit.patterns.substitution
  1766. lineno = self.state_machine.abs_line_number()
  1767. block, indent, offset, blank_finish = \
  1768. self.state_machine.get_first_known_indented(match.end(),
  1769. strip_indent=0)
  1770. blocktext = (match.string[:match.end()] + '\n'.join(block))
  1771. block.disconnect()
  1772. escaped = escape2null(block[0].rstrip())
  1773. blockindex = 0
  1774. while 1:
  1775. subdefmatch = pattern.match(escaped)
  1776. if subdefmatch:
  1777. break
  1778. blockindex += 1
  1779. try:
  1780. escaped = escaped + ' ' + escape2null(block[blockindex].strip())
  1781. except IndexError:
  1782. raise MarkupError('malformed substitution definition.',
  1783. lineno)
  1784. del block[:blockindex] # strip out the substitution marker
  1785. block[0] = (block[0].strip() + ' ')[subdefmatch.end()-len(escaped)-1:-1]
  1786. if not block[0]:
  1787. del block[0]
  1788. offset += 1
  1789. while block and not block[-1].strip():
  1790. block.pop()
  1791. subname = subdefmatch.group('name')
  1792. substitution_node = nodes.substitution_definition(blocktext)
  1793. substitution_node.line = lineno
  1794. if not block:
  1795. msg = self.reporter.warning(
  1796. 'Substitution definition "%s" missing contents.' % subname,
  1797. nodes.literal_block(blocktext, blocktext), line=lineno)
  1798. return [msg], blank_finish
  1799. block[0] = block[0].strip()
  1800. substitution_node['names'].append(
  1801. nodes.whitespace_normalize_name(subname))
  1802. new_abs_offset, blank_finish = self.nested_list_parse(
  1803. block, input_offset=offset, node=substitution_node,
  1804. initial_state='SubstitutionDef', blank_finish=blank_finish)
  1805. i = 0
  1806. for node in substitution_node[:]:
  1807. if not (isinstance(node, nodes.Inline) or
  1808. isinstance(node, nodes.Text)):
  1809. self.parent += substitution_node[i]
  1810. del substitution_node[i]
  1811. else:
  1812. i += 1
  1813. for node in substitution_node.traverse(nodes.Element):
  1814. if self.disallowed_inside_substitution_definitions(node):
  1815. pformat = nodes.literal_block('', node.pformat().rstrip())
  1816. msg = self.reporter.error(
  1817. 'Substitution definition contains illegal element:',
  1818. pformat, nodes.literal_block(blocktext, blocktext),
  1819. line=lineno)
  1820. return [msg], blank_finish
  1821. if len(substitution_node) == 0:
  1822. msg = self.reporter.warning(
  1823. 'Substitution definition "%s" empty or invalid.'
  1824. % subname,
  1825. nodes.literal_block(blocktext, blocktext), line=lineno)
  1826. return [msg], blank_finish
  1827. self.document.note_substitution_def(
  1828. substitution_node, subname, self.parent)
  1829. return [substitution_node], blank_finish
  1830. def disallowed_inside_substitution_definitions(self, node):
  1831. if (node['ids'] or
  1832. isinstance(node, nodes.reference) and node.get('anonymous') or
  1833. isinstance(node, nodes.footnote_reference) and node.get('auto')):
  1834. return 1
  1835. else:
  1836. return 0
  1837. def directive(self, match, **option_presets):
  1838. """Returns a 2-tuple: list of nodes, and a "blank finish" boolean."""
  1839. type_name = match.group(1)
  1840. directive_class, messages = directives.directive(
  1841. type_name, self.memo.language, self.document)
  1842. self.parent += messages
  1843. if directive_class:
  1844. return self.run_directive(
  1845. directive_class, match, type_name, option_presets)
  1846. else:
  1847. return self.unknown_directive(type_name)
  1848. def run_directive(self, directive, match, type_name, option_presets):
  1849. """
  1850. Parse a directive then run its directive function.
  1851. Parameters:
  1852. - `directive`: The class implementing the directive. Must be
  1853. a subclass of `rst.Directive`.
  1854. - `match`: A regular expression match object which matched the first
  1855. line of the directive.
  1856. - `type_name`: The directive name, as used in the source text.
  1857. - `option_presets`: A dictionary of preset options, defaults for the
  1858. directive options. Currently, only an "alt" option is passed by
  1859. substitution definitions (value: the substitution name), which may
  1860. be used by an embedded image directive.
  1861. Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
  1862. """
  1863. if isinstance(directive, (FunctionType, MethodType)):
  1864. from docutils.parsers.rst import convert_directive_function
  1865. directive = convert_directive_function(directive)
  1866. lineno = self.state_machine.abs_line_number()
  1867. initial_line_offset = self.state_machine.line_offset
  1868. indented, indent, line_offset, blank_finish \
  1869. = self.state_machine.get_first_known_indented(match.end(),
  1870. strip_top=0)
  1871. block_text = '\n'.join(self.state_machine.input_lines[
  1872. initial_line_offset : self.state_machine.line_offset + 1])
  1873. try:
  1874. arguments, options, content, content_offset = (
  1875. self.parse_directive_block(indented, line_offset,
  1876. directive, option_presets))
  1877. except MarkupError, detail:
  1878. error = self.reporter.error(
  1879. 'Error in "%s" directive:\n%s.' % (type_name,
  1880. ' '.join(detail.args)),
  1881. nodes.literal_block(block_text, block_text), line=lineno)
  1882. return [error], blank_finish
  1883. directive_instance = directive(
  1884. type_name, arguments, options, content, lineno,
  1885. content_offset, block_text, self, self.state_machine)
  1886. try:
  1887. result = directive_instance.run()
  1888. except docutils.parsers.rst.DirectiveError, error:
  1889. msg_node = self.reporter.system_message(error.level, error.msg,
  1890. source=error.source, line=error.line)
  1891. msg_node += nodes.literal_block(block_text, block_text)
  1892. msg_node['line'] = lineno
  1893. result = [msg_node]
  1894. assert isinstance(result, list), \
  1895. 'Directive "%s" must return a list of nodes.' % type_name
  1896. for i in range(len(result)):
  1897. assert isinstance(result[i], nodes.Node), \
  1898. ('Directive "%s" returned non-Node object (index %s): %r'
  1899. % (type_name, i, result[i]))
  1900. return (result,
  1901. blank_finish or self.state_machine.is_next_line_blank())
  1902. def parse_directive_block(self, indented, line_offset, directive,
  1903. option_presets):
  1904. option_spec = directive.option_spec
  1905. has_content = directive.has_content
  1906. if indented and not indented[0].strip():
  1907. indented.trim_start()
  1908. line_offset += 1
  1909. while indented and not indented[-1].strip():
  1910. indented.trim_end()
  1911. if indented and (directive.required_arguments
  1912. or directive.optional_arguments
  1913. or option_spec):
  1914. for i in range(len(indented)):
  1915. if not indented[i].strip():
  1916. break
  1917. else:
  1918. i += 1
  1919. arg_block = indented[:i]
  1920. content = indented[i+1:]
  1921. content_offset = line_offset + i + 1
  1922. else:
  1923. content = indented
  1924. content_offset = line_offset
  1925. arg_block = []
  1926. while content and not content[0].strip():
  1927. content.trim_start()
  1928. content_offset += 1
  1929. if option_spec:
  1930. options, arg_block = self.parse_directive_options(
  1931. option_presets, option_spec, arg_block)
  1932. if arg_block and not (directive.required_arguments
  1933. or directive.optional_arguments):
  1934. raise MarkupError('no arguments permitted; blank line '
  1935. 'required before content block')
  1936. else:
  1937. options = {}
  1938. if directive.required_arguments or directive.optional_arguments:
  1939. arguments = self.parse_directive_arguments(
  1940. directive, arg_block)
  1941. else:
  1942. arguments = []
  1943. if content and not has_content:
  1944. raise MarkupError('no content permitted')
  1945. return (arguments, options, content, content_offset)
  1946. def parse_directive_options(self, option_presets, option_spec, arg_block):
  1947. options = option_presets.copy()
  1948. for i in range(len(arg_block)):
  1949. if arg_block[i][:1] == ':':
  1950. opt_block = arg_block[i:]
  1951. arg_block = arg_block[:i]
  1952. break
  1953. else:
  1954. opt_block = []
  1955. if opt_block:
  1956. success, data = self.parse_extension_options(option_spec,
  1957. opt_block)
  1958. if success: # data is a dict of options
  1959. options.update(data)
  1960. else: # data is an error string
  1961. raise MarkupError(data)
  1962. return options, arg_block
  1963. def parse_directive_arguments(self, directive, arg_block):
  1964. required = directive.required_arguments
  1965. optional = directive.optional_arguments
  1966. arg_text = '\n'.join(arg_block)
  1967. arguments = arg_text.split()
  1968. if len(arguments) < required:
  1969. raise MarkupError('%s argument(s) required, %s supplied'
  1970. % (required, len(arguments)))
  1971. elif len(arguments) > required + optional:
  1972. if directive.final_argument_whitespace:
  1973. arguments = arg_text.split(None, required + optional - 1)
  1974. else:
  1975. raise MarkupError(
  1976. 'maximum %s argument(s) allowed, %s supplied'
  1977. % (required + optional, len(arguments)))
  1978. return arguments
  1979. def parse_extension_options(self, option_spec, datalines):
  1980. """
  1981. Parse `datalines` for a field list containing extension options
  1982. matching `option_spec`.
  1983. :Parameters:
  1984. - `option_spec`: a mapping of option name to conversion
  1985. function, which should raise an exception on bad input.
  1986. - `datalines`: a list of input strings.
  1987. :Return:
  1988. - Success value, 1 or 0.
  1989. - An option dictionary on success, an error string on failure.
  1990. """
  1991. node = nodes.field_list()
  1992. newline_offset, blank_finish = self.nested_list_parse(
  1993. datalines, 0, node, initial_state='ExtensionOptions',
  1994. blank_finish=1)
  1995. if newline_offset != len(datalines): # incomplete parse of block
  1996. return 0, 'invalid option block'
  1997. try:
  1998. options = utils.extract_extension_options(node, option_spec)
  1999. except KeyError, detail:
  2000. return 0, ('unknown option: "%s"' % detail.args[0])
  2001. except (ValueError, TypeError), detail:
  2002. return 0, ('invalid option value: %s' % ' '.join(detail.args))
  2003. except utils.ExtensionOptionError, detail:
  2004. return 0, ('invalid option data: %s' % ' '.join(detail.args))
  2005. if blank_finish:
  2006. return 1, options
  2007. else:
  2008. return 0, 'option data incompletely parsed'
  2009. def unknown_directive(self, type_name):
  2010. lineno = self.state_machine.abs_line_number()
  2011. indented, indent, offset, blank_finish = \
  2012. self.state_machine.get_first_known_indented(0, strip_indent=0)
  2013. text = '\n'.join(indented)
  2014. error = self.reporter.error(
  2015. 'Unknown directive type "%s".' % type_name,
  2016. nodes.literal_block(text, text), line=lineno)
  2017. return [error], blank_finish
  2018. def comment(self, match):
  2019. if not match.string[match.end():].strip() \
  2020. and self.state_machine.is_next_line_blank(): # an empty comment?
  2021. return [nodes.comment()], 1 # "A tiny but practical wart."
  2022. indented, indent, offset, blank_finish = \
  2023. self.state_machine.get_first_known_indented(match.end())
  2024. while indented and not indented[-1].strip():
  2025. indented.trim_end()
  2026. text = '\n'.join(indented)
  2027. return [nodes.comment(text, text)], blank_finish
  2028. explicit.constructs = [
  2029. (footnote,
  2030. re.compile(r"""
  2031. \.\.[ ]+ # explicit markup start
  2032. \[
  2033. ( # footnote label:
  2034. [0-9]+ # manually numbered footnote
  2035. | # *OR*
  2036. \# # anonymous auto-numbered footnote
  2037. | # *OR*
  2038. \#%s # auto-number ed?) footnote label
  2039. | # *OR*
  2040. \* # auto-symbol footnote
  2041. )
  2042. \]
  2043. ([ ]+|$) # whitespace or end of line
  2044. """ % Inliner.simplename, re.VERBOSE | re.UNICODE)),
  2045. (citation,
  2046. re.compile(r"""
  2047. \.\.[ ]+ # explicit markup start
  2048. \[(%s)\] # citation label
  2049. ([ ]+|$) # whitespace or end of line
  2050. """ % Inliner.simplename, re.VERBOSE | re.UNICODE)),
  2051. (hyperlink_target,
  2052. re.compile(r"""
  2053. \.\.[ ]+ # explicit markup start
  2054. _ # target indicator
  2055. (?![ ]|$) # first char. not space or EOL
  2056. """, re.VERBOSE)),
  2057. (substitution_def,
  2058. re.compile(r"""
  2059. \.\.[ ]+ # explicit markup start
  2060. \| # substitution indicator
  2061. (?![ ]|$) # first char. not space or EOL
  2062. """, re.VERBOSE)),
  2063. (directive,
  2064. re.compile(r"""
  2065. \.\.[ ]+ # explicit markup start
  2066. (%s) # directive name
  2067. [ ]? # optional space
  2068. :: # directive delimiter
  2069. ([ ]+|$) # whitespace or end of line
  2070. """ % Inliner.simplename, re.VERBOSE | re.UNICODE))]
  2071. def explicit_markup(self, match, context, next_state):
  2072. """Footnotes, hyperlink targets, directives, comments."""
  2073. nodelist, blank_finish = self.explicit_construct(match)
  2074. self.parent += nodelist
  2075. self.explicit_list(blank_finish)
  2076. return [], next_state, []
  2077. def explicit_construct(self, match):
  2078. """Determine which explicit construct this is, parse & return it."""
  2079. errors = []
  2080. for method, pattern in self.explicit.constructs:
  2081. expmatch = pattern.match(match.string)
  2082. if expmatch:
  2083. try:
  2084. return method(self, expmatch)
  2085. except MarkupError, error: # never reached?
  2086. message, lineno = error.args
  2087. errors.append(self.reporter.warning(message, line=lineno))
  2088. break
  2089. nodelist, blank_finish = self.comment(match)
  2090. return nodelist + errors, blank_finish
  2091. def explicit_list(self, blank_finish):
  2092. """
  2093. Create a nested state machine for a series of explicit markup
  2094. constructs (including anonymous hyperlink targets).
  2095. """
  2096. offset = self.state_machine.line_offset + 1 # next line
  2097. newline_offset, blank_finish = self.nested_list_parse(
  2098. self.state_machine.input_lines[offset:],
  2099. input_offset=self.state_machine.abs_line_offset() + 1,
  2100. node=self.parent, initial_state='Explicit',
  2101. blank_finish=blank_finish,
  2102. match_titles=self.state_machine.match_titles)
  2103. self.goto_line(newline_offset)
  2104. if not blank_finish:
  2105. self.parent += self.unindent_warning('Explicit markup')
  2106. def anonymous(self, match, context, next_state):
  2107. """Anonymous hyperlink targets."""
  2108. nodelist, blank_finish = self.anonymous_target(match)
  2109. self.parent += nodelist
  2110. self.explicit_list(blank_finish)
  2111. return [], next_state, []
  2112. def anonymous_target(self, match):
  2113. lineno = self.state_machine.abs_line_number()
  2114. block, indent, offset, blank_finish \
  2115. = self.state_machine.get_first_known_indented(match.end(),
  2116. until_blank=1)
  2117. blocktext = match.string[:match.end()] + '\n'.join(block)
  2118. block = [escape2null(line) for line in block]
  2119. target = self.make_target(block, blocktext, lineno, '')
  2120. return [target], blank_finish
  2121. def line(self, match, context, next_state):
  2122. """Section title overline or transition marker."""
  2123. if self.state_machine.match_titles:
  2124. return [match.string], 'Line', []
  2125. elif match.string.strip() == '::':
  2126. raise statemachine.TransitionCorrection('text')
  2127. elif len(match.string.strip()) < 4:
  2128. msg = self.reporter.info(
  2129. 'Unexpected possible title overline or transition.\n'
  2130. "Treating it as ordinary text because it's so short.",
  2131. line=self.state_machine.abs_line_number())
  2132. self.parent += msg
  2133. raise statemachine.TransitionCorrection('text')
  2134. else:
  2135. blocktext = self.state_machine.line
  2136. msg = self.reporter.severe(
  2137. 'Unexpected section title or transition.',
  2138. nodes.literal_block(blocktext, blocktext),
  2139. line=self.state_machine.abs_line_number())
  2140. self.parent += msg
  2141. return [], next_state, []
  2142. def text(self, match, context, next_state):
  2143. """Titles, definition lists, paragraphs."""
  2144. return [match.string], 'Text', []
  2145. class RFC2822Body(Body):
  2146. """
  2147. RFC2822 headers are only valid as the first constructs in documents. As
  2148. soon as anything else appears, the `Body` state should take over.
  2149. """
  2150. patterns = Body.patterns.copy() # can't modify the original
  2151. patterns['rfc2822'] = r'[!-9;-~]+:( +|$)'
  2152. initial_transitions = [(name, 'Body')
  2153. for name in Body.initial_transitions]
  2154. initial_transitions.insert(-1, ('rfc2822', 'Body')) # just before 'text'
  2155. def rfc2822(self, match, context, next_state):
  2156. """RFC2822-style field list item."""
  2157. fieldlist = nodes.field_list(classes=['rfc2822'])
  2158. self.parent += fieldlist
  2159. field, blank_finish = self.rfc2822_field(match)
  2160. fieldlist += field
  2161. offset = self.state_machine.line_offset + 1 # next line
  2162. newline_offset, blank_finish = self.nested_list_parse(
  2163. self.state_machine.input_lines[offset:],
  2164. input_offset=self.state_machine.abs_line_offset() + 1,
  2165. node=fieldlist, initial_state='RFC2822List',
  2166. blank_finish=blank_finish)
  2167. self.goto_line(newline_offset)
  2168. if not blank_finish:
  2169. self.parent += self.unindent_warning(
  2170. 'RFC2822-style field list')
  2171. return [], next_state, []
  2172. def rfc2822_field(self, match):
  2173. name = match.string[:match.string.find(':')]
  2174. indented, indent, line_offset, blank_finish = \
  2175. self.state_machine.get_first_known_indented(match.end(),
  2176. until_blank=1)
  2177. fieldnode = nodes.field()
  2178. fieldnode += nodes.field_name(name, name)
  2179. fieldbody = nodes.field_body('\n'.join(indented))
  2180. fieldnode += fieldbody
  2181. if indented:
  2182. self.nested_parse(indented, input_offset=line_offset,
  2183. node=fieldbody)
  2184. return fieldnode, blank_finish
  2185. class SpecializedBody(Body):
  2186. """
  2187. Superclass for second and subsequent compound element members. Compound
  2188. elements are lists and list-like constructs.
  2189. All transition methods are disabled (redefined as `invalid_input`).
  2190. Override individual methods in subclasses to re-enable.
  2191. For example, once an initial bullet list item, say, is recognized, the
  2192. `BulletList` subclass takes over, with a "bullet_list" node as its
  2193. container. Upon encountering the initial bullet list item, `Body.bullet`
  2194. calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which
  2195. starts up a nested parsing session with `BulletList` as the initial state.
  2196. Only the ``bullet`` transition method is enabled in `BulletList`; as long
  2197. as only bullet list items are encountered, they are parsed and inserted
  2198. into the container. The first construct which is *not* a bullet list item
  2199. triggers the `invalid_input` method, which ends the nested parse and
  2200. closes the container. `BulletList` needs to recognize input that is
  2201. invalid in the context of a bullet list, which means everything *other
  2202. than* bullet list items, so it inherits the transition list created in
  2203. `Body`.
  2204. """
  2205. def invalid_input(self, match=None, context=None, next_state=None):
  2206. """Not a compound element member. Abort this state machine."""
  2207. self.state_machine.previous_line() # back up so parent SM can reassess
  2208. raise EOFError
  2209. indent = invalid_input
  2210. bullet = invalid_input
  2211. enumerator = invalid_input
  2212. field_marker = invalid_input
  2213. option_marker = invalid_input
  2214. doctest = invalid_input
  2215. line_block = invalid_input
  2216. grid_table_top = invalid_input
  2217. simple_table_top = invalid_input
  2218. explicit_markup = invalid_input
  2219. anonymous = invalid_input
  2220. line = invalid_input
  2221. text = invalid_input
  2222. class BulletList(SpecializedBody):
  2223. """Second and subsequent bullet_list list_items."""
  2224. def bullet(self, match, context, next_state):
  2225. """Bullet list item."""
  2226. if match.string[0] != self.parent['bullet']:
  2227. # different bullet: new list
  2228. self.invalid_input()
  2229. listitem, blank_finish = self.list_item(match.end())
  2230. self.parent += listitem
  2231. self.blank_finish = blank_finish
  2232. return [], next_state, []
  2233. class DefinitionList(SpecializedBody):
  2234. """Second and subsequent definition_list_items."""
  2235. def text(self, match, context, next_state):
  2236. """Definition lists."""
  2237. return [match.string], 'Definition', []
  2238. class EnumeratedList(SpecializedBody):
  2239. """Second and subsequent enumerated_list list_items."""
  2240. def enumerator(self, match, context, next_state):
  2241. """Enumerated list item."""
  2242. format, sequence, text, ordinal = self.parse_enumerator(
  2243. match, self.parent['enumtype'])
  2244. if ( format != self.format
  2245. or (sequence != '#' and (sequence != self.parent['enumtype']
  2246. or self.auto
  2247. or ordinal != (self.lastordinal + 1)))
  2248. or not self.is_enumerated_list_item(ordinal, sequence, format)):
  2249. # different enumeration: new list
  2250. self.invalid_input()
  2251. if sequence == '#':
  2252. self.auto = 1
  2253. listitem, blank_finish = self.list_item(match.end())
  2254. self.parent += listitem
  2255. self.blank_finish = blank_finish
  2256. self.lastordinal = ordinal
  2257. return [], next_state, []
  2258. class FieldList(SpecializedBody):
  2259. """Second and subsequent field_list fields."""
  2260. def field_marker(self, match, context, next_state):
  2261. """Field list field."""
  2262. field, blank_finish = self.field(match)
  2263. self.parent += field
  2264. self.blank_finish = blank_finish
  2265. return [], next_state, []
  2266. class OptionList(SpecializedBody):
  2267. """Second and subsequent option_list option_list_items."""
  2268. def option_marker(self, match, context, next_state):
  2269. """Option list item."""
  2270. try:
  2271. option_list_item, blank_finish = self.option_list_item(match)
  2272. except MarkupError, (message, lineno):
  2273. self.invalid_input()
  2274. self.parent += option_list_item
  2275. self.blank_finish = blank_finish
  2276. return [], next_state, []
  2277. class RFC2822List(SpecializedBody, RFC2822Body):
  2278. """Second and subsequent RFC2822-style field_list fields."""
  2279. patterns = RFC2822Body.patterns
  2280. initial_transitions = RFC2822Body.initial_transitions
  2281. def rfc2822(self, match, context, next_state):
  2282. """RFC2822-style field list item."""
  2283. field, blank_finish = self.rfc2822_field(match)
  2284. self.parent += field
  2285. self.blank_finish = blank_finish
  2286. return [], 'RFC2822List', []
  2287. blank = SpecializedBody.invalid_input
  2288. class ExtensionOptions(FieldList):
  2289. """
  2290. Parse field_list fields for extension options.
  2291. No nested parsing is done (including inline markup parsing).
  2292. """
  2293. def parse_field_body(self, indented, offset, node):
  2294. """Override `Body.parse_field_body` for simpler parsing."""
  2295. lines = []
  2296. for line in list(indented) + ['']:
  2297. if line.strip():
  2298. lines.append(line)
  2299. elif lines:
  2300. text = '\n'.join(lines)
  2301. node += nodes.paragraph(text, text)
  2302. lines = []
  2303. class LineBlock(SpecializedBody):
  2304. """Second and subsequent lines of a line_block."""
  2305. blank = SpecializedBody.invalid_input
  2306. def line_block(self, match, context, next_state):
  2307. """New line of line block."""
  2308. lineno = self.state_machine.abs_line_number()
  2309. line, messages, blank_finish = self.line_block_line(match, lineno)
  2310. self.parent += line
  2311. self.parent.parent += messages
  2312. self.blank_finish = blank_finish
  2313. return [], next_state, []
  2314. class Explicit(SpecializedBody):
  2315. """Second and subsequent explicit markup construct."""
  2316. def explicit_markup(self, match, context, next_state):
  2317. """Footnotes, hyperlink targets, directives, comments."""
  2318. nodelist, blank_finish = self.explicit_construct(match)
  2319. self.parent += nodelist
  2320. self.blank_finish = blank_finish
  2321. return [], next_state, []
  2322. def anonymous(self, match, context, next_state):
  2323. """Anonymous hyperlink targets."""
  2324. nodelist, blank_finish = self.anonymous_target(match)
  2325. self.parent += nodelist
  2326. self.blank_finish = blank_finish
  2327. return [], next_state, []
  2328. blank = SpecializedBody.invalid_input
  2329. class SubstitutionDef(Body):
  2330. """
  2331. Parser for the contents of a substitution_definition element.
  2332. """
  2333. patterns = {
  2334. 'embedded_directive': re.compile(r'(%s)::( +|$)'
  2335. % Inliner.simplename, re.UNICODE),
  2336. 'text': r''}
  2337. initial_transitions = ['embedded_directive', 'text']
  2338. def embedded_directive(self, match, context, next_state):
  2339. nodelist, blank_finish = self.directive(match,
  2340. alt=self.parent['names'][0])
  2341. self.parent += nodelist
  2342. if not self.state_machine.at_eof():
  2343. self.blank_finish = blank_finish
  2344. raise EOFError
  2345. def text(self, match, context, next_state):
  2346. if not self.state_machine.at_eof():
  2347. self.blank_finish = self.state_machine.is_next_line_blank()
  2348. raise EOFError
  2349. class Text(RSTState):
  2350. """
  2351. Classifier of second line of a text block.
  2352. Could be a paragraph, a definition list item, or a title.
  2353. """
  2354. patterns = {'underline': Body.patterns['line'],
  2355. 'text': r''}
  2356. initial_transitions = [('underline', 'Body'), ('text', 'Body')]
  2357. def blank(self, match, context, next_state):
  2358. """End of paragraph."""
  2359. paragraph, literalnext = self.paragraph(
  2360. context, self.state_machine.abs_line_number() - 1)
  2361. self.parent += paragraph
  2362. if literalnext:
  2363. self.parent += self.literal_block()
  2364. return [], 'Body', []
  2365. def eof(self, context):
  2366. if context:
  2367. self.blank(None, context, None)
  2368. return []
  2369. def indent(self, match, context, next_state):
  2370. """Definition list item."""
  2371. definitionlist = nodes.definition_list()
  2372. definitionlistitem, blank_finish = self.definition_list_item(context)
  2373. definitionlist += definitionlistitem
  2374. self.parent += definitionlist
  2375. offset = self.state_machine.line_offset + 1 # next line
  2376. newline_offset, blank_finish = self.nested_list_parse(
  2377. self.state_machine.input_lines[offset:],
  2378. input_offset=self.state_machine.abs_line_offset() + 1,
  2379. node=definitionlist, initial_state='DefinitionList',
  2380. blank_finish=blank_finish, blank_finish_state='Definition')
  2381. self.goto_line(newline_offset)
  2382. if not blank_finish:
  2383. self.parent += self.unindent_warning('Definition list')
  2384. return [], 'Body', []
  2385. def underline(self, match, context, next_state):
  2386. """Section title."""
  2387. lineno = self.state_machine.abs_line_number()
  2388. title = context[0].rstrip()
  2389. underline = match.string.rstrip()
  2390. source = title + '\n' + underline
  2391. messages = []
  2392. if column_width(title) > len(underline):
  2393. if len(underline) < 4:
  2394. if self.state_machine.match_titles:
  2395. msg = self.reporter.info(
  2396. 'Possible title underline, too short for the title.\n'
  2397. "Treating it as ordinary text because it's so short.",
  2398. line=lineno)
  2399. self.parent += msg
  2400. raise statemachine.TransitionCorrection('text')
  2401. else:
  2402. blocktext = context[0] + '\n' + self.state_machine.line
  2403. msg = self.reporter.warning(
  2404. 'Title underline too short.',
  2405. nodes.literal_block(blocktext, blocktext), line=lineno)
  2406. messages.append(msg)
  2407. if not self.state_machine.match_titles:
  2408. blocktext = context[0] + '\n' + self.state_machine.line
  2409. msg = self.reporter.severe(
  2410. 'Unexpected section title.',
  2411. nodes.literal_block(blocktext, blocktext), line=lineno)
  2412. self.parent += messages
  2413. self.parent += msg
  2414. return [], next_state, []
  2415. style = underline[0]
  2416. context[:] = []
  2417. self.section(title, source, style, lineno - 1, messages)
  2418. return [], next_state, []
  2419. def text(self, match, context, next_state):
  2420. """Paragraph."""
  2421. startline = self.state_machine.abs_line_number() - 1
  2422. msg = None
  2423. try:
  2424. block = self.state_machine.get_text_block(flush_left=1)
  2425. except statemachine.UnexpectedIndentationError, instance:
  2426. block, source, lineno = instance.args
  2427. msg = self.reporter.error('Unexpected indentation.',
  2428. source=source, line=lineno)
  2429. lines = context + list(block)
  2430. paragraph, literalnext = self.paragraph(lines, startline)
  2431. self.parent += paragraph
  2432. self.parent += msg
  2433. if literalnext:
  2434. try:
  2435. self.state_machine.next_line()
  2436. except EOFError:
  2437. pass
  2438. self.parent += self.literal_block()
  2439. return [], next_state, []
  2440. def literal_block(self):
  2441. """Return a list of nodes."""
  2442. indented, indent, offset, blank_finish = \
  2443. self.state_machine.get_indented()
  2444. while indented and not indented[-1].strip():
  2445. indented.trim_end()
  2446. if not indented:
  2447. return self.quoted_literal_block()
  2448. data = '\n'.join(indented)
  2449. literal_block = nodes.literal_block(data, data)
  2450. literal_block.line = offset + 1
  2451. nodelist = [literal_block]
  2452. if not blank_finish:
  2453. nodelist.append(self.unindent_warning('Literal block'))
  2454. return nodelist
  2455. def quoted_literal_block(self):
  2456. abs_line_offset = self.state_machine.abs_line_offset()
  2457. offset = self.state_machine.line_offset
  2458. parent_node = nodes.Element()
  2459. new_abs_offset = self.nested_parse(
  2460. self.state_machine.input_lines[offset:],
  2461. input_offset=abs_line_offset, node=parent_node, match_titles=0,
  2462. state_machine_kwargs={'state_classes': (QuotedLiteralBlock,),
  2463. 'initial_state': 'QuotedLiteralBlock'})
  2464. self.goto_line(new_abs_offset)
  2465. return parent_node.children
  2466. def definition_list_item(self, termline):
  2467. indented, indent, line_offset, blank_finish = \
  2468. self.state_machine.get_indented()
  2469. definitionlistitem = nodes.definition_list_item(
  2470. '\n'.join(termline + list(indented)))
  2471. lineno = self.state_machine.abs_line_number() - 1
  2472. definitionlistitem.line = lineno
  2473. termlist, messages = self.term(termline, lineno)
  2474. definitionlistitem += termlist
  2475. definition = nodes.definition('', *messages)
  2476. definitionlistitem += definition
  2477. if termline[0][-2:] == '::':
  2478. definition += self.reporter.info(
  2479. 'Blank line missing before literal block (after the "::")? '
  2480. 'Interpreted as a definition list item.', line=line_offset+1)
  2481. self.nested_parse(indented, input_offset=line_offset, node=definition)
  2482. return definitionlistitem, blank_finish
  2483. classifier_delimiter = re.compile(' +: +')
  2484. def term(self, lines, lineno):
  2485. """Return a definition_list's term and optional classifiers."""
  2486. assert len(lines) == 1
  2487. text_nodes, messages = self.inline_text(lines[0], lineno)
  2488. term_node = nodes.term()
  2489. node_list = [term_node]
  2490. for i in range(len(text_nodes)):
  2491. node = text_nodes[i]
  2492. if isinstance(node, nodes.Text):
  2493. parts = self.classifier_delimiter.split(node.rawsource)
  2494. if len(parts) == 1:
  2495. node_list[-1] += node
  2496. else:
  2497. node_list[-1] += nodes.Text(parts[0].rstrip())
  2498. for part in parts[1:]:
  2499. classifier_node = nodes.classifier('', part)
  2500. node_list.append(classifier_node)
  2501. else:
  2502. node_list[-1] += node
  2503. return node_list, messages
  2504. class SpecializedText(Text):
  2505. """
  2506. Superclass for second and subsequent lines of Text-variants.
  2507. All transition methods are disabled. Override individual methods in
  2508. subclasses to re-enable.
  2509. """
  2510. def eof(self, context):
  2511. """Incomplete construct."""
  2512. return []
  2513. def invalid_input(self, match=None, context=None, next_state=None):
  2514. """Not a compound element member. Abort this state machine."""
  2515. raise EOFError
  2516. blank = invalid_input
  2517. indent = invalid_input
  2518. underline = invalid_input
  2519. text = invalid_input
  2520. class Definition(SpecializedText):
  2521. """Second line of potential definition_list_item."""
  2522. def eof(self, context):
  2523. """Not a definition."""
  2524. self.state_machine.previous_line(2) # so parent SM can reassess
  2525. return []
  2526. def indent(self, match, context, next_state):
  2527. """Definition list item."""
  2528. definitionlistitem, blank_finish = self.definition_list_item(context)
  2529. self.parent += definitionlistitem
  2530. self.blank_finish = blank_finish
  2531. return [], 'DefinitionList', []
  2532. class Line(SpecializedText):
  2533. """
  2534. Second line of over- & underlined section title or transition marker.
  2535. """
  2536. eofcheck = 1 # @@@ ???
  2537. """Set to 0 while parsing sections, so that we don't catch the EOF."""
  2538. def eof(self, context):
  2539. """Transition marker at end of section or document."""
  2540. marker = context[0].strip()
  2541. if self.memo.section_bubble_up_kludge:
  2542. self.memo.section_bubble_up_kludge = 0
  2543. elif len(marker) < 4:
  2544. self.state_correction(context)
  2545. if self.eofcheck: # ignore EOFError with sections
  2546. lineno = self.state_machine.abs_line_number() - 1
  2547. transition = nodes.transition(rawsource=context[0])
  2548. transition.line = lineno
  2549. self.parent += transition
  2550. self.eofcheck = 1
  2551. return []
  2552. def blank(self, match, context, next_state):
  2553. """Transition marker."""
  2554. lineno = self.state_machine.abs_line_number() - 1
  2555. marker = context[0].strip()
  2556. if len(marker) < 4:
  2557. self.state_correction(context)
  2558. transition = nodes.transition(rawsource=marker)
  2559. transition.line = lineno
  2560. self.parent += transition
  2561. return [], 'Body', []
  2562. def text(self, match, context, next_state):
  2563. """Potential over- & underlined title."""
  2564. lineno = self.state_machine.abs_line_number() - 1
  2565. overline = context[0]
  2566. title = match.string
  2567. underline = ''
  2568. try:
  2569. underline = self.state_machine.next_line()
  2570. except EOFError:
  2571. blocktext = overline + '\n' + title
  2572. if len(overline.rstrip()) < 4:
  2573. self.short_overline(context, blocktext, lineno, 2)
  2574. else:
  2575. msg = self.reporter.severe(
  2576. 'Incomplete section title.',
  2577. nodes.literal_block(blocktext, blocktext), line=lineno)
  2578. self.parent += msg
  2579. return [], 'Body', []
  2580. source = '%s\n%s\n%s' % (overline, title, underline)
  2581. overline = overline.rstrip()
  2582. underline = underline.rstrip()
  2583. if not self.transitions['underline'][0].match(underline):
  2584. blocktext = overline + '\n' + title + '\n' + underline
  2585. if len(overline.rstrip()) < 4:
  2586. self.short_overline(context, blocktext, lineno, 2)
  2587. else:
  2588. msg = self.reporter.severe(
  2589. 'Missing matching underline for section title overline.',
  2590. nodes.literal_block(source, source), line=lineno)
  2591. self.parent += msg
  2592. return [], 'Body', []
  2593. elif overline != underline:
  2594. blocktext = overline + '\n' + title + '\n' + underline
  2595. if len(overline.rstrip()) < 4:
  2596. self.short_overline(context, blocktext, lineno, 2)
  2597. else:
  2598. msg = self.reporter.severe(
  2599. 'Title overline & underline mismatch.',
  2600. nodes.literal_block(source, source), line=lineno)
  2601. self.parent += msg
  2602. return [], 'Body', []
  2603. title = title.rstrip()
  2604. messages = []
  2605. if column_width(title) > len(overline):
  2606. blocktext = overline + '\n' + title + '\n' + underline
  2607. if len(overline.rstrip()) < 4:
  2608. self.short_overline(context, blocktext, lineno, 2)
  2609. else:
  2610. msg = self.reporter.warning(
  2611. 'Title overline too short.',
  2612. nodes.literal_block(source, source), line=lineno)
  2613. messages.append(msg)
  2614. style = (overline[0], underline[0])
  2615. self.eofcheck = 0 # @@@ not sure this is correct
  2616. self.section(title.lstrip(), source, style, lineno + 1, messages)
  2617. self.eofcheck = 1
  2618. return [], 'Body', []
  2619. indent = text # indented title
  2620. def underline(self, match, context, next_state):
  2621. overline = context[0]
  2622. blocktext = overline + '\n' + self.state_machine.line
  2623. lineno = self.state_machine.abs_line_number() - 1
  2624. if len(overline.rstrip()) < 4:
  2625. self.short_overline(context, blocktext, lineno, 1)
  2626. msg = self.reporter.error(
  2627. 'Invalid section title or transition marker.',
  2628. nodes.literal_block(blocktext, blocktext), line=lineno)
  2629. self.parent += msg
  2630. return [], 'Body', []
  2631. def short_overline(self, context, blocktext, lineno, lines=1):
  2632. msg = self.reporter.info(
  2633. 'Possible incomplete section title.\nTreating the overline as '
  2634. "ordinary text because it's so short.", line=lineno)
  2635. self.parent += msg
  2636. self.state_correction(context, lines)
  2637. def state_correction(self, context, lines=1):
  2638. self.state_machine.previous_line(lines)
  2639. context[:] = []
  2640. raise statemachine.StateCorrection('Body', 'text')
  2641. class QuotedLiteralBlock(RSTState):
  2642. """
  2643. Nested parse handler for quoted (unindented) literal blocks.
  2644. Special-purpose. Not for inclusion in `state_classes`.
  2645. """
  2646. patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats,
  2647. 'text': r''}
  2648. initial_transitions = ('initial_quoted', 'text')
  2649. def __init__(self, state_machine, debug=0):
  2650. RSTState.__init__(self, state_machine, debug)
  2651. self.messages = []
  2652. self.initial_lineno = None
  2653. def blank(self, match, context, next_state):
  2654. if context:
  2655. raise EOFError
  2656. else:
  2657. return context, next_state, []
  2658. def eof(self, context):
  2659. if context:
  2660. text = '\n'.join(context)
  2661. literal_block = nodes.literal_block(text, text)
  2662. literal_block.line = self.initial_lineno
  2663. self.parent += literal_block
  2664. else:
  2665. self.parent += self.reporter.warning(
  2666. 'Literal block expected; none found.',
  2667. line=self.state_machine.abs_line_number())
  2668. self.state_machine.previous_line()
  2669. self.parent += self.messages
  2670. return []
  2671. def indent(self, match, context, next_state):
  2672. assert context, ('QuotedLiteralBlock.indent: context should not '
  2673. 'be empty!')
  2674. self.messages.append(
  2675. self.reporter.error('Unexpected indentation.',
  2676. line=self.state_machine.abs_line_number()))
  2677. self.state_machine.previous_line()
  2678. raise EOFError
  2679. def initial_quoted(self, match, context, next_state):
  2680. """Match arbitrary quote character on the first line only."""
  2681. self.remove_transition('initial_quoted')
  2682. quote = match.string[0]
  2683. pattern = re.compile(re.escape(quote))
  2684. # New transition matches consistent quotes only:
  2685. self.add_transition('quoted',
  2686. (pattern, self.quoted, self.__class__.__name__))
  2687. self.initial_lineno = self.state_machine.abs_line_number()
  2688. return [match.string], next_state, []
  2689. def quoted(self, match, context, next_state):
  2690. """Match consistent quotes on subsequent lines."""
  2691. context.append(match.string)
  2692. return context, next_state, []
  2693. def text(self, match, context, next_state):
  2694. if context:
  2695. self.messages.append(
  2696. self.reporter.error('Inconsistent literal block quoting.',
  2697. line=self.state_machine.abs_line_number()))
  2698. self.state_machine.previous_line()
  2699. raise EOFError
  2700. state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList,
  2701. OptionList, LineBlock, ExtensionOptions, Explicit, Text,
  2702. Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List)
  2703. """Standard set of State classes used to start `RSTStateMachine`."""