PageRenderTime 36ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

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

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