Comment on control character dot or apostrophe
[docutils.git] / docutils / docutils / writers / manpage.py
blobce51499bfe6cb56c9044c3c4bd719dafb5986b87
1 # $Id$
2 # Author: Engelbert Gruber <grubert@users.sourceforge.net>
3 # Copyright: This module is put into the public domain.
5 """
6 Simple man page writer for reStructuredText.
8 Man pages (short for "manual pages") contain system documentation on unix-like
9 systems. The pages are grouped in numbered sections:
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
20 Man pages are written *troff*, a text file formatting system.
22 See http://www.tldp.org/HOWTO/Man-Page for a start.
24 Man pages have no subsection only parts.
25 Standard parts
27 NAME ,
28 SYNOPSIS ,
29 DESCRIPTION ,
30 OPTIONS ,
31 FILES ,
32 SEE ALSO ,
33 BUGS ,
35 and
37 AUTHOR .
39 A unix-like system keeps an index of the DESCRIPTIONs, which is accessible
40 by the command whatis or apropos.
42 """
44 __docformat__ = 'reStructuredText'
46 import re
48 from docutils import nodes, writers, languages
49 try:
50 import roman
51 except ImportError:
52 import docutils.utils.roman as roman
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
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
65 .de1 rstReportMargin
66 \\$1 \\n[an-margin]
67 level \\n[rst2man-indent-level]
68 level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
70 \\n[rst2man-indent0]
71 \\n[rst2man-indent1]
72 \\n[rst2man-indent2]
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:
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
89 """)
92 class Writer(writers.Writer):
94 supported = ('manpage',)
95 """Formats this writer supports."""
97 output = None
98 """Final translated form of `document`."""
100 def __init__(self):
101 writers.Writer.__init__(self)
102 self.translator_class = Translator
104 def translate(self):
105 visitor = self.translator_class(self.document)
106 self.document.walkabout(visitor)
107 self.output = visitor.astext()
110 class Table:
111 def __init__(self):
112 self._rows = []
113 self._options = ['center']
114 self._tab_char = '\t'
115 self._coldefs = []
117 def new_row(self):
118 self._rows.append([])
120 def append_separator(self, separator):
121 """Append the separator for table head."""
122 self._rows.append([separator])
124 def append_cell(self, cell_lines):
125 """cell_lines is an array of lines"""
126 start = 0
127 if len(cell_lines) > 0 and cell_lines[0] == '.sp\n':
128 start = 1
129 self._rows[-1].append(cell_lines[start:])
130 if len(self._coldefs) < len(self._rows[-1]):
131 self._coldefs.append('l')
133 def _minimize_cell(self, cell_lines):
134 """Remove leading and trailing blank and ``.sp`` lines"""
135 while cell_lines and cell_lines[0] in ('\n', '.sp\n'):
136 del cell_lines[0]
137 while cell_lines and cell_lines[-1] in ('\n', '.sp\n'):
138 del cell_lines[-1]
140 def as_list(self):
141 text = ['.TS\n']
142 text.append(' '.join(self._options) + ';\n')
143 text.append('|%s|.\n' % ('|'.join(self._coldefs)))
144 for row in self._rows:
145 # row = array of cells. cell = array of lines.
146 text.append('_\n') # line above
147 text.append('T{\n')
148 for i in range(len(row)):
149 cell = row[i]
150 self._minimize_cell(cell)
151 text.extend(cell)
152 if not text[-1].endswith('\n'):
153 text[-1] += '\n'
154 if i < len(row)-1:
155 text.append('T}'+self._tab_char+'T{\n')
156 else:
157 text.append('T}\n')
158 text.append('_\n')
159 text.append('.TE\n')
160 return text
163 class Translator(nodes.NodeVisitor):
164 """"""
166 words_and_spaces = re.compile(r'\S+| +|\n')
167 possibly_a_roff_command = re.compile(r'\.\w')
168 document_start = """Man page generated from reStructuredText."""
170 def __init__(self, document):
171 nodes.NodeVisitor.__init__(self, document)
172 self.settings = settings = document.settings
173 lcode = settings.language_code
174 self.language = languages.get_language(lcode, document.reporter)
175 self.head = []
176 self.body = []
177 self.foot = []
178 self.section_level = 0
179 self.context = []
180 self.topic_class = ''
181 self.colspecs = []
182 self.compact_p = 1
183 self.compact_simple = None
184 # the list style "*" bullet or "#" numbered
185 self._list_char = []
186 # writing the header .TH and .SH NAME is postboned after
187 # docinfo.
188 self._docinfo = {
189 "title": "", "title_upper": "",
190 "subtitle": "",
191 "manual_section": "", "manual_group": "",
192 "author": [],
193 "date": "",
194 "copyright": "",
195 "version": "",
197 self._docinfo_keys = [] # a list to keep the sequence as in source.
198 self._docinfo_names = {} # to get name from text not normalized.
199 self._in_docinfo = None
200 self._field_name = None
201 self._active_table = None
202 self._in_literal = False
203 self.header_written = 0
204 self._line_block = 0
205 self.authors = []
206 self.section_level = 0
207 self._indent = [0]
208 # central definition of simple processing rules
209 # what to output on : visit, depart
210 # Do not use paragraph requests ``.PP`` because these set indentation.
211 # use ``.sp``. Remove superfluous ``.sp`` in ``astext``.
213 # Fonts are put on a stack, the top one is used.
214 # ``.ft P`` or ``\\fP`` pop from stack.
215 # But ``.BI`` seams to fill stack with BIBIBIBIB...
216 # ``B`` bold, ``I`` italic, ``R`` roman should be available.
218 # Requests start wit a dot ``.`` or the no-break control character,
219 # a neutral apostrophe ``'``, suppresses the break implied by some requests.
220 self.defs = {
221 'indent': ('.INDENT %.1f\n', '.UNINDENT\n'),
222 'definition_list_item': ('.TP', ''), # par. with hanging tag
223 'field_name': ('.TP\n.B ', '\n'),
224 'literal': ('\\fB', '\\fP'),
225 'literal_block': ('.sp\n.EX\n', '\n.EE\n'),
227 'option_list_item': ('.TP\n', ''),
229 'reference': (r'\fI\%', r'\fP'),
230 'emphasis': ('\\fI', '\\fP'),
231 'strong': ('\\fB', '\\fP'),
232 'term': ('\n.B ', '\n'),
233 'title_reference': ('\\fI', '\\fP'),
235 'topic-title': ('.SS ',),
236 'sidebar-title': ('.SS ',),
238 'problematic': ('\n.nf\n', '\n.fi\n'),
240 # NOTE do not specify the newline before a dot-command, but ensure
241 # it is there.
243 def comment_begin(self, text):
244 """Return commented version of the passed text WITHOUT end of
245 line/comment."""
246 prefix = '.\\" '
247 out_text = ''.join([(prefix + in_line + '\n')
248 for in_line in text.split('\n')])
249 return out_text
251 def comment(self, text):
252 """Return commented version of the passed text."""
253 return self.comment_begin(text)+'.\n'
255 def ensure_eol(self):
256 """Ensure the last line in body is terminated by new line."""
257 if len(self.body) > 0 and self.body[-1][-1] != '\n':
258 self.body.append('\n')
260 def astext(self):
261 """Return the final formatted document as a string."""
262 if not self.header_written:
263 # ensure we get a ".TH" as viewers require it.
264 self.append_header()
265 # filter body
266 for i in range(len(self.body)-1, 0, -1):
267 # remove superfluous vertical gaps.
268 if self.body[i] == '.sp\n':
269 if self.body[i - 1][:4] in ('.BI ', '.IP '):
270 self.body[i] = '.\n'
271 elif (self.body[i - 1][:3] == '.B '
272 and self.body[i - 2][:4] == '.TP\n'):
273 self.body[i] = '.\n'
274 elif (self.body[i - 1] == '\n'
275 and not self.possibly_a_roff_command.match(
276 self.body[i - 2])
277 and (self.body[i - 3][:7] == '.TP\n.B '
278 or self.body[i - 3][:4] == '\n.B ')
280 self.body[i] = '.\n'
281 return ''.join(self.head + self.body + self.foot)
283 def deunicode(self, text):
284 text = text.replace('\xa0', '\\ ')
285 text = text.replace('\u2020', '\\(dg')
286 return text
288 def visit_Text(self, node):
289 text = node.astext()
290 text = text.replace('\\', '\\e')
291 replace_pairs = [
292 ('-', '\\-'),
293 ('\'', '\\(aq'),
294 ('´', "\\'"),
295 ('`', '\\(ga'),
296 ('"', '\\(dq'), # double quotes are a problem on macro lines
298 for (in_char, out_markup) in replace_pairs:
299 text = text.replace(in_char, out_markup)
300 # unicode
301 text = self.deunicode(text)
302 # prevent interpretation of "." at line start
303 if text.startswith('.'):
304 text = '\\&' + text
305 if self._in_literal:
306 text = text.replace('\n.', '\n\\&.')
307 self.body.append(text)
309 def depart_Text(self, node):
310 pass
312 def list_start(self, node):
313 class EnumChar:
314 enum_style = {
315 'bullet': '\\(bu',
316 'emdash': '\\(em',
319 def __init__(self, style):
320 self._style = style
321 if 'start' in node:
322 self._cnt = node['start'] - 1
323 else:
324 self._cnt = 0
325 self._indent = 2
326 if style == 'arabic':
327 # indentation depends on number of children
328 # and start value.
329 self._indent = len(str(len(node.children)))
330 self._indent += len(str(self._cnt)) + 1
331 elif style == 'loweralpha':
332 self._cnt += ord('a') - 1
333 self._indent = 3
334 elif style == 'upperalpha':
335 self._cnt += ord('A') - 1
336 self._indent = 3
337 elif style.endswith('roman'):
338 self._indent = 5
340 def __next__(self):
341 if self._style == 'bullet':
342 return self.enum_style[self._style]
343 elif self._style == 'emdash':
344 return self.enum_style[self._style]
345 self._cnt += 1
346 # TODO add prefix postfix
347 if self._style == 'arabic':
348 return "%d." % self._cnt
349 elif self._style in ('loweralpha', 'upperalpha'):
350 return "%c." % self._cnt
351 elif self._style.endswith('roman'):
352 res = roman.toRoman(self._cnt) + '.'
353 if self._style.startswith('upper'):
354 return res.upper()
355 return res.lower()
356 else:
357 return "%d." % self._cnt
359 def get_width(self):
360 return self._indent
362 def __repr__(self):
363 return 'enum_style-%s' % list(self._style)
365 if 'enumtype' in node:
366 self._list_char.append(EnumChar(node['enumtype']))
367 else:
368 self._list_char.append(EnumChar('bullet'))
369 if len(self._list_char) > 1:
370 # indent nested lists
371 self.indent(self._list_char[-2].get_width())
372 else:
373 self.indent(self._list_char[-1].get_width())
375 def list_end(self):
376 self.dedent()
377 self._list_char.pop()
379 def header(self):
380 th = (".TH \"%(title_upper)s\" %(manual_section)s"
381 " \"%(date)s\" \"%(version)s\"") % self._docinfo
382 if self._docinfo["manual_group"]:
383 th += " \"%(manual_group)s\"" % self._docinfo
384 th += "\n"
385 sh_tmpl = (".SH NAME\n"
386 "%(title)s \\- %(subtitle)s\n")
387 return th + sh_tmpl % self._docinfo
389 def append_header(self):
390 """append header with .TH and .SH NAME"""
391 # NOTE before everything
392 # .TH title_upper section date source manual
393 # BUT macros before .TH for whatis database generators.
394 if self.header_written:
395 return
396 self.head.append(MACRO_DEF)
397 self.head.append(self.header())
398 self.header_written = 1
400 def visit_address(self, node):
401 self.visit_docinfo_item(node, 'address')
403 def depart_address(self, node):
404 pass
406 def visit_admonition(self, node, name=None):
408 # Make admonitions a simple block quote
409 # with a strong heading
411 # Using .IP/.RE doesn't preserve indentation
412 # when admonitions contain bullets, literal,
413 # and/or block quotes.
415 if name:
416 # .. admonition:: has no name
417 self.body.append('.sp\n')
418 name = '%s%s:%s\n' % (
419 self.defs['strong'][0],
420 self.language.labels.get(name, name).upper(),
421 self.defs['strong'][1],
423 self.body.append(name)
424 self.visit_block_quote(node)
426 def depart_admonition(self, node):
427 self.depart_block_quote(node)
429 def visit_attention(self, node):
430 self.visit_admonition(node, 'attention')
432 depart_attention = depart_admonition
434 def visit_docinfo_item(self, node, name):
435 if name == 'author':
436 self._docinfo[name].append(node.astext())
437 else:
438 self._docinfo[name] = node.astext()
439 self._docinfo_keys.append(name)
440 raise nodes.SkipNode
442 def depart_docinfo_item(self, node):
443 pass
445 def visit_author(self, node):
446 self.visit_docinfo_item(node, 'author')
448 depart_author = depart_docinfo_item
450 def visit_authors(self, node):
451 # _author is called anyway.
452 pass
454 def depart_authors(self, node):
455 pass
457 def visit_block_quote(self, node):
458 # BUG/HACK: indent always uses the _last_ indentation,
459 # thus we need two of them.
460 self.indent(BLOCKQOUTE_INDENT)
461 self.indent(0)
463 def depart_block_quote(self, node):
464 self.dedent()
465 self.dedent()
467 def visit_bullet_list(self, node):
468 self.list_start(node)
470 def depart_bullet_list(self, node):
471 self.list_end()
473 def visit_caption(self, node):
474 pass
476 def depart_caption(self, node):
477 pass
479 def visit_caution(self, node):
480 self.visit_admonition(node, 'caution')
482 depart_caution = depart_admonition
484 def visit_citation(self, node):
485 num = node.astext().split(None, 1)[0]
486 num = num.strip()
487 self.body.append('.IP [%s] 5\n' % num)
489 def depart_citation(self, node):
490 pass
492 def visit_citation_reference(self, node):
493 self.body.append('['+node.astext()+']')
494 raise nodes.SkipNode
496 def visit_classifier(self, node):
497 pass
499 def depart_classifier(self, node):
500 pass
502 def visit_colspec(self, node):
503 self.colspecs.append(node)
505 def depart_colspec(self, node):
506 pass
508 def write_colspecs(self):
509 self.body.append("%s.\n" % ('L '*len(self.colspecs)))
511 def visit_comment(self, node,
512 sub=re.compile('-(?=-)').sub):
513 self.body.append(self.comment(node.astext()))
514 raise nodes.SkipNode
516 def visit_contact(self, node):
517 self.visit_docinfo_item(node, 'contact')
519 depart_contact = depart_docinfo_item
521 def visit_container(self, node):
522 pass
524 def depart_container(self, node):
525 pass
527 def visit_compound(self, node):
528 pass
530 def depart_compound(self, node):
531 pass
533 def visit_copyright(self, node):
534 self.visit_docinfo_item(node, 'copyright')
536 def visit_danger(self, node):
537 self.visit_admonition(node, 'danger')
539 depart_danger = depart_admonition
541 def visit_date(self, node):
542 self.visit_docinfo_item(node, 'date')
544 def visit_decoration(self, node):
545 pass
547 def depart_decoration(self, node):
548 pass
550 def visit_definition(self, node):
551 pass
553 def depart_definition(self, node):
554 pass
556 def visit_definition_list(self, node):
557 self.indent(DEFINITION_LIST_INDENT)
559 def depart_definition_list(self, node):
560 self.dedent()
562 def visit_definition_list_item(self, node):
563 self.body.append(self.defs['definition_list_item'][0])
565 def depart_definition_list_item(self, node):
566 self.body.append(self.defs['definition_list_item'][1])
568 def visit_description(self, node):
569 pass
571 def depart_description(self, node):
572 pass
574 def visit_docinfo(self, node):
575 self._in_docinfo = 1
577 def depart_docinfo(self, node):
578 self._in_docinfo = None
579 # NOTE nothing should be written before this
580 self.append_header()
582 def visit_doctest_block(self, node):
583 self.body.append(self.defs['literal_block'][0])
584 self._in_literal = True
586 def depart_doctest_block(self, node):
587 self._in_literal = False
588 self.body.append(self.defs['literal_block'][1])
590 def visit_document(self, node):
591 # no blank line between comment and header.
592 self.head.append(self.comment(self.document_start).rstrip()+'\n')
593 # writing header is postponed
594 self.header_written = 0
596 def depart_document(self, node):
597 if self._docinfo['author']:
598 self.body.append('.SH AUTHOR\n%s\n'
599 % ', '.join(self._docinfo['author']))
600 skip = ('author', 'copyright', 'date',
601 'manual_group', 'manual_section',
602 'subtitle',
603 'title', 'title_upper', 'version')
604 for name in self._docinfo_keys:
605 if name == 'address':
606 self.body.append("\n%s:\n%s%s.nf\n%s\n.fi\n%s%s" % (
607 self.language.labels.get(name, name),
608 self.defs['indent'][0] % 0,
609 self.defs['indent'][0] % BLOCKQOUTE_INDENT,
610 self._docinfo[name],
611 self.defs['indent'][1],
612 self.defs['indent'][1]))
613 elif name not in skip:
614 if name in self._docinfo_names:
615 label = self._docinfo_names[name]
616 else:
617 label = self.language.labels.get(name, name)
618 self.body.append("\n%s: %s\n" % (label, self._docinfo[name]))
619 if self._docinfo['copyright']:
620 self.body.append('.SH COPYRIGHT\n%s\n'
621 % self._docinfo['copyright'])
622 self.body.append(self.comment('Generated by docutils manpage writer.'))
624 def visit_emphasis(self, node):
625 self.body.append(self.defs['emphasis'][0])
627 def depart_emphasis(self, node):
628 self.body.append(self.defs['emphasis'][1])
630 def visit_entry(self, node):
631 # a cell in a table row
632 if 'morerows' in node:
633 self.document.reporter.warning(
634 '"table row spanning" not supported', base_node=node)
635 if 'morecols' in node:
636 self.document.reporter.warning(
637 '"table cell spanning" not supported', base_node=node)
638 self.context.append(len(self.body))
640 def depart_entry(self, node):
641 start = self.context.pop()
642 self._active_table.append_cell(self.body[start:])
643 del self.body[start:]
645 def visit_enumerated_list(self, node):
646 self.list_start(node)
648 def depart_enumerated_list(self, node):
649 self.list_end()
651 def visit_error(self, node):
652 self.visit_admonition(node, 'error')
654 depart_error = depart_admonition
656 def visit_field(self, node):
657 pass
659 def depart_field(self, node):
660 pass
662 def visit_field_body(self, node):
663 if self._in_docinfo:
664 name_normalized = self._field_name.lower().replace(" ", "_")
665 self._docinfo_names[name_normalized] = self._field_name
666 self.visit_docinfo_item(node, name_normalized)
667 raise nodes.SkipNode
669 def depart_field_body(self, node):
670 pass
672 def visit_field_list(self, node):
673 self.indent(FIELD_LIST_INDENT)
675 def depart_field_list(self, node):
676 self.dedent()
678 def visit_field_name(self, node):
679 if self._in_docinfo:
680 self._field_name = node.astext()
681 raise nodes.SkipNode
682 else:
683 self.body.append(self.defs['field_name'][0])
685 def depart_field_name(self, node):
686 self.body.append(self.defs['field_name'][1])
688 def visit_figure(self, node):
689 self.indent(2.5)
690 self.indent(0)
692 def depart_figure(self, node):
693 self.dedent()
694 self.dedent()
696 def visit_footer(self, node):
697 self.document.reporter.warning('"footer" not supported',
698 base_node=node)
700 def depart_footer(self, node):
701 pass
703 def visit_footnote(self, node):
704 num, text = node.astext().split(None, 1)
705 num = num.strip()
706 self.body.append('.IP [%s] 5\n' % self.deunicode(num))
708 def depart_footnote(self, node):
709 pass
711 def footnote_backrefs(self, node):
712 self.document.reporter.warning('"footnote_backrefs" not supported',
713 base_node=node)
715 def visit_footnote_reference(self, node):
716 self.body.append('['+self.deunicode(node.astext())+']')
717 raise nodes.SkipNode
719 def depart_footnote_reference(self, node):
720 pass
722 def visit_generated(self, node):
723 pass
725 def depart_generated(self, node):
726 pass
728 def visit_header(self, node):
729 raise NotImplementedError(node.astext())
731 def depart_header(self, node):
732 pass
734 def visit_hint(self, node):
735 self.visit_admonition(node, 'hint')
737 depart_hint = depart_admonition
739 def visit_subscript(self, node):
740 self.body.append('\\s-2\\d')
742 def depart_subscript(self, node):
743 self.body.append('\\u\\s0')
745 def visit_superscript(self, node):
746 self.body.append('\\s-2\\u')
748 def depart_superscript(self, node):
749 self.body.append('\\d\\s0')
751 def visit_attribution(self, node):
752 self.body.append('\\(em ')
754 def depart_attribution(self, node):
755 self.body.append('\n')
757 def visit_image(self, node):
758 self.document.reporter.warning('"image" not supported',
759 base_node=node)
760 text = []
761 if 'alt' in node.attributes:
762 text.append(node.attributes['alt'])
763 if 'uri' in node.attributes:
764 text.append(node.attributes['uri'])
765 self.body.append('[image: %s]\n' % ('/'.join(text)))
766 raise nodes.SkipNode
768 def visit_important(self, node):
769 self.visit_admonition(node, 'important')
771 depart_important = depart_admonition
773 def visit_inline(self, node):
774 pass
776 def depart_inline(self, node):
777 pass
779 def visit_label(self, node):
780 # footnote and citation
781 if (isinstance(node.parent, nodes.footnote)
782 or isinstance(node.parent, nodes.citation)):
783 raise nodes.SkipNode
784 self.document.reporter.warning('"unsupported "label"',
785 base_node=node)
786 self.body.append('[')
788 def depart_label(self, node):
789 self.body.append(']\n')
791 def visit_legend(self, node):
792 pass
794 def depart_legend(self, node):
795 pass
797 # WHAT should we use .INDENT, .UNINDENT ?
798 def visit_line_block(self, node):
799 self._line_block += 1
800 if self._line_block == 1:
801 # TODO: separate inline blocks from previous paragraphs
802 # see http://hg.intevation.org/mercurial/crew/rev/9c142ed9c405
803 # self.body.append('.sp\n')
804 # but it does not work for me.
805 self.body.append('.nf\n')
806 else:
807 self.body.append('.in +2\n')
809 def depart_line_block(self, node):
810 self._line_block -= 1
811 if self._line_block == 0:
812 self.body.append('.fi\n')
813 self.body.append('.sp\n')
814 else:
815 self.body.append('.in -2\n')
817 def visit_line(self, node):
818 pass
820 def depart_line(self, node):
821 self.body.append('\n')
823 def visit_list_item(self, node):
824 # man 7 man argues to use ".IP" instead of ".TP"
825 self.body.append('.IP %s %d\n' % (
826 next(self._list_char[-1]),
827 self._list_char[-1].get_width(),))
829 def depart_list_item(self, node):
830 pass
832 def visit_literal(self, node):
833 self.body.append(self.defs['literal'][0])
835 def depart_literal(self, node):
836 self.body.append(self.defs['literal'][1])
838 def visit_literal_block(self, node):
839 # BUG/HACK: indent always uses the _last_ indentation,
840 # thus we need two of them.
841 self.indent(LITERAL_BLOCK_INDENT)
842 self.indent(0)
843 self.body.append(self.defs['literal_block'][0])
844 self._in_literal = True
846 def depart_literal_block(self, node):
847 self._in_literal = False
848 self.body.append(self.defs['literal_block'][1])
849 self.dedent()
850 self.dedent()
852 def visit_math(self, node):
853 self.document.reporter.warning('"math" role not supported',
854 base_node=node)
855 self.visit_literal(node)
857 def depart_math(self, node):
858 self.depart_literal(node)
860 def visit_math_block(self, node):
861 self.document.reporter.warning('"math" directive not supported',
862 base_node=node)
863 self.visit_literal_block(node)
865 def depart_math_block(self, node):
866 self.depart_literal_block(node)
868 # <meta> shall become an optional standard node:
869 # def visit_meta(self, node):
870 # raise NotImplementedError(node.astext())
872 # def depart_meta(self, node):
873 # pass
875 def visit_note(self, node):
876 self.visit_admonition(node, 'note')
878 depart_note = depart_admonition
880 def indent(self, by=0.5):
881 # if we are in a section ".SH" there already is a .RS
882 step = self._indent[-1]
883 self._indent.append(by)
884 self.body.append(self.defs['indent'][0] % step)
886 def dedent(self):
887 self._indent.pop()
888 self.body.append(self.defs['indent'][1])
890 def visit_option_list(self, node):
891 self.indent(OPTION_LIST_INDENT)
893 def depart_option_list(self, node):
894 self.dedent()
896 def visit_option_list_item(self, node):
897 # one item of the list
898 self.body.append(self.defs['option_list_item'][0])
900 def depart_option_list_item(self, node):
901 self.body.append(self.defs['option_list_item'][1])
903 def visit_option_group(self, node):
904 # as one option could have several forms it is a group
905 # options without parameter bold only, .B, -v
906 # options with parameter bold italic, .BI, -f file
908 # we do not know if .B or .BI, blind guess:
909 self.context.append('.B ') # Add blank for sphinx (docutils/bugs/380)
910 self.context.append(len(self.body)) # to be able to insert later
911 self.context.append(0) # option counter
913 def depart_option_group(self, node):
914 self.context.pop() # the counter
915 start_position = self.context.pop()
916 text = self.body[start_position:]
917 del self.body[start_position:]
918 self.body.append('%s%s\n' % (self.context.pop(), ''.join(text)))
920 def visit_option(self, node):
921 # each form of the option will be presented separately
922 if self.context[-1] > 0:
923 if self.context[-3] == '.BI':
924 self.body.append('\\fR,\\fB ')
925 else:
926 self.body.append('\\fP,\\fB ')
927 if self.context[-3] == '.BI':
928 self.body.append('\\')
929 self.body.append(' ')
931 def depart_option(self, node):
932 self.context[-1] += 1
934 def visit_option_string(self, node):
935 # do not know if .B or .BI
936 pass
938 def depart_option_string(self, node):
939 pass
941 def visit_option_argument(self, node):
942 self.context[-3] = '.BI' # bold/italic alternate
943 if node['delimiter'] != ' ':
944 self.body.append('\\fB%s ' % node['delimiter'])
945 elif self.body[len(self.body)-1].endswith('='):
946 # a blank only means no blank in output, just changing font
947 self.body.append(' ')
948 else:
949 # blank backslash blank, switch font then a blank
950 self.body.append(' \\ ')
952 def depart_option_argument(self, node):
953 pass
955 def visit_organization(self, node):
956 self.visit_docinfo_item(node, 'organization')
958 def depart_organization(self, node):
959 pass
961 def first_child(self, node):
962 first = isinstance(node.parent[0], nodes.label) # skip label
963 for child in node.parent.children[first:]:
964 if isinstance(child, nodes.Invisible):
965 continue
966 if child is node:
967 return 1
968 break
969 return 0
971 def visit_paragraph(self, node):
972 # ``.PP`` : Start standard indented paragraph.
973 # ``.LP`` : Start block paragraph, all except the first.
974 # ``.P [type]`` : Start paragraph type.
975 # NOTE do not use paragraph starts because they reset indentation.
976 # ``.sp`` is only vertical space
977 self.ensure_eol()
978 if not self.first_child(node):
979 self.body.append('.sp\n')
980 # set in literal to escape dots after a new-line-character
981 self._in_literal = True
983 def depart_paragraph(self, node):
984 self._in_literal = False
985 self.body.append('\n')
987 def visit_problematic(self, node):
988 self.body.append(self.defs['problematic'][0])
990 def depart_problematic(self, node):
991 self.body.append(self.defs['problematic'][1])
993 def visit_raw(self, node):
994 if node.get('format') == 'manpage':
995 self.body.append(node.astext() + "\n")
996 # Keep non-manpage raw text out of output:
997 raise nodes.SkipNode
999 def visit_reference(self, node):
1000 """E.g. link or email address."""
1001 self.body.append(self.defs['reference'][0])
1003 def depart_reference(self, node):
1004 # TODO check node text is different from refuri
1005 # self.body.append("\n'UR " + node['refuri'] + "\n'UE\n")
1006 self.body.append(self.defs['reference'][1])
1008 def visit_revision(self, node):
1009 self.visit_docinfo_item(node, 'revision')
1011 depart_revision = depart_docinfo_item
1013 def visit_row(self, node):
1014 self._active_table.new_row()
1016 def depart_row(self, node):
1017 pass
1019 def visit_section(self, node):
1020 self.section_level += 1
1022 def depart_section(self, node):
1023 self.section_level -= 1
1025 def visit_status(self, node):
1026 self.visit_docinfo_item(node, 'status')
1028 depart_status = depart_docinfo_item
1030 def visit_strong(self, node):
1031 self.body.append(self.defs['strong'][0])
1033 def depart_strong(self, node):
1034 self.body.append(self.defs['strong'][1])
1036 def visit_substitution_definition(self, node):
1037 """Internal only."""
1038 raise nodes.SkipNode
1040 def visit_substitution_reference(self, node):
1041 self.document.reporter.warning(
1042 '"substitution_reference" not supported', base_node=node)
1044 def visit_subtitle(self, node):
1045 if isinstance(node.parent, nodes.sidebar):
1046 self.body.append(self.defs['strong'][0])
1047 elif isinstance(node.parent, nodes.document):
1048 self.visit_docinfo_item(node, 'subtitle')
1049 elif isinstance(node.parent, nodes.section):
1050 self.body.append(self.defs['strong'][0])
1052 def depart_subtitle(self, node):
1053 # document subtitle calls SkipNode
1054 self.body.append(self.defs['strong'][1]+'\n.PP\n')
1056 def visit_system_message(self, node):
1057 # TODO add report_level
1058 # if node['level'] < self.document.reporter['writer'].report_level:
1059 # Level is too low to display:
1060 # raise nodes.SkipNode
1061 attr = {}
1062 if node.hasattr('id'):
1063 attr['name'] = node['id']
1064 if node.hasattr('line'):
1065 line = ', line %s' % node['line']
1066 else:
1067 line = ''
1068 self.body.append('.IP "System Message: %s/%s (%s:%s)"\n'
1069 % (node['type'], node['level'], node['source'], line))
1071 def depart_system_message(self, node):
1072 pass
1074 def visit_table(self, node):
1075 self._active_table = Table()
1077 def depart_table(self, node):
1078 self.ensure_eol()
1079 self.body.extend(self._active_table.as_list())
1080 self._active_table = None
1082 def visit_target(self, node):
1083 # targets are in-document hyper targets, without any use for man-pages.
1084 raise nodes.SkipNode
1086 def visit_tbody(self, node):
1087 pass
1089 def depart_tbody(self, node):
1090 pass
1092 def visit_term(self, node):
1093 self.body.append(self.defs['term'][0])
1095 def depart_term(self, node):
1096 self.body.append(self.defs['term'][1])
1098 def visit_tgroup(self, node):
1099 pass
1101 def depart_tgroup(self, node):
1102 pass
1104 def visit_thead(self, node):
1105 # MAYBE double line '='
1106 pass
1108 def depart_thead(self, node):
1109 # MAYBE double line '='
1110 pass
1112 def visit_tip(self, node):
1113 self.visit_admonition(node, 'tip')
1115 depart_tip = depart_admonition
1117 def visit_title(self, node):
1118 if isinstance(node.parent, nodes.topic):
1119 self.body.append(self.defs['topic-title'][0])
1120 elif isinstance(node.parent, nodes.sidebar):
1121 self.body.append(self.defs['sidebar-title'][0])
1122 elif isinstance(node.parent, nodes.admonition):
1123 self.body.append('.IP "')
1124 elif self.section_level == 0:
1125 self._docinfo['title'] = node.astext()
1126 # document title for .TH
1127 self._docinfo['title_upper'] = node.astext().upper()
1128 raise nodes.SkipNode
1129 elif self.section_level == 1:
1130 self.body.append('.SH %s\n'%self.deunicode(node.astext().upper()))
1131 raise nodes.SkipNode
1132 else:
1133 self.body.append('.SS ')
1135 def depart_title(self, node):
1136 if isinstance(node.parent, nodes.admonition):
1137 self.body.append('"')
1138 self.body.append('\n')
1140 def visit_title_reference(self, node):
1141 """inline citation reference"""
1142 self.body.append(self.defs['title_reference'][0])
1144 def depart_title_reference(self, node):
1145 self.body.append(self.defs['title_reference'][1])
1147 def visit_topic(self, node):
1148 pass
1150 def depart_topic(self, node):
1151 pass
1153 def visit_sidebar(self, node):
1154 pass
1156 def depart_sidebar(self, node):
1157 pass
1159 def visit_rubric(self, node):
1160 pass
1162 def depart_rubric(self, node):
1163 self.body.append('\n')
1165 def visit_transition(self, node):
1166 # .PP Begin a new paragraph and reset prevailing indent.
1167 # .sp N leaves N lines of blank space.
1168 # .ce centers the next line
1169 self.body.append('\n.sp\n.ce\n----\n')
1171 def depart_transition(self, node):
1172 self.body.append('\n.ce 0\n.sp\n')
1174 def visit_version(self, node):
1175 self.visit_docinfo_item(node, 'version')
1177 def visit_warning(self, node):
1178 self.visit_admonition(node, 'warning')
1180 depart_warning = depart_admonition
1182 def unimplemented_visit(self, node):
1183 raise NotImplementedError('visiting unimplemented node type: %s'
1184 % node.__class__.__name__)
1186 # vim: set fileencoding=utf-8 et ts=4 ai :