##// END OF EJS Templates
Fixed errors after testing...
Jonathan Frederic -
Show More
@@ -0,0 +1,42 b''
1 #!/usr/bin/env python
2 """
3 Contains writer for writing nbconvert output to PDF.
4 """
5 #-----------------------------------------------------------------------------
6 #Copyright (c) 2013, the IPython Development Team.
7 #
8 #Distributed under the terms of the Modified BSD License.
9 #
10 #The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 import subprocess
18 import os
19
20 from IPython.utils.traitlets import Integer
21
22 from .files import FilesWriter
23
24 #-----------------------------------------------------------------------------
25 # Classes
26 #-----------------------------------------------------------------------------
27 class PDFWriter(FilesWriter):
28 """Writer designed to write to PDF files"""
29
30 iteration_count = Integer(3, config=True, help="""
31 How many times pdflatex will be called.
32 """)
33
34 def write(self, output, resources, notebook_name=None, **kw):
35 """
36 Consume and write Jinja output a PDF.
37 See files.py for more...
38 """
39 dest = super(PDFWriter, self).write(output, resources, notebook_name=notebook_name, **kw)
40 command = 'pdflatex ' + dest
41 for index in range(self.iteration_count):
42 subprocess.Popen(command, shell=True, stdout=open(os.devnull, 'wb'))
@@ -1,249 +1,259 b''
1 1 #!/usr/bin/env python
2 2 """NBConvert is a utility for conversion of .ipynb files.
3 3
4 4 Command-line interface for the NbConvert conversion utility.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 #Copyright (c) 2013, the IPython Development Team.
8 8 #
9 9 #Distributed under the terms of the Modified BSD License.
10 10 #
11 11 #The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 #Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 # Stdlib imports
19 19 from __future__ import print_function
20 20 import sys
21 21 import os
22 22 import glob
23 23
24 24 # From IPython
25 25 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
26 26 from IPython.config import catch_config_error, Configurable
27 27 from IPython.utils.traitlets import (
28 28 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
29 29 )
30 30 from IPython.utils.importstring import import_item
31 31
32 32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
33 33 from IPython.nbconvert import exporters, transformers, writers
34 34 from .utils.base import NbConvertBase
35 35 from .utils.exceptions import ConversionException
36 36
37 37 #-----------------------------------------------------------------------------
38 38 #Classes and functions
39 39 #-----------------------------------------------------------------------------
40 40
41 41 nbconvert_aliases = {}
42 42 nbconvert_aliases.update(base_aliases)
43 43 nbconvert_aliases.update({
44 44 'to' : 'NbConvertApp.export_format',
45 45 'flavor' : 'Exporter.flavor',
46 46 'template' : 'Exporter.template_file',
47 47 'notebooks' : 'NbConvertApp.notebooks',
48 48 'writer' : 'NbConvertApp.writer_class',
49 49 })
50 50
51 51 nbconvert_flags = {}
52 52 nbconvert_flags.update(base_flags)
53 53 nbconvert_flags.update({
54 54 'stdout' : (
55 55 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
56 56 "Write notebook output to stdout instead of files."
57 ),
58
59 'pdf' : (
60 {'NbConvertApp' : {'writer_class' : "PDFWriter"}},
61 "Compile notebook output to a PDF."
57 62 )
58 63 })
59 64
60 65
61 66 class NbConvertApp(BaseIPythonApplication):
62 67 """Application used to convert to and from notebook file type (*.ipynb)"""
63 68
64 69 name = 'ipython-nbconvert'
65 70 aliases = nbconvert_aliases
66 71 flags = nbconvert_flags
67 72
68 73 def _classes_default(self):
69 74 classes = [NbConvertBase]
70 75 for pkg in (exporters, transformers, writers):
71 76 for name in dir(pkg):
72 77 cls = getattr(pkg, name)
73 78 if isinstance(cls, type) and issubclass(cls, Configurable):
74 79 classes.append(cls)
75 80 return classes
76 81
77 82 description = Unicode(
78 83 u"""This application is used to convert notebook files (*.ipynb)
79 84 to various other formats.""")
80 85
81 86 examples = Unicode(u"""
82 87 The simplest way to use nbconvert is
83 88
84 89 > ipython nbconvert mynotebook.ipynb
85 90
86 91 which will convert mynotebook.ipynb to the default format (probably HTML).
87 92
88 93 You can specify the export format with `--to`.
89 94 Options include {0}
90 95
91 96 > ipython nbconvert --to latex mynotebook.ipnynb
92 97
93 98 Both HTML and LaTeX support multiple flavors of output. LaTeX includes
94 99 'basic', 'book', and 'article'. HTML includes 'basic', 'full', and
95 100 'reveal'. You can specify the flavor of the format used.
96 101
97 102 > ipython nbconvert --to html --flavor reveal mynotebook.ipnynb
98 103
99 104 You can also pipe the output to stdout, rather than a file
100 105
101 106 > ipython nbconvert mynotebook.ipynb --stdout
102 107
108 or to a PDF
109
110 > ipython nbconvert mynotebook.ipynb --pdf
111
103 112 Multiple notebooks can be given at the command line in a couple of
104 113 different ways:
105 114
106 115 > ipython nbconvert notebook*.ipynb
107 116 > ipython nbconvert notebook1.ipynb notebook2.ipynb
108 117
109 118 or you can specify the notebooks list in a config file, containing::
110 119
111 120 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
112 121
113 122 > ipython nbconvert --config mycfg.py
114 123 """.format(get_export_names()))
115 124 # Writer specific variables
116 125 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
117 126 help="""Instance of the writer class used to write the
118 127 results of the conversion.""")
119 128 writer_class = DottedObjectName('FilesWriter', config=True,
120 129 help="""Writer class used to write the
121 130 results of the conversion""")
122 131 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
132 'PDFWriter': 'IPython.nbconvert.writers.pdf.PDFWriter',
123 133 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
124 134 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
125 135 writer_factory = Type()
126 136
127 137 def _writer_class_changed(self, name, old, new):
128 138 if new in self.writer_aliases:
129 139 new = self.writer_aliases[new]
130 140 self.writer_factory = import_item(new)
131 141
132 142
133 143 # Other configurable variables
134 144 export_format = CaselessStrEnum(get_export_names(),
135 145 default_value="html",
136 146 config=True,
137 147 help="""The export format to be used."""
138 148 )
139 149
140 150 notebooks = List([], config=True, help="""List of notebooks to convert.
141 151 Wildcards are supported.
142 152 Filenames passed positionally will be added to the list.
143 153 """)
144 154
145 155 @catch_config_error
146 156 def initialize(self, argv=None):
147 157 super(NbConvertApp, self).initialize(argv)
148 158 self.init_syspath()
149 159 self.init_notebooks()
150 160 self.init_writer()
151 161
152 162
153 163 def init_syspath(self):
154 164 """
155 165 Add the cwd to the sys.path ($PYTHONPATH)
156 166 """
157 167 sys.path.insert(0, os.getcwd())
158 168
159 169
160 170 def init_notebooks(self):
161 171 """Construct the list of notebooks.
162 172 If notebooks are passed on the command-line,
163 173 they override notebooks specified in config files.
164 174 Glob each notebook to replace notebook patterns with filenames.
165 175 """
166 176
167 177 # Specifying notebooks on the command-line overrides (rather than adds)
168 178 # the notebook list
169 179 if self.extra_args:
170 180 patterns = self.extra_args
171 181 else:
172 182 patterns = self.notebooks
173 183
174 184 # Use glob to replace all the notebook patterns with filenames.
175 185 filenames = []
176 186 for pattern in patterns:
177 187
178 188 # Use glob to find matching filenames. Allow the user to convert
179 189 # notebooks without having to type the extension.
180 190 globbed_files = glob.glob(pattern)
181 191 globbed_files.extend(glob.glob(pattern + '.ipynb'))
182 192
183 193 for filename in globbed_files:
184 194 if not filename in filenames:
185 195 filenames.append(filename)
186 196 self.notebooks = filenames
187 197
188 198 def init_writer(self):
189 199 """
190 200 Initialize the writer (which is stateless)
191 201 """
192 202 self._writer_class_changed(None, self.writer_class, self.writer_class)
193 203 self.writer = self.writer_factory(parent=self)
194 204
195 205 def start(self):
196 206 """
197 207 Ran after initialization completed
198 208 """
199 209 super(NbConvertApp, self).start()
200 210 self.convert_notebooks()
201 211
202 212 def convert_notebooks(self):
203 213 """
204 214 Convert the notebooks in the self.notebook traitlet
205 215 """
206 216 # Export each notebook
207 217 conversion_success = 0
208 218 for notebook_filename in self.notebooks:
209 219
210 220 # Get a unique key for the notebook and set it in the resources object.
211 221 basename = os.path.basename(notebook_filename)
212 222 notebook_name = basename[:basename.rfind('.')]
213 223 resources = {}
214 224 resources['unique_key'] = notebook_name
215 225 resources['output_files_dir'] = '%s_files' % notebook_name
216 226
217 227 # Try to export
218 228 try:
219 229 output, resources = export_by_name(self.export_format,
220 230 notebook_filename,
221 231 resources=resources,
222 232 config=self.config)
223 233 except ExporterNameError as e:
224 234 print("Error while converting '%s': '%s' exporter not found."
225 235 %(notebook_filename, self.export_format),
226 236 file=sys.stderr)
227 237 print("Known exporters are:",
228 238 "\n\t" + "\n\t".join(get_export_names()),
229 239 file=sys.stderr)
230 240 self.exit(1)
231 241 except ConversionException as e:
232 242 print("Error while converting '%s': %s" %(notebook_filename, e),
233 243 file=sys.stderr)
234 244 self.exit(1)
235 245 else:
236 246 self.writer.write(output, resources, notebook_name=notebook_name)
237 247 conversion_success += 1
238 248
239 249 # If nothing was converted successfully, help the user.
240 250 if conversion_success == 0:
241 251 self.print_help()
242 252 sys.exit(-1)
243 253
244 254
245 255 #-----------------------------------------------------------------------------
246 256 # Main entry point
247 257 #-----------------------------------------------------------------------------
248 258
249 259 launch_new_instance = NbConvertApp.launch_instance
@@ -1,258 +1,260 b''
1 1 ((*- extends 'display_priority.tplx' -*))
2 2
3 \nonstopmode
4
3 5 ((* block in_prompt *))((* endblock in_prompt *))
4 6
5 7 ((* block output_prompt *))((* endblock output_prompt *))
6 8
7 9 ((* block codecell *))\begin{codecell}((( super() )))
8 10 \end{codecell}
9 11 ((* endblock *))
10 12
11 13 ((* block input *))
12 14 \begin{codeinput}
13 15 \begin{lstlisting}
14 16 ((( cell.input )))
15 17 \end{lstlisting}
16 18 \end{codeinput}
17 19 ((* endblock input *))
18 20
19 21
20 22 ((= Those Two are for error displaying
21 23 even if the first one seem to do nothing,
22 24 it introduces a new line
23 25
24 26 =))
25 27 ((* block pyerr *))
26 28 \begin{traceback}
27 29 \begin{verbatim}((( super() )))
28 30 \end{verbatim}
29 31 \end{traceback}
30 32 ((* endblock pyerr *))
31 33
32 34 ((* block traceback_line *))
33 35 ((( line |indent| strip_ansi )))((* endblock traceback_line *))
34 36 ((= .... =))
35 37
36 38
37 39 ((*- block output_group -*))
38 40 \begin{codeoutput}
39 41 ((( super() )))
40 42 \end{codeoutput}((* endblock *))
41 43
42 44 ((*- block data_png -*))
43 45 \begin{center}
44 46 \includegraphics[max size={0.7\textwidth}{0.9\textheight}]{(((output.png_filename)))}
45 47 \par
46 48 \end{center}
47 49 ((*- endblock -*))
48 50
49 51 ((*- block data_jpg -*))
50 52 \begin{center}
51 53 \includegraphics[max size={0.7\textwidth}{0.9\textheight}]{(((output.jpeg_filename)))}
52 54 \par
53 55 \end{center}
54 56 ((*- endblock -*))
55 57
56 58 ((*- block data_svg -*))
57 59 \begin{center}
58 60 \includegraphics[width=0.7\textwidth]{(((output.svg_filename)))}
59 61 \par
60 62 \end{center}
61 63 ((*- endblock -*))
62 64
63 65 ((*- block data_pdf -*))
64 66 \begin{center}
65 67 \includegraphics[width=0.7\textwidth]{(((output.pdf_filename)))}
66 68 \par
67 69 \end{center}
68 70 ((*- endblock -*))
69 71
70 72 ((* block pyout *))
71 73 ((* block data_priority scoped *))((( super() )))((* endblock *))
72 74 ((* endblock pyout *))
73 75
74 76 ((* block data_text *))
75 77 \begin{verbatim}
76 78 ((( output.text )))
77 79 \end{verbatim}
78 80 ((* endblock *))
79 81
80 82 ((* block data_latex -*))
81 83 ((*- if output.latex.startswith('$'): -*)) \begin{equation*}
82 84 ((( output.latex | strip_dollars)))
83 85 \end{equation*}
84 86 ((*- else -*)) ((( output.latex ))) ((*- endif *))
85 87 ((* endblock *))
86 88
87 89 ((* block stream *))
88 90 \begin{Verbatim}[commandchars=\\\{\}]
89 91 ((( output.text | ansi2latex)))
90 92 \end{Verbatim}
91 93 ((* endblock stream *))
92 94
93 95 ((* block markdowncell scoped *))((( cell.source | markdown2latex )))
94 96 ((* endblock markdowncell *))
95 97
96 98 ((* block headingcell scoped -*))
97 99 ((( ('#' * cell.level + cell.source) | replace('\n', ' ') | markdown2latex )))
98 100 ((* endblock headingcell *))
99 101
100 102 ((* block rawcell scoped *))
101 103 ((( cell.source | comment_lines )))
102 104 ((* endblock rawcell *))
103 105
104 106 ((* block unknowncell scoped *))
105 107 unknown type (((cell.type)))
106 108 ((* endblock unknowncell *))
107 109
108 110
109 111
110 112 ((* block body *))
111 113
112 114 ((* block bodyBegin *))
113 115 \begin{document}
114 116 ((* endblock bodyBegin *))
115 117
116 118 ((( super() )))
117 119
118 120 ((* block bodyEnd *))
119 121 \end{document}
120 122 ((* endblock bodyEnd *))
121 123 ((* endblock body *))
122 124
123 125 ((* block header *))
124 126 %% This file was auto-generated by IPython.
125 127 %% Conversion from the original notebook file:
126 128 %%
127 129 \documentclass[11pt,english]{article}
128 130
129 131 %% This is the automatic preamble used by IPython. Note that it does *not*
130 132 %% include a documentclass declaration, that is added at runtime to the overall
131 133 %% document.
132 134
133 135 \usepackage{amsmath}
134 136 \usepackage{amssymb}
135 137 \usepackage{graphicx}
136 138 \usepackage{ucs}
137 139 \usepackage[utf8x]{inputenc}
138 140
139 141 % Scale down larger images
140 142 \usepackage[export]{adjustbox}
141 143
142 144 %fancy verbatim
143 145 \usepackage{fancyvrb}
144 146 % needed for markdown enumerations to work
145 147 \usepackage{enumerate}
146 148
147 149 % Slightly bigger margins than the latex defaults
148 150 \usepackage{geometry}
149 151 \geometry{verbose,tmargin=3cm,bmargin=3cm,lmargin=2.5cm,rmargin=2.5cm}
150 152
151 153 % Define a few colors for use in code, links and cell shading
152 154 \usepackage{color}
153 155 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
154 156 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
155 157 \definecolor{darkgreen}{rgb}{.12,.54,.11}
156 158 \definecolor{myteal}{rgb}{.26, .44, .56}
157 159 \definecolor{gray}{gray}{0.45}
158 160 \definecolor{lightgray}{gray}{.95}
159 161 \definecolor{mediumgray}{gray}{.8}
160 162 \definecolor{inputbackground}{rgb}{.95, .95, .85}
161 163 \definecolor{outputbackground}{rgb}{.95, .95, .95}
162 164 \definecolor{traceback}{rgb}{1, .95, .95}
163 165
164 166 % new ansi colors
165 167 \definecolor{brown}{rgb}{0.54,0.27,0.07}
166 168 \definecolor{purple}{rgb}{0.5,0.0,0.5}
167 169 \definecolor{darkgray}{gray}{0.25}
168 170 \definecolor{lightred}{rgb}{1.0,0.39,0.28}
169 171 \definecolor{lightgreen}{rgb}{0.48,0.99,0.0}
170 172 \definecolor{lightblue}{rgb}{0.53,0.81,0.92}
171 173 \definecolor{lightpurple}{rgb}{0.87,0.63,0.87}
172 174 \definecolor{lightcyan}{rgb}{0.5,1.0,0.83}
173 175
174 176 % Framed environments for code cells (inputs, outputs, errors, ...). The
175 177 % various uses of \unskip (or not) at the end were fine-tuned by hand, so don't
176 178 % randomly change them unless you're sure of the effect it will have.
177 179 \usepackage{framed}
178 180
179 181 % remove extraneous vertical space in boxes
180 182 \setlength\fboxsep{0pt}
181 183
182 184 % codecell is the whole input+output set of blocks that a Code cell can
183 185 % generate.
184 186
185 187 % TODO: unfortunately, it seems that using a framed codecell environment breaks
186 188 % the ability of the frames inside of it to be broken across pages. This
187 189 % causes at least the problem of having lots of empty space at the bottom of
188 190 % pages as new frames are moved to the next page, and if a single frame is too
189 191 % long to fit on a page, will completely stop latex from compiling the
190 192 % document. So unless we figure out a solution to this, we'll have to instead
191 193 % leave the codecell env. as empty. I'm keeping the original codecell
192 194 % definition here (a thin vertical bar) for reference, in case we find a
193 195 % solution to the page break issue.
194 196
195 197 %% \newenvironment{codecell}{%
196 198 %% \def\FrameCommand{\color{mediumgray} \vrule width 1pt \hspace{5pt}}%
197 199 %% \MakeFramed{\vspace{-0.5em}}}
198 200 %% {\unskip\endMakeFramed}
199 201
200 202 % For now, make this a no-op...
201 203 \newenvironment{codecell}{}
202 204
203 205 \newenvironment{codeinput}{%
204 206 \def\FrameCommand{\colorbox{inputbackground}}%
205 207 \MakeFramed{\advance\hsize-\width \FrameRestore}}
206 208 {\unskip\endMakeFramed}
207 209
208 210 \newenvironment{codeoutput}{%
209 211 \def\FrameCommand{\colorbox{outputbackground}}%
210 212 \vspace{-1.4em}
211 213 \MakeFramed{\advance\hsize-\width \FrameRestore}}
212 214 {\unskip\medskip\endMakeFramed}
213 215
214 216 \newenvironment{traceback}{%
215 217 \def\FrameCommand{\colorbox{traceback}}%
216 218 \MakeFramed{\advance\hsize-\width \FrameRestore}}
217 219 {\endMakeFramed}
218 220
219 221 % Use and configure listings package for nicely formatted code
220 222 \usepackage{listingsutf8}
221 223 \lstset{
222 224 language=python,
223 225 inputencoding=utf8x,
224 226 extendedchars=\true,
225 227 aboveskip=\smallskipamount,
226 228 belowskip=\smallskipamount,
227 229 xleftmargin=2mm,
228 230 breaklines=true,
229 231 basicstyle=\small \ttfamily,
230 232 showstringspaces=false,
231 233 keywordstyle=\color{blue}\bfseries,
232 234 commentstyle=\color{myteal},
233 235 stringstyle=\color{darkgreen},
234 236 identifierstyle=\color{darkorange},
235 237 columns=fullflexible, % tighter character kerning, like verb
236 238 }
237 239
238 240 % The hyperref package gives us a pdf with properly built
239 241 % internal navigation ('pdf bookmarks' for the table of contents,
240 242 % internal cross-reference links, web links for URLs, etc.)
241 243 \usepackage{hyperref}
242 244 \hypersetup{
243 245 breaklinks=true, % so long urls are correctly broken across lines
244 246 colorlinks=true,
245 247 urlcolor=blue,
246 248 linkcolor=darkorange,
247 249 citecolor=darkgreen,
248 250 }
249 251
250 252 % hardcode size of all verbatim environments to be a bit smaller
251 253 \makeatletter
252 254 \g@addto@macro\@verbatim\small\topsep=0.5em\partopsep=0pt
253 255 \makeatother
254 256
255 257 % Prevent overflowing lines due to urls and other hard-to-break entities.
256 258 \sloppy
257 259
258 260 ((* endblock *))
@@ -1,450 +1,452 b''
1 1 ((= NBConvert Sphinx-Latex Template
2 2
3 3 Purpose: Allow export of PDF friendly Latex inspired by Sphinx. Most of the
4 4 template is derived directly from Sphinx source.
5 5
6 6 Inheritance: null>display_priority
7 7
8 8 Note: For best display, use latex syntax highlighting. =))
9 9
10 10 ((*- extends 'display_priority.tplx' -*))
11 11
12 \nonstopmode
13
12 14 %==============================================================================
13 15 % Declarations
14 16 %==============================================================================
15 17
16 18 % In order to make sure that the input/output header follows the code it
17 19 % preceeds, the needspace package is used to request that a certain
18 20 % amount of lines (specified by this variable) are reserved. If those
19 21 % lines aren't available on the current page, the documenter will break
20 22 % to the next page and the header along with accomanying lines will be
21 23 % rendered together. This value specifies the number of lines that
22 24 % the header will be forced to group with without a page break.
23 25 ((*- set min_header_lines = 4 -*))
24 26
25 27 % This is the number of characters that are permitted per line. It's
26 28 % important that this limit is set so characters do not run off the
27 29 % edges of latex pages (since latex does not always seem smart enough
28 30 % to prevent this in some cases.) This is only applied to textual output
29 31 ((* if resources.sphinx.outputstyle == 'simple' *))
30 32 ((*- set wrap_size = 85 -*))
31 33 ((* elif resources.sphinx.outputstyle == 'notebook' *))
32 34 ((*- set wrap_size = 70 -*))
33 35 ((* endif *))
34 36
35 37 %==============================================================================
36 38 % Header
37 39 %==============================================================================
38 40 ((* block header *))
39 41
40 42 % Header, overrides base
41 43
42 44 % Make sure that the sphinx doc style knows who it inherits from.
43 45 \def\sphinxdocclass{(((parentdocumentclass)))}
44 46
45 47 % Declare the document class
46 48 \documentclass[letterpaper,10pt,english]{((( resources.sphinx.texinputs )))/sphinx(((documentclass)))}
47 49
48 50 % Imports
49 51 \usepackage[utf8]{inputenc}
50 52 \DeclareUnicodeCharacter{00A0}{\\nobreakspace}
51 53 \usepackage[T1]{fontenc}
52 54 \usepackage{babel}
53 55 \usepackage{times}
54 56 \usepackage{import}
55 57 \usepackage[((( resources.sphinx.chapterstyle )))]{((( resources.sphinx.texinputs )))/fncychap}
56 58 \usepackage{longtable}
57 59 \usepackage{((( resources.sphinx.texinputs )))/sphinx}
58 60 \usepackage{multirow}
59 61
60 62 \usepackage{amsmath}
61 63 \usepackage{amssymb}
62 64 \usepackage{ucs}
63 65 \usepackage{enumerate}
64 66
65 67 % Used to make the Input/Output rules follow around the contents.
66 68 \usepackage{needspace}
67 69
68 70 % Pygments requirements
69 71 \usepackage{fancyvrb}
70 72 \usepackage{color}
71 73 % ansi colors additions
72 74 \definecolor{darkgreen}{rgb}{.12,.54,.11}
73 75 \definecolor{lightgray}{gray}{.95}
74 76 \definecolor{brown}{rgb}{0.54,0.27,0.07}
75 77 \definecolor{purple}{rgb}{0.5,0.0,0.5}
76 78 \definecolor{darkgray}{gray}{0.25}
77 79 \definecolor{lightred}{rgb}{1.0,0.39,0.28}
78 80 \definecolor{lightgreen}{rgb}{0.48,0.99,0.0}
79 81 \definecolor{lightblue}{rgb}{0.53,0.81,0.92}
80 82 \definecolor{lightpurple}{rgb}{0.87,0.63,0.87}
81 83 \definecolor{lightcyan}{rgb}{0.5,1.0,0.83}
82 84
83 85 % Needed to box output/input
84 86 \usepackage{tikz}
85 87 \usetikzlibrary{calc,arrows,shadows}
86 88 \usepackage[framemethod=tikz]{mdframed}
87 89
88 90 \usepackage{alltt}
89 91
90 92 % Used to load and display graphics
91 93 \usepackage{graphicx}
92 94 \graphicspath{ {figs/} }
93 95 \usepackage[Export]{adjustbox} % To resize
94 96
95 97
96 98 % For formatting output while also word wrapping.
97 99 \usepackage{listings}
98 100 \lstset{breaklines=true}
99 101 \lstset{basicstyle=\small\ttfamily}
100 102 \def\smaller{\fontsize{9.5pt}{9.5pt}\selectfont}
101 103
102 104 %Pygments definitions
103 105 ((( resources.sphinx.pygment_definitions )))
104 106
105 107 %Set pygments styles if needed...
106 108 ((* if resources.sphinx.outputstyle == 'notebook' *))
107 109 \definecolor{nbframe-border}{rgb}{0.867,0.867,0.867}
108 110 \definecolor{nbframe-bg}{rgb}{0.969,0.969,0.969}
109 111 \definecolor{nbframe-in-prompt}{rgb}{0.0,0.0,0.502}
110 112 \definecolor{nbframe-out-prompt}{rgb}{0.545,0.0,0.0}
111 113
112 114 \newenvironment{ColorVerbatim}
113 115 {\begin{mdframed}[%
114 116 roundcorner=1.0pt, %
115 117 backgroundcolor=nbframe-bg, %
116 118 userdefinedwidth=1\linewidth, %
117 119 leftmargin=0.1\linewidth, %
118 120 innerleftmargin=0pt, %
119 121 innerrightmargin=0pt, %
120 122 linecolor=nbframe-border, %
121 123 linewidth=1pt, %
122 124 usetwoside=false, %
123 125 everyline=true, %
124 126 innerlinewidth=3pt, %
125 127 innerlinecolor=nbframe-bg, %
126 128 middlelinewidth=1pt, %
127 129 middlelinecolor=nbframe-bg, %
128 130 outerlinewidth=0.5pt, %
129 131 outerlinecolor=nbframe-border, %
130 132 needspace=0pt
131 133 ]}
132 134 {\end{mdframed}}
133 135
134 136 \newenvironment{InvisibleVerbatim}
135 137 {\begin{mdframed}[leftmargin=0.1\linewidth,innerleftmargin=3pt,innerrightmargin=3pt, userdefinedwidth=1\linewidth, linewidth=0pt, linecolor=white, usetwoside=false]}
136 138 {\end{mdframed}}
137 139
138 140 \renewenvironment{Verbatim}[1][\unskip]
139 141 {\begin{alltt}\smaller}
140 142 {\end{alltt}}
141 143 ((* endif *))
142 144
143 145 % Help prevent overflowing lines due to urls and other hard-to-break
144 146 % entities. This doesn't catch everything...
145 147 \sloppy
146 148
147 149 % Document level variables
148 150 \title{((( resources.metadata.name | escape_latex )))}
149 151 \date{((( resources.sphinx.date | escape_latex )))}
150 152 \release{((( resources.sphinx.version | escape_latex )))}
151 153 \author{((( resources.sphinx.author | escape_latex )))}
152 154 \renewcommand{\releasename}{((( resources.sphinx.release | escape_latex )))}
153 155
154 156 % TODO: Add option for the user to specify a logo for his/her export.
155 157 \newcommand{\sphinxlogo}{}
156 158
157 159 % Make the index page of the document.
158 160 \makeindex
159 161
160 162 % Import sphinx document type specifics.
161 163 ((* block sphinxheader *))((* endblock sphinxheader *))
162 164 ((* endblock header *))
163 165
164 166 %==============================================================================
165 167 % Body
166 168 %==============================================================================
167 169 ((* block body *))
168 170 ((* block bodyBegin *))
169 171 % Body
170 172
171 173 % Start of the document
172 174 \begin{document}
173 175
174 176 ((* if resources.sphinx.header *))
175 177 \maketitle
176 178 ((* endif *))
177 179
178 180 ((* block toc *))
179 181 \tableofcontents
180 182 ((* endblock toc *))
181 183
182 184 ((* endblock bodyBegin *))((( super() )))((* block bodyEnd *))
183 185
184 186 \renewcommand{\indexname}{Index}
185 187 \printindex
186 188
187 189 % End of document
188 190 \end{document}
189 191 ((* endblock bodyEnd *))
190 192 ((* endblock body *))
191 193
192 194 %==============================================================================
193 195 % Footer
194 196 %==============================================================================
195 197 ((* block footer *))
196 198 ((* endblock footer *))
197 199
198 200 %==============================================================================
199 201 % Headings
200 202 %
201 203 % Purpose: Format pynb headers as sphinx headers. Depending on the Sphinx
202 204 % style that is active, this will change. Thus sphinx styles will
203 205 % override the values here.
204 206 %==============================================================================
205 207 ((* block headingcell -*))
206 208 \
207 209 ((*- if cell.level == 1 -*))
208 210 ((* block h1 -*))part((* endblock h1 -*))
209 211 ((*- elif cell.level == 2 -*))
210 212 ((* block h2 -*))chapter((* endblock h2 -*))
211 213 ((*- elif cell.level == 3 -*))
212 214 ((* block h3 -*))section((* endblock h3 -*))
213 215 ((*- elif cell.level == 4 -*))
214 216 ((* block h4 -*))subsection((* endblock h4 -*))
215 217 ((*- elif cell.level == 5 -*))
216 218 ((* block h5 -*))subsubsection((* endblock h5 -*))
217 219 ((*- elif cell.level == 6 -*))
218 220 ((* block h6 -*))paragraph((* endblock h6 -*))
219 221
220 222 ((= It's important to make sure that underscores (which tend to be common
221 223 in IPYNB file titles) do not make their way into latex. Sometimes this
222 224 causes latex to barf. =))
223 225 ((*- endif -*)){((( cell.source | markdown2latex )))}
224 226 ((*- endblock headingcell *))
225 227
226 228 %==============================================================================
227 229 % Markdown
228 230 %
229 231 % Purpose: Convert markdown to latex. Here markdown2latex is explicitly
230 232 % called since we know we want latex output.
231 233 %==============================================================================
232 234 ((*- block markdowncell scoped-*))
233 235 ((( cell.source | markdown2latex )))
234 236 ((*- endblock markdowncell -*))
235 237
236 238 %==============================================================================
237 239 % Rawcell
238 240 %
239 241 % Purpose: Raw text cells allow the user to manually inject document code that
240 242 % will not get touched by the templating system.
241 243 %==============================================================================
242 244 ((*- block rawcell *))
243 245 ((( cell.source | wrap_text(wrap_size) )))
244 246 ((* endblock rawcell -*))
245 247
246 248 %==============================================================================
247 249 % Unknowncell
248 250 %
249 251 % Purpose: This is the catch anything unhandled. To display this data, we
250 252 % remove all possible latex conflicts and wrap the characters so they
251 253 % can't flow off of the page.
252 254 %==============================================================================
253 255 ((* block unknowncell scoped*))
254 256
255 257 % Unsupported cell type, no formatting
256 258 ((( cell.source | wrap_text | escape_latex )))
257 259 ((* endblock unknowncell *))
258 260
259 261 %==============================================================================
260 262 % Input
261 263 %==============================================================================
262 264 ((* block input *))
263 265
264 266 % Make sure that atleast 4 lines are below the HR
265 267 \needspace{((( min_header_lines )))\baselineskip}
266 268
267 269 ((* if resources.sphinx.outputstyle == 'simple' *))
268 270
269 271 % Add a horizantal break, along with break title.
270 272 \vspace{10pt}
271 273 {\scriptsize Input}\\*
272 274 \rule[10pt]{\linewidth}{0.5pt}
273 275 \vspace{-25pt}
274 276
275 277 % Add contents below.
276 278 ((( cell.input | highlight2latex )))
277 279
278 280 ((* elif resources.sphinx.outputstyle == 'notebook' *))
279 281 \vspace{6pt}
280 282 ((( write_prompt("In", cell.prompt_number, "nbframe-in-prompt") )))
281 283 \vspace{-2.65\baselineskip}
282 284 \begin{ColorVerbatim}
283 285 \vspace{-0.7\baselineskip}
284 286 ((( cell.input | highlight2latex )))
285 287 ((* if cell.input == None or cell.input == '' *))
286 288 \vspace{0.3\baselineskip}
287 289 ((* else *))
288 290 \vspace{-0.2\baselineskip}
289 291 ((* endif *))
290 292 \end{ColorVerbatim}
291 293 ((* endif *))
292 294 ((* endblock input *))
293 295
294 296 %==============================================================================
295 297 % Output_Group
296 298 %
297 299 % Purpose: Make sure that only one header bar only attaches to the output
298 300 % once. By keeping track of when an input group is started
299 301 %==============================================================================
300 302 ((* block output_group *))
301 303 ((* if cell.outputs.__len__() > 0 *))
302 304
303 305 % If the first block is an image, minipage the image. Else
304 306 % request a certain amount of space for the input text.
305 307 ((( iff_figure(cell.outputs[0], "\\begin{minipage}{1.0\\textwidth}", "\\needspace{" ~ min_header_lines ~ "\\baselineskip}") )))
306 308
307 309 ((* if resources.sphinx.outputstyle == 'simple' *))
308 310
309 311 % Add a horizantal break, along with break title.
310 312 \vspace{10pt}
311 313 {\scriptsize Output}\\*
312 314 \rule[10pt]{\linewidth}{0.5pt}
313 315 \vspace{-20pt}
314 316
315 317 % Add the contents of the first block.
316 318 ((( render_output(cell.outputs[0]) )))
317 319
318 320 % Close the minipage.
319 321 ((( iff_figure(cell.outputs[0], "\\end{minipage}", "") )))
320 322
321 323 % Add remainer of the document contents below.
322 324 ((* for output in cell.outputs[1:] *))
323 325 ((( render_output(output, cell.prompt_number) )))
324 326 ((* endfor *))
325 327 ((* elif resources.sphinx.outputstyle == 'notebook' *))
326 328
327 329 % Add document contents.
328 330 ((* for output in cell.outputs *))
329 331 ((( render_output(output, cell.prompt_number) )))
330 332 ((* endfor *))
331 333 ((* endif *))
332 334 ((* endif *))
333 335 ((* endblock *))
334 336
335 337 %==============================================================================
336 338 % Additional formating
337 339 %==============================================================================
338 340 ((* block data_text *))
339 341 ((( custom_verbatim(output.text) | ansi2latex)))
340 342 ((* endblock *))
341 343
342 344 ((* block traceback_line *))
343 345 ((( conditionally_center_output(line | indent| strip_ansi) )))
344 346 ((* endblock traceback_line *))
345 347
346 348 %==============================================================================
347 349 % Supported image formats
348 350 %==============================================================================
349 351 ((*- block data_png -*))
350 352 ((( conditionally_center_output(insert_graphics(output.png_filename)) )))
351 353 ((*- endblock -*))
352 354
353 355 ((*- block data_jpg -*))
354 356 ((( conditionally_center_output(insert_graphics(output.jpg_filename)) )))
355 357 ((*- endblock -*))
356 358
357 359 ((*- block data_svg -*))
358 360 ((( conditionally_center_output(insert_graphics(output.svg_filename)) )))
359 361 ((*- endblock -*))
360 362
361 363 ((*- block data_pdf -*))
362 364 ((( conditionally_center_output(insert_graphics(output.pdf_filename)) )))
363 365 ((*- endblock -*))
364 366
365 367 ((*- block data_latex *))
366 368 ((* if resources.sphinx.centeroutput *))\begin{center}((* endif -*))((( output.latex | strip_math_space )))((*- if resources.sphinx.centeroutput *))\end{center} ((* endif -*))
367 369 ((*- endblock -*))
368 370
369 371 %==============================================================================
370 372 % Support Macros
371 373 %==============================================================================
372 374
373 375 % Name: write_prompt
374 376 % Purpose: Renders an output/input prompt for notebook style pdfs
375 377 ((* macro write_prompt(prompt, number, color) -*))
376 378 \makebox[0.1\linewidth]{\smaller\hfill\tt\color{((( color )))}((( prompt )))\hspace{4pt}{[}((( number ))){]}:\hspace{4pt}}\\*
377 379 ((*- endmacro *))
378 380
379 381 % Name: render_output
380 382 % Purpose: Renders an output block appropriately.
381 383 ((* macro render_output(output, prompt_number) -*))
382 384 ((*- if output.output_type == 'pyerr' -*))
383 385 ((*- block pyerr scoped *))
384 386 ((( custom_verbatim(super()) )))
385 387 ((* endblock pyerr -*))
386 388 ((*- else -*))
387 389
388 390 ((* if resources.sphinx.outputstyle == 'notebook' *))
389 391 ((*- if output.output_type == 'pyout' -*))
390 392 ((( write_prompt("Out", prompt_number, "nbframe-out-prompt") )))
391 393 \vspace{-2.55\baselineskip}
392 394 ((*- endif -*))
393 395
394 396 \begin{InvisibleVerbatim}
395 397 \vspace{-0.5\baselineskip}
396 398 ((*- endif -*))
397 399
398 400 ((*- block display_data scoped -*))
399 401 ((( super() )))
400 402 ((*- endblock display_data -*))
401 403
402 404 ((* if resources.sphinx.outputstyle == 'notebook' *))
403 405 \end{InvisibleVerbatim}
404 406 ((*- endif -*))
405 407 ((*- endif -*))
406 408 ((*- endmacro *))
407 409
408 410 % Name: iff_figure
409 411 % Purpose: If the output block provided is a figure type, the 'true_content'
410 412 % parameter will be returned. Else, the 'false_content'.
411 413 ((* macro iff_figure(output, true_content, false_content) -*))
412 414 ((*- set is_figure = false -*))
413 415 ((*- for type in output | filter_data_type -*))
414 416 ((*- if type in ['pdf', 'svg', 'png', 'jpeg','html']*))
415 417 ((*- set is_figure = true -*))
416 418 ((*- endif -*))
417 419 ((*- endfor -*))
418 420
419 421 ((* if is_figure -*))
420 422 ((( true_content )))
421 423 ((*- else -*))
422 424 ((( false_content )))
423 425 ((*- endif *))
424 426 ((*- endmacro *))
425 427
426 428 % Name: custom_verbatim
427 429 % Purpose: This macro creates a verbatim style block that fits the existing
428 430 % sphinx style more readily than standard verbatim blocks.
429 431 ((* macro custom_verbatim(text) -*))
430 432 \begin{alltt}
431 433 ((*- if resources.sphinx.centeroutput *))\begin{center} ((* endif -*))
432 434 ((( text | wrap_text(wrap_size) )))
433 435 ((*- if resources.sphinx.centeroutput *))\end{center}((* endif -*))
434 436 \end{alltt}
435 437 ((*- endmacro *))
436 438
437 439 % Name: conditionally_center_output
438 440 % Purpose: This macro centers the output if the output centering is enabled.
439 441 ((* macro conditionally_center_output(text) -*))
440 442 ((* if resources.sphinx.centeroutput *)){\centering ((* endif *))((( text )))((* if resources.sphinx.centeroutput *))}((* endif *))
441 443 ((*- endmacro *))
442 444
443 445 % Name: insert_graphics
444 446 % Purpose: This macro will insert an image in the latex document given a path.
445 447 ((* macro insert_graphics(path) -*))
446 448 \begin{center}
447 449 \includegraphics[max size={\textwidth}{\textheight}]{(((path)))}
448 450 \par
449 451 \end{center}
450 452 ((*- endmacro *))
@@ -1,2 +1,3 b''
1 1 from .files import FilesWriter
2 2 from .stdout import StdoutWriter
3 from .pdf import PDFWriter
@@ -1,102 +1,103 b''
1 1 #!/usr/bin/env python
2 2 """
3 3 Contains writer for writing nbconvert output to filesystem.
4 4 """
5 5 #-----------------------------------------------------------------------------
6 6 #Copyright (c) 2013, the IPython Development Team.
7 7 #
8 8 #Distributed under the terms of the Modified BSD License.
9 9 #
10 10 #The full license is in the file COPYING.txt, distributed with this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import io
18 18 import os
19 19 import glob
20 20
21 21 from IPython.utils.traitlets import Unicode
22 22 from IPython.utils.path import link_or_copy
23 23
24 24 from .base import WriterBase
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Classes
28 28 #-----------------------------------------------------------------------------
29 29
30 30 class FilesWriter(WriterBase):
31 31 """Consumes nbconvert output and produces files."""
32 32
33 33
34 34 build_directory = Unicode(".", config=True,
35 35 help="""Directory to write output to. Leave blank
36 36 to output to the current directory""")
37 37
38 38
39 39 # Make sure that the output directory exists.
40 40 def _build_directory_changed(self, name, old, new):
41 41 if new and not os.path.isdir(new):
42 42 os.makedirs(new)
43 43
44 44
45 45 def __init__(self, **kw):
46 46 super(FilesWriter, self).__init__(**kw)
47 47 self._build_directory_changed('build_directory', self.build_directory,
48 48 self.build_directory)
49 49
50 50
51 51 def write(self, output, resources, notebook_name=None, **kw):
52 52 """
53 53 Consume and write Jinja output to the file system. Output directory
54 54 is set via the 'build_directory' variable of this instance (a
55 55 configurable).
56 56
57 57 See base for more...
58 58 """
59 59
60 60 # Pull the extension and subdir from the resources dict.
61 61 output_extension = resources['output_extension']
62 62
63 63 # Write all of the extracted resources to the destination directory.
64 64 # NOTE: WE WRITE EVERYTHING AS-IF IT'S BINARY. THE EXTRACT FIG
65 65 # TRANSFORMER SHOULD HANDLE UNIX/WINDOWS LINE ENDINGS...
66 66 for filename, data in resources.get('outputs', {}).items():
67 67
68 68 # Determine where to write the file to
69 69 dest = os.path.join(self.build_directory, filename)
70 70 path = os.path.dirname(dest)
71 71 if not os.path.isdir(path):
72 72 os.makedirs(path)
73 73
74 74 # Write file
75 75 with io.open(dest, 'wb') as f:
76 76 f.write(data)
77 77
78 78 # Copy referenced files to output directory
79 79 if self.build_directory:
80 80 for filename in self.files:
81 81
82 82 # Copy files that match search pattern
83 83 for matching_filename in glob.glob(filename):
84 84
85 85 # Make sure folder exists.
86 86 dest = os.path.join(self.build_directory, filename)
87 87 path = os.path.dirname(dest)
88 88 if not os.path.isdir(path):
89 89 os.makedirs(path)
90 90
91 91 # Copy if destination is different.
92 92 if not os.path.normpath(dest) == os.path.normpath(matching_filename):
93 93 link_or_copy(matching_filename, dest)
94 94
95 95 # Determine where to write conversion results.
96 96 dest = notebook_name + '.' + output_extension
97 97 if self.build_directory:
98 98 dest = os.path.join(self.build_directory, dest)
99 99
100 100 # Write conversion results.
101 101 with io.open(dest, 'w') as f:
102 102 f.write(output)
103 return dest No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now