##// END OF EJS Templates
Merge pull request #4174 from minrk/markup-templates...
Min RK -
r12461:8c88aec6 merge
parent child Browse files
Show More
@@ -1,519 +1,520 b''
1 """This module defines Exporter, a highly configurable converter
1 """This module defines Exporter, a highly configurable converter
2 that uses Jinja2 to export notebook files into different formats.
2 that uses Jinja2 to export notebook files into different formats.
3 """
3 """
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 from __future__ import print_function, absolute_import
17 from __future__ import print_function, absolute_import
18
18
19 # Stdlib imports
19 # Stdlib imports
20 import io
20 import io
21 import os
21 import os
22 import inspect
22 import inspect
23 import copy
23 import copy
24 import collections
24 import collections
25 import datetime
25 import datetime
26
26
27 # other libs/dependencies
27 # other libs/dependencies
28 from jinja2 import Environment, FileSystemLoader, ChoiceLoader, TemplateNotFound
28 from jinja2 import Environment, FileSystemLoader, ChoiceLoader, TemplateNotFound
29
29
30 # IPython imports
30 # IPython imports
31 from IPython.config.configurable import LoggingConfigurable
31 from IPython.config.configurable import LoggingConfigurable
32 from IPython.config import Config
32 from IPython.config import Config
33 from IPython.nbformat import current as nbformat
33 from IPython.nbformat import current as nbformat
34 from IPython.utils.traitlets import MetaHasTraits, DottedObjectName, Unicode, List, Dict, Any
34 from IPython.utils.traitlets import MetaHasTraits, DottedObjectName, Unicode, List, Dict, Any
35 from IPython.utils.importstring import import_item
35 from IPython.utils.importstring import import_item
36 from IPython.utils import text
36 from IPython.utils import text
37 from IPython.utils import py3compat
37 from IPython.utils import py3compat
38
38
39 from IPython.nbconvert import preprocessors as nbpreprocessors
39 from IPython.nbconvert import preprocessors as nbpreprocessors
40 from IPython.nbconvert import filters
40 from IPython.nbconvert import filters
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals and constants
43 # Globals and constants
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45
45
46 #Jinja2 extensions to load.
46 #Jinja2 extensions to load.
47 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
47 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
48
48
49 default_filters = {
49 default_filters = {
50 'indent': text.indent,
50 'indent': text.indent,
51 'markdown2html': filters.markdown2html,
51 'markdown2html': filters.markdown2html,
52 'ansi2html': filters.ansi2html,
52 'ansi2html': filters.ansi2html,
53 'filter_data_type': filters.DataTypeFilter,
53 'filter_data_type': filters.DataTypeFilter,
54 'get_lines': filters.get_lines,
54 'get_lines': filters.get_lines,
55 'highlight2html': filters.highlight2html,
55 'highlight2html': filters.highlight2html,
56 'highlight2latex': filters.highlight2latex,
56 'highlight2latex': filters.highlight2latex,
57 'ipython2python': filters.ipython2python,
57 'ipython2python': filters.ipython2python,
58 'posix_path': filters.posix_path,
58 'posix_path': filters.posix_path,
59 'markdown2latex': filters.markdown2latex,
59 'markdown2latex': filters.markdown2latex,
60 'markdown2rst': filters.markdown2rst,
60 'markdown2rst': filters.markdown2rst,
61 'comment_lines': filters.comment_lines,
61 'comment_lines': filters.comment_lines,
62 'strip_ansi': filters.strip_ansi,
62 'strip_ansi': filters.strip_ansi,
63 'strip_dollars': filters.strip_dollars,
63 'strip_dollars': filters.strip_dollars,
64 'strip_files_prefix': filters.strip_files_prefix,
64 'strip_files_prefix': filters.strip_files_prefix,
65 'html2text' : filters.html2text,
65 'html2text' : filters.html2text,
66 'add_anchor': filters.add_anchor,
66 'add_anchor': filters.add_anchor,
67 'ansi2latex': filters.ansi2latex,
67 'ansi2latex': filters.ansi2latex,
68 'strip_math_space': filters.strip_math_space,
68 'strip_math_space': filters.strip_math_space,
69 'wrap_text': filters.wrap_text,
69 'wrap_text': filters.wrap_text,
70 'escape_latex': filters.escape_latex,
70 'escape_latex': filters.escape_latex,
71 'citation2latex': filters.citation2latex
71 'citation2latex': filters.citation2latex,
72 'path2url': filters.path2url,
72 }
73 }
73
74
74 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
75 # Class
76 # Class
76 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
77
78
78 class ResourcesDict(collections.defaultdict):
79 class ResourcesDict(collections.defaultdict):
79 def __missing__(self, key):
80 def __missing__(self, key):
80 return ''
81 return ''
81
82
82
83
83 class Exporter(LoggingConfigurable):
84 class Exporter(LoggingConfigurable):
84 """
85 """
85 Exports notebooks into other file formats. Uses Jinja 2 templating engine
86 Exports notebooks into other file formats. Uses Jinja 2 templating engine
86 to output new formats. Inherit from this class if you are creating a new
87 to output new formats. Inherit from this class if you are creating a new
87 template type along with new filters/preprocessors. If the filters/
88 template type along with new filters/preprocessors. If the filters/
88 preprocessors provided by default suffice, there is no need to inherit from
89 preprocessors provided by default suffice, there is no need to inherit from
89 this class. Instead, override the template_file and file_extension
90 this class. Instead, override the template_file and file_extension
90 traits via a config file.
91 traits via a config file.
91
92
92 {filters}
93 {filters}
93 """
94 """
94
95
95 # finish the docstring
96 # finish the docstring
96 __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
97 __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
97
98
98
99
99 template_file = Unicode(u'default',
100 template_file = Unicode(u'default',
100 config=True,
101 config=True,
101 help="Name of the template file to use")
102 help="Name of the template file to use")
102 def _template_file_changed(self, name, old, new):
103 def _template_file_changed(self, name, old, new):
103 if new=='default':
104 if new=='default':
104 self.template_file = self.default_template
105 self.template_file = self.default_template
105 else:
106 else:
106 self.template_file = new
107 self.template_file = new
107 self.template = None
108 self.template = None
108 self._load_template()
109 self._load_template()
109
110
110 default_template = Unicode(u'')
111 default_template = Unicode(u'')
111 template = Any()
112 template = Any()
112 environment = Any()
113 environment = Any()
113
114
114 file_extension = Unicode(
115 file_extension = Unicode(
115 'txt', config=True,
116 'txt', config=True,
116 help="Extension of the file that should be written to disk"
117 help="Extension of the file that should be written to disk"
117 )
118 )
118
119
119 template_path = List(['.'], config=True)
120 template_path = List(['.'], config=True)
120 def _template_path_changed(self, name, old, new):
121 def _template_path_changed(self, name, old, new):
121 self._load_template()
122 self._load_template()
122
123
123 default_template_path = Unicode(
124 default_template_path = Unicode(
124 os.path.join("..", "templates"),
125 os.path.join("..", "templates"),
125 help="Path where the template files are located.")
126 help="Path where the template files are located.")
126
127
127 template_skeleton_path = Unicode(
128 template_skeleton_path = Unicode(
128 os.path.join("..", "templates", "skeleton"),
129 os.path.join("..", "templates", "skeleton"),
129 help="Path where the template skeleton files are located.")
130 help="Path where the template skeleton files are located.")
130
131
131 #Jinja block definitions
132 #Jinja block definitions
132 jinja_comment_block_start = Unicode("", config=True)
133 jinja_comment_block_start = Unicode("", config=True)
133 jinja_comment_block_end = Unicode("", config=True)
134 jinja_comment_block_end = Unicode("", config=True)
134 jinja_variable_block_start = Unicode("", config=True)
135 jinja_variable_block_start = Unicode("", config=True)
135 jinja_variable_block_end = Unicode("", config=True)
136 jinja_variable_block_end = Unicode("", config=True)
136 jinja_logic_block_start = Unicode("", config=True)
137 jinja_logic_block_start = Unicode("", config=True)
137 jinja_logic_block_end = Unicode("", config=True)
138 jinja_logic_block_end = Unicode("", config=True)
138
139
139 #Extension that the template files use.
140 #Extension that the template files use.
140 template_extension = Unicode(".tpl", config=True)
141 template_extension = Unicode(".tpl", config=True)
141
142
142 #Configurability, allows the user to easily add filters and preprocessors.
143 #Configurability, allows the user to easily add filters and preprocessors.
143 preprocessors = List(config=True,
144 preprocessors = List(config=True,
144 help="""List of preprocessors, by name or namespace, to enable.""")
145 help="""List of preprocessors, by name or namespace, to enable.""")
145
146
146 filters = Dict(config=True,
147 filters = Dict(config=True,
147 help="""Dictionary of filters, by name and namespace, to add to the Jinja
148 help="""Dictionary of filters, by name and namespace, to add to the Jinja
148 environment.""")
149 environment.""")
149
150
150 default_preprocessors = List([nbpreprocessors.coalesce_streams,
151 default_preprocessors = List([nbpreprocessors.coalesce_streams,
151 nbpreprocessors.SVG2PDFPreprocessor,
152 nbpreprocessors.SVG2PDFPreprocessor,
152 nbpreprocessors.ExtractOutputPreprocessor,
153 nbpreprocessors.ExtractOutputPreprocessor,
153 nbpreprocessors.CSSHTMLHeaderPreprocessor,
154 nbpreprocessors.CSSHTMLHeaderPreprocessor,
154 nbpreprocessors.RevealHelpPreprocessor,
155 nbpreprocessors.RevealHelpPreprocessor,
155 nbpreprocessors.LatexPreprocessor,
156 nbpreprocessors.LatexPreprocessor,
156 nbpreprocessors.SphinxPreprocessor],
157 nbpreprocessors.SphinxPreprocessor],
157 config=True,
158 config=True,
158 help="""List of preprocessors available by default, by name, namespace,
159 help="""List of preprocessors available by default, by name, namespace,
159 instance, or type.""")
160 instance, or type.""")
160
161
161
162
162 def __init__(self, config=None, extra_loaders=None, **kw):
163 def __init__(self, config=None, extra_loaders=None, **kw):
163 """
164 """
164 Public constructor
165 Public constructor
165
166
166 Parameters
167 Parameters
167 ----------
168 ----------
168 config : config
169 config : config
169 User configuration instance.
170 User configuration instance.
170 extra_loaders : list[of Jinja Loaders]
171 extra_loaders : list[of Jinja Loaders]
171 ordered list of Jinja loader to find templates. Will be tried in order
172 ordered list of Jinja loader to find templates. Will be tried in order
172 before the default FileSystem ones.
173 before the default FileSystem ones.
173 template : str (optional, kw arg)
174 template : str (optional, kw arg)
174 Template to use when exporting.
175 Template to use when exporting.
175 """
176 """
176 if not config:
177 if not config:
177 config = self.default_config
178 config = self.default_config
178
179
179 super(Exporter, self).__init__(config=config, **kw)
180 super(Exporter, self).__init__(config=config, **kw)
180
181
181 #Init
182 #Init
182 self._init_template()
183 self._init_template()
183 self._init_environment(extra_loaders=extra_loaders)
184 self._init_environment(extra_loaders=extra_loaders)
184 self._init_preprocessors()
185 self._init_preprocessors()
185 self._init_filters()
186 self._init_filters()
186
187
187
188
188 @property
189 @property
189 def default_config(self):
190 def default_config(self):
190 return Config()
191 return Config()
191
192
192 def _config_changed(self, name, old, new):
193 def _config_changed(self, name, old, new):
193 """When setting config, make sure to start with our default_config"""
194 """When setting config, make sure to start with our default_config"""
194 c = self.default_config
195 c = self.default_config
195 if new:
196 if new:
196 c.merge(new)
197 c.merge(new)
197 if c != old:
198 if c != old:
198 self.config = c
199 self.config = c
199 super(Exporter, self)._config_changed(name, old, c)
200 super(Exporter, self)._config_changed(name, old, c)
200
201
201
202
202 def _load_template(self):
203 def _load_template(self):
203 """Load the Jinja template object from the template file
204 """Load the Jinja template object from the template file
204
205
205 This is a no-op if the template attribute is already defined,
206 This is a no-op if the template attribute is already defined,
206 or the Jinja environment is not setup yet.
207 or the Jinja environment is not setup yet.
207
208
208 This is triggered by various trait changes that would change the template.
209 This is triggered by various trait changes that would change the template.
209 """
210 """
210 if self.template is not None:
211 if self.template is not None:
211 return
212 return
212 # called too early, do nothing
213 # called too early, do nothing
213 if self.environment is None:
214 if self.environment is None:
214 return
215 return
215 # Try different template names during conversion. First try to load the
216 # Try different template names during conversion. First try to load the
216 # template by name with extension added, then try loading the template
217 # template by name with extension added, then try loading the template
217 # as if the name is explicitly specified, then try the name as a
218 # as if the name is explicitly specified, then try the name as a
218 # 'flavor', and lastly just try to load the template by module name.
219 # 'flavor', and lastly just try to load the template by module name.
219 module_name = self.__module__.rsplit('.', 1)[-1]
220 module_name = self.__module__.rsplit('.', 1)[-1]
220 try_names = []
221 try_names = []
221 if self.template_file:
222 if self.template_file:
222 try_names.extend([
223 try_names.extend([
223 self.template_file + self.template_extension,
224 self.template_file + self.template_extension,
224 self.template_file,
225 self.template_file,
225 module_name + '_' + self.template_file + self.template_extension,
226 module_name + '_' + self.template_file + self.template_extension,
226 ])
227 ])
227 try_names.append(module_name + self.template_extension)
228 try_names.append(module_name + self.template_extension)
228 for try_name in try_names:
229 for try_name in try_names:
229 self.log.debug("Attempting to load template %s", try_name)
230 self.log.debug("Attempting to load template %s", try_name)
230 try:
231 try:
231 self.template = self.environment.get_template(try_name)
232 self.template = self.environment.get_template(try_name)
232 except (TemplateNotFound, IOError):
233 except (TemplateNotFound, IOError):
233 pass
234 pass
234 except Exception as e:
235 except Exception as e:
235 self.log.warn("Unexpected exception loading template: %s", try_name, exc_info=True)
236 self.log.warn("Unexpected exception loading template: %s", try_name, exc_info=True)
236 else:
237 else:
237 self.log.info("Loaded template %s", try_name)
238 self.log.info("Loaded template %s", try_name)
238 break
239 break
239
240
240 def from_notebook_node(self, nb, resources=None, **kw):
241 def from_notebook_node(self, nb, resources=None, **kw):
241 """
242 """
242 Convert a notebook from a notebook node instance.
243 Convert a notebook from a notebook node instance.
243
244
244 Parameters
245 Parameters
245 ----------
246 ----------
246 nb : Notebook node
247 nb : Notebook node
247 resources : dict (**kw)
248 resources : dict (**kw)
248 of additional resources that can be accessed read/write by
249 of additional resources that can be accessed read/write by
249 preprocessors and filters.
250 preprocessors and filters.
250 """
251 """
251 nb_copy = copy.deepcopy(nb)
252 nb_copy = copy.deepcopy(nb)
252 resources = self._init_resources(resources)
253 resources = self._init_resources(resources)
253
254
254 # Preprocess
255 # Preprocess
255 nb_copy, resources = self._preprocess(nb_copy, resources)
256 nb_copy, resources = self._preprocess(nb_copy, resources)
256
257
257 self._load_template()
258 self._load_template()
258
259
259 if self.template is not None:
260 if self.template is not None:
260 output = self.template.render(nb=nb_copy, resources=resources)
261 output = self.template.render(nb=nb_copy, resources=resources)
261 else:
262 else:
262 raise IOError('template file "%s" could not be found' % self.template_file)
263 raise IOError('template file "%s" could not be found' % self.template_file)
263 return output, resources
264 return output, resources
264
265
265
266
266 def from_filename(self, filename, resources=None, **kw):
267 def from_filename(self, filename, resources=None, **kw):
267 """
268 """
268 Convert a notebook from a notebook file.
269 Convert a notebook from a notebook file.
269
270
270 Parameters
271 Parameters
271 ----------
272 ----------
272 filename : str
273 filename : str
273 Full filename of the notebook file to open and convert.
274 Full filename of the notebook file to open and convert.
274 """
275 """
275
276
276 #Pull the metadata from the filesystem.
277 #Pull the metadata from the filesystem.
277 if resources is None:
278 if resources is None:
278 resources = ResourcesDict()
279 resources = ResourcesDict()
279 if not 'metadata' in resources or resources['metadata'] == '':
280 if not 'metadata' in resources or resources['metadata'] == '':
280 resources['metadata'] = ResourcesDict()
281 resources['metadata'] = ResourcesDict()
281 basename = os.path.basename(filename)
282 basename = os.path.basename(filename)
282 notebook_name = basename[:basename.rfind('.')]
283 notebook_name = basename[:basename.rfind('.')]
283 resources['metadata']['name'] = notebook_name
284 resources['metadata']['name'] = notebook_name
284
285
285 modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
286 modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
286 resources['metadata']['modified_date'] = modified_date.strftime(text.date_format)
287 resources['metadata']['modified_date'] = modified_date.strftime(text.date_format)
287
288
288 with io.open(filename) as f:
289 with io.open(filename) as f:
289 return self.from_notebook_node(nbformat.read(f, 'json'), resources=resources,**kw)
290 return self.from_notebook_node(nbformat.read(f, 'json'), resources=resources,**kw)
290
291
291
292
292 def from_file(self, file_stream, resources=None, **kw):
293 def from_file(self, file_stream, resources=None, **kw):
293 """
294 """
294 Convert a notebook from a notebook file.
295 Convert a notebook from a notebook file.
295
296
296 Parameters
297 Parameters
297 ----------
298 ----------
298 file_stream : file-like object
299 file_stream : file-like object
299 Notebook file-like object to convert.
300 Notebook file-like object to convert.
300 """
301 """
301 return self.from_notebook_node(nbformat.read(file_stream, 'json'), resources=resources, **kw)
302 return self.from_notebook_node(nbformat.read(file_stream, 'json'), resources=resources, **kw)
302
303
303
304
304 def register_preprocessor(self, preprocessor, enabled=False):
305 def register_preprocessor(self, preprocessor, enabled=False):
305 """
306 """
306 Register a preprocessor.
307 Register a preprocessor.
307 Preprocessors are classes that act upon the notebook before it is
308 Preprocessors are classes that act upon the notebook before it is
308 passed into the Jinja templating engine. Preprocessors are also
309 passed into the Jinja templating engine. Preprocessors are also
309 capable of passing additional information to the Jinja
310 capable of passing additional information to the Jinja
310 templating engine.
311 templating engine.
311
312
312 Parameters
313 Parameters
313 ----------
314 ----------
314 preprocessor : preprocessor
315 preprocessor : preprocessor
315 """
316 """
316 if preprocessor is None:
317 if preprocessor is None:
317 raise TypeError('preprocessor')
318 raise TypeError('preprocessor')
318 isclass = isinstance(preprocessor, type)
319 isclass = isinstance(preprocessor, type)
319 constructed = not isclass
320 constructed = not isclass
320
321
321 #Handle preprocessor's registration based on it's type
322 #Handle preprocessor's registration based on it's type
322 if constructed and isinstance(preprocessor, py3compat.string_types):
323 if constructed and isinstance(preprocessor, py3compat.string_types):
323 #Preprocessor is a string, import the namespace and recursively call
324 #Preprocessor is a string, import the namespace and recursively call
324 #this register_preprocessor method
325 #this register_preprocessor method
325 preprocessor_cls = import_item(preprocessor)
326 preprocessor_cls = import_item(preprocessor)
326 return self.register_preprocessor(preprocessor_cls, enabled)
327 return self.register_preprocessor(preprocessor_cls, enabled)
327
328
328 if constructed and hasattr(preprocessor, '__call__'):
329 if constructed and hasattr(preprocessor, '__call__'):
329 #Preprocessor is a function, no need to construct it.
330 #Preprocessor is a function, no need to construct it.
330 #Register and return the preprocessor.
331 #Register and return the preprocessor.
331 if enabled:
332 if enabled:
332 preprocessor.enabled = True
333 preprocessor.enabled = True
333 self._preprocessors.append(preprocessor)
334 self._preprocessors.append(preprocessor)
334 return preprocessor
335 return preprocessor
335
336
336 elif isclass and isinstance(preprocessor, MetaHasTraits):
337 elif isclass and isinstance(preprocessor, MetaHasTraits):
337 #Preprocessor is configurable. Make sure to pass in new default for
338 #Preprocessor is configurable. Make sure to pass in new default for
338 #the enabled flag if one was specified.
339 #the enabled flag if one was specified.
339 self.register_preprocessor(preprocessor(parent=self), enabled)
340 self.register_preprocessor(preprocessor(parent=self), enabled)
340
341
341 elif isclass:
342 elif isclass:
342 #Preprocessor is not configurable, construct it
343 #Preprocessor is not configurable, construct it
343 self.register_preprocessor(preprocessor(), enabled)
344 self.register_preprocessor(preprocessor(), enabled)
344
345
345 else:
346 else:
346 #Preprocessor is an instance of something without a __call__
347 #Preprocessor is an instance of something without a __call__
347 #attribute.
348 #attribute.
348 raise TypeError('preprocessor')
349 raise TypeError('preprocessor')
349
350
350
351
351 def register_filter(self, name, jinja_filter):
352 def register_filter(self, name, jinja_filter):
352 """
353 """
353 Register a filter.
354 Register a filter.
354 A filter is a function that accepts and acts on one string.
355 A filter is a function that accepts and acts on one string.
355 The filters are accesible within the Jinja templating engine.
356 The filters are accesible within the Jinja templating engine.
356
357
357 Parameters
358 Parameters
358 ----------
359 ----------
359 name : str
360 name : str
360 name to give the filter in the Jinja engine
361 name to give the filter in the Jinja engine
361 filter : filter
362 filter : filter
362 """
363 """
363 if jinja_filter is None:
364 if jinja_filter is None:
364 raise TypeError('filter')
365 raise TypeError('filter')
365 isclass = isinstance(jinja_filter, type)
366 isclass = isinstance(jinja_filter, type)
366 constructed = not isclass
367 constructed = not isclass
367
368
368 #Handle filter's registration based on it's type
369 #Handle filter's registration based on it's type
369 if constructed and isinstance(jinja_filter, py3compat.string_types):
370 if constructed and isinstance(jinja_filter, py3compat.string_types):
370 #filter is a string, import the namespace and recursively call
371 #filter is a string, import the namespace and recursively call
371 #this register_filter method
372 #this register_filter method
372 filter_cls = import_item(jinja_filter)
373 filter_cls = import_item(jinja_filter)
373 return self.register_filter(name, filter_cls)
374 return self.register_filter(name, filter_cls)
374
375
375 if constructed and hasattr(jinja_filter, '__call__'):
376 if constructed and hasattr(jinja_filter, '__call__'):
376 #filter is a function, no need to construct it.
377 #filter is a function, no need to construct it.
377 self.environment.filters[name] = jinja_filter
378 self.environment.filters[name] = jinja_filter
378 return jinja_filter
379 return jinja_filter
379
380
380 elif isclass and isinstance(jinja_filter, MetaHasTraits):
381 elif isclass and isinstance(jinja_filter, MetaHasTraits):
381 #filter is configurable. Make sure to pass in new default for
382 #filter is configurable. Make sure to pass in new default for
382 #the enabled flag if one was specified.
383 #the enabled flag if one was specified.
383 filter_instance = jinja_filter(parent=self)
384 filter_instance = jinja_filter(parent=self)
384 self.register_filter(name, filter_instance )
385 self.register_filter(name, filter_instance )
385
386
386 elif isclass:
387 elif isclass:
387 #filter is not configurable, construct it
388 #filter is not configurable, construct it
388 filter_instance = jinja_filter()
389 filter_instance = jinja_filter()
389 self.register_filter(name, filter_instance)
390 self.register_filter(name, filter_instance)
390
391
391 else:
392 else:
392 #filter is an instance of something without a __call__
393 #filter is an instance of something without a __call__
393 #attribute.
394 #attribute.
394 raise TypeError('filter')
395 raise TypeError('filter')
395
396
396
397
397 def _init_template(self):
398 def _init_template(self):
398 """
399 """
399 Make sure a template name is specified. If one isn't specified, try to
400 Make sure a template name is specified. If one isn't specified, try to
400 build one from the information we know.
401 build one from the information we know.
401 """
402 """
402 self._template_file_changed('template_file', self.template_file, self.template_file)
403 self._template_file_changed('template_file', self.template_file, self.template_file)
403
404
404
405
405 def _init_environment(self, extra_loaders=None):
406 def _init_environment(self, extra_loaders=None):
406 """
407 """
407 Create the Jinja templating environment.
408 Create the Jinja templating environment.
408 """
409 """
409 here = os.path.dirname(os.path.realpath(__file__))
410 here = os.path.dirname(os.path.realpath(__file__))
410 loaders = []
411 loaders = []
411 if extra_loaders:
412 if extra_loaders:
412 loaders.extend(extra_loaders)
413 loaders.extend(extra_loaders)
413
414
414 paths = self.template_path
415 paths = self.template_path
415 paths.extend([os.path.join(here, self.default_template_path),
416 paths.extend([os.path.join(here, self.default_template_path),
416 os.path.join(here, self.template_skeleton_path)])
417 os.path.join(here, self.template_skeleton_path)])
417 loaders.append(FileSystemLoader(paths))
418 loaders.append(FileSystemLoader(paths))
418
419
419 self.environment = Environment(
420 self.environment = Environment(
420 loader= ChoiceLoader(loaders),
421 loader= ChoiceLoader(loaders),
421 extensions=JINJA_EXTENSIONS
422 extensions=JINJA_EXTENSIONS
422 )
423 )
423
424
424 #Set special Jinja2 syntax that will not conflict with latex.
425 #Set special Jinja2 syntax that will not conflict with latex.
425 if self.jinja_logic_block_start:
426 if self.jinja_logic_block_start:
426 self.environment.block_start_string = self.jinja_logic_block_start
427 self.environment.block_start_string = self.jinja_logic_block_start
427 if self.jinja_logic_block_end:
428 if self.jinja_logic_block_end:
428 self.environment.block_end_string = self.jinja_logic_block_end
429 self.environment.block_end_string = self.jinja_logic_block_end
429 if self.jinja_variable_block_start:
430 if self.jinja_variable_block_start:
430 self.environment.variable_start_string = self.jinja_variable_block_start
431 self.environment.variable_start_string = self.jinja_variable_block_start
431 if self.jinja_variable_block_end:
432 if self.jinja_variable_block_end:
432 self.environment.variable_end_string = self.jinja_variable_block_end
433 self.environment.variable_end_string = self.jinja_variable_block_end
433 if self.jinja_comment_block_start:
434 if self.jinja_comment_block_start:
434 self.environment.comment_start_string = self.jinja_comment_block_start
435 self.environment.comment_start_string = self.jinja_comment_block_start
435 if self.jinja_comment_block_end:
436 if self.jinja_comment_block_end:
436 self.environment.comment_end_string = self.jinja_comment_block_end
437 self.environment.comment_end_string = self.jinja_comment_block_end
437
438
438
439
439 def _init_preprocessors(self):
440 def _init_preprocessors(self):
440 """
441 """
441 Register all of the preprocessors needed for this exporter, disabled
442 Register all of the preprocessors needed for this exporter, disabled
442 unless specified explicitly.
443 unless specified explicitly.
443 """
444 """
444 self._preprocessors = []
445 self._preprocessors = []
445
446
446 #Load default preprocessors (not necessarly enabled by default).
447 #Load default preprocessors (not necessarly enabled by default).
447 if self.default_preprocessors:
448 if self.default_preprocessors:
448 for preprocessor in self.default_preprocessors:
449 for preprocessor in self.default_preprocessors:
449 self.register_preprocessor(preprocessor)
450 self.register_preprocessor(preprocessor)
450
451
451 #Load user preprocessors. Enable by default.
452 #Load user preprocessors. Enable by default.
452 if self.preprocessors:
453 if self.preprocessors:
453 for preprocessor in self.preprocessors:
454 for preprocessor in self.preprocessors:
454 self.register_preprocessor(preprocessor, enabled=True)
455 self.register_preprocessor(preprocessor, enabled=True)
455
456
456
457
457 def _init_filters(self):
458 def _init_filters(self):
458 """
459 """
459 Register all of the filters required for the exporter.
460 Register all of the filters required for the exporter.
460 """
461 """
461
462
462 #Add default filters to the Jinja2 environment
463 #Add default filters to the Jinja2 environment
463 for key, value in default_filters.items():
464 for key, value in default_filters.items():
464 self.register_filter(key, value)
465 self.register_filter(key, value)
465
466
466 #Load user filters. Overwrite existing filters if need be.
467 #Load user filters. Overwrite existing filters if need be.
467 if self.filters:
468 if self.filters:
468 for key, user_filter in self.filters.items():
469 for key, user_filter in self.filters.items():
469 self.register_filter(key, user_filter)
470 self.register_filter(key, user_filter)
470
471
471
472
472 def _init_resources(self, resources):
473 def _init_resources(self, resources):
473
474
474 #Make sure the resources dict is of ResourcesDict type.
475 #Make sure the resources dict is of ResourcesDict type.
475 if resources is None:
476 if resources is None:
476 resources = ResourcesDict()
477 resources = ResourcesDict()
477 if not isinstance(resources, ResourcesDict):
478 if not isinstance(resources, ResourcesDict):
478 new_resources = ResourcesDict()
479 new_resources = ResourcesDict()
479 new_resources.update(resources)
480 new_resources.update(resources)
480 resources = new_resources
481 resources = new_resources
481
482
482 #Make sure the metadata extension exists in resources
483 #Make sure the metadata extension exists in resources
483 if 'metadata' in resources:
484 if 'metadata' in resources:
484 if not isinstance(resources['metadata'], ResourcesDict):
485 if not isinstance(resources['metadata'], ResourcesDict):
485 resources['metadata'] = ResourcesDict(resources['metadata'])
486 resources['metadata'] = ResourcesDict(resources['metadata'])
486 else:
487 else:
487 resources['metadata'] = ResourcesDict()
488 resources['metadata'] = ResourcesDict()
488 if not resources['metadata']['name']:
489 if not resources['metadata']['name']:
489 resources['metadata']['name'] = 'Notebook'
490 resources['metadata']['name'] = 'Notebook'
490
491
491 #Set the output extension
492 #Set the output extension
492 resources['output_extension'] = self.file_extension
493 resources['output_extension'] = self.file_extension
493 return resources
494 return resources
494
495
495
496
496 def _preprocess(self, nb, resources):
497 def _preprocess(self, nb, resources):
497 """
498 """
498 Preprocess the notebook before passing it into the Jinja engine.
499 Preprocess the notebook before passing it into the Jinja engine.
499 To preprocess the notebook is to apply all of the
500 To preprocess the notebook is to apply all of the
500
501
501 Parameters
502 Parameters
502 ----------
503 ----------
503 nb : notebook node
504 nb : notebook node
504 notebook that is being exported.
505 notebook that is being exported.
505 resources : a dict of additional resources that
506 resources : a dict of additional resources that
506 can be accessed read/write by preprocessors
507 can be accessed read/write by preprocessors
507 and filters.
508 and filters.
508 """
509 """
509
510
510 # Do a copy.deepcopy first,
511 # Do a copy.deepcopy first,
511 # we are never safe enough with what the preprocessors could do.
512 # we are never safe enough with what the preprocessors could do.
512 nbc = copy.deepcopy(nb)
513 nbc = copy.deepcopy(nb)
513 resc = copy.deepcopy(resources)
514 resc = copy.deepcopy(resources)
514
515
515 #Run each preprocessor on the notebook. Carry the output along
516 #Run each preprocessor on the notebook. Carry the output along
516 #to each preprocessor
517 #to each preprocessor
517 for preprocessor in self._preprocessors:
518 for preprocessor in self._preprocessors:
518 nbc, resc = preprocessor(nbc, resc)
519 nbc, resc = preprocessor(nbc, resc)
519 return nbc, resc
520 return nbc, resc
@@ -1,31 +1,38 b''
1 """
1 """
2 Exporter that will export your ipynb to Markdown.
2 Exporter that will export your ipynb to Markdown.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
5 # Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 from IPython.config import Config
16 from IPython.utils.traitlets import Unicode
17 from IPython.utils.traitlets import Unicode
17
18
18 from .exporter import Exporter
19 from .exporter import Exporter
19
20
20 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
21 # Classes
22 # Classes
22 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
23
24
24 class MarkdownExporter(Exporter):
25 class MarkdownExporter(Exporter):
25 """
26 """
26 Exports to a markdown document (.md)
27 Exports to a markdown document (.md)
27 """
28 """
28
29
29 file_extension = Unicode(
30 file_extension = Unicode(
30 'md', config=True,
31 'md', config=True,
31 help="Extension of the file that should be written to disk")
32 help="Extension of the file that should be written to disk")
33
34 @property
35 def default_config(self):
36 c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
37 c.merge(super(MarkdownExporter,self).default_config)
38 return c
@@ -1,183 +1,190 b''
1 # coding: utf-8
1 # coding: utf-8
2 """String filters.
2 """String filters.
3
3
4 Contains a collection of useful string manipulation filters for use in Jinja
4 Contains a collection of useful string manipulation filters for use in Jinja
5 templates.
5 templates.
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (c) 2013, the IPython Development Team.
8 # Copyright (c) 2013, the IPython Development Team.
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import os
19 import os
20 import re
20 import re
21 import textwrap
21 import textwrap
22 from urllib2 import quote
22 from xml.etree import ElementTree
23 from xml.etree import ElementTree
23
24
24 from IPython.core.interactiveshell import InteractiveShell
25 from IPython.core.interactiveshell import InteractiveShell
25 from IPython.utils import py3compat
26 from IPython.utils import py3compat
26
27
27 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
28 # Functions
29 # Functions
29 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
30
31
31 __all__ = [
32 __all__ = [
32 'wrap_text',
33 'wrap_text',
33 'html2text',
34 'html2text',
34 'add_anchor',
35 'add_anchor',
35 'strip_dollars',
36 'strip_dollars',
36 'strip_files_prefix',
37 'strip_files_prefix',
37 'comment_lines',
38 'comment_lines',
38 'get_lines',
39 'get_lines',
39 'ipython2python',
40 'ipython2python',
40 'posix_path',
41 'posix_path',
42 'path2url',
41 ]
43 ]
42
44
43
45
44 def wrap_text(text, width=100):
46 def wrap_text(text, width=100):
45 """
47 """
46 Intelligently wrap text.
48 Intelligently wrap text.
47 Wrap text without breaking words if possible.
49 Wrap text without breaking words if possible.
48
50
49 Parameters
51 Parameters
50 ----------
52 ----------
51 text : str
53 text : str
52 Text to wrap.
54 Text to wrap.
53 width : int, optional
55 width : int, optional
54 Number of characters to wrap to, default 100.
56 Number of characters to wrap to, default 100.
55 """
57 """
56
58
57 split_text = text.split('\n')
59 split_text = text.split('\n')
58 wrp = map(lambda x:textwrap.wrap(x,width), split_text)
60 wrp = map(lambda x:textwrap.wrap(x,width), split_text)
59 wrpd = map('\n'.join, wrp)
61 wrpd = map('\n'.join, wrp)
60 return '\n'.join(wrpd)
62 return '\n'.join(wrpd)
61
63
62
64
63 def html2text(element):
65 def html2text(element):
64 """extract inner text from html
66 """extract inner text from html
65
67
66 Analog of jQuery's $(element).text()
68 Analog of jQuery's $(element).text()
67 """
69 """
68 if isinstance(element, py3compat.string_types):
70 if isinstance(element, py3compat.string_types):
69 element = ElementTree.fromstring(element)
71 element = ElementTree.fromstring(element)
70
72
71 text = element.text or ""
73 text = element.text or ""
72 for child in element:
74 for child in element:
73 text += html2text(child)
75 text += html2text(child)
74 text += (element.tail or "")
76 text += (element.tail or "")
75 return text
77 return text
76
78
77
79
78 def add_anchor(html):
80 def add_anchor(html):
79 """Add an anchor-link to an html header tag
81 """Add an anchor-link to an html header tag
80
82
81 For use in heading cells
83 For use in heading cells
82 """
84 """
83 h = ElementTree.fromstring(py3compat.cast_bytes_py2(html, encoding='utf-8'))
85 h = ElementTree.fromstring(py3compat.cast_bytes_py2(html, encoding='utf-8'))
84 link = html2text(h).replace(' ', '-')
86 link = html2text(h).replace(' ', '-')
85 h.set('id', link)
87 h.set('id', link)
86 a = ElementTree.Element("a", {"class" : "anchor-link", "href" : "#" + link})
88 a = ElementTree.Element("a", {"class" : "anchor-link", "href" : "#" + link})
87 a.text = u'ΒΆ'
89 a.text = u'ΒΆ'
88 h.append(a)
90 h.append(a)
89
91
90 # Known issue of Python3.x, ElementTree.tostring() returns a byte string
92 # Known issue of Python3.x, ElementTree.tostring() returns a byte string
91 # instead of a text string. See issue http://bugs.python.org/issue10942
93 # instead of a text string. See issue http://bugs.python.org/issue10942
92 # Workaround is to make sure the bytes are casted to a string.
94 # Workaround is to make sure the bytes are casted to a string.
93 return py3compat.decode(ElementTree.tostring(h), 'utf-8')
95 return py3compat.decode(ElementTree.tostring(h), 'utf-8')
94
96
95
97
96 def strip_dollars(text):
98 def strip_dollars(text):
97 """
99 """
98 Remove all dollar symbols from text
100 Remove all dollar symbols from text
99
101
100 Parameters
102 Parameters
101 ----------
103 ----------
102 text : str
104 text : str
103 Text to remove dollars from
105 Text to remove dollars from
104 """
106 """
105
107
106 return text.strip('$')
108 return text.strip('$')
107
109
108
110
109 files_url_pattern = re.compile(r'(src|href)\=([\'"]?)files/')
111 files_url_pattern = re.compile(r'(src|href)\=([\'"]?)files/')
110
112
111 def strip_files_prefix(text):
113 def strip_files_prefix(text):
112 """
114 """
113 Fix all fake URLs that start with `files/`,
115 Fix all fake URLs that start with `files/`,
114 stripping out the `files/` prefix.
116 stripping out the `files/` prefix.
115
117
116 Parameters
118 Parameters
117 ----------
119 ----------
118 text : str
120 text : str
119 Text in which to replace 'src="files/real...' with 'src="real...'
121 Text in which to replace 'src="files/real...' with 'src="real...'
120 """
122 """
121 return files_url_pattern.sub(r"\1=\2", text)
123 return files_url_pattern.sub(r"\1=\2", text)
122
124
123
125
124 def comment_lines(text, prefix='# '):
126 def comment_lines(text, prefix='# '):
125 """
127 """
126 Build a Python comment line from input text.
128 Build a Python comment line from input text.
127
129
128 Parameters
130 Parameters
129 ----------
131 ----------
130 text : str
132 text : str
131 Text to comment out.
133 Text to comment out.
132 prefix : str
134 prefix : str
133 Character to append to the start of each line.
135 Character to append to the start of each line.
134 """
136 """
135
137
136 #Replace line breaks with line breaks and comment symbols.
138 #Replace line breaks with line breaks and comment symbols.
137 #Also add a comment symbol at the beginning to comment out
139 #Also add a comment symbol at the beginning to comment out
138 #the first line.
140 #the first line.
139 return prefix + ('\n'+prefix).join(text.split('\n'))
141 return prefix + ('\n'+prefix).join(text.split('\n'))
140
142
141
143
142 def get_lines(text, start=None,end=None):
144 def get_lines(text, start=None,end=None):
143 """
145 """
144 Split the input text into separate lines and then return the
146 Split the input text into separate lines and then return the
145 lines that the caller is interested in.
147 lines that the caller is interested in.
146
148
147 Parameters
149 Parameters
148 ----------
150 ----------
149 text : str
151 text : str
150 Text to parse lines from.
152 Text to parse lines from.
151 start : int, optional
153 start : int, optional
152 First line to grab from.
154 First line to grab from.
153 end : int, optional
155 end : int, optional
154 Last line to grab from.
156 Last line to grab from.
155 """
157 """
156
158
157 # Split the input into lines.
159 # Split the input into lines.
158 lines = text.split("\n")
160 lines = text.split("\n")
159
161
160 # Return the right lines.
162 # Return the right lines.
161 return "\n".join(lines[start:end]) #re-join
163 return "\n".join(lines[start:end]) #re-join
162
164
163 def ipython2python(code):
165 def ipython2python(code):
164 """Transform IPython syntax to pure Python syntax
166 """Transform IPython syntax to pure Python syntax
165
167
166 Parameters
168 Parameters
167 ----------
169 ----------
168
170
169 code : str
171 code : str
170 IPython code, to be transformed to pure Python
172 IPython code, to be transformed to pure Python
171 """
173 """
172 shell = InteractiveShell.instance()
174 shell = InteractiveShell.instance()
173 return shell.input_transformer_manager.transform_cell(code)
175 return shell.input_transformer_manager.transform_cell(code)
174
176
175 def posix_path(path):
177 def posix_path(path):
176 """Turn a path into posix-style path/to/etc
178 """Turn a path into posix-style path/to/etc
177
179
178 Mainly for use in latex on Windows,
180 Mainly for use in latex on Windows,
179 where native Windows paths are not allowed.
181 where native Windows paths are not allowed.
180 """
182 """
181 if os.path.sep != '/':
183 if os.path.sep != '/':
182 return path.replace(os.path.sep, '/')
184 return path.replace(os.path.sep, '/')
183 return path
185 return path
186
187 def path2url(path):
188 """Turn a file path into a URL"""
189 parts = path.split(os.path.sep)
190 return '/'.join(quote(part) for part in parts)
@@ -1,472 +1,472 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
12
13 \nonstopmode
13 \nonstopmode
14
14
15 %==============================================================================
15 %==============================================================================
16 % Declarations
16 % Declarations
17 %==============================================================================
17 %==============================================================================
18
18
19 % In order to make sure that the input/output header follows the code it
19 % In order to make sure that the input/output header follows the code it
20 % preceeds, the needspace package is used to request that a certain
20 % preceeds, the needspace package is used to request that a certain
21 % amount of lines (specified by this variable) are reserved. If those
21 % amount of lines (specified by this variable) are reserved. If those
22 % lines aren't available on the current page, the documenter will break
22 % lines aren't available on the current page, the documenter will break
23 % to the next page and the header along with accomanying lines will be
23 % to the next page and the header along with accomanying lines will be
24 % rendered together. This value specifies the number of lines that
24 % rendered together. This value specifies the number of lines that
25 % the header will be forced to group with without a page break.
25 % the header will be forced to group with without a page break.
26 ((*- set min_header_lines = 4 -*))
26 ((*- set min_header_lines = 4 -*))
27
27
28 % This is the number of characters that are permitted per line. It's
28 % This is the number of characters that are permitted per line. It's
29 % important that this limit is set so characters do not run off the
29 % important that this limit is set so characters do not run off the
30 % edges of latex pages (since latex does not always seem smart enough
30 % edges of latex pages (since latex does not always seem smart enough
31 % to prevent this in some cases.) This is only applied to textual output
31 % to prevent this in some cases.) This is only applied to textual output
32 ((* if resources.sphinx.outputstyle == 'simple' *))
32 ((* if resources.sphinx.outputstyle == 'simple' *))
33 ((*- set wrap_size = 85 -*))
33 ((*- set wrap_size = 85 -*))
34 ((* elif resources.sphinx.outputstyle == 'notebook' *))
34 ((* elif resources.sphinx.outputstyle == 'notebook' *))
35 ((*- set wrap_size = 70 -*))
35 ((*- set wrap_size = 70 -*))
36 ((* endif *))
36 ((* endif *))
37
37
38 %==============================================================================
38 %==============================================================================
39 % Header
39 % Header
40 %==============================================================================
40 %==============================================================================
41 ((* block header *))
41 ((* block header *))
42
42
43 % Header, overrides base
43 % Header, overrides base
44
44
45 % Make sure that the sphinx doc style knows who it inherits from.
45 % Make sure that the sphinx doc style knows who it inherits from.
46 \def\sphinxdocclass{(((parentdocumentclass)))}
46 \def\sphinxdocclass{(((parentdocumentclass)))}
47
47
48 % Declare the document class
48 % Declare the document class
49 \documentclass[letterpaper,10pt,english]{((( resources.sphinx.texinputs | posix_path )))/sphinx(((documentclass)))}
49 \documentclass[letterpaper,10pt,english]{((( resources.sphinx.texinputs | posix_path )))/sphinx(((documentclass)))}
50
50
51 % Imports
51 % Imports
52 \usepackage[utf8]{inputenc}
52 \usepackage[utf8]{inputenc}
53 \DeclareUnicodeCharacter{00A0}{\\nobreakspace}
53 \DeclareUnicodeCharacter{00A0}{\\nobreakspace}
54 \usepackage[T1]{fontenc}
54 \usepackage[T1]{fontenc}
55 \usepackage{babel}
55 \usepackage{babel}
56 \usepackage{times}
56 \usepackage{times}
57 \usepackage{import}
57 \usepackage{import}
58 \usepackage[((( resources.sphinx.chapterstyle )))]{((( resources.sphinx.texinputs | posix_path )))/fncychap}
58 \usepackage[((( resources.sphinx.chapterstyle )))]{((( resources.sphinx.texinputs | posix_path )))/fncychap}
59 \usepackage{longtable}
59 \usepackage{longtable}
60 \usepackage{((( resources.sphinx.texinputs | posix_path )))/sphinx}
60 \usepackage{((( resources.sphinx.texinputs | posix_path )))/sphinx}
61 \usepackage{multirow}
61 \usepackage{multirow}
62
62
63 \usepackage{amsmath}
63 \usepackage{amsmath}
64 \usepackage{amssymb}
64 \usepackage{amssymb}
65 \usepackage{ucs}
65 \usepackage{ucs}
66 \usepackage{enumerate}
66 \usepackage{enumerate}
67
67
68 % Used to make the Input/Output rules follow around the contents.
68 % Used to make the Input/Output rules follow around the contents.
69 \usepackage{needspace}
69 \usepackage{needspace}
70
70
71 % Pygments requirements
71 % Pygments requirements
72 \usepackage{fancyvrb}
72 \usepackage{fancyvrb}
73 \usepackage{color}
73 \usepackage{color}
74 % ansi colors additions
74 % ansi colors additions
75 \definecolor{darkgreen}{rgb}{.12,.54,.11}
75 \definecolor{darkgreen}{rgb}{.12,.54,.11}
76 \definecolor{lightgray}{gray}{.95}
76 \definecolor{lightgray}{gray}{.95}
77 \definecolor{brown}{rgb}{0.54,0.27,0.07}
77 \definecolor{brown}{rgb}{0.54,0.27,0.07}
78 \definecolor{purple}{rgb}{0.5,0.0,0.5}
78 \definecolor{purple}{rgb}{0.5,0.0,0.5}
79 \definecolor{darkgray}{gray}{0.25}
79 \definecolor{darkgray}{gray}{0.25}
80 \definecolor{lightred}{rgb}{1.0,0.39,0.28}
80 \definecolor{lightred}{rgb}{1.0,0.39,0.28}
81 \definecolor{lightgreen}{rgb}{0.48,0.99,0.0}
81 \definecolor{lightgreen}{rgb}{0.48,0.99,0.0}
82 \definecolor{lightblue}{rgb}{0.53,0.81,0.92}
82 \definecolor{lightblue}{rgb}{0.53,0.81,0.92}
83 \definecolor{lightpurple}{rgb}{0.87,0.63,0.87}
83 \definecolor{lightpurple}{rgb}{0.87,0.63,0.87}
84 \definecolor{lightcyan}{rgb}{0.5,1.0,0.83}
84 \definecolor{lightcyan}{rgb}{0.5,1.0,0.83}
85
85
86 % Needed to box output/input
86 % Needed to box output/input
87 \usepackage{tikz}
87 \usepackage{tikz}
88 \usetikzlibrary{calc,arrows,shadows}
88 \usetikzlibrary{calc,arrows,shadows}
89 \usepackage[framemethod=tikz]{mdframed}
89 \usepackage[framemethod=tikz]{mdframed}
90
90
91 \usepackage{alltt}
91 \usepackage{alltt}
92
92
93 % Used to load and display graphics
93 % Used to load and display graphics
94 \usepackage{graphicx}
94 \usepackage{graphicx}
95 \graphicspath{ {figs/} }
95 \graphicspath{ {figs/} }
96 \usepackage[Export]{adjustbox} % To resize
96 \usepackage[Export]{adjustbox} % To resize
97
97
98 % used so that images for notebooks which have spaces in the name can still be included
98 % used so that images for notebooks which have spaces in the name can still be included
99 \usepackage{grffile}
99 \usepackage{grffile}
100
100
101
101
102 % For formatting output while also word wrapping.
102 % For formatting output while also word wrapping.
103 \usepackage{listings}
103 \usepackage{listings}
104 \lstset{breaklines=true}
104 \lstset{breaklines=true}
105 \lstset{basicstyle=\small\ttfamily}
105 \lstset{basicstyle=\small\ttfamily}
106 \def\smaller{\fontsize{9.5pt}{9.5pt}\selectfont}
106 \def\smaller{\fontsize{9.5pt}{9.5pt}\selectfont}
107
107
108 %Pygments definitions
108 %Pygments definitions
109 ((( resources.sphinx.pygment_definitions )))
109 ((( resources.sphinx.pygment_definitions )))
110
110
111 %Set pygments styles if needed...
111 %Set pygments styles if needed...
112 ((* if resources.sphinx.outputstyle == 'notebook' *))
112 ((* if resources.sphinx.outputstyle == 'notebook' *))
113 \definecolor{nbframe-border}{rgb}{0.867,0.867,0.867}
113 \definecolor{nbframe-border}{rgb}{0.867,0.867,0.867}
114 \definecolor{nbframe-bg}{rgb}{0.969,0.969,0.969}
114 \definecolor{nbframe-bg}{rgb}{0.969,0.969,0.969}
115 \definecolor{nbframe-in-prompt}{rgb}{0.0,0.0,0.502}
115 \definecolor{nbframe-in-prompt}{rgb}{0.0,0.0,0.502}
116 \definecolor{nbframe-out-prompt}{rgb}{0.545,0.0,0.0}
116 \definecolor{nbframe-out-prompt}{rgb}{0.545,0.0,0.0}
117
117
118 \newenvironment{ColorVerbatim}
118 \newenvironment{ColorVerbatim}
119 {\begin{mdframed}[%
119 {\begin{mdframed}[%
120 roundcorner=1.0pt, %
120 roundcorner=1.0pt, %
121 backgroundcolor=nbframe-bg, %
121 backgroundcolor=nbframe-bg, %
122 userdefinedwidth=1\linewidth, %
122 userdefinedwidth=1\linewidth, %
123 leftmargin=0.1\linewidth, %
123 leftmargin=0.1\linewidth, %
124 innerleftmargin=0pt, %
124 innerleftmargin=0pt, %
125 innerrightmargin=0pt, %
125 innerrightmargin=0pt, %
126 linecolor=nbframe-border, %
126 linecolor=nbframe-border, %
127 linewidth=1pt, %
127 linewidth=1pt, %
128 usetwoside=false, %
128 usetwoside=false, %
129 everyline=true, %
129 everyline=true, %
130 innerlinewidth=3pt, %
130 innerlinewidth=3pt, %
131 innerlinecolor=nbframe-bg, %
131 innerlinecolor=nbframe-bg, %
132 middlelinewidth=1pt, %
132 middlelinewidth=1pt, %
133 middlelinecolor=nbframe-bg, %
133 middlelinecolor=nbframe-bg, %
134 outerlinewidth=0.5pt, %
134 outerlinewidth=0.5pt, %
135 outerlinecolor=nbframe-border, %
135 outerlinecolor=nbframe-border, %
136 needspace=0pt
136 needspace=0pt
137 ]}
137 ]}
138 {\end{mdframed}}
138 {\end{mdframed}}
139
139
140 \newenvironment{InvisibleVerbatim}
140 \newenvironment{InvisibleVerbatim}
141 {\begin{mdframed}[leftmargin=0.1\linewidth,innerleftmargin=3pt,innerrightmargin=3pt, userdefinedwidth=1\linewidth, linewidth=0pt, linecolor=white, usetwoside=false]}
141 {\begin{mdframed}[leftmargin=0.1\linewidth,innerleftmargin=3pt,innerrightmargin=3pt, userdefinedwidth=1\linewidth, linewidth=0pt, linecolor=white, usetwoside=false]}
142 {\end{mdframed}}
142 {\end{mdframed}}
143
143
144 \renewenvironment{Verbatim}[1][\unskip]
144 \renewenvironment{Verbatim}[1][\unskip]
145 {\begin{alltt}\smaller}
145 {\begin{alltt}\smaller}
146 {\end{alltt}}
146 {\end{alltt}}
147 ((* endif *))
147 ((* endif *))
148
148
149 % Help prevent overflowing lines due to urls and other hard-to-break
149 % Help prevent overflowing lines due to urls and other hard-to-break
150 % entities. This doesn't catch everything...
150 % entities. This doesn't catch everything...
151 \sloppy
151 \sloppy
152
152
153 % Document level variables
153 % Document level variables
154 \title{((( resources.metadata.name | escape_latex )))}
154 \title{((( resources.metadata.name | escape_latex )))}
155 \date{((( resources.sphinx.date | escape_latex )))}
155 \date{((( resources.sphinx.date | escape_latex )))}
156 \release{((( resources.sphinx.version | escape_latex )))}
156 \release{((( resources.sphinx.version | escape_latex )))}
157 \author{((( resources.sphinx.author | escape_latex )))}
157 \author{((( resources.sphinx.author | escape_latex )))}
158 \renewcommand{\releasename}{((( resources.sphinx.release | escape_latex )))}
158 \renewcommand{\releasename}{((( resources.sphinx.release | escape_latex )))}
159
159
160 % TODO: Add option for the user to specify a logo for his/her export.
160 % TODO: Add option for the user to specify a logo for his/her export.
161 \newcommand{\sphinxlogo}{}
161 \newcommand{\sphinxlogo}{}
162
162
163 % Make the index page of the document.
163 % Make the index page of the document.
164 \makeindex
164 \makeindex
165
165
166 % Import sphinx document type specifics.
166 % Import sphinx document type specifics.
167 ((* block sphinxheader *))((* endblock sphinxheader *))
167 ((* block sphinxheader *))((* endblock sphinxheader *))
168 ((* endblock header *))
168 ((* endblock header *))
169
169
170 %==============================================================================
170 %==============================================================================
171 % Body
171 % Body
172 %==============================================================================
172 %==============================================================================
173 ((* block body *))
173 ((* block body *))
174 ((* block bodyBegin *))
174 ((* block bodyBegin *))
175 % Body
175 % Body
176
176
177 % Start of the document
177 % Start of the document
178 \begin{document}
178 \begin{document}
179
179
180 ((* if resources.sphinx.header *))
180 ((* if resources.sphinx.header *))
181 \maketitle
181 \maketitle
182 ((* endif *))
182 ((* endif *))
183
183
184 ((* block toc *))
184 ((* block toc *))
185 \tableofcontents
185 \tableofcontents
186 ((* endblock toc *))
186 ((* endblock toc *))
187
187
188 ((* endblock bodyBegin *))
188 ((* endblock bodyBegin *))
189 ((( super() )))
189 ((( super() )))
190 ((* block bodyEnd *))
190 ((* block bodyEnd *))
191
191
192 \renewcommand{\indexname}{Index}
192 \renewcommand{\indexname}{Index}
193 \printindex
193 \printindex
194
194
195 ((* block bibliography *))
195 ((* block bibliography *))
196 ((* endblock bibliography *))
196 ((* endblock bibliography *))
197
197
198 % End of document
198 % End of document
199 \end{document}
199 \end{document}
200 ((* endblock bodyEnd *))
200 ((* endblock bodyEnd *))
201 ((* endblock body *))
201 ((* endblock body *))
202
202
203 %==============================================================================
203 %==============================================================================
204 % Footer
204 % Footer
205 %==============================================================================
205 %==============================================================================
206 ((* block footer *))
206 ((* block footer *))
207 ((* endblock footer *))
207 ((* endblock footer *))
208
208
209 %==============================================================================
209 %==============================================================================
210 % Headings
210 % Headings
211 %
211 %
212 % Purpose: Format pynb headers as sphinx headers. Depending on the Sphinx
212 % Purpose: Format pynb headers as sphinx headers. Depending on the Sphinx
213 % style that is active, this will change. Thus sphinx styles will
213 % style that is active, this will change. Thus sphinx styles will
214 % override the values here.
214 % override the values here.
215 %==============================================================================
215 %==============================================================================
216 ((* block headingcell -*))
216 ((* block headingcell -*))
217 \
217 \
218 ((*- if cell.level == 1 -*))
218 ((*- if cell.level == 1 -*))
219 ((* block h1 -*))part((* endblock h1 -*))
219 ((* block h1 -*))part((* endblock h1 -*))
220 ((*- elif cell.level == 2 -*))
220 ((*- elif cell.level == 2 -*))
221 ((* block h2 -*))chapter((* endblock h2 -*))
221 ((* block h2 -*))chapter((* endblock h2 -*))
222 ((*- elif cell.level == 3 -*))
222 ((*- elif cell.level == 3 -*))
223 ((* block h3 -*))section((* endblock h3 -*))
223 ((* block h3 -*))section((* endblock h3 -*))
224 ((*- elif cell.level == 4 -*))
224 ((*- elif cell.level == 4 -*))
225 ((* block h4 -*))subsection((* endblock h4 -*))
225 ((* block h4 -*))subsection((* endblock h4 -*))
226 ((*- elif cell.level == 5 -*))
226 ((*- elif cell.level == 5 -*))
227 ((* block h5 -*))subsubsection((* endblock h5 -*))
227 ((* block h5 -*))subsubsection((* endblock h5 -*))
228 ((*- elif cell.level == 6 -*))
228 ((*- elif cell.level == 6 -*))
229 ((* block h6 -*))paragraph((* endblock h6 -*))
229 ((* block h6 -*))paragraph((* endblock h6 -*))
230
230
231 ((= It's important to make sure that underscores (which tend to be common
231 ((= It's important to make sure that underscores (which tend to be common
232 in IPYNB file titles) do not make their way into latex. Sometimes this
232 in IPYNB file titles) do not make their way into latex. Sometimes this
233 causes latex to barf. =))
233 causes latex to barf. =))
234 ((*- endif -*))
234 ((*- endif -*))
235 {((( cell.source | replace('\n', ' ') | citation2latex | markdown2latex )))}
235 {((( cell.source | replace('\n', ' ') | citation2latex | markdown2latex )))}
236 ((*- endblock headingcell *))
236 ((*- endblock headingcell *))
237
237
238 %==============================================================================
238 %==============================================================================
239 % Markdown
239 % Markdown
240 %
240 %
241 % Purpose: Convert markdown to latex. Here markdown2latex is explicitly
241 % Purpose: Convert markdown to latex. Here markdown2latex is explicitly
242 % called since we know we want latex output.
242 % called since we know we want latex output.
243 %==============================================================================
243 %==============================================================================
244 ((*- block markdowncell scoped-*))
244 ((*- block markdowncell scoped-*))
245 ((( cell.source | citation2latex | markdown2latex )))
245 ((( cell.source | citation2latex | markdown2latex )))
246 ((*- endblock markdowncell -*))
246 ((*- endblock markdowncell -*))
247
247
248 %==============================================================================
248 %==============================================================================
249 % Rawcell
249 % Rawcell
250 %
250 %
251 % Purpose: Raw text cells allow the user to manually inject document code that
251 % Purpose: Raw text cells allow the user to manually inject document code that
252 % will not get touched by the templating system.
252 % will not get touched by the templating system.
253 %==============================================================================
253 %==============================================================================
254 ((*- block rawcell *))
254 ((*- block rawcell *))
255 ((( cell.source | wrap_text(wrap_size) )))
255 ((( cell.source | wrap_text(wrap_size) )))
256 ((* endblock rawcell -*))
256 ((* endblock rawcell -*))
257
257
258 %==============================================================================
258 %==============================================================================
259 % Unknowncell
259 % Unknowncell
260 %
260 %
261 % Purpose: This is the catch anything unhandled. To display this data, we
261 % Purpose: This is the catch anything unhandled. To display this data, we
262 % remove all possible latex conflicts and wrap the characters so they
262 % remove all possible latex conflicts and wrap the characters so they
263 % can't flow off of the page.
263 % can't flow off of the page.
264 %==============================================================================
264 %==============================================================================
265 ((* block unknowncell scoped*))
265 ((* block unknowncell scoped*))
266 % Unsupported cell type, no formatting
266 % Unsupported cell type, no formatting
267 ((( cell.source | wrap_text | escape_latex )))
267 ((( cell.source | wrap_text | escape_latex )))
268 ((* endblock unknowncell *))
268 ((* endblock unknowncell *))
269
269
270 %==============================================================================
270 %==============================================================================
271 % Input
271 % Input
272 %==============================================================================
272 %==============================================================================
273 ((* block input *))
273 ((* block input *))
274
274
275 % Make sure that atleast 4 lines are below the HR
275 % Make sure that atleast 4 lines are below the HR
276 \needspace{((( min_header_lines )))\baselineskip}
276 \needspace{((( min_header_lines )))\baselineskip}
277
277
278 ((* if resources.sphinx.outputstyle == 'simple' *))
278 ((* if resources.sphinx.outputstyle == 'simple' *))
279
279
280 % Add a horizantal break, along with break title.
280 % Add a horizantal break, along with break title.
281 \vspace{10pt}
281 \vspace{10pt}
282 {\scriptsize Input}\\*
282 {\scriptsize Input}\\*
283 \rule[10pt]{\linewidth}{0.5pt}
283 \rule[10pt]{\linewidth}{0.5pt}
284 \vspace{-25pt}
284 \vspace{-25pt}
285
285
286 % Add contents below.
286 % Add contents below.
287 ((( cell.input | highlight2latex )))
287 ((( cell.input | highlight2latex )))
288
288
289 ((* elif resources.sphinx.outputstyle == 'notebook' *))
289 ((* elif resources.sphinx.outputstyle == 'notebook' *))
290 \vspace{6pt}
290 \vspace{6pt}
291 ((( write_prompt("In", cell.prompt_number, "nbframe-in-prompt") )))
291 ((( write_prompt("In", cell.prompt_number, "nbframe-in-prompt") )))
292 \vspace{-2.65\baselineskip}
292 \vspace{-2.65\baselineskip}
293 \begin{ColorVerbatim}
293 \begin{ColorVerbatim}
294 \vspace{-0.7\baselineskip}
294 \vspace{-0.7\baselineskip}
295 ((( cell.input | highlight2latex )))
295 ((( cell.input | highlight2latex )))
296 ((* if cell.input == None or cell.input == '' *))
296 ((* if cell.input == None or cell.input == '' *))
297 \vspace{0.3\baselineskip}
297 \vspace{0.3\baselineskip}
298 ((* else *))
298 ((* else *))
299 \vspace{-0.2\baselineskip}
299 \vspace{-0.2\baselineskip}
300 ((* endif *))
300 ((* endif *))
301 \end{ColorVerbatim}
301 \end{ColorVerbatim}
302 ((* endif *))
302 ((* endif *))
303 ((* endblock input *))
303 ((* endblock input *))
304
304
305 %==============================================================================
305 %==============================================================================
306 % Output_Group
306 % Output_Group
307 %
307 %
308 % Purpose: Make sure that only one header bar only attaches to the output
308 % Purpose: Make sure that only one header bar only attaches to the output
309 % once. By keeping track of when an input group is started
309 % once. By keeping track of when an input group is started
310 %==============================================================================
310 %==============================================================================
311 ((* block output_group *))
311 ((* block output_group *))
312 ((* if cell.outputs.__len__() > 0 *))
312 ((* if cell.outputs.__len__() > 0 *))
313
313
314 % If the first block is an image, minipage the image. Else
314 % If the first block is an image, minipage the image. Else
315 % request a certain amount of space for the input text.
315 % request a certain amount of space for the input text.
316 ((( iff_figure(cell.outputs[0], "\\begin{minipage}{1.0\\textwidth}", "\\needspace{" ~ min_header_lines ~ "\\baselineskip}") )))
316 ((( iff_figure(cell.outputs[0], "\\begin{minipage}{1.0\\textwidth}", "\\needspace{" ~ min_header_lines ~ "\\baselineskip}") )))
317
317
318 ((* if resources.sphinx.outputstyle == 'simple' *))
318 ((* if resources.sphinx.outputstyle == 'simple' *))
319
319
320 % Add a horizantal break, along with break title.
320 % Add a horizantal break, along with break title.
321 \vspace{10pt}
321 \vspace{10pt}
322 {\scriptsize Output}\\*
322 {\scriptsize Output}\\*
323 \rule[10pt]{\linewidth}{0.5pt}
323 \rule[10pt]{\linewidth}{0.5pt}
324 \vspace{-20pt}
324 \vspace{-20pt}
325
325
326 % Add the contents of the first block.
326 % Add the contents of the first block.
327 ((( render_output(cell.outputs[0]) )))
327 ((( render_output(cell.outputs[0]) )))
328
328
329 % Close the minipage.
329 % Close the minipage.
330 ((( iff_figure(cell.outputs[0], "\\end{minipage}", "") )))
330 ((( iff_figure(cell.outputs[0], "\\end{minipage}", "") )))
331
331
332 % Add remainer of the document contents below.
332 % Add remainer of the document contents below.
333 ((* for output in cell.outputs[1:] *))
333 ((* for output in cell.outputs[1:] *))
334 ((( render_output(output, cell.prompt_number) )))
334 ((( render_output(output, cell.prompt_number) )))
335 ((* endfor *))
335 ((* endfor *))
336 ((* elif resources.sphinx.outputstyle == 'notebook' *))
336 ((* elif resources.sphinx.outputstyle == 'notebook' *))
337
337
338 % Add document contents.
338 % Add document contents.
339 ((* for output in cell.outputs *))
339 ((* for output in cell.outputs *))
340 ((( render_output(output, cell.prompt_number) )))
340 ((( render_output(output, cell.prompt_number) )))
341 ((* endfor *))
341 ((* endfor *))
342 ((* endif *))
342 ((* endif *))
343 ((* endif *))
343 ((* endif *))
344 ((* endblock *))
344 ((* endblock *))
345
345
346 %==============================================================================
346 %==============================================================================
347 % Additional formating
347 % Additional formating
348 %==============================================================================
348 %==============================================================================
349 ((* block data_text *))
349 ((* block data_text *))
350 ((( custom_verbatim(output.text) | ansi2latex )))
350 ((( custom_verbatim(output.text) | ansi2latex )))
351 ((* endblock *))
351 ((* endblock *))
352
352
353 ((* block traceback_line *))
353 ((* block traceback_line *))
354 ((( conditionally_center_output( line | indent| strip_ansi ) )))
354 ((( conditionally_center_output( line | indent| strip_ansi ) )))
355 ((* endblock traceback_line *))
355 ((* endblock traceback_line *))
356
356
357 %==============================================================================
357 %==============================================================================
358 % Supported image formats
358 % Supported image formats
359 %==============================================================================
359 %==============================================================================
360 ((*- block data_png -*))
360 ((*- block data_png -*))
361 ((( conditionally_center_output(insert_graphics(output.png_filename | posix_path)) )))
361 ((( conditionally_center_output(insert_graphics(output.png_filename | posix_path)) )))
362 ((*- endblock -*))
362 ((*- endblock -*))
363
363
364 ((*- block data_jpg -*))
364 ((*- block data_jpg -*))
365 ((( conditionally_center_output(insert_graphics(output.jpg_filename | posix_path)) )))
365 ((( conditionally_center_output(insert_graphics(output.jpeg_filename | posix_path)) )))
366 ((*- endblock -*))
366 ((*- endblock -*))
367
367
368 ((*- block data_svg -*))
368 ((*- block data_svg -*))
369 ((( conditionally_center_output(insert_graphics(output.svg_filename | posix_path)) )))
369 ((( conditionally_center_output(insert_graphics(output.svg_filename | posix_path)) )))
370 ((*- endblock -*))
370 ((*- endblock -*))
371
371
372 ((*- block data_pdf -*))
372 ((*- block data_pdf -*))
373 ((( conditionally_center_output(insert_graphics(output.pdf_filename | posix_path)) )))
373 ((( conditionally_center_output(insert_graphics(output.pdf_filename | posix_path)) )))
374 ((*- endblock -*))
374 ((*- endblock -*))
375
375
376 ((*- block data_latex *))
376 ((*- block data_latex *))
377 ((* if resources.sphinx.centeroutput *))
377 ((* if resources.sphinx.centeroutput *))
378 \begin{center}
378 \begin{center}
379 ((* endif -*))
379 ((* endif -*))
380 ((( output.latex | strip_math_space )))
380 ((( output.latex | strip_math_space )))
381 ((*- if resources.sphinx.centeroutput *))
381 ((*- if resources.sphinx.centeroutput *))
382 \end{center}
382 \end{center}
383 ((* endif -*))
383 ((* endif -*))
384 ((*- endblock -*))
384 ((*- endblock -*))
385
385
386 %==============================================================================
386 %==============================================================================
387 % Support Macros
387 % Support Macros
388 %==============================================================================
388 %==============================================================================
389
389
390 % Name: write_prompt
390 % Name: write_prompt
391 % Purpose: Renders an output/input prompt for notebook style pdfs
391 % Purpose: Renders an output/input prompt for notebook style pdfs
392 ((* macro write_prompt(prompt, number, color) -*))
392 ((* macro write_prompt(prompt, number, color) -*))
393 \makebox[0.1\linewidth]{\smaller\hfill\tt\color{((( color )))}((( prompt )))\hspace{4pt}{[}((( number ))){]}:\hspace{4pt}}\\*
393 \makebox[0.1\linewidth]{\smaller\hfill\tt\color{((( color )))}((( prompt )))\hspace{4pt}{[}((( number ))){]}:\hspace{4pt}}\\*
394 ((*- endmacro *))
394 ((*- endmacro *))
395
395
396 % Name: render_output
396 % Name: render_output
397 % Purpose: Renders an output block appropriately.
397 % Purpose: Renders an output block appropriately.
398 ((* macro render_output(output, prompt_number) -*))
398 ((* macro render_output(output, prompt_number) -*))
399 ((*- if output.output_type == 'pyerr' -*))
399 ((*- if output.output_type == 'pyerr' -*))
400 ((*- block pyerr scoped *))
400 ((*- block pyerr scoped *))
401 ((( custom_verbatim(super()) )))
401 ((( custom_verbatim(super()) )))
402 ((* endblock pyerr -*))
402 ((* endblock pyerr -*))
403 ((*- else -*))
403 ((*- else -*))
404
404
405 ((* if resources.sphinx.outputstyle == 'notebook' *))
405 ((* if resources.sphinx.outputstyle == 'notebook' *))
406 ((*- if output.output_type == 'pyout' -*))
406 ((*- if output.output_type == 'pyout' -*))
407 ((( write_prompt("Out", prompt_number, "nbframe-out-prompt") )))
407 ((( write_prompt("Out", prompt_number, "nbframe-out-prompt") )))
408 \vspace{-2.55\baselineskip}
408 \vspace{-2.55\baselineskip}
409 ((*- endif -*))
409 ((*- endif -*))
410
410
411 \begin{InvisibleVerbatim}
411 \begin{InvisibleVerbatim}
412 \vspace{-0.5\baselineskip}
412 \vspace{-0.5\baselineskip}
413 ((*- endif -*))
413 ((*- endif -*))
414
414
415 ((*- block display_data scoped -*))
415 ((*- block display_data scoped -*))
416 ((( super() )))
416 ((( super() )))
417 ((*- endblock display_data -*))
417 ((*- endblock display_data -*))
418
418
419 ((* if resources.sphinx.outputstyle == 'notebook' *))
419 ((* if resources.sphinx.outputstyle == 'notebook' *))
420 \end{InvisibleVerbatim}
420 \end{InvisibleVerbatim}
421 ((*- endif -*))
421 ((*- endif -*))
422 ((*- endif -*))
422 ((*- endif -*))
423 ((*- endmacro *))
423 ((*- endmacro *))
424
424
425 % Name: iff_figure
425 % Name: iff_figure
426 % Purpose: If the output block provided is a figure type, the 'true_content'
426 % Purpose: If the output block provided is a figure type, the 'true_content'
427 % parameter will be returned. Else, the 'false_content'.
427 % parameter will be returned. Else, the 'false_content'.
428 ((* macro iff_figure(output, true_content, false_content) -*))
428 ((* macro iff_figure(output, true_content, false_content) -*))
429 ((*- set is_figure = false -*))
429 ((*- set is_figure = false -*))
430 ((*- for type in output | filter_data_type -*))
430 ((*- for type in output | filter_data_type -*))
431 ((*- if type in ['pdf', 'svg', 'png', 'jpeg','html']*))
431 ((*- if type in ['pdf', 'svg', 'png', 'jpeg','html']*))
432 ((*- set is_figure = true -*))
432 ((*- set is_figure = true -*))
433 ((*- endif -*))
433 ((*- endif -*))
434 ((*- endfor -*))
434 ((*- endfor -*))
435
435
436 ((* if is_figure -*))
436 ((* if is_figure -*))
437 ((( true_content )))
437 ((( true_content )))
438 ((*- else -*))
438 ((*- else -*))
439 ((( false_content )))
439 ((( false_content )))
440 ((*- endif *))
440 ((*- endif *))
441 ((*- endmacro *))
441 ((*- endmacro *))
442
442
443 % Name: custom_verbatim
443 % Name: custom_verbatim
444 % Purpose: This macro creates a verbatim style block that fits the existing
444 % Purpose: This macro creates a verbatim style block that fits the existing
445 % sphinx style more readily than standard verbatim blocks.
445 % sphinx style more readily than standard verbatim blocks.
446 ((* macro custom_verbatim(text) -*))
446 ((* macro custom_verbatim(text) -*))
447 \begin{alltt}
447 \begin{alltt}
448 ((*- if resources.sphinx.centeroutput *))\begin{center} ((* endif -*))
448 ((*- if resources.sphinx.centeroutput *))\begin{center} ((* endif -*))
449 ((( text | wrap_text(wrap_size) | escape_latex )))
449 ((( text | wrap_text(wrap_size) | escape_latex )))
450 ((*- if resources.sphinx.centeroutput *))\end{center}((* endif -*))
450 ((*- if resources.sphinx.centeroutput *))\end{center}((* endif -*))
451 \end{alltt}
451 \end{alltt}
452 ((*- endmacro *))
452 ((*- endmacro *))
453
453
454 % Name: conditionally_center_output
454 % Name: conditionally_center_output
455 % Purpose: This macro centers the output if the output centering is enabled.
455 % Purpose: This macro centers the output if the output centering is enabled.
456 ((* macro conditionally_center_output(text) -*))
456 ((* macro conditionally_center_output(text) -*))
457 ((* if resources.sphinx.centeroutput *))
457 ((* if resources.sphinx.centeroutput *))
458 {\centering
458 {\centering
459 ((* endif *))
459 ((* endif *))
460 ((( text )))
460 ((( text )))
461 ((* if resources.sphinx.centeroutput *))}
461 ((* if resources.sphinx.centeroutput *))}
462 ((* endif *))
462 ((* endif *))
463 ((*- endmacro *))
463 ((*- endmacro *))
464
464
465 % Name: insert_graphics
465 % Name: insert_graphics
466 % Purpose: This macro will insert an image in the latex document given a path.
466 % Purpose: This macro will insert an image in the latex document given a path.
467 ((* macro insert_graphics(path) -*))
467 ((* macro insert_graphics(path) -*))
468 \begin{center}
468 \begin{center}
469 \includegraphics[max size={\textwidth}{\textheight}]{((( path )))}
469 \includegraphics[max size={\textwidth}{\textheight}]{((( path )))}
470 \par
470 \par
471 \end{center}
471 \end{center}
472 ((*- endmacro *))
472 ((*- endmacro *))
@@ -1,74 +1,72 b''
1 {% extends 'display_priority.tpl' %}
1 {% extends 'display_priority.tpl' %}
2
2
3
3
4 {% block in_prompt %}
4 {% block in_prompt %}
5 In[{{ cell.prompt_number if cell.prompt_number else ' ' }}]:
6 {% endblock in_prompt %}
5 {% endblock in_prompt %}
7
6
8 {% block output_prompt %}
7 {% block output_prompt %}
9 {% if cell.haspyout %}
10 Out[{{ cell.prompt_number }}]:
11 {%- endif %}
12 {%- endblock output_prompt %}
8 {%- endblock output_prompt %}
13
9
14 {% block input %}
10 {% block input %}
15 ```
11 {{ cell.input | indent(4)}}
16 {{ cell.input }}
17 ```
18 {% endblock input %}
12 {% endblock input %}
19
13
20 {% block pyerr %}
14 {% block pyerr %}
21 {{ super() }}
15 {{ super() }}
22 {% endblock pyerr %}
16 {% endblock pyerr %}
23
17
24 {% block traceback_line %}
18 {% block traceback_line %}
25 {{ line | indent | strip_ansi }}
19 {{ line | indent | strip_ansi }}
26 {% endblock traceback_line %}
20 {% endblock traceback_line %}
27
21
28 {% block pyout %}
22 {% block pyout %}
23
29 {% block data_priority scoped %}
24 {% block data_priority scoped %}
30 {{ super() }}
25 {{ super() }}
31 {% endblock %}
26 {% endblock %}
32 {% endblock pyout %}
27 {% endblock pyout %}
33
28
34 {% block stream %}
29 {% block stream %}
35 {{ output.text | indent }}
30 {{ output.text | indent }}
36 {% endblock stream %}
31 {% endblock stream %}
37
32
38 {% block data_svg %}
33 {% block data_svg %}
39 [!image]({{ output.svg_filename }})
34 ![svg]({{ output.svg_filename | path2url }})
40 {% endblock data_svg %}
35 {% endblock data_svg %}
41
36
42 {% block data_png %}
37 {% block data_png %}
43 [!image]({{ output.png_filename }})
38 ![png]({{ output.png_filename | path2url }})
44 {% endblock data_png %}
39 {% endblock data_png %}
45
40
46 {% block data_jpg %}
41 {% block data_jpg %}
47 [!image]({{ output.jpg_filename }})
42 ![jpeg]({{ output.jpeg_filename | path2url }})
48 {% endblock data_jpg %}
43 {% endblock data_jpg %}
49
44
50 {% block data_latex %}
45 {% block data_latex %}
51 $$
52 {{ output.latex }}
46 {{ output.latex }}
53 $$
54 {% endblock data_latex %}
47 {% endblock data_latex %}
55
48
49 {% block data_html scoped %}
50 {{ output.html }}
51 {% endblock data_html %}
52
56 {% block data_text scoped %}
53 {% block data_text scoped %}
57 {{ output.text | indent }}
54 {{ output.text | indent }}
58 {% endblock data_text %}
55 {% endblock data_text %}
59
56
60 {% block markdowncell scoped %}
57 {% block markdowncell scoped %}
61 {{ cell.source | wrap_text(80) }}
58 {{ cell.source | wrap_text(80) }}
62 {% endblock markdowncell %}
59 {% endblock markdowncell %}
63
60
61
64 {% block headingcell scoped %}
62 {% block headingcell scoped %}
65 {{ '#' * cell.level }} {{ cell.source | replace('\n', ' ') }}
63 {{ '#' * cell.level }} {{ cell.source | replace('\n', ' ') }}
66 {% endblock headingcell %}
64 {% endblock headingcell %}
67
65
68 {% block rawcell scoped %}
66 {% block rawcell scoped %}
69 {{ cell.source }}
67 {{ cell.source }}
70 {% endblock rawcell %}
68 {% endblock rawcell %}
71
69
72 {% block unknowncell scoped %}
70 {% block unknowncell scoped %}
73 unknown type {{ cell.type }}
71 unknown type {{ cell.type }}
74 {% endblock unknowncell %} No newline at end of file
72 {% endblock unknowncell %}
@@ -1,79 +1,84 b''
1 {%- extends 'display_priority.tpl' -%}
1 {%- extends 'display_priority.tpl' -%}
2
2
3
3
4 {% block in_prompt %}
4 {% block in_prompt %}
5
6 In[{{ cell.prompt_number if cell.prompt_number else ' ' }}]:
7
8 .. code:: python
9
10 {% endblock in_prompt %}
5 {% endblock in_prompt %}
11
6
12 {% block output_prompt %}
7 {% block output_prompt %}
13 {% if cell.haspyout -%}
14 Out[{{ cell.prompt_number }}]:
15 {% endif %}
16 {% endblock output_prompt %}
8 {% endblock output_prompt %}
17
9
18 {% block input %}
10 {% block input %}
11 {%- if not cell.input.isspace() -%}
12 .. code:: python
13
19 {{ cell.input | indent}}
14 {{ cell.input | indent}}
15 {%- endif -%}
20 {% endblock input %}
16 {% endblock input %}
21
17
22 {% block pyerr %}
18 {% block pyerr %}
23 ::
19 ::
20
24 {{ super() }}
21 {{ super() }}
25 {% endblock pyerr %}
22 {% endblock pyerr %}
26
23
27 {% block traceback_line %}
24 {% block traceback_line %}
28 {{ line | indent | strip_ansi }}
25 {{ line | indent | strip_ansi }}
29 {% endblock traceback_line %}
26 {% endblock traceback_line %}
30
27
31 {% block pyout %}
28 {% block pyout %}
32 {% block data_priority scoped %}
29 {% block data_priority scoped %}
33 {{ super() }}
30 {{ super() }}
34 {% endblock %}
31 {% endblock %}
35 {% endblock pyout %}
32 {% endblock pyout %}
36
33
37 {% block stream %}
34 {% block stream %}
38 .. parsed-literal::
35 .. parsed-literal::
39
36
40 {{ output.text | indent }}
37 {{ output.text | indent }}
41 {% endblock stream %}
38 {% endblock stream %}
42
39
43 {% block data_svg %}
40 {% block data_svg %}
44 .. image:: {{ output.svg_filename }}
41 .. image:: {{ output.svg_filename }}
45 {% endblock data_svg %}
42 {% endblock data_svg %}
46
43
47 {% block data_png %}
44 {% block data_png %}
48 .. image:: {{ output.png_filename }}
45 .. image:: {{ output.png_filename }}
49 {% endblock data_png %}
46 {% endblock data_png %}
50
47
51 {% block data_jpg %}
48 {% block data_jpg %}
52 ..jpg image:: {{ output.jpg_filename }}
49 .. image:: {{ output.jpeg_filename }}
53 {% endblock data_jpg %}
50 {% endblock data_jpg %}
54
51
55 {% block data_latex %}
52 {% block data_latex %}
56 .. math::
53 .. math::
57 {{ output.latex | indent }}
54
55 {{ output.latex | strip_dollars | indent }}
58 {% endblock data_latex %}
56 {% endblock data_latex %}
59
57
60 {% block data_text scoped %}
58 {% block data_text scoped %}
61 .. parsed-literal::
59 .. parsed-literal::
60
62 {{ output.text | indent }}
61 {{ output.text | indent }}
63 {% endblock data_text %}
62 {% endblock data_text %}
64
63
64 {% block data_html scoped %}
65 .. raw:: html
66
67 {{ output.html | indent }}
68 {% endblock data_html %}
69
65 {% block markdowncell scoped %}
70 {% block markdowncell scoped %}
66 {{ cell.source | markdown2rst }}
71 {{ cell.source | markdown2rst }}
67 {% endblock markdowncell %}
72 {% endblock markdowncell %}
68
73
69 {% block headingcell scoped %}
74 {% block headingcell scoped %}
70 {{ ("#" * cell.level + cell.source) | replace('\n', ' ') | markdown2rst }}
75 {{ ("#" * cell.level + cell.source) | replace('\n', ' ') | markdown2rst }}
71 {% endblock headingcell %}
76 {% endblock headingcell %}
72
77
73 {% block rawcell scoped %}
78 {% block rawcell scoped %}
74 {{ cell.source }}
79 {{ cell.source }}
75 {% endblock rawcell %}
80 {% endblock rawcell %}
76
81
77 {% block unknowncell scoped %}
82 {% block unknowncell scoped %}
78 unknown type {{cell.type}}
83 unknown type {{cell.type}}
79 {% endblock unknowncell %}
84 {% endblock unknowncell %}
General Comments 0
You need to be logged in to leave comments. Login now