Skip to content

Commit 1f0fa7f

Browse files
authored
DOC: add example for including nbsphinx docs in another LaTeX file (#719)
1 parent f81828b commit 1f0fa7f

File tree

12 files changed

+276
-0
lines changed

12 files changed

+276
-0
lines changed

.circleci/config.yml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,24 @@ jobs:
8787
path: build/latex/nbsphinx.pdf
8888
destination: nbsphinx.pdf
8989

90+
- run:
91+
name: Building LaTeX document with nbsphinx docs as chapter
92+
# NB: There is a warning about :footcite:, so we are not using "-W"
93+
command: |
94+
cd include-in-latex
95+
python -m sphinx --color ../doc _build -c . -b latex
96+
97+
- run:
98+
name: Building PDF of above
99+
command: |
100+
cd include-in-latex
101+
latexmk
102+
103+
- store_artifacts:
104+
name: Uploading another PDF file
105+
path: include-in-latex/my-latex-document.pdf
106+
destination: my-latex-document.pdf
107+
90108
workflows:
91109
version: 2
92110
build-me-my-docs:

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,6 @@ nbsphinx.egg-info/
99
doc/_build
1010
doc/gallery/a-local-file.png
1111
/theme_comparison/
12+
/include-in-latex/_build/
13+
/include-in-latex/pygmentize.py.tex
14+
/include-in-latex/latexmkrc.tex

include-in-latex/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
Including Sphinx-Generated Content in a LaTeX Document
2+
======================================================
3+
4+
This sub-directory is an example for how a Sphinx-based project
5+
(in this case the `nbsphinx` documentation)
6+
can be included as part or chapter of a larger,
7+
otherwise hand-written LaTeX document
8+
(in this case [my-latex-document.tex][]).
9+
10+
This technique is not specific to `nbsphinx`, except for this one line:
11+
12+
\usepackage{nbsphinx}
13+
14+
If you want to use it without `nbsphinx`, just remove this line.
15+
16+
The main idea of this setup is that Sphinx is called with
17+
the original source directory `../doc`
18+
but specifying this directory
19+
(which contains another [conf.py][] overriding some of the original settings)
20+
as configuration directory (with `-c .`):
21+
22+
python -m sphinx ../doc _build -c . -b latex
23+
24+
Note that even though Sphinx suggests that in its console messages,
25+
running LaTeX in the `_build` directory will *not* work,
26+
because the `.tex` file in there is not a stand-alone LaTeX document
27+
(it is based on a [minimalistic template][]).
28+
It is meant to be included in the file [my-latex-document.tex][]
29+
in this directory, so LaTeX has to be called from here:
30+
31+
latexmk -pv
32+
33+
The configuration file [latexmkrc][] manipulates the environment variable
34+
`TEXINPUTS` so that LaTeX can find all necessary files.
35+
36+
[my-latex-document.tex]: my-latex-document.tex
37+
[conf.py]: conf.py
38+
[minimalistic template]: _templates/latex.tex_t
39+
[latexmkrc]: latexmkrc
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
%% Generated by Sphinx.
2+
%% This is meant to be included in another LaTeX document.
3+
<%= body %>
4+
<%= atendofbody %>

include-in-latex/conf.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import docutils
2+
import sphinx
3+
4+
original_conf_py = '../doc/conf.py'
5+
6+
locals().update(sphinx.config.eval_config_file(original_conf_py, tags))
7+
8+
templates_path = ['_templates']
9+
html_favicon = None
10+
11+
exclude_patterns = ['_build']
12+
13+
latex_documents = [(
14+
'index', # main source file
15+
'nbsphinx-chapter.tex', # output file
16+
'', # unused
17+
'', # unused
18+
'howto', # use 'manual' to generate \chapter{}s instead of \section{}s
19+
True, # toctree_only. Use True to hide contents of main source file
20+
)]
21+
22+
latex_engine = 'lualatex'
23+
24+
# Additional configuration options can be added here.
25+
26+
###############################################################################
27+
# The rest of this file is for handling the bibliography:
28+
29+
extensions.remove('sphinxcontrib.bibtex')
30+
exclude_patterns.append('references.rst')
31+
suppress_warnings = ['toc.excluded']
32+
33+
34+
def cite_role(macroname):
35+
36+
def role(name, rawtext, text, lineno, inliner, options=None, content=None):
37+
latex_code = rf'\{macroname}{{{text}}}'
38+
return [docutils.nodes.raw('', latex_code, format='latex')], []
39+
40+
return role
41+
42+
43+
def setup(app):
44+
app.add_role('cite', cite_role('parencite'))
45+
app.add_role('cite:t', cite_role('textcite'))

include-in-latex/latexmkrc

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Configuration for latexmk
2+
3+
@default_files = ('my-latex-document');
4+
5+
#$pdf_mode = 1; # $pdflatex
6+
#$pdf_mode = 3; # $dvipdf
7+
$pdf_mode = 4; # $lualatex
8+
#$pdf_mode = 5; # $xelatex
9+
10+
# Add current directory (and subdirs) to LaTeX path:
11+
ensure_path('TEXINPUTS', './/');
12+
13+
# syntax highlighting of code blocks:
14+
system("./pygmentize.py");
15+
16+
$clean_ext = "run.xml";
17+
18+
$bibtex_use = 2; # run always, delete .bbl files on cleanup
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
\RequirePackage{luatex85}
2+
\documentclass[a4paper]{book}
3+
4+
\newdimen\sphinxpxdimen
5+
\sphinxpxdimen=.75bp
6+
\ifdefined\pdfimageresolution \pdfimageresolution= 96\relax\fi
7+
8+
\catcode`^^^^00a0\active\protected\def^^^^00a0{\leavevmode\nobreak\ }
9+
10+
\usepackage{fontspec}
11+
\usepackage{mathpazo}
12+
\linespread{1.05} % see http://www.tug.dk/FontCatalogue/urwpalladio/
13+
\setmainfont{TeX Gyre Pagella}[Numbers=OldStyle]
14+
\setmonofont{Latin Modern Mono Light}[Numbers=Lining]
15+
16+
\usepackage{amsmath,amssymb,amstext}
17+
18+
\usepackage{polyglossia}
19+
\setmainlanguage{english}
20+
21+
\usepackage[booktabs]{sphinx}
22+
\sphinxsetup{
23+
%verbatimwrapslines=false,
24+
%verbatimhintsturnover=false,
25+
div.note_border-TeXcolor={HTML}{E0E0E0},
26+
div.note_border-width=0.5pt,
27+
div.warning_border-TeXcolor={HTML}{E0E0E0},
28+
div.warning_border-width=1.5pt,
29+
div.warning_background-TeXcolor={HTML}{FBFBFB},
30+
}
31+
\fvset{fontsize=\small}
32+
33+
\usepackage{nbsphinx}
34+
35+
\usepackage[
36+
style=authoryear-comp,
37+
backref=true,
38+
]{biblatex}
39+
% We need the original bibliography from the Sphinx project ...
40+
\addbibresource{../doc/references.bib}
41+
% ... and we can add our own if we want:
42+
\addbibresource{my-own-references.bib}
43+
44+
% This should be the last package in the preamble:
45+
\usepackage{hyperref}
46+
47+
\sphinxsetup{
48+
InnerLinkColor={named}{black},
49+
OuterLinkColor={named}{black},
50+
}
51+
52+
\title{Including Sphinx-Generated Content in a \LaTeX\ Document}
53+
54+
\begin{document}
55+
56+
\maketitle
57+
58+
\tableofcontents
59+
60+
\chapter{A Hand-Written \LaTeX\ Chapter}
61+
62+
\section{References to Sphinx Content}
63+
64+
We can create references to the Sphinx content,
65+
for example to section~\ref{code-cells:Code,-Output,-Streams}.
66+
67+
68+
\section{Bibliography}
69+
70+
We can cite bibliography items from the Sphinx project:
71+
\parencite{perez2011python}.
72+
But we can also use our own bibliography file:
73+
\parencite{knuth1986texbook}.
74+
75+
We only have to make sure that the bibliography keys are unique.
76+
77+
\section{Code Blocks}
78+
79+
We can use the \texttt{sphinxVerbatim} environment
80+
to get code blocks like those generated by Sphinx:
81+
82+
\begin{sphinxVerbatim}
83+
some code
84+
\end{sphinxVerbatim}
85+
86+
\begin{sphinxVerbatim}[commandchars=\\\{\}]
87+
some code with \emph{markup}
88+
\end{sphinxVerbatim}
89+
90+
With a little additional work
91+
we can even use the same syntax highlighting as Sphinx uses:
92+
93+
See \texttt{pygmentize.py}:
94+
95+
\input{pygmentize.py}
96+
97+
\dots and \texttt{latexmkrc}:
98+
99+
\input{latexmkrc}
100+
101+
\chapter{A Chapter Containing a Sphinx Project}
102+
103+
Depending on whether the last element of \texttt{latex\_documents}
104+
(\url{https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-latex_documents})
105+
is \texttt{False} or \texttt{True},
106+
the content of the main source file (without the main heading)
107+
is shown here or not, respectively:
108+
109+
% NB: The name of the input file is defined with latex_documents in conf.py:
110+
\input{_build/nbsphinx-chapter}
111+
112+
\printbibliography[title=References,heading=bibintoc]
113+
114+
\end{document}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
@book{knuth1986texbook,
2+
author = {Donald E. Knuth},
3+
title = {The \TeX{}book},
4+
publisher = {Addison-Wesley},
5+
year = {1986},
6+
isbn = {0-201-13447-0},
7+
}

include-in-latex/pygmentize.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python3
2+
from pathlib import Path
3+
4+
from sphinx import highlighting
5+
6+
7+
def pygmentize(source, destination, lang=None):
8+
source = Path(source)
9+
destination = Path(destination)
10+
if lang is None:
11+
lang = source.suffix[1:]
12+
code = source.read_text()
13+
highlighter = highlighting.PygmentsBridge(
14+
'latex', latex_engine='lualatex')
15+
hlcode = highlighter.highlight_block(code, lang)
16+
hlcode = hlcode.replace(r'\begin{Verbatim}', r'\begin{sphinxVerbatim}')
17+
hlcode = hlcode.replace(r'\end{Verbatim}', r'\end{sphinxVerbatim}')
18+
destination.parent.mkdir(exist_ok=True)
19+
destination.write_text(hlcode)
20+
21+
22+
if __name__ == '__main__':
23+
pygmentize('pygmentize.py', 'pygmentize.py.tex')
24+
pygmentize('latexmkrc', 'latexmkrc.tex', lang='perl')
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
% Empty file to disable the one provided by Sphinx

0 commit comments

Comments
 (0)