Skip to content

Commit

Permalink
DOC: add example for including nbsphinx docs in another LaTeX file (#719
Browse files Browse the repository at this point in the history
)
  • Loading branch information
mgeier committed Oct 12, 2023
1 parent f81828b commit 1f0fa7f
Show file tree
Hide file tree
Showing 12 changed files with 276 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ jobs:
path: build/latex/nbsphinx.pdf
destination: nbsphinx.pdf

- run:
name: Building LaTeX document with nbsphinx docs as chapter
# NB: There is a warning about :footcite:, so we are not using "-W"
command: |
cd include-in-latex
python -m sphinx --color ../doc _build -c . -b latex
- run:
name: Building PDF of above
command: |
cd include-in-latex
latexmk
- store_artifacts:
name: Uploading another PDF file
path: include-in-latex/my-latex-document.pdf
destination: my-latex-document.pdf

workflows:
version: 2
build-me-my-docs:
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ nbsphinx.egg-info/
doc/_build
doc/gallery/a-local-file.png
/theme_comparison/
/include-in-latex/_build/
/include-in-latex/pygmentize.py.tex
/include-in-latex/latexmkrc.tex
39 changes: 39 additions & 0 deletions include-in-latex/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
Including Sphinx-Generated Content in a LaTeX Document
======================================================

This sub-directory is an example for how a Sphinx-based project
(in this case the `nbsphinx` documentation)
can be included as part or chapter of a larger,
otherwise hand-written LaTeX document
(in this case [my-latex-document.tex][]).

This technique is not specific to `nbsphinx`, except for this one line:

\usepackage{nbsphinx}

If you want to use it without `nbsphinx`, just remove this line.

The main idea of this setup is that Sphinx is called with
the original source directory `../doc`
but specifying this directory
(which contains another [conf.py][] overriding some of the original settings)
as configuration directory (with `-c .`):

python -m sphinx ../doc _build -c . -b latex

Note that even though Sphinx suggests that in its console messages,
running LaTeX in the `_build` directory will *not* work,
because the `.tex` file in there is not a stand-alone LaTeX document
(it is based on a [minimalistic template][]).
It is meant to be included in the file [my-latex-document.tex][]
in this directory, so LaTeX has to be called from here:

latexmk -pv

The configuration file [latexmkrc][] manipulates the environment variable
`TEXINPUTS` so that LaTeX can find all necessary files.

[my-latex-document.tex]: my-latex-document.tex
[conf.py]: conf.py
[minimalistic template]: _templates/latex.tex_t
[latexmkrc]: latexmkrc
4 changes: 4 additions & 0 deletions include-in-latex/_templates/latex.tex_t
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
%% Generated by Sphinx.
%% This is meant to be included in another LaTeX document.
<%= body %>
<%= atendofbody %>
45 changes: 45 additions & 0 deletions include-in-latex/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import docutils
import sphinx

original_conf_py = '../doc/conf.py'

locals().update(sphinx.config.eval_config_file(original_conf_py, tags))

templates_path = ['_templates']
html_favicon = None

exclude_patterns = ['_build']

latex_documents = [(
'index', # main source file
'nbsphinx-chapter.tex', # output file
'', # unused
'', # unused
'howto', # use 'manual' to generate \chapter{}s instead of \section{}s
True, # toctree_only. Use True to hide contents of main source file
)]

latex_engine = 'lualatex'

# Additional configuration options can be added here.

###############################################################################
# The rest of this file is for handling the bibliography:

extensions.remove('sphinxcontrib.bibtex')
exclude_patterns.append('references.rst')
suppress_warnings = ['toc.excluded']


def cite_role(macroname):

def role(name, rawtext, text, lineno, inliner, options=None, content=None):
latex_code = rf'\{macroname}{{{text}}}'
return [docutils.nodes.raw('', latex_code, format='latex')], []

return role


def setup(app):
app.add_role('cite', cite_role('parencite'))
app.add_role('cite:t', cite_role('textcite'))
18 changes: 18 additions & 0 deletions include-in-latex/latexmkrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Configuration for latexmk

@default_files = ('my-latex-document');

#$pdf_mode = 1; # $pdflatex
#$pdf_mode = 3; # $dvipdf
$pdf_mode = 4; # $lualatex
#$pdf_mode = 5; # $xelatex

# Add current directory (and subdirs) to LaTeX path:
ensure_path('TEXINPUTS', './/');

# syntax highlighting of code blocks:
system("./pygmentize.py");

$clean_ext = "run.xml";

$bibtex_use = 2; # run always, delete .bbl files on cleanup
114 changes: 114 additions & 0 deletions include-in-latex/my-latex-document.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
\RequirePackage{luatex85}
\documentclass[a4paper]{book}

\newdimen\sphinxpxdimen
\sphinxpxdimen=.75bp
\ifdefined\pdfimageresolution \pdfimageresolution= 96\relax\fi

\catcode`^^^^00a0\active\protected\def^^^^00a0{\leavevmode\nobreak\ }

\usepackage{fontspec}
\usepackage{mathpazo}
\linespread{1.05} % see http://www.tug.dk/FontCatalogue/urwpalladio/
\setmainfont{TeX Gyre Pagella}[Numbers=OldStyle]
\setmonofont{Latin Modern Mono Light}[Numbers=Lining]

\usepackage{amsmath,amssymb,amstext}

\usepackage{polyglossia}
\setmainlanguage{english}

\usepackage[booktabs]{sphinx}
\sphinxsetup{
%verbatimwrapslines=false,
%verbatimhintsturnover=false,
div.note_border-TeXcolor={HTML}{E0E0E0},
div.note_border-width=0.5pt,
div.warning_border-TeXcolor={HTML}{E0E0E0},
div.warning_border-width=1.5pt,
div.warning_background-TeXcolor={HTML}{FBFBFB},
}
\fvset{fontsize=\small}

\usepackage{nbsphinx}

\usepackage[
style=authoryear-comp,
backref=true,
]{biblatex}
% We need the original bibliography from the Sphinx project ...
\addbibresource{../doc/references.bib}
% ... and we can add our own if we want:
\addbibresource{my-own-references.bib}

% This should be the last package in the preamble:
\usepackage{hyperref}

\sphinxsetup{
InnerLinkColor={named}{black},
OuterLinkColor={named}{black},
}

\title{Including Sphinx-Generated Content in a \LaTeX\ Document}

\begin{document}

\maketitle

\tableofcontents

\chapter{A Hand-Written \LaTeX\ Chapter}

\section{References to Sphinx Content}

We can create references to the Sphinx content,
for example to section~\ref{code-cells:Code,-Output,-Streams}.


\section{Bibliography}

We can cite bibliography items from the Sphinx project:
\parencite{perez2011python}.
But we can also use our own bibliography file:
\parencite{knuth1986texbook}.

We only have to make sure that the bibliography keys are unique.

\section{Code Blocks}

We can use the \texttt{sphinxVerbatim} environment
to get code blocks like those generated by Sphinx:

\begin{sphinxVerbatim}
some code
\end{sphinxVerbatim}

\begin{sphinxVerbatim}[commandchars=\\\{\}]
some code with \emph{markup}
\end{sphinxVerbatim}

With a little additional work
we can even use the same syntax highlighting as Sphinx uses:

See \texttt{pygmentize.py}:

\input{pygmentize.py}

\dots and \texttt{latexmkrc}:

\input{latexmkrc}

\chapter{A Chapter Containing a Sphinx Project}

Depending on whether the last element of \texttt{latex\_documents}
(\url{https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-latex_documents})
is \texttt{False} or \texttt{True},
the content of the main source file (without the main heading)
is shown here or not, respectively:

% NB: The name of the input file is defined with latex_documents in conf.py:
\input{_build/nbsphinx-chapter}

\printbibliography[title=References,heading=bibintoc]

\end{document}
7 changes: 7 additions & 0 deletions include-in-latex/my-own-references.bib
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@book{knuth1986texbook,
author = {Donald E. Knuth},
title = {The \TeX{}book},
publisher = {Addison-Wesley},
year = {1986},
isbn = {0-201-13447-0},
}
24 changes: 24 additions & 0 deletions include-in-latex/pygmentize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
from pathlib import Path

from sphinx import highlighting


def pygmentize(source, destination, lang=None):
source = Path(source)
destination = Path(destination)
if lang is None:
lang = source.suffix[1:]
code = source.read_text()
highlighter = highlighting.PygmentsBridge(
'latex', latex_engine='lualatex')
hlcode = highlighter.highlight_block(code, lang)
hlcode = hlcode.replace(r'\begin{Verbatim}', r'\begin{sphinxVerbatim}')
hlcode = hlcode.replace(r'\end{Verbatim}', r'\end{sphinxVerbatim}')
destination.parent.mkdir(exist_ok=True)
destination.write_text(hlcode)


if __name__ == '__main__':
pygmentize('pygmentize.py', 'pygmentize.py.tex')
pygmentize('latexmkrc', 'latexmkrc.tex', lang='perl')
1 change: 1 addition & 0 deletions include-in-latex/sphinxlatexindbibtoc.sty
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
% Empty file to disable the one provided by Sphinx
2 changes: 2 additions & 0 deletions include-in-latex/sphinxlatexstyleheadings.sty
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
% This file disables the one provided by Sphinx
\newcommand{\py@HeaderFamily}{}
1 change: 1 addition & 0 deletions include-in-latex/sphinxoptionsgeometry.sty
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
% Empty file to disable the one provided by Sphinx

0 comments on commit 1f0fa7f

Please sign in to comment.