Skip to content

Commit

Permalink
Merge pull request #19 from t-makaro/fancybreak
Browse files Browse the repository at this point in the history
fancy verbatim line breaks without minted
  • Loading branch information
t-makaro authored Mar 26, 2019
2 parents 6fd3e79 + 326d05d commit 122a6b5
Show file tree
Hide file tree
Showing 10 changed files with 126 additions and 224 deletions.
32 changes: 10 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ A more accurate representation of jupyter notebooks when converting to pdfs.
This template was designed to make converted jupyter notebooks look (almost) identical to the actual notebook. If something doesn't exist in the original notebook then it doesn't belong in the conversion.

## Improvements
1. \maketitle is removed (If you want a title then add a markdown cell to the top of your notebook)
2. Sections are no longer numbered automatically (notebooks don't number sections so the pdf shouldn't)
1. \maketitle is removed (If you want a title then add a markdown cell to the top of your notebook).
2. Sections are no longer numbered automatically (notebooks don't number sections so the pdf shouldn't).
3. **BOXES!** are drawn around code cells.
4. In/Out will move to the left as the execution count increases instead of pushing code to the right.
5. ~~$\LaTeX$ and $\Tex$ in markdown cells will no longer cause conversion to fail~~ **(This change was merged into nbconvert 5.4.0)**
6. "\LaTeX" and "\TeX" are no longer converted into a logo on conversion to pdf unless they are in math mode. (This and the above point replicate the functionality of these commands in notebook markdown)
7. In/Out text colours updated to match Jupyter
8. Markdown paragraphs are no longer auto-indented in the pdf
4. In/Out counts will move to the left as the execution count increases instead of pushing code to the right (only numbers are displayed by default to save page width).
5. ~~$\LaTeX$ and $\Tex$ in markdown cells will no longer cause conversion to fail.~~ **(This change was merged into nbconvert 5.4.0)**
6. "\LaTeX" and "\TeX" are no longer converted into a logo on conversion to pdf unless they are in math mode. (This and the above point replicate the functionality of these commands in notebook markdown).
7. In/Out prompt colours updated to match Jupyter.
8. Markdown paragraphs are no longer auto-indented in the pdf.
9. Syntax highlighting improvements. (Bonus if using XeLaTeX)
10. Output text wrapping improvements.
11. Code cell text wrapping (requires extra setup)
11. Code cell text wrapping.

Quick Comparison:
![comparison](example/comparison.png)
Expand All @@ -32,18 +32,6 @@ pip install nb_pdf_template
python -m nb_pdf_template.install
```

### Optional Extra Setup
In order to make code cells wrap text, we need to change how nbconvert does syntax highlighting. This feature is experimental. (And known not to work with TeX Live 2015).

Add the following to your ```jupyter_nbconvert_config.py``` and your ```jupyter_notebook_config.py```:
```
c.PDFExporter.latex_command = ['xelatex', '-8bit', '-shell-escape','{filename}']
```
then run:
```
python -m nb_pdf_template.install --minted
```

## Use
From the command line:
```
Expand All @@ -63,8 +51,8 @@ This package offers the following templates:

Template | Use
---------|-------
classic.tplx | For most accurate recreation of the default Jupyter Notebook Style.
classicm.tplx **(Recommended)**| m for modified. Similar to classic.tplx, but in/out prompts are above cells instead of in the margin. Bonus left margins are smaller so code cells are wider.
classic.tplx **(Recommended)**| For most accurate recreation of the default Jupyter Notebook Style.
classicm.tplx | m for modified. Similar to classic.tplx, but in/out prompts are above cells instead of in the margin. Bonus left margins are smaller so code cells are wider.
style_jupyter.tplx | DO NOT use this directly. Inherit from this template if you want to build your own.

## Tips (Good for any template)
Expand Down
Binary file modified example/comparison.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified example/test_classic_template.pdf
Binary file not shown.
Binary file modified example/test_classicm_template.pdf
Binary file not shown.
12 changes: 1 addition & 11 deletions nb_pdf_template/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@
import argparse


parser = argparse.ArgumentParser(description='none')
parser.add_argument('--minted', action='store_true')
args = parser.parse_args()

TEMPLATES = {"style_jupyter.tplx", "style_jupyter_minted.tplx",
"classic.tplx", "classicm.tplx"}
TEMPLATES = {"style_jupyter.tplx", "classic.tplx", "classicm.tplx"}


def install():
Expand All @@ -33,11 +28,6 @@ def install():
src = os.path.join(template_path, template)
shutil.copy(src, dst)

if args.minted:
src = os.path.join(template_path, 'style_jupyter_minted.tplx')
dst_ = os.path.join(dst, 'style_jupyter.tplx')
shutil.copy(src, dst_)

print("Success")


Expand Down
2 changes: 1 addition & 1 deletion nb_pdf_template/templates/classic.tplx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
((*- endblock definitions -*))

((*- block margins -*))
\geometry{verbose,tmargin=.5in,bmargin=.7in,lmargin=1.1in,rmargin=.5in}
\geometry{verbose,tmargin=.5in,bmargin=.7in,lmargin=.7in,rmargin=.7in}
((*- endblock margins -*))

((* block maketitle *))((* endblock maketitle *))
20 changes: 19 additions & 1 deletion nb_pdf_template/templates/classicm.tplx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
((*- extends 'classic.tplx' -*))

((*- block packages -*))
\usepackage{needspace}
((( super() )))
((*- endblock packages -*))

((*- block margins -*))
\geometry{verbose,tmargin=.5in,bmargin=.7in,lmargin=.5in,rmargin=.5in}
((*- endblock margins -*))
Expand All @@ -9,6 +14,19 @@
\needspace{1.1cm}
\noindent{\color{#2}#1 [#3]:}
}
((* endblock style_prompt *))
((* endblock style_prompt *))

((* set charlim = 94 *))

((* macro draw_cell(text, cell, prompt, prompt_color) -*))
((*- if prompt == 'In' -*))
((*- set style = "breakable, size=fbox, boxrule=1pt, pad at break*=1mm,colback=cellbackground, colframe=cellborder"-*))
((*- else -*))((*- set style = "breakable, boxrule=.5pt, size=fbox, pad at break*=1mm, opacityfill=0"-*))((*- endif -*))

(((- draw_prompt(cell, prompt, prompt_color) )))
\begin{tcolorbox}[((( style )))]
\begin{Verbatim}[commandchars=\\\{\}]
((( text )))
\end{Verbatim}
\end{tcolorbox}
((*- endmacro *))
128 changes: 94 additions & 34 deletions nb_pdf_template/templates/style_jupyter.tplx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
((*- block packages -*))
\usepackage[breakable]{tcolorbox}
\tcbset{nobeforeafter}
\usepackage{needspace}
((( super() )))
((*- endblock packages -*))

Expand Down Expand Up @@ -47,48 +46,101 @@
\fi %end magical operator highlighting
%End Reconfigured Pygments
((* endblock repygments *))


% For linebreaks inside Verbatim environment from package fancyvrb.
\makeatletter
\newbox\Wrappedcontinuationbox
\newbox\Wrappedvisiblespacebox
% These are user customizable e.g. from latex_elements's preamble key.
% Use of \textvisiblespace for compatibility with XeTeX/LuaTeX/fontspec.
\newcommand*\Wrappedvisiblespace {\textcolor{red}{\textvisiblespace}}
\newcommand*\Wrappedcontinuationsymbol {\textcolor{red}{\llap{\tiny$\m@th\hookrightarrow$}}}
\newcommand*\Wrappedcontinuationindent {3ex }
\newcommand*\Wrappedafterbreak {\kern\Wrappedcontinuationindent\copy\Wrappedcontinuationbox}
% Take advantage of the already applied Pygments mark-up to insert
% potential linebreaks for TeX processing.
% {, <, #, %, $, ' and ": go to next line.
% _, }, ^, &, >, - and ~: stay at end of broken line.
% Use of \textquotesingle for straight quote.
\newcommand*\Wrappedbreaksatspecials {%
\def\PYGZus{\discretionary{\char`\_}{\Wrappedafterbreak}{\char`\_}}%
\def\PYGZob{\discretionary{}{\Wrappedafterbreak\char`\{}{\char`\{}}%
\def\PYGZcb{\discretionary{\char`\}}{\Wrappedafterbreak}{\char`\}}}%
\def\PYGZca{\discretionary{\char`\^}{\Wrappedafterbreak}{\char`\^}}%
\def\PYGZam{\discretionary{\char`\&}{\Wrappedafterbreak}{\char`\&}}%
\def\PYGZlt{\discretionary{}{\Wrappedafterbreak\char`\<}{\char`\<}}%
\def\PYGZgt{\discretionary{\char`\>}{\Wrappedafterbreak}{\char`\>}}%
\def\PYGZsh{\discretionary{}{\Wrappedafterbreak\char`\#}{\char`\#}}%
\def\PYGZpc{\discretionary{}{\Wrappedafterbreak\char`\%}{\char`\%}}%
\def\PYGZdl{\discretionary{}{\Wrappedafterbreak\char`\$}{\char`\$}}%
\def\PYGZhy{\discretionary{\char`\-}{\Wrappedafterbreak}{\char`\-}}%
\def\PYGZsq{\discretionary{}{\Wrappedafterbreak\textquotesingle}{\textquotesingle}}%
\def\PYGZdq{\discretionary{}{\Wrappedafterbreak\char`\"}{\char`\"}}%
\def\PYGZti{\discretionary{\char`\~}{\Wrappedafterbreak}{\char`\~}}%
}
% Some characters . , ; ? ! / are not pygmentized.
% This macro makes them "active" and they will insert potential linebreaks
\newcommand*\Wrappedbreaksatpunct {%
\lccode`\~`\.\lowercase{\def~}{\discretionary{\hbox{\char`\.}}{\Wrappedafterbreak}{\hbox{\char`\.}}}%
\lccode`\~`\,\lowercase{\def~}{\discretionary{\hbox{\char`\,}}{\Wrappedafterbreak}{\hbox{\char`\,}}}%
\lccode`\~`\;\lowercase{\def~}{\discretionary{\hbox{\char`\;}}{\Wrappedafterbreak}{\hbox{\char`\;}}}%
\lccode`\~`\:\lowercase{\def~}{\discretionary{\hbox{\char`\:}}{\Wrappedafterbreak}{\hbox{\char`\:}}}%
\lccode`\~`\?\lowercase{\def~}{\discretionary{\hbox{\char`\?}}{\Wrappedafterbreak}{\hbox{\char`\?}}}%
\lccode`\~`\!\lowercase{\def~}{\discretionary{\hbox{\char`\!}}{\Wrappedafterbreak}{\hbox{\char`\!}}}%
\lccode`\~`\/\lowercase{\def~}{\discretionary{\hbox{\char`\/}}{\Wrappedafterbreak}{\hbox{\char`\/}}}%
\catcode`\.\active
\catcode`\,\active
\catcode`\;\active
\catcode`\:\active
\catcode`\?\active
\catcode`\!\active
\catcode`\/\active
\lccode`\~`\~
}
\makeatother

\let\OriginalVerbatim=\Verbatim
\makeatletter
\renewcommand{\Verbatim}[1][1]{%
%\parskip\z@skip
\sbox\Wrappedcontinuationbox {\Wrappedcontinuationsymbol}%
\sbox\Wrappedvisiblespacebox {\FV@SetupFont\Wrappedvisiblespace}%
\def\FancyVerbFormatLine ##1{\hsize\linewidth
\vtop{\raggedright\hyphenpenalty\z@\exhyphenpenalty\z@
\doublehyphendemerits\z@\finalhyphendemerits\z@
\strut ##1\strut}%
}%
% If the linebreak is at a space, the latter will be displayed as visible
% space at end of first line, and a continuation symbol starts next line.
% Stretch/shrink are however usually zero for typewriter font.
\def\FV@Space {%
\nobreak\hskip\z@ plus\fontdimen3\font minus\fontdimen4\font
\discretionary{\copy\Wrappedvisiblespacebox}{\Wrappedafterbreak}
{\kern\fontdimen2\font}%
}%

% Allow breaks at special characters using \PYG... macros.
\Wrappedbreaksatspecials
% Breaks at punctuation characters . , ; ? ! and / need catcode=\active
\OriginalVerbatim[#1,codes*=\Wrappedbreaksatpunct]%
}
\makeatother

% Exact colors from NB
((*- block style_colors *))
\definecolor{incolor}{HTML}{303F9F}
\definecolor{outcolor}{HTML}{D84315}
\definecolor{cellborder}{HTML}{CFCFCF}
\definecolor{cellbackground}{HTML}{F7F7F7}
((*- endblock style_colors *))

% needed definitions
\newlength{\promptlength}

% prompt
((*- block style_prompt *))
\newcommand{\prompt}[3]{
\needspace{1.1cm}
\settowidth{\promptlength}{ #1 [#3] }
\hspace{-\promptlength}\hspace{-5pt}
\noindent{\color{#2}#1 [#3]:}
\vspace{-2.7ex}
\llap{{\color{#2}[#3]: \ }}\vspace{-1.25em}
}
((* endblock style_prompt *))

% environments
((*- block style_environments *))
\newenvironment{InVerbatim}{\VerbatimEnvironment%
\begin{tcolorbox}[breakable, size=fbox, boxrule=1pt, pad at break*=1mm,
colback=cellbackground, colframe=cellborder]
\begin{Verbatim}
}{
\end{Verbatim}
\end{tcolorbox}
}
\newenvironment{OutVerbatim}{\VerbatimEnvironment%
\begin{tcolorbox}[breakable, boxrule=.5pt, size=fbox, pad at break*=1mm, opacityfill=0]
\begin{Verbatim}
}{
\end{Verbatim}
\end{tcolorbox}
}
((* endblock style_environments *))

((*- endblock definitions -*))

%===============================================================================
Expand All @@ -105,7 +157,7 @@
%===============================================================================

((*- if charlim is not defined -*))
((* set charlim = 86 *))
((* set charlim = 89 *))
((*- endif -*))

((* block execute_result scoped *))
Expand All @@ -121,7 +173,7 @@

((* block stream *))
\begin{Verbatim}[commandchars=\\\{\}]
((( output.text | wrap_text(charlim) | escape_latex | ansi2latex )))
((( output.text | wrap_text(charlim) | escape_latex | ansi2latex -)))
\end{Verbatim}
((* endblock stream *))

Expand All @@ -131,12 +183,20 @@

% Name: draw_cell
% Purpose: Renders an output/input prompt
((*- if draw_cell is not defined -*))
((* macro draw_cell(text, cell, prompt, prompt_color) -*))
((( draw_prompt(cell, prompt, prompt_color) )))
\begin{((( prompt ~ 'Verbatim')))}[commandchars=\\\{\}]
((*- if prompt == 'In' -*))
((*- set style = "breakable, size=fbox, boxrule=1pt, pad at break*=1mm,colback=cellbackground, colframe=cellborder"-*))
((*- else -*))((*- set style = "breakable, boxrule=.5pt, size=fbox, pad at break*=1mm, opacityfill=0"-*))((*- endif -*))

\begin{tcolorbox}[((( style )))]
(((- draw_prompt(cell, prompt, prompt_color) )))
\begin{Verbatim}[commandchars=\\\{\}]
((( text )))
\end{((( prompt ~ 'Verbatim')))}
\end{Verbatim}
\end{tcolorbox}
((*- endmacro *))
((*- endif -*))

% Name: draw_prompt
% Purpose: Renders an output/input prompt
Expand Down
Loading

0 comments on commit 122a6b5

Please sign in to comment.