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