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