frontmatter.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. # $Id: frontmatter.py 9030 2022-03-05 23:28:32Z milde $
  2. # Author: David Goodger, Ueli Schlaepfer <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. Transforms related to the front matter of a document or a section
  6. (information found before the main text):
  7. - `DocTitle`: Used to transform a lone top level section's title to
  8. the document title, promote a remaining lone top-level section's
  9. title to the document subtitle, and determine the document's title
  10. metadata (document['title']) based on the document title and/or the
  11. "title" setting.
  12. - `SectionSubTitle`: Used to transform a lone subsection into a
  13. subtitle.
  14. - `DocInfo`: Used to transform a bibliographic field list into docinfo
  15. elements.
  16. """
  17. __docformat__ = 'reStructuredText'
  18. import re
  19. from docutils import nodes, utils
  20. from docutils.transforms import TransformError, Transform
  21. class TitlePromoter(Transform):
  22. """
  23. Abstract base class for DocTitle and SectionSubTitle transforms.
  24. """
  25. def promote_title(self, node):
  26. """
  27. Transform the following tree::
  28. <node>
  29. <section>
  30. <title>
  31. ...
  32. into ::
  33. <node>
  34. <title>
  35. ...
  36. `node` is normally a document.
  37. """
  38. # Type check
  39. if not isinstance(node, nodes.Element):
  40. raise TypeError('node must be of Element-derived type.')
  41. # `node` must not have a title yet.
  42. assert not (len(node) and isinstance(node[0], nodes.title))
  43. section, index = self.candidate_index(node)
  44. if index is None:
  45. return False
  46. # Transfer the section's attributes to the node:
  47. # NOTE: Change `replace` to False to NOT replace attributes that
  48. # already exist in node with those in section.
  49. # NOTE: Remove `and_source` to NOT copy the 'source'
  50. # attribute from section
  51. node.update_all_atts_concatenating(section, replace=True,
  52. and_source=True)
  53. # setup_child is called automatically for all nodes.
  54. node[:] = (section[:1] # section title
  55. + node[:index] # everything that was in the
  56. # node before the section
  57. + section[1:]) # everything that was in the section
  58. assert isinstance(node[0], nodes.title)
  59. return True
  60. def promote_subtitle(self, node):
  61. """
  62. Transform the following node tree::
  63. <node>
  64. <title>
  65. <section>
  66. <title>
  67. ...
  68. into ::
  69. <node>
  70. <title>
  71. <subtitle>
  72. ...
  73. """
  74. # Type check
  75. if not isinstance(node, nodes.Element):
  76. raise TypeError('node must be of Element-derived type.')
  77. subsection, index = self.candidate_index(node)
  78. if index is None:
  79. return False
  80. subtitle = nodes.subtitle()
  81. # Transfer the subsection's attributes to the new subtitle
  82. # NOTE: Change `replace` to False to NOT replace attributes
  83. # that already exist in node with those in section.
  84. # NOTE: Remove `and_source` to NOT copy the 'source'
  85. # attribute from section.
  86. subtitle.update_all_atts_concatenating(subsection, replace=True,
  87. and_source=True)
  88. # Transfer the contents of the subsection's title to the
  89. # subtitle:
  90. subtitle[:] = subsection[0][:]
  91. node[:] = (node[:1] # title
  92. + [subtitle]
  93. # everything that was before the section:
  94. + node[1:index]
  95. # everything that was in the subsection:
  96. + subsection[1:])
  97. return True
  98. def candidate_index(self, node):
  99. """
  100. Find and return the promotion candidate and its index.
  101. Return (None, None) if no valid candidate was found.
  102. """
  103. index = node.first_child_not_matching_class(
  104. nodes.PreBibliographic)
  105. if (index is None or len(node) > (index + 1)
  106. or not isinstance(node[index], nodes.section)):
  107. return None, None
  108. else:
  109. return node[index], index
  110. class DocTitle(TitlePromoter):
  111. """
  112. In reStructuredText_, there is no way to specify a document title
  113. and subtitle explicitly. Instead, we can supply the document title
  114. (and possibly the subtitle as well) implicitly, and use this
  115. two-step transform to "raise" or "promote" the title(s) (and their
  116. corresponding section contents) to the document level.
  117. 1. If the document contains a single top-level section as its
  118. first non-comment element, the top-level section's title
  119. becomes the document's title, and the top-level section's
  120. contents become the document's immediate contents. The lone
  121. top-level section header must be the first non-comment element
  122. in the document.
  123. For example, take this input text::
  124. =================
  125. Top-Level Title
  126. =================
  127. A paragraph.
  128. Once parsed, it looks like this::
  129. <document>
  130. <section names="top-level title">
  131. <title>
  132. Top-Level Title
  133. <paragraph>
  134. A paragraph.
  135. After running the DocTitle transform, we have::
  136. <document names="top-level title">
  137. <title>
  138. Top-Level Title
  139. <paragraph>
  140. A paragraph.
  141. 2. If step 1 successfully determines the document title, we
  142. continue by checking for a subtitle.
  143. If the lone top-level section itself contains a single
  144. second-level section as its first non-comment element, that
  145. section's title is promoted to the document's subtitle, and
  146. that section's contents become the document's immediate
  147. contents. Given this input text::
  148. =================
  149. Top-Level Title
  150. =================
  151. Second-Level Title
  152. ~~~~~~~~~~~~~~~~~~
  153. A paragraph.
  154. After parsing and running the Section Promotion transform, the
  155. result is::
  156. <document names="top-level title">
  157. <title>
  158. Top-Level Title
  159. <subtitle names="second-level title">
  160. Second-Level Title
  161. <paragraph>
  162. A paragraph.
  163. (Note that the implicit hyperlink target generated by the
  164. "Second-Level Title" is preserved on the "subtitle" element
  165. itself.)
  166. Any comment elements occurring before the document title or
  167. subtitle are accumulated and inserted as the first body elements
  168. after the title(s).
  169. This transform also sets the document's metadata title
  170. (document['title']).
  171. .. _reStructuredText: https://docutils.sourceforge.io/rst.html
  172. """
  173. default_priority = 320
  174. def set_metadata(self):
  175. """
  176. Set document['title'] metadata title from the following
  177. sources, listed in order of priority:
  178. * Existing document['title'] attribute.
  179. * "title" setting.
  180. * Document title node (as promoted by promote_title).
  181. """
  182. if not self.document.hasattr('title'):
  183. if self.document.settings.title is not None:
  184. self.document['title'] = self.document.settings.title
  185. elif len(self.document) and isinstance(self.document[0],
  186. nodes.title):
  187. self.document['title'] = self.document[0].astext()
  188. def apply(self):
  189. if self.document.settings.setdefault('doctitle_xform', True):
  190. # promote_(sub)title defined in TitlePromoter base class.
  191. if self.promote_title(self.document):
  192. # If a title has been promoted, also try to promote a
  193. # subtitle.
  194. self.promote_subtitle(self.document)
  195. # Set document['title'].
  196. self.set_metadata()
  197. class SectionSubTitle(TitlePromoter):
  198. """
  199. This works like document subtitles, but for sections. For example, ::
  200. <section>
  201. <title>
  202. Title
  203. <section>
  204. <title>
  205. Subtitle
  206. ...
  207. is transformed into ::
  208. <section>
  209. <title>
  210. Title
  211. <subtitle>
  212. Subtitle
  213. ...
  214. For details refer to the docstring of DocTitle.
  215. """
  216. default_priority = 350
  217. def apply(self):
  218. if not self.document.settings.setdefault('sectsubtitle_xform', True):
  219. return
  220. for section in self.document.findall(nodes.section):
  221. # On our way through the node tree, we are modifying it
  222. # but only the not-yet-visited part, so that the iterator
  223. # returned by findall() is not corrupted.
  224. self.promote_subtitle(section)
  225. class DocInfo(Transform):
  226. """
  227. This transform is specific to the reStructuredText_ markup syntax;
  228. see "Bibliographic Fields" in the `reStructuredText Markup
  229. Specification`_ for a high-level description. This transform
  230. should be run *after* the `DocTitle` transform.
  231. Given a field list as the first non-comment element after the
  232. document title and subtitle (if present), registered bibliographic
  233. field names are transformed to the corresponding DTD elements,
  234. becoming child elements of the "docinfo" element (except for a
  235. dedication and/or an abstract, which become "topic" elements after
  236. "docinfo").
  237. For example, given this document fragment after parsing::
  238. <document>
  239. <title>
  240. Document Title
  241. <field_list>
  242. <field>
  243. <field_name>
  244. Author
  245. <field_body>
  246. <paragraph>
  247. A. Name
  248. <field>
  249. <field_name>
  250. Status
  251. <field_body>
  252. <paragraph>
  253. $RCSfile$
  254. ...
  255. After running the bibliographic field list transform, the
  256. resulting document tree would look like this::
  257. <document>
  258. <title>
  259. Document Title
  260. <docinfo>
  261. <author>
  262. A. Name
  263. <status>
  264. frontmatter.py
  265. ...
  266. The "Status" field contained an expanded RCS keyword, which is
  267. normally (but optionally) cleaned up by the transform. The sole
  268. contents of the field body must be a paragraph containing an
  269. expanded RCS keyword of the form "$keyword: expansion text $". Any
  270. RCS keyword can be processed in any bibliographic field. The
  271. dollar signs and leading RCS keyword name are removed. Extra
  272. processing is done for the following RCS keywords:
  273. - "RCSfile" expands to the name of the file in the RCS or CVS
  274. repository, which is the name of the source file with a ",v"
  275. suffix appended. The transform will remove the ",v" suffix.
  276. - "Date" expands to the format "YYYY/MM/DD hh:mm:ss" (in the UTC
  277. time zone). The RCS Keywords transform will extract just the
  278. date itself and transform it to an ISO 8601 format date, as in
  279. "2000-12-31".
  280. (Since the source file for this text is itself stored under CVS,
  281. we can't show an example of the "Date" RCS keyword because we
  282. can't prevent any RCS keywords used in this explanation from
  283. being expanded. Only the "RCSfile" keyword is stable; its
  284. expansion text changes only if the file name changes.)
  285. .. _reStructuredText: https://docutils.sourceforge.io/rst.html
  286. .. _reStructuredText Markup Specification:
  287. https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html
  288. """
  289. default_priority = 340
  290. biblio_nodes = {
  291. 'author': nodes.author,
  292. 'authors': nodes.authors,
  293. 'organization': nodes.organization,
  294. 'address': nodes.address,
  295. 'contact': nodes.contact,
  296. 'version': nodes.version,
  297. 'revision': nodes.revision,
  298. 'status': nodes.status,
  299. 'date': nodes.date,
  300. 'copyright': nodes.copyright,
  301. 'dedication': nodes.topic,
  302. 'abstract': nodes.topic}
  303. """Canonical field name (lowcased) to node class name mapping for
  304. bibliographic fields (field_list)."""
  305. def apply(self):
  306. if not self.document.settings.setdefault('docinfo_xform', True):
  307. return
  308. document = self.document
  309. index = document.first_child_not_matching_class(
  310. nodes.PreBibliographic)
  311. if index is None:
  312. return
  313. candidate = document[index]
  314. if isinstance(candidate, nodes.field_list):
  315. biblioindex = document.first_child_not_matching_class(
  316. (nodes.Titular, nodes.Decorative, nodes.meta))
  317. nodelist = self.extract_bibliographic(candidate)
  318. del document[index] # untransformed field list (candidate)
  319. document[biblioindex:biblioindex] = nodelist
  320. def extract_bibliographic(self, field_list):
  321. docinfo = nodes.docinfo()
  322. bibliofields = self.language.bibliographic_fields
  323. labels = self.language.labels
  324. topics = {'dedication': None, 'abstract': None}
  325. for field in field_list:
  326. try:
  327. name = field[0][0].astext()
  328. normedname = nodes.fully_normalize_name(name)
  329. if not (len(field) == 2 and normedname in bibliofields
  330. and self.check_empty_biblio_field(field, name)):
  331. raise TransformError
  332. canonical = bibliofields[normedname]
  333. biblioclass = self.biblio_nodes[canonical]
  334. if issubclass(biblioclass, nodes.TextElement):
  335. if not self.check_compound_biblio_field(field, name):
  336. raise TransformError
  337. utils.clean_rcs_keywords(
  338. field[1][0], self.rcs_keyword_substitutions)
  339. docinfo.append(biblioclass('', '', *field[1][0]))
  340. elif issubclass(biblioclass, nodes.authors):
  341. self.extract_authors(field, name, docinfo)
  342. elif issubclass(biblioclass, nodes.topic):
  343. if topics[canonical]:
  344. field[-1] += self.document.reporter.warning(
  345. 'There can only be one "%s" field.' % name,
  346. base_node=field)
  347. raise TransformError
  348. title = nodes.title(name, labels[canonical])
  349. title[0].rawsource = labels[canonical]
  350. topics[canonical] = biblioclass(
  351. '', title, classes=[canonical], *field[1].children)
  352. else:
  353. docinfo.append(biblioclass('', *field[1].children))
  354. except TransformError:
  355. if len(field[-1]) == 1 \
  356. and isinstance(field[-1][0], nodes.paragraph):
  357. utils.clean_rcs_keywords(
  358. field[-1][0], self.rcs_keyword_substitutions)
  359. # if normedname not in bibliofields:
  360. classvalue = nodes.make_id(normedname)
  361. if classvalue:
  362. field['classes'].append(classvalue)
  363. docinfo.append(field)
  364. nodelist = []
  365. if len(docinfo) != 0:
  366. nodelist.append(docinfo)
  367. for name in ('dedication', 'abstract'):
  368. if topics[name]:
  369. nodelist.append(topics[name])
  370. return nodelist
  371. def check_empty_biblio_field(self, field, name):
  372. if len(field[-1]) < 1:
  373. field[-1] += self.document.reporter.warning(
  374. 'Cannot extract empty bibliographic field "%s".' % name,
  375. base_node=field)
  376. return None
  377. return 1
  378. def check_compound_biblio_field(self, field, name):
  379. if len(field[-1]) > 1:
  380. field[-1] += self.document.reporter.warning(
  381. 'Cannot extract compound bibliographic field "%s".' % name,
  382. base_node=field)
  383. return None
  384. if not isinstance(field[-1][0], nodes.paragraph):
  385. field[-1] += self.document.reporter.warning(
  386. 'Cannot extract bibliographic field "%s" containing '
  387. 'anything other than a single paragraph.' % name,
  388. base_node=field)
  389. return None
  390. return 1
  391. rcs_keyword_substitutions = [
  392. (re.compile(r'\$' r'Date: (\d\d\d\d)[-/](\d\d)[-/](\d\d)[ T][\d:]+'
  393. r'[^$]* \$', re.IGNORECASE), r'\1-\2-\3'),
  394. (re.compile(r'\$' r'RCSfile: (.+),v \$', re.IGNORECASE), r'\1'),
  395. (re.compile(r'\$[a-zA-Z]+: (.+) \$'), r'\1')]
  396. def extract_authors(self, field, name, docinfo):
  397. try:
  398. if len(field[1]) == 1:
  399. if isinstance(field[1][0], nodes.paragraph):
  400. authors = self.authors_from_one_paragraph(field)
  401. elif isinstance(field[1][0], nodes.bullet_list):
  402. authors = self.authors_from_bullet_list(field)
  403. else:
  404. raise TransformError
  405. else:
  406. authors = self.authors_from_paragraphs(field)
  407. authornodes = [nodes.author('', '', *author)
  408. for author in authors if author]
  409. if len(authornodes) >= 1:
  410. docinfo.append(nodes.authors('', *authornodes))
  411. else:
  412. raise TransformError
  413. except TransformError:
  414. field[-1] += self.document.reporter.warning(
  415. 'Bibliographic field "%s" incompatible with extraction: '
  416. 'it must contain either a single paragraph (with authors '
  417. 'separated by one of "%s"), multiple paragraphs (one per '
  418. 'author), or a bullet list with one paragraph (one author) '
  419. 'per item.'
  420. % (name, ''.join(self.language.author_separators)),
  421. base_node=field)
  422. raise
  423. def authors_from_one_paragraph(self, field):
  424. """Return list of Text nodes with author names in `field`.
  425. Author names must be separated by one of the "autor separators"
  426. defined for the document language (default: ";" or ",").
  427. """
  428. # @@ keep original formatting? (e.g. ``:authors: A. Test, *et-al*``)
  429. text = ''.join(str(node)
  430. for node in field[1].findall(nodes.Text))
  431. if not text:
  432. raise TransformError
  433. for authorsep in self.language.author_separators:
  434. # don't split at escaped `authorsep`:
  435. pattern = '(?<!\x00)%s' % authorsep
  436. authornames = re.split(pattern, text)
  437. if len(authornames) > 1:
  438. break
  439. authornames = (name.strip() for name in authornames)
  440. return [[nodes.Text(name)] for name in authornames if name]
  441. def authors_from_bullet_list(self, field):
  442. authors = []
  443. for item in field[1][0]:
  444. if isinstance(item, nodes.comment):
  445. continue
  446. if len(item) != 1 or not isinstance(item[0], nodes.paragraph):
  447. raise TransformError
  448. authors.append(item[0].children)
  449. if not authors:
  450. raise TransformError
  451. return authors
  452. def authors_from_paragraphs(self, field):
  453. for item in field[1]:
  454. if not isinstance(item, (nodes.paragraph, nodes.comment)):
  455. raise TransformError
  456. authors = [item.children for item in field[1]
  457. if not isinstance(item, nodes.comment)]
  458. return authors