Skip to content

Instantly share code, notes, and snippets.

@tk0miya
Last active September 1, 2020 06:21
Show Gist options
  • Save tk0miya/603f81c3e168831cca99537949357c7b to your computer and use it in GitHub Desktop.
Save tk0miya/603f81c3e168831cca99537949357c7b to your computer and use it in GitHub Desktop.
preface and appendix for Sphinx
# extension testbed
from docutils import nodes
from sphinx.writers.latex import LaTeXTranslator
class AppendixLaTeXTranslator(LaTeXTranslator):
def visit_title(self, node):
if isinstance(node.parent, nodes.section) and 'preface' in node.parent['classes']:
for i, value in enumerate(self.sectionnames):
self.sectionnames[i] += "*"
if isinstance(node.parent, nodes.section) and 'appendix' in node.parent['classes']:
self.body.append(r'\appendix')
super().visit_title(node)
if isinstance(node.parent, nodes.section) and 'preface' in node.parent['classes']:
for i, value in enumerate(self.sectionnames):
self.sectionnames[i] = value[:-1]
self.pushbody([])
def depart_title(self, node):
if isinstance(node.parent, nodes.section) and 'preface' in node.parent['classes']:
body = self.popbody()
self.body.extend(body)
super().depart_title(node)
if isinstance(node.parent, nodes.section) and 'preface' in node.parent['classes']:
sectionname = self.sectionnames[self.sectionlevel]
self.body.append(r'\addcontentsline{toc}{%s}{' % sectionname)
self.body.extend(body)
self.body.append(r'}')
def setup(app):
app.set_translator('latex', AppendixLaTeXTranslator)

Welcome to project's documentation!

.. cssclass:: preface

blah

blah

blah

blah

blah

.. cssclass:: appendix

blah

blah

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment