Debian Codegraph @

docutils/writers/manpage.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # $Id: manpage.py 10161 2025-06-10 19:50:50Z grubert $
2 # Author: Engelbert Gruber <[email protected]>
3 # Copyright: This module is put into the public domain.
4
5 """
6 Simple man page writer for reStructuredText.
7
8 Man pages (short for "manual pages") contain system documentation on unix-like
9 systems. The pages are grouped in numbered sections:
10
11 1 executable programs and shell commands
12 2 system calls
13 3 library functions
14 4 special files
15 5 file formats
16 6 games
17 7 miscellaneous
18 8 system administration
19
20 Man pages are written in the *roff* markup language.
21
22 See https://www.tldp.org/HOWTO/Man-Page for a start.
23
24 Man pages have no subsection only parts.
25 Standard parts
26
27 Name ,
28 Synopsis ,
29 Description ,
30 Options ,
31 Files ,
32 See also ,
33 Bugs ,
34
35 and
36
37 AUthor .
38
39 A unix-like system keeps an index of the Descriptions, which is accessible
40 by the command whatis or apropos.
41
42 """
43
44 from __future__ import annotations
45
46 __docformat__ = 'reStructuredText'
47
48 import re
49
50 import docutils
51 from docutils import frontend, nodes, writers, languages
52 from docutils.utils._roman_numerals import RomanNumeral
53
54 FIELD_LIST_INDENT = 7
55 DEFINITION_LIST_INDENT = 7
56 OPTION_LIST_INDENT = 7
57 BLOCKQOUTE_INDENT = 3.5
58 LITERAL_BLOCK_INDENT = 3.5
59
60 # Define two macros so man/roff can calculate the
61 # indent/unindent margins by itself
62 MACRO_DEF = r""".
63 .nr rst2man-indent-level 0
64 .
65 .de1 rstReportMargin
66 \\$1 \\n[an-margin]
67 level \\n[rst2man-indent-level]
68 level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
69 -
70 \\n[rst2man-indent0]
71 \\n[rst2man-indent1]
72 \\n[rst2man-indent2]
73 ..
74 .de1 INDENT
75 .\" .rstReportMargin pre:
76 . RS \\$1
77 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
78 . nr rst2man-indent-level +1
79 .\" .rstReportMargin post:
80 ..
81 .de UNINDENT
82 . RE
83 .\" indent \\n[an-margin]
84 .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
85 .nr rst2man-indent-level -1
86 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
87 .in \\n[rst2man-indent\\n[rst2man-indent-level]]u
88 ..
89 """
90
91 # see groff_man_style recommends applying non-printing break points
92 # in long URIs.
93 NONPRINTING_BREAKPOINT = r'\:'
94
95 # after a slash series of
96 # after an at sign
97 # after question marks
98 # after ampersands
99 # after number signs
100 # (?=.) avoids matching the end of string, requires something
101 # MAYBE require 5 after the break point
102 NONBREAKING_INSERT_RE = re.compile(r'([/@?&#]+)(?=.{3,})')
103 # before each dot or a series of
104 NONBREAKING_INSERT_RE2 = re.compile(r'([^\.]+)(?=\.+)(?=.{3,})')
105
106
107 def insert_URI_breakpoints(s):
108 # TODO only for long URIs ?
109 return NONBREAKING_INSERT_RE2.sub(
110 r'\1' + NONPRINTING_BREAKPOINT,
111 NONBREAKING_INSERT_RE.sub(r'\1' + NONPRINTING_BREAKPOINT, s))
112
113
114 class Writer(writers.Writer):
115 """
116 manpage writer class
117 """
118
119 supported = ('manpage',)
120 """Formats this writer supports."""
121
122 settings_spec = (
123 'Manpage Writer Options',
124 None,
125 (('Write references in plain text form. (default)',
126 ['--text-references'],
127 {'action': 'store_true',
128 'default': True, # remove in Docutils 1.0
129 'validator': frontend.validate_boolean}),
130 ('Use man macros UR and MT for references.',
131 ['--macro-references'],
132 {'dest': 'text_references',
133 'action': 'store_false',
134 'validator': frontend.validate_boolean}),
135 ),
136 )
137
138 config_section_dependencies = ('writers',)
139
140 output = None
141 """Final translated form of `document`."""
142
143 def __init__(self) -> None:
144 writers.Writer.__init__(self)
145 self.translator_class = Translator
146
147 def translate(self) -> None:
148 visitor = self.translator_class(self.document)
149 self.document.walkabout(visitor)
150 self.output = visitor.astext()
151
152
153 class Table:
154 """
155 man package table handling.
156 """
157 def __init__(self) -> None:
158 self._rows = []
159 self._options = ['box', 'center']
160 self._tab_char = '\t'
161 self._coldefs = []
162
163 def new_row(self) -> None:
164 self._rows.append([])
165
166 def append_separator(self, separator) -> None:
167 """Append the separator for table head."""
168 self._rows.append([separator])
169
170 def append_cell(self, cell_lines) -> None:
171 """cell_lines is an array of lines"""
172 start = 0
173 if len(cell_lines) > 0 and cell_lines[0] == '.sp\n':
174 start = 1
175 self._rows[-1].append(cell_lines[start:])
176 if len(self._coldefs) < len(self._rows[-1]):
177 self._coldefs.append('l')
178
179 def _minimize_cell(self, cell_lines) -> None:
180 """Remove leading and trailing blank and ``.sp`` lines"""
181 while cell_lines and cell_lines[0] in ('\n', '.sp\n'):
182 del cell_lines[0]
183 while cell_lines and cell_lines[-1] in ('\n', '.sp\n'):
184 del cell_lines[-1]
185
186 def as_list(self):
187 text = ['.TS\n',
188 ' '.join(self._options) + ';\n',
189 '%s.\n' % '|'.join(self._coldefs),
190 ]
191 for row in self._rows:
192 # row = array of cells. cell = array of lines.
193 text.append('T{\n')
194 for i in range(len(row)):
195 cell = row[i]
196 self._minimize_cell(cell)
197 text.extend(cell)
198 if not text[-1].endswith('\n'):
199 text[-1] += '\n'
200 if i < len(row)-1:
201 text.append('T}'+self._tab_char+'T{\n')
202 else:
203 text.append('T}\n')
204 text.append('_\n') # line between rows
205 text.pop() # pop last "line between"
206 text.append('.TE\n')
207 return text
208
209
210 class Translator(nodes.NodeVisitor):
211 """
212 Docutils to man page translator.
213
214 Generate unix-like manual pages using the "man macro package"
215 from a Docutils document tree.
216 """
217
218 words_and_spaces = re.compile(r'\S+| +|\n')
219 possibly_a_roff_command = re.compile(r'\.\w')
220 document_start = (
221 'Man page generated from reStructuredText\n'
222 f'by the Docutils {docutils.__version__} manpage writer.'
223 )
224
225 def __init__(self, document) -> None:
226 nodes.NodeVisitor.__init__(self, document)
227 self.settings = settings = document.settings
228 if settings.text_references:
229 self.visit_reference = self._visit_reference_no_macro
230 self.depart_reference = self._depart_reference_no_macro
231 else:
232 self.visit_reference = self._visit_reference_with_macro
233 self.depart_reference = self._depart_reference_with_macro
234 lcode = settings.language_code
235 self.language = languages.get_language(lcode, document.reporter)
236 self.head = []
237 self.body = []
238 self.foot = []
239 self.section_level = 0
240 self.context = []
241 self.topic_class = ''
242 self.colspecs = []
243 self.compact_p = 1
244 self.compact_simple = None
245 # the list style "*" bullet or "#" numbered
246 self._list_char = []
247 # writing the header .TH and .SH Name is postponed after docinfo.
248 self._docinfo = {
249 "title": "",
250 "subtitle": "",
251 "manual_section": "", "manual_group": "",
252 "author": [],
253 "date": "",
254 "copyright": "",
255 "version": "",
256 }
257 self._docinfo_keys = [] # a list to keep the sequence as in source.
258 self._docinfo_names = {} # to get name from text not normalized.
259 self._in_docinfo = None
260 self._field_name = None
261 self._active_table = None
262 self._has_a_table = False # is there a table in this document
263 self._in_literal = False
264 self.header_written = 0
265 self._line_block = 0
266 self.authors = []
267 self.section_level = 0
268 self._indent = [0]
269 # Do not use paragraph requests ``.PP`` because these set indentation.
270 # use ``.sp``. Remove superfluous ``.sp`` in ``astext``.
271
272 # Fonts are put on a stack, the top one is used.
273 # ``.ft P`` or ``\\fP`` pop from stack.
274 # But ``.BI`` seams to fill stack with BIBIBIBIB...
275 # ``B`` bold, ``I`` italic, ``R`` roman should be available.
276
277 # from groff_man_style(7)
278 #
279 # \c End a text line without inserting space or attempting a
280 # break. ...
281 # The next line is interpreted as usual and can include a
282 # macro call (contrast with \newline). ...
283 # useful when three font styles are needed in a single
284 # word, as in a command synopsis.
285 #
286 # .RB [ \-\-stylesheet=\c
287 # .IR name ]
288
289 # Requests start wit a dot ``.`` or the no-break control character,
290 # a neutral apostrophe ``'`` suppresses the break implied by some
291 # requests.
292
293 # central definition of simple processing rules
294 # what to output on : visit, depart
295 self.defs = {
296 'indent': ('.INDENT %.1f\n', '.UNINDENT\n'),
297 'definition_list_item': ('.TP', ''), # par. with hanging tag
298 'field_name': ('.TP\n.B ', '\n'),
299 'literal': ('\\fB', '\\fP'),
300 'literal_block': ('.sp\n.EX\n', '\n.EE\n'),
301
302 'option_list_item': ('.TP\n', ''),
303
304 'emphasis': ('\\fI', '\\fP'),
305 'strong': ('\\fB', '\\fP'),
306 'title_reference': ('\\fI', '\\fP'),
307
308 'topic-title': ('.SS ',),
309 'sidebar-title': ('.SS ',),
310
311 'problematic': ('\n.nf\n', '\n.fi\n'),
312 }
313 # NOTE do not specify the newline before a dot-command, but ensure
314 # it is there.
315
316 def comment_begin(self, text):
317 """Return commented version of the passed text WITHOUT end of
318 line/comment."""
319 prefix = '.\\" '
320 out_text = ''.join([(prefix + in_line + '\n')
321 for in_line in text.split('\n')])
322 return out_text
323
324 def comment(self, text):
325 """Return commented version of the passed text."""
326 return self.comment_begin(text)+'.\n'
327
328 def ensure_eol(self) -> None:
329 """Ensure the last line in body is terminated by new line."""
330 if len(self.body) > 0 and self.body[-1][-1] != '\n':
331 self.body.append('\n')
332
333 def ensure_c_eol(self) -> None:
334 """Ensure the last line in body is terminated by new line."""
335 if len(self.body) > 0 and self.body[-1][-1] != '\n':
336 self.body.append('\\c\n')
337
338 def astext(self):
339 """Return the final formatted document as a string."""
340 if not self.header_written:
341 # ensure we get a ".TH" as viewers require it.
342 self.append_header()
343 # filter body
344 for i in range(len(self.body)-1, 0, -1):
345 # remove superfluous vertical gaps.
346 if self.body[i] == '.sp\n':
347 if self.body[i - 1][:4] in ('.BI ', '.IP '):
348 self.body[i] = '.\n'
349 elif (self.body[i - 1][:3] == '.B '
350 and self.body[i - 2][:4] == '.TP\n'):
351 self.body[i] = '.\n'
352 elif (self.body[i - 1] == '\n'
353 and not self.possibly_a_roff_command.match(
354 self.body[i - 2])
355 and (self.body[i - 3][:7] == '.TP\n.B '
356 or self.body[i - 3][:4] == '\n.B ')
357 ):
358 self.body[i] = '.\n'
359 elif self.body[i][:4] in ('.UE\n', '.ME\n'):
360 # if next item starts with
361 # a) a line end, disable it
362 if self.body[i+1][0] in ('\n', '\r'):
363 self.body[i+1] = '.' + self.body[i+1]
364 # b) with a separator: moving the 1st char to current item
365 # would require to check the second, use \c instead.
366 else:
367 # append \c to end the text line, .ME or .UE without
368 # inserting space or attempting a break.
369 self.body[i] = "%s \\c\n" % (self.body[i][:3])
370 return ''.join(self.head + self.body + self.foot)
371
372 def deunicode(self, text):
373 text = text.replace('\xa0', '\\ ')
374 text = text.replace('\u2020', '\\(dg')
375 return text
376
377 def encode_special_chars(self, text):
378 replace_pairs = [
379 ('-', '\\-'),
380 ('\'', '\\(aq'),
381 ('ยด', "\\'"),
382 ('`', '\\(ga'),
383 ('"', '\\(dq'), # double quotes are a problem on macro lines
384 ]
385 for (in_char, out_markup) in replace_pairs:
386 text = text.replace(in_char, out_markup)
387 return text
388
389 def visit_Text(self, node) -> None:
390 text = node.astext()
391 text = text.replace('\\', '\\e')
392 text = self.encode_special_chars(text)
393 # unicode
394 text = self.deunicode(text)
395 # prevent interpretation of "." at line start
396 if text.startswith('.'):
397 text = '\\&' + text
398 if self._in_literal:
399 text = text.replace('\n.', '\n\\&.')
400 self.body.append(text)
401
402 def depart_Text(self, node) -> None:
403 pass
404
405 def list_start(self, node) -> None:
406 class EnumChar:
407 """list item numbering/markup handling"""
408 enum_style = {
409 'bullet': '\\(bu',
410 }
411
412 def __init__(self, style) -> None:
413 self._style = style
414 if 'start' in node:
415 self._cnt = node['start'] - 1
416 else:
417 self._cnt = 0
418 self._indent = 2
419 if style == 'arabic':
420 # indentation depends on number of children
421 # and start value.
422 self._indent = len(str(len(node.children)))
423 self._indent += len(str(self._cnt)) + 1
424 elif style == 'loweralpha':
425 self._cnt += ord('a') - 1
426 self._indent = 3
427 elif style == 'upperalpha':
428 self._cnt += ord('A') - 1
429 self._indent = 3
430 elif style.endswith('roman'):
431 self._indent = 5
432
433 def __next__(self):
434 if self._style == 'bullet':
435 return self.enum_style[self._style]
436 self._cnt += 1
437 # TODO add prefix postfix
438 if self._style in ('loweralpha', 'upperalpha'):
439 return "%c." % self._cnt
440 if self._style.endswith('roman'):
441 res = RomanNumeral(self._cnt)
442 if self._style.startswith('upper'):
443 return res.to_uppercase() + '.'
444 else:
445 return res.to_lowercase() + '.'
446 # else 'arabic', ...
447 return "%d." % self._cnt
448
449 def get_width(self):
450 return self._indent
451
452 def __repr__(self) -> str:
453 return 'enum_style-%s' % list(self._style)
454
455 if 'enumtype' in node:
456 self._list_char.append(EnumChar(node['enumtype']))
457 else:
458 # INFO node['bullet'] contains the bullet style "*+-"
459 # BUT man pages only use "*".
460 self._list_char.append(EnumChar('bullet'))
461 if len(self._list_char) > 1:
462 # indent nested lists
463 self.indent(self._list_char[-2].get_width())
464 else:
465 self.indent(self._list_char[-1].get_width())
466
467 def list_end(self) -> None:
468 self.dedent()
469 self._list_char.pop()
470
471 def header(self):
472 th = (".TH \"%(title)s\" \"%(manual_section)s\""
473 " \"%(date)s\" \"%(version)s\"") % self._docinfo
474 if self._docinfo["manual_group"]:
475 th += " \"%(manual_group)s\"" % self._docinfo
476 th += "\n"
477 sh_tmpl = (".SH Name\n"
478 "%(title)s \\- %(subtitle)s\n")
479 return th + sh_tmpl % self._docinfo
480
481 def append_header(self) -> None:
482 """append header with .TH and .SH Name"""
483 # NOTE before everything
484 # .TH title section date source manual
485 # BUT macros before .TH for whatis database generators.
486 if self.header_written:
487 return
488 self.head.append(MACRO_DEF)
489 self.head.append(self.header())
490 self.header_written = 1
491
492 def visit_address(self, node) -> None:
493 self.visit_docinfo_item(node, 'address')
494
495 def depart_address(self, node) -> None:
496 pass
497
498 def visit_admonition(self, node, name=None) -> None:
499 #
500 # Make admonitions a simple block quote
501 # with a strong heading
502 #
503 # Using .IP/.RE doesn't preserve indentation
504 # when admonitions contain bullets, literal,
505 # and/or block quotes.
506 #
507 if name:
508 # .. admonition:: has no name
509 self.body.append('.sp\n')
510 name = '%s%s:%s\n' % (
511 self.defs['strong'][0],
512 self.language.labels.get(name, name),
513 self.defs['strong'][1],
514 )
515 self.body.append(name)
516 self.visit_block_quote(node)
517
518 def depart_admonition(self, node) -> None:
519 self.depart_block_quote(node)
520
521 def visit_attention(self, node) -> None:
522 self.visit_admonition(node, 'attention')
523
524 depart_attention = depart_admonition
525
526 def visit_docinfo_item(self, node, name):
527 if name == 'author':
528 self._docinfo[name].append(node.astext())
529 else:
530 self._docinfo[name] = node.astext()
531 self._docinfo_keys.append(name)
532 raise nodes.SkipNode
533
534 def depart_docinfo_item(self, node) -> None:
535 pass
536
537 def visit_author(self, node) -> None:
538 self.visit_docinfo_item(node, 'author')
539
540 depart_author = depart_docinfo_item
541
542 def visit_authors(self, node) -> None:
543 # _author is called anyway.
544 pass
545
546 def depart_authors(self, node) -> None:
547 pass
548
549 def visit_block_quote(self, node) -> None:
550 # BUG/HACK: indent always uses the _last_ indentation,
551 # thus we need two of them.
552 self.indent(BLOCKQOUTE_INDENT)
553 self.indent(0)
554
555 def depart_block_quote(self, node) -> None:
556 self.dedent()
557 self.dedent()
558
559 def visit_bullet_list(self, node) -> None:
560 self.list_start(node)
561
562 def depart_bullet_list(self, node) -> None:
563 self.list_end()
564
565 def visit_caption(self, node) -> None:
566 pass
567
568 def depart_caption(self, node) -> None:
569 pass
570
571 def visit_caution(self, node) -> None:
572 self.visit_admonition(node, 'caution')
573
574 depart_caution = depart_admonition
575
576 def visit_citation(self, node) -> None:
577 num = node.astext().split(None, 1)[0]
578 num = num.strip()
579 self.body.append('.IP [%s] 5\n' % num)
580
581 def depart_citation(self, node) -> None:
582 pass
583
584 def visit_citation_reference(self, node):
585 self.body.append('['+node.astext()+']')
586 raise nodes.SkipNode
587
588 def visit_classifier(self, node) -> None:
589 self.body.append('(')
590
591 def depart_classifier(self, node) -> None:
592 self.body.append(')')
593 self.depart_term(node) # close the term element after last classifier
594
595 def visit_colspec(self, node) -> None:
596 self.colspecs.append(node)
597
598 def depart_colspec(self, node) -> None:
599 pass
600
601 def write_colspecs(self) -> None:
602 self.body.append("%s.\n" % ('L '*len(self.colspecs)))
603
604 def visit_comment(self, node,
605 sub=re.compile('-(?=-)').sub):
606 self.body.append(self.comment(node.astext()))
607 raise nodes.SkipNode
608
609 def visit_contact(self, node) -> None:
610 self.visit_docinfo_item(node, 'contact')
611
612 depart_contact = depart_docinfo_item
613
614 def visit_container(self, node) -> None:
615 pass
616
617 def depart_container(self, node) -> None:
618 pass
619
620 def visit_compound(self, node) -> None:
621 pass
622
623 def depart_compound(self, node) -> None:
624 pass
625
626 def visit_copyright(self, node) -> None:
627 self.visit_docinfo_item(node, 'copyright')
628
629 def visit_danger(self, node) -> None:
630 self.visit_admonition(node, 'danger')
631
632 depart_danger = depart_admonition
633
634 def visit_date(self, node) -> None:
635 self.visit_docinfo_item(node, 'date')
636
637 def visit_decoration(self, node) -> None:
638 pass
639
640 def depart_decoration(self, node) -> None:
641 pass
642
643 def visit_definition(self, node) -> None:
644 pass
645
646 def depart_definition(self, node) -> None:
647 pass
648
649 def visit_definition_list(self, node) -> None:
650 self.indent(DEFINITION_LIST_INDENT)
651
652 def depart_definition_list(self, node) -> None:
653 self.dedent()
654
655 def visit_definition_list_item(self, node) -> None:
656 self.body.append(self.defs['definition_list_item'][0])
657
658 def depart_definition_list_item(self, node) -> None:
659 self.body.append(self.defs['definition_list_item'][1])
660
661 def visit_description(self, node) -> None:
662 pass
663
664 def depart_description(self, node) -> None:
665 pass
666
667 def visit_docinfo(self, node) -> None:
668 self._in_docinfo = 1
669
670 def depart_docinfo(self, node) -> None:
671 self._in_docinfo = None
672 # NOTE nothing should be written before this
673 self.append_header()
674
675 def visit_doctest_block(self, node) -> None:
676 self.body.append(self.defs['literal_block'][0])
677 self._in_literal = True
678
679 def depart_doctest_block(self, node) -> None:
680 self._in_literal = False
681 self.body.append(self.defs['literal_block'][1])
682
683 def visit_document(self, node) -> None:
684 # no blank line between comment and header.
685 self.head.append(self.comment(self.document_start).rstrip()+'\n')
686 # writing header is postponed
687 self.header_written = 0
688
689 def depart_document(self, node) -> None:
690 if self._docinfo['author']:
691 self.body.append('.SH Author\n%s\n'
692 % ', '.join(self._docinfo['author']))
693 skip = ('author', 'copyright', 'date',
694 'manual_group', 'manual_section',
695 'subtitle',
696 'title', 'version')
697 for name in self._docinfo_keys:
698 if name == 'address':
699 self.body.append("\n%s:\n%s%s.nf\n%s\n.fi\n%s%s" % (
700 self.language.labels.get(name, name),
701 self.defs['indent'][0] % 0,
702 self.defs['indent'][0] % BLOCKQOUTE_INDENT,
703 self._docinfo[name],
704 self.defs['indent'][1],
705 self.defs['indent'][1]))
706 elif name not in skip:
707 if name in self._docinfo_names:
708 label = self._docinfo_names[name]
709 else:
710 label = self.language.labels.get(name, name)
711 self.body.append("\n%s: %s\n" % (label, self._docinfo[name]))
712 if self._docinfo['copyright']:
713 self.body.append('.SH Copyright\n%s\n'
714 % self._docinfo['copyright'])
715 self.body.append(self.comment_begin('End of generated man page.'))
716
717 def visit_emphasis(self, node) -> None:
718 self.body.append(self.defs['emphasis'][0])
719
720 def depart_emphasis(self, node) -> None:
721 self.body.append(self.defs['emphasis'][1])
722
723 def visit_entry(self, node) -> None:
724 # a cell in a table row
725 if 'morerows' in node:
726 self.document.reporter.warning(
727 '"table row spanning" not supported', base_node=node)
728 if 'morecols' in node:
729 self.document.reporter.warning(
730 '"table cell spanning" not supported', base_node=node)
731 self.context.append(len(self.body))
732
733 def depart_entry(self, node) -> None:
734 start = self.context.pop()
735 self._active_table.append_cell(self.body[start:])
736 del self.body[start:]
737
738 def visit_enumerated_list(self, node) -> None:
739 self.list_start(node)
740
741 def depart_enumerated_list(self, node) -> None:
742 self.list_end()
743
744 def visit_error(self, node) -> None:
745 self.visit_admonition(node, 'error')
746
747 depart_error = depart_admonition
748
749 def visit_field(self, node) -> None:
750 pass
751
752 def depart_field(self, node) -> None:
753 pass
754
755 def visit_field_body(self, node):
756 if self._in_docinfo:
757 name_normalized = self._field_name.lower().replace(" ", "_")
758 self._docinfo_names[name_normalized] = self._field_name
759 self.visit_docinfo_item(node, name_normalized)
760 raise nodes.SkipNode
761
762 def depart_field_body(self, node) -> None:
763 pass
764
765 def visit_field_list(self, node) -> None:
766 self.indent(FIELD_LIST_INDENT)
767
768 def depart_field_list(self, node) -> None:
769 self.dedent()
770
771 def visit_field_name(self, node):
772 if self._in_docinfo:
773 self._field_name = node.astext()
774 raise nodes.SkipNode
775 self.body.append(self.defs['field_name'][0])
776
777 def depart_field_name(self, node) -> None:
778 self.body.append(self.defs['field_name'][1])
779
780 def visit_figure(self, node) -> None:
781 self.indent(2.5)
782 self.indent(0)
783
784 def depart_figure(self, node) -> None:
785 self.dedent()
786 self.dedent()
787
788 def visit_footer(self, node):
789 self.document.reporter.warning('"footer" not supported',
790 base_node=node)
791 # avoid output the link to document source
792 raise nodes.SkipNode
793
794 def depart_footer(self, node) -> None:
795 pass
796
797 def visit_footnote(self, node) -> None:
798 num, _text = node.astext().split(maxsplit=1)
799 num = num.strip()
800 self.body.append('.IP [%s] 5\n' % self.deunicode(num))
801
802 def depart_footnote(self, node) -> None:
803 pass
804
805 def footnote_backrefs(self, node) -> None:
806 self.document.reporter.warning('"footnote_backrefs" not supported',
807 base_node=node)
808
809 def visit_footnote_reference(self, node):
810 self.body.append('['+self.deunicode(node.astext())+']')
811 raise nodes.SkipNode
812
813 def depart_footnote_reference(self, node) -> None:
814 pass
815
816 def visit_generated(self, node) -> None:
817 pass
818
819 def depart_generated(self, node) -> None:
820 pass
821
822 def visit_header(self, node):
823 raise NotImplementedError(node.astext())
824
825 def depart_header(self, node) -> None:
826 pass
827
828 def visit_hint(self, node) -> None:
829 self.visit_admonition(node, 'hint')
830
831 depart_hint = depart_admonition
832
833 def visit_subscript(self, node) -> None:
834 self.body.append('\\s-2\\d')
835
836 def depart_subscript(self, node) -> None:
837 self.body.append('\\u\\s0')
838
839 def visit_superscript(self, node) -> None:
840 self.body.append('\\s-2\\u')
841
842 def depart_superscript(self, node) -> None:
843 self.body.append('\\d\\s0')
844
845 def visit_attribution(self, node) -> None:
846 self.body.append('\\(em ')
847
848 def depart_attribution(self, node) -> None:
849 self.body.append('\n')
850
851 def visit_image(self, node):
852 msg = '"image" not supported by "manpage" writer.'
853 if 'alt' in node.attributes:
854 self.document.reporter.info(msg,
855 base_node=node)
856 self.body.append('.sp\n %s\n' % (
857 node.attributes['alt']))
858 elif 'uri' in node.attributes:
859 self.body.append('.sp\n image: %s\n' % (
860 node.attributes['uri']))
861 self.document.reporter.warning(
862 f'{msg}\nPlease provide an "alt" attribute with textual'
863 ' replacement.', base_node=node)
864 # else 0 arguments to image not allowed
865 raise nodes.SkipNode
866
867 def visit_important(self, node) -> None:
868 self.visit_admonition(node, 'important')
869
870 depart_important = depart_admonition
871
872 def visit_inline(self, node) -> None:
873 pass
874
875 def depart_inline(self, node) -> None:
876 pass
877
878 def visit_label(self, node):
879 # footnote and citation labels are written in their visit_ functions.
880 if isinstance(node.parent, (nodes.footnote, nodes.citation)):
881 raise nodes.SkipNode
882 self.document.reporter.warning('"unsupported "label"',
883 base_node=node)
884 self.body.append('[')
885
886 def depart_label(self, node) -> None:
887 self.body.append(']\n')
888
889 def visit_legend(self, node) -> None:
890 pass
891
892 def depart_legend(self, node) -> None:
893 pass
894
895 # WHAT should we use .INDENT, .UNINDENT ?
896 def visit_line_block(self, node) -> None:
897 self._line_block += 1
898 if self._line_block == 1:
899 # TODO: separate inline blocks from previous paragraphs
900 # see http://hg.intevation.org/mercurial/crew/rev/9c142ed9c405
901 # self.body.append('.sp\n')
902 # but it does not work for me.
903 self.body.append('.nf\n')
904 else:
905 self.body.append('.in +2\n')
906
907 def depart_line_block(self, node) -> None:
908 self._line_block -= 1
909 if self._line_block == 0:
910 self.body.append('.fi\n')
911 self.body.append('.sp\n')
912 else:
913 self.body.append('.in -2\n')
914
915 def visit_line(self, node) -> None:
916 pass
917
918 def depart_line(self, node) -> None:
919 self.body.append('\n')
920
921 def visit_list_item(self, node) -> None:
922 # man 7 man argues to use ".IP" instead of ".TP"
923 self.body.append('.IP %s %d\n' % (
924 next(self._list_char[-1]),
925 self._list_char[-1].get_width(),))
926
927 def depart_list_item(self, node) -> None:
928 pass
929
930 def visit_literal(self, node) -> None:
931 self.body.append(self.defs['literal'][0])
932
933 def depart_literal(self, node) -> None:
934 self.body.append(self.defs['literal'][1])
935
936 def visit_literal_block(self, node) -> None:
937 # BUG/HACK: indent always uses the _last_ indentation,
938 # thus we need two of them.
939 self.indent(LITERAL_BLOCK_INDENT)
940 self.indent(0)
941 self.body.append(self.defs['literal_block'][0])
942 self._in_literal = True
943
944 def depart_literal_block(self, node) -> None:
945 self._in_literal = False
946 self.body.append(self.defs['literal_block'][1])
947 self.dedent()
948 self.dedent()
949
950 def visit_math(self, node) -> None:
951 self.document.reporter.warning('"math" role not supported',
952 base_node=node)
953 self.visit_literal(node)
954
955 def depart_math(self, node) -> None:
956 self.depart_literal(node)
957
958 def visit_math_block(self, node) -> None:
959 self.document.reporter.warning('"math" directive not supported',
960 base_node=node)
961 self.visit_literal_block(node)
962
963 def depart_math_block(self, node) -> None:
964 self.depart_literal_block(node)
965
966 # <meta> shall become an optional standard node:
967 # def visit_meta(self, node):
968 # raise NotImplementedError(node.astext())
969
970 # def depart_meta(self, node):
971 # pass
972
973 def visit_note(self, node) -> None:
974 self.visit_admonition(node, 'note')
975
976 depart_note = depart_admonition
977
978 def indent(self, by=0.5) -> None:
979 # if we are in a section ".SH" there already is a .RS
980 step = self._indent[-1]
981 self._indent.append(by)
982 self.body.append(self.defs['indent'][0] % step)
983
984 def dedent(self) -> None:
985 self._indent.pop()
986 self.body.append(self.defs['indent'][1])
987
988 def visit_option_list(self, node) -> None:
989 self.indent(OPTION_LIST_INDENT)
990
991 def depart_option_list(self, node) -> None:
992 self.dedent()
993
994 def visit_option_list_item(self, node) -> None:
995 # one item of the list
996 self.body.append(self.defs['option_list_item'][0])
997
998 def depart_option_list_item(self, node) -> None:
999 self.body.append(self.defs['option_list_item'][1])
1000
1001 def visit_option_group(self, node) -> None:
1002 # as one option could have several forms it is a group
1003 # options without parameter bold only, .B, -v
1004 # options with parameter bold italic, .BI, -f file
1005 #
1006 # we do not know if .B or .BI, blind guess:
1007 self.context.append('.B ') # Add blank for sphinx (docutils/bugs/380)
1008 self.context.append(len(self.body)) # to be able to insert later
1009 self.context.append(0) # option counter
1010
1011 def depart_option_group(self, node) -> None:
1012 self.context.pop() # the counter
1013 start_position = self.context.pop()
1014 text = self.body[start_position:]
1015 del self.body[start_position:]
1016 self.body.append('%s%s\n' % (self.context.pop(), ''.join(text)))
1017
1018 def visit_option(self, node) -> None:
1019 # each form of the option will be presented separately
1020 if self.context[-1] > 0:
1021 if self.context[-3] == '.BI':
1022 self.body.append('\\fR,\\fB ')
1023 else:
1024 self.body.append('\\fP,\\fB ')
1025 if self.context[-3] == '.BI':
1026 self.body.append('\\')
1027 self.body.append(' ')
1028
1029 def depart_option(self, node) -> None:
1030 self.context[-1] += 1
1031
1032 def visit_option_string(self, node) -> None:
1033 # do not know if .B or .BI
1034 pass
1035
1036 def depart_option_string(self, node) -> None:
1037 pass
1038
1039 def visit_option_argument(self, node) -> None:
1040 self.context[-3] = '.BI' # bold/italic alternate
1041 if node['delimiter'] != ' ':
1042 self.body.append('\\fB%s ' % node['delimiter'])
1043 elif self.body[len(self.body)-1].endswith('='):
1044 # a blank only means no blank in output, just changing font
1045 self.body.append(' ')
1046 else:
1047 # blank backslash blank, switch font then a blank
1048 self.body.append(' \\ ')
1049
1050 def depart_option_argument(self, node) -> None:
1051 pass
1052
1053 def visit_organization(self, node) -> None:
1054 self.visit_docinfo_item(node, 'organization')
1055
1056 def depart_organization(self, node) -> None:
1057 pass
1058
1059 def first_child(self, node) -> int:
1060 first = isinstance(node.parent[0], nodes.label) # skip label
1061 for child in node.parent.children[first:]:
1062 if isinstance(child, nodes.Invisible):
1063 continue
1064 if child is node:
1065 return 1
1066 break
1067 return 0
1068
1069 def visit_paragraph(self, node) -> None:
1070 # ``.PP`` : Start standard indented paragraph.
1071 # ``.LP`` : Start block paragraph, all except the first.
1072 # ``.P [type]`` : Start paragraph type.
1073 # NOTE do not use paragraph starts because they reset indentation.
1074 # ``.sp`` is only vertical space
1075 self.ensure_eol()
1076 if not self.first_child(node):
1077 self.body.append('.sp\n')
1078 # set in literal to escape dots after a new-line-character
1079 self._in_literal = True
1080
1081 def depart_paragraph(self, node) -> None:
1082 self._in_literal = False
1083 self.body.append('\n')
1084
1085 def visit_problematic(self, node) -> None:
1086 self.body.append(self.defs['problematic'][0])
1087
1088 def depart_problematic(self, node) -> None:
1089 self.body.append(self.defs['problematic'][1])
1090
1091 def visit_raw(self, node):
1092 if 'manpage' in node.get('format', '').split():
1093 self.body.append(node.astext() + "\n")
1094 # Keep non-manpage raw text out of output:
1095 raise nodes.SkipNode
1096
1097 # references ----
1098
1099 def _visit_reference_no_macro(self, node) -> None:
1100 """E.g. link or email address."""
1101 # For .UR/.UE and .MT/.ME macros groff might use OSC8 escape sequences
1102 # which are not supported everywhere yet
1103 # therefore make the markup ourself
1104
1105 # precede with backslash-% to disable standard hyphenation
1106 if 'refuri' in node:
1107 # check if content is the uri and only output reference.
1108 # MAYBE if only content is ouput hyphens "-" get a backslash.
1109 if (node['refuri'] == node.astext()
1110 or node['refuri'] == "mailto:"+node.astext()):
1111 # without mailto:
1112 self.body.append(r"\%%<%s>"
1113 % insert_URI_breakpoints(node.astext()))
1114 raise nodes.SkipNode
1115 # TODO markup the target
1116 # elif 'refid' in node:
1117 # internal cross references are ignored (just print the text)
1118
1119 def _depart_reference_no_macro(self, node) -> None:
1120 if 'refuri' in node:
1121 self.body.append(r" \%%<%s>"
1122 % insert_URI_breakpoints(node['refuri']))
1123 # elif 'refid' in node:
1124
1125 def _visit_reference_with_macro(self, node) -> None:
1126 # use UR/UE or MT/ME
1127 if 'refuri' in node:
1128 self.ensure_c_eol() # c_eol avoids space before the refuri
1129 _uri = node['refuri']
1130 if _uri.startswith('mailto:'):
1131 _uri = _uri[7:] # remove "mailto:"
1132 # groff macro in an.tmac adds "mailto:"
1133 # mandoc does not.
1134 self.body.append(".MT ")
1135 self.context.append('.ME\n')
1136 else:
1137 self.body.append(".UR ")
1138 self.context.append('.UE\n')
1139 self.body.append("\\%%%s\n" % insert_URI_breakpoints(_uri))
1140 if (node['refuri'] == node.astext()
1141 or node['refuri'] == "mailto:"+node.astext()):
1142 self.body.append(self.context.pop())
1143 # if content is uri skip content
1144 raise nodes.SkipNode
1145 else:
1146 # TODO markup the target
1147 self.context.append('')
1148
1149 def _depart_reference_with_macro(self, node) -> None:
1150 macro_end = self.context.pop()
1151 if macro_end:
1152 self.ensure_eol()
1153 self.body.append(macro_end)
1154 # problems to handle in astext looking ahead.
1155 # * if the ref is at end of line
1156 # we get a blank line following which we dont want.
1157 # * if ref is followed by )., there will be a space separating
1158 # ----
1159
1160 def visit_revision(self, node) -> None:
1161 self.visit_docinfo_item(node, 'revision')
1162
1163 depart_revision = depart_docinfo_item
1164
1165 def visit_row(self, node) -> None:
1166 self._active_table.new_row()
1167
1168 def depart_row(self, node) -> None:
1169 pass
1170
1171 def visit_section(self, node) -> None:
1172 self.section_level += 1
1173
1174 def depart_section(self, node) -> None:
1175 self.section_level -= 1
1176
1177 def visit_status(self, node) -> None:
1178 self.visit_docinfo_item(node, 'status')
1179
1180 depart_status = depart_docinfo_item
1181
1182 def visit_strong(self, node) -> None:
1183 self.body.append(self.defs['strong'][0])
1184
1185 def depart_strong(self, node) -> None:
1186 self.body.append(self.defs['strong'][1])
1187
1188 def visit_substitution_definition(self, node):
1189 """Internal only."""
1190 raise nodes.SkipNode
1191
1192 def visit_substitution_reference(self, node) -> None:
1193 self.document.reporter.warning(
1194 '"substitution_reference" not supported', base_node=node)
1195
1196 def visit_subtitle(self, node) -> None:
1197 if isinstance(node.parent, nodes.sidebar):
1198 self.body.append(self.defs['strong'][0])
1199 elif isinstance(node.parent, nodes.document):
1200 self.visit_docinfo_item(node, 'subtitle')
1201 elif isinstance(node.parent, nodes.section):
1202 self.body.append(self.defs['strong'][0])
1203
1204 def depart_subtitle(self, node) -> None:
1205 # document subtitle calls SkipNode
1206 self.body.append(self.defs['strong'][1]+'\n.PP\n')
1207
1208 def visit_system_message(self, node) -> None:
1209 # TODO add report_level
1210 # if node['level'] < self.document.reporter['writer'].report_level:
1211 # Level is too low to display:
1212 # raise nodes.SkipNode
1213 attr = {}
1214 if node.hasattr('id'):
1215 attr['name'] = node['id']
1216 if node.hasattr('line'):
1217 line = ', line %s' % node['line']
1218 else:
1219 line = ''
1220 self.body.append('.IP "System Message: %s/%s (%s:%s)"\n'
1221 % (node['type'], node['level'], node['source'], line))
1222
1223 def depart_system_message(self, node) -> None:
1224 pass
1225
1226 def visit_table(self, node) -> None:
1227 self._active_table = Table()
1228 if not self._has_a_table:
1229 self._has_a_table = True
1230 # the comment to hint that preprocessor tbl should be called
1231 self.head.insert(0, "'\\\" t\n") # ``'\" t`` + newline
1232
1233 def depart_table(self, node) -> None:
1234 self.ensure_eol()
1235 self.body.extend(self._active_table.as_list())
1236 self._active_table = None
1237
1238 def visit_target(self, node):
1239 # <target> elements are anchors of internal hyperlinks (not used
1240 # in man-pages). Just print content (inline targets may contain text):
1241 pass
1242
1243 def depart_target(self, node):
1244 pass
1245
1246 def visit_tbody(self, node) -> None:
1247 pass
1248
1249 def depart_tbody(self, node) -> None:
1250 pass
1251
1252 def visit_term(self, node) -> None:
1253 self.body.append('\n.B ')
1254
1255 def depart_term(self, node) -> None:
1256 _next = node.next_node(None, descend=False, siblings=True)
1257 # Nest (optional) classifier(s) in the <term> element
1258 if isinstance(_next, nodes.classifier):
1259 self.body.append(' ')
1260 return # skip (depart_classifier() calls this function again)
1261 if isinstance(_next, nodes.term):
1262 # .TQ Additional paragraph tag
1263 self.body.append('\n.TQ')
1264 else:
1265 self.body.append('\n')
1266
1267 def visit_tgroup(self, node) -> None:
1268 pass
1269
1270 def depart_tgroup(self, node) -> None:
1271 pass
1272
1273 def visit_thead(self, node) -> None:
1274 # MAYBE double line '='
1275 pass
1276
1277 def depart_thead(self, node) -> None:
1278 # MAYBE double line '='
1279 pass
1280
1281 def visit_tip(self, node) -> None:
1282 self.visit_admonition(node, 'tip')
1283
1284 depart_tip = depart_admonition
1285
1286 def visit_title(self, node):
1287 if isinstance(node.parent, nodes.topic):
1288 self.body.append(self.defs['topic-title'][0])
1289 elif isinstance(node.parent, nodes.sidebar):
1290 self.body.append(self.defs['sidebar-title'][0])
1291 elif isinstance(node.parent, nodes.admonition):
1292 self.body.append('.IP "')
1293 elif self.section_level == 0:
1294 self._docinfo['title'] = node.astext()
1295 raise nodes.SkipNode
1296 elif self.section_level == 1:
1297 self.body.append('.SH %s\n'%self.deunicode(node.astext()))
1298 raise nodes.SkipNode
1299 else:
1300 self.body.append('.SS ')
1301
1302 def depart_title(self, node) -> None:
1303 if isinstance(node.parent, nodes.admonition):
1304 self.body.append('"')
1305 self.body.append('\n')
1306
1307 def visit_title_reference(self, node) -> None:
1308 """inline citation reference"""
1309 self.body.append(self.defs['title_reference'][0])
1310
1311 def depart_title_reference(self, node) -> None:
1312 self.body.append(self.defs['title_reference'][1])
1313
1314 def visit_topic(self, node) -> None:
1315 pass
1316
1317 def depart_topic(self, node) -> None:
1318 pass
1319
1320 def visit_sidebar(self, node) -> None:
1321 pass
1322
1323 def depart_sidebar(self, node) -> None:
1324 pass
1325
1326 def visit_rubric(self, node) -> None:
1327 pass
1328
1329 def depart_rubric(self, node) -> None:
1330 self.body.append('\n')
1331
1332 def visit_transition(self, node) -> None:
1333 # .PP Begin a new paragraph and reset prevailing indent.
1334 # .sp N leaves N lines of blank space.
1335 # .ce centers the next line
1336 self.body.append('\n.sp\n.ce\n----\n')
1337
1338 def depart_transition(self, node) -> None:
1339 self.body.append('\n.ce 0\n.sp\n')
1340
1341 def visit_version(self, node) -> None:
1342 self.visit_docinfo_item(node, 'version')
1343
1344 def visit_warning(self, node) -> None:
1345 self.visit_admonition(node, 'warning')
1346
1347 depart_warning = depart_admonition
1348
1349 def unimplemented_visit(self, node):
1350 raise NotImplementedError('visiting unimplemented node type: %s'
1351 % node.__class__.__name__)
1352
1353 # vim: set fileencoding=utf-8 et ts=4 ai :