##// END OF EJS Templates
finish up config merging
Matthias BUSSONNIER -
Show More
@@ -1,71 +1,70 b''
1 """
1 """
2 Exporter that exports Basic HTML.
2 Exporter that exports Basic HTML.
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 IPython.utils.traitlets import Unicode
17 from IPython.utils.traitlets import Unicode
18 from IPython.config import Config
18 from IPython.config import Config
19 from copy import deepcopy
19 from copy import deepcopy
20
20
21 import nbconvert.transformers.csshtmlheader
21 import nbconvert.transformers.csshtmlheader
22
22
23 # local import
23 # local import
24 import exporter
24 import exporter
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes
27 # Classes
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class BasicHtmlExporter(exporter.Exporter):
30 class BasicHtmlExporter(exporter.Exporter):
31 """
31 """
32 Exports a basic HTML document. This exporter assists with the export of
32 Exports a basic HTML document. This exporter assists with the export of
33 HTML. Inherit from it if you are writing your own HTML template and need
33 HTML. Inherit from it if you are writing your own HTML template and need
34 custom transformers/filters. If you don't need custom transformers/
34 custom transformers/filters. If you don't need custom transformers/
35 filters, just change the 'template_file' config option.
35 filters, just change the 'template_file' config option.
36 """
36 """
37
37
38 file_extension = Unicode(
38 file_extension = Unicode(
39 'html', config=True,
39 'html', config=True,
40 help="Extension of the file that should be written to disk"
40 help="Extension of the file that should be written to disk"
41 )
41 )
42
42
43 template_file = Unicode(
43 template_file = Unicode(
44 'basichtml', config=True,
44 'basichtml', config=True,
45 help="Name of the template file to use")
45 help="Name of the template file to use")
46
46
47 _default_config = Config({})
48
47
49 def __init__(self, transformers=None, filters=None, config=None, **kw):
48 def __init__(self, transformers=None, filters=None, config=None, **kw):
50
49
51 c = self.default_config
50 c = self.default_config
52 if config :
51 if config :
53 c.update(config)
52 c.merge(config)
54
53
55 super(BasicHtmlExporter, self).__init__(transformers=transformers,
54 super(BasicHtmlExporter, self).__init__(transformers=transformers,
56 filters=filters,
55 filters=filters,
57 config=c,
56 config=c,
58 **kw)
57 **kw)
59
58
60
59
61 def _register_transformers(self):
60 def _register_transformers(self):
62 """
61 """
63 Register all of the transformers needed for this exporter.
62 Register all of the transformers needed for this exporter.
64 """
63 """
65
64
66 #Register the transformers of the base class.
65 #Register the transformers of the base class.
67 super(BasicHtmlExporter, self)._register_transformers()
66 super(BasicHtmlExporter, self)._register_transformers()
68
67
69 #Register CSSHtmlHeaderTransformer transformer
68 #Register CSSHtmlHeaderTransformer transformer
70 self.register_transformer(nbconvert.transformers.csshtmlheader.CSSHtmlHeaderTransformer)
69 self.register_transformer(nbconvert.transformers.csshtmlheader.CSSHtmlHeaderTransformer)
71
70
@@ -1,347 +1,348 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 from copy import deepcopy
23 from copy import deepcopy
24
24
25 # IPython imports
25 # IPython imports
26 from IPython.config.configurable import Configurable
26 from IPython.config.configurable import Configurable
27 from IPython.config import Config
27 from IPython.config import Config
28 from IPython.nbformat import current as nbformat
28 from IPython.nbformat import current as nbformat
29 from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool
29 from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool
30 from IPython.utils.text import indent
30 from IPython.utils.text import indent
31
31
32 # other libs/dependencies
32 # other libs/dependencies
33 from jinja2 import Environment, FileSystemLoader
33 from jinja2 import Environment, FileSystemLoader
34 from markdown import markdown
34 from markdown import markdown
35
35
36 # local import
36 # local import
37 import nbconvert.filters.strings
37 import nbconvert.filters.strings
38 import nbconvert.filters.markdown
38 import nbconvert.filters.markdown
39 import nbconvert.filters.latex
39 import nbconvert.filters.latex
40 import nbconvert.filters.datatypefilter
40 import nbconvert.filters.datatypefilter
41 import nbconvert.filters.highlight
41 import nbconvert.filters.highlight
42 import nbconvert.filters.ansi
42 import nbconvert.filters.ansi
43
43
44 import nbconvert.transformers.extractfigure
44 import nbconvert.transformers.extractfigure
45 import nbconvert.transformers.coalescestreams
45 import nbconvert.transformers.coalescestreams
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Globals and constants
48 # Globals and constants
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51 #Jinja2 extensions to load.
51 #Jinja2 extensions to load.
52 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
52 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
53
53
54 default_filters = {
54 default_filters = {
55 'indent': indent,
55 'indent': indent,
56 'markdown': markdown,
56 'markdown': markdown,
57 'ansi2html': nbconvert.filters.ansi.ansi2html,
57 'ansi2html': nbconvert.filters.ansi.ansi2html,
58 'filter_data_type': nbconvert.filters.datatypefilter.DataTypeFilter,
58 'filter_data_type': nbconvert.filters.datatypefilter.DataTypeFilter,
59 'get_lines': nbconvert.filters.strings.get_lines,
59 'get_lines': nbconvert.filters.strings.get_lines,
60 'highlight': nbconvert.filters.highlight.highlight,
60 'highlight': nbconvert.filters.highlight.highlight,
61 'highlight2html': nbconvert.filters.highlight.highlight,
61 'highlight2html': nbconvert.filters.highlight.highlight,
62 'highlight2latex': nbconvert.filters.highlight.highlight2latex,
62 'highlight2latex': nbconvert.filters.highlight.highlight2latex,
63 'markdown2latex': nbconvert.filters.markdown.markdown2latex,
63 'markdown2latex': nbconvert.filters.markdown.markdown2latex,
64 'markdown2rst': nbconvert.filters.markdown.markdown2rst,
64 'markdown2rst': nbconvert.filters.markdown.markdown2rst,
65 'pycomment': nbconvert.filters.strings.python_comment,
65 'pycomment': nbconvert.filters.strings.python_comment,
66 'rm_ansi': nbconvert.filters.ansi.remove_ansi,
66 'rm_ansi': nbconvert.filters.ansi.remove_ansi,
67 'rm_dollars': nbconvert.filters.strings.strip_dollars,
67 'rm_dollars': nbconvert.filters.strings.strip_dollars,
68 'rm_fake': nbconvert.filters.strings.rm_fake,
68 'rm_fake': nbconvert.filters.strings.rm_fake,
69 'rm_math_space': nbconvert.filters.latex.rm_math_space,
69 'rm_math_space': nbconvert.filters.latex.rm_math_space,
70 'wrap': nbconvert.filters.strings.wrap
70 'wrap': nbconvert.filters.strings.wrap
71 }
71 }
72
72
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74 # Class
74 # Class
75 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
76
76
77 class Exporter(Configurable):
77 class Exporter(Configurable):
78 """
78 """
79 Exports notebooks into other file formats. Uses Jinja 2 templating engine
79 Exports notebooks into other file formats. Uses Jinja 2 templating engine
80 to output new formats. Inherit from this class if you are creating a new
80 to output new formats. Inherit from this class if you are creating a new
81 template type along with new filters/transformers. If the filters/
81 template type along with new filters/transformers. If the filters/
82 transformers provided by default suffice, there is no need to inherit from
82 transformers provided by default suffice, there is no need to inherit from
83 this class. Instead, override the template_file and file_extension
83 this class. Instead, override the template_file and file_extension
84 traits via a config file.
84 traits via a config file.
85
85
86 {filters}
86 {filters}
87 """
87 """
88
88
89
89 # finish the docstring
90
91 __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
90 __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
92
91
93
92
94 template_file = Unicode(
93 template_file = Unicode(
95 '', config=True,
94 '', config=True,
96 help="Name of the template file to use")
95 help="Name of the template file to use")
97
96
98 file_extension = Unicode(
97 file_extension = Unicode(
99 'txt', config=True,
98 'txt', config=True,
100 help="Extension of the file that should be written to disk"
99 help="Extension of the file that should be written to disk"
101 )
100 )
102
101
103 template_path = Unicode(
102 template_path = Unicode(
104 "/../templates/", config=True,
103 "/../templates/", config=True,
105 help="Path where the template files are located.")
104 help="Path where the template files are located.")
106
105
107 template_skeleton_path = Unicode(
106 template_skeleton_path = Unicode(
108 "/../templates/skeleton/", config=True,
107 "/../templates/skeleton/", config=True,
109 help="Path where the template skeleton files are located.")
108 help="Path where the template skeleton files are located.")
110
109
111 #Jinja block definitions
110 #Jinja block definitions
112 jinja_comment_block_start = Unicode("", config=True)
111 jinja_comment_block_start = Unicode("", config=True)
113 jinja_comment_block_end = Unicode("", config=True)
112 jinja_comment_block_end = Unicode("", config=True)
114 jinja_variable_block_start = Unicode("", config=True)
113 jinja_variable_block_start = Unicode("", config=True)
115 jinja_variable_block_end = Unicode("", config=True)
114 jinja_variable_block_end = Unicode("", config=True)
116 jinja_logic_block_start = Unicode("", config=True)
115 jinja_logic_block_start = Unicode("", config=True)
117 jinja_logic_block_end = Unicode("", config=True)
116 jinja_logic_block_end = Unicode("", config=True)
118
117
119 #Extension that the template files use.
118 #Extension that the template files use.
120 template_extension = Unicode(".tpl", config=True)
119 template_extension = Unicode(".tpl", config=True)
121
120
122 #Processors that process the input data prior to the export, set in the
121 #Processors that process the input data prior to the export, set in the
123 #constructor for this class.
122 #constructor for this class.
124 transformers = None
123 transformers = None
125
124
125 _default_config = Config()
126
126
127
127 def __init__(self, transformers=None, filters=None, config=None, **kw):
128 def __init__(self, transformers=None, filters=None, config=None, **kw):
128 """
129 """
129 Public constructor
130 Public constructor
130
131
131 Parameters
132 Parameters
132 ----------
133 ----------
133 transformers : list[of transformer]
134 transformers : list[of transformer]
134 Custom transformers to apply to the notebook prior to engaging
135 Custom transformers to apply to the notebook prior to engaging
135 the Jinja template engine. Any transformers specified here
136 the Jinja template engine. Any transformers specified here
136 will override existing transformers if a naming conflict
137 will override existing transformers if a naming conflict
137 occurs.
138 occurs.
138 filters : dict[of filter]
139 filters : dict[of filter]
139 filters specified here will override existing filters if a naming
140 filters specified here will override existing filters if a naming
140 conflict occurs. Filters are availlable in jinja template through
141 conflict occurs. Filters are availlable in jinja template through
141 the name of the corresponding key. Cf class docstring for
142 the name of the corresponding key. Cf class docstring for
142 availlable default filters.
143 availlable default filters.
143 config : config
144 config : config
144 User configuration instance.
145 User configuration instance.
145 """
146 """
146
147
147 #Call the base class constructor
148 #Call the base class constructor
148 super(Exporter, self).__init__(config=config, **kw)
149 super(Exporter, self).__init__(config=config, **kw)
149
150
150 #Standard environment
151 #Standard environment
151 self._init_environment()
152 self._init_environment()
152
153
153 #Add transformers
154 #Add transformers
154 self._register_transformers()
155 self._register_transformers()
155
156
156 #Add filters to the Jinja2 environment
157 #Add filters to the Jinja2 environment
157 self._register_filters()
158 self._register_filters()
158
159
159 #Load user transformers. Overwrite existing transformers if need be.
160 #Load user transformers. Overwrite existing transformers if need be.
160 if transformers :
161 if transformers :
161 for transformer in transformers:
162 for transformer in transformers:
162 self.register_transformer(transformer)
163 self.register_transformer(transformer)
163
164
164 #Load user filters. Overwrite existing filters if need be.
165 #Load user filters. Overwrite existing filters if need be.
165 if not filters is None:
166 if not filters is None:
166 for key, user_filter in filters.iteritems():
167 for key, user_filter in filters.iteritems():
167 if issubclass(user_filter, MetaHasTraits):
168 if issubclass(user_filter, MetaHasTraits):
168 self.environment.filters[key] = user_filter(config=config)
169 self.environment.filters[key] = user_filter(config=config)
169 else:
170 else:
170 self.environment.filters[key] = user_filter
171 self.environment.filters[key] = user_filter
171
172
172 @property
173 @property
173 def default_config(self):
174 def default_config(self):
174 if self._default_config:
175 if self._default_config:
175 return Config(deepcopy(self._default_config))
176 return Config(deepcopy(self._default_config))
176 else :
177 else :
177 return Config({})
178 return Config()
178
179
179
180
180 def from_notebook_node(self, nb, resources=None):
181 def from_notebook_node(self, nb, resources=None):
181 """
182 """
182 Convert a notebook from a notebook node instance.
183 Convert a notebook from a notebook node instance.
183
184
184 Parameters
185 Parameters
185 ----------
186 ----------
186 nb : Notebook node
187 nb : Notebook node
187 resources : a dict of additional resources that
188 resources : a dict of additional resources that
188 can be accessed read/write by transformers
189 can be accessed read/write by transformers
189 and filters.
190 and filters.
190 """
191 """
191 if resources is None:
192 if resources is None:
192 resources = {}
193 resources = {}
193 nb, resources = self._preprocess(nb, resources)
194 nb, resources = self._preprocess(nb, resources)
194
195
195 #Load the template file.
196 #Load the template file.
196 self.template = self.environment.get_template(self.template_file+self.template_extension)
197 self.template = self.environment.get_template(self.template_file+self.template_extension)
197
198
198 return self.template.render(nb=nb, resources=resources), resources
199 return self.template.render(nb=nb, resources=resources), resources
199
200
200
201
201 def from_filename(self, filename):
202 def from_filename(self, filename):
202 """
203 """
203 Convert a notebook from a notebook file.
204 Convert a notebook from a notebook file.
204
205
205 Parameters
206 Parameters
206 ----------
207 ----------
207 filename : str
208 filename : str
208 Full filename of the notebook file to open and convert.
209 Full filename of the notebook file to open and convert.
209 """
210 """
210
211
211 with io.open(filename) as f:
212 with io.open(filename) as f:
212 return self.from_notebook_node(nbformat.read(f, 'json'))
213 return self.from_notebook_node(nbformat.read(f, 'json'))
213
214
214
215
215 def from_file(self, file_stream):
216 def from_file(self, file_stream):
216 """
217 """
217 Convert a notebook from a notebook file.
218 Convert a notebook from a notebook file.
218
219
219 Parameters
220 Parameters
220 ----------
221 ----------
221 file_stream : file-like object
222 file_stream : file-like object
222 Notebook file-like object to convert.
223 Notebook file-like object to convert.
223 """
224 """
224 return self.from_notebook_node(nbformat.read(file_stream, 'json'))
225 return self.from_notebook_node(nbformat.read(file_stream, 'json'))
225
226
226
227
227 def register_transformer(self, transformer):
228 def register_transformer(self, transformer):
228 """
229 """
229 Register a transformer.
230 Register a transformer.
230 Transformers are classes that act upon the notebook before it is
231 Transformers are classes that act upon the notebook before it is
231 passed into the Jinja templating engine. Transformers are also
232 passed into the Jinja templating engine. Transformers are also
232 capable of passing additional information to the Jinja
233 capable of passing additional information to the Jinja
233 templating engine.
234 templating engine.
234
235
235 Parameters
236 Parameters
236 ----------
237 ----------
237 transformer : transformer
238 transformer : transformer
238 """
239 """
239 if self.transformers is None:
240 if self.transformers is None:
240 self.transformers = []
241 self.transformers = []
241
242
242 if inspect.isfunction(transformer):
243 if inspect.isfunction(transformer):
243 self.transformers.append(transformer)
244 self.transformers.append(transformer)
244 return transformer
245 return transformer
245 elif isinstance(transformer, MetaHasTraits):
246 elif isinstance(transformer, MetaHasTraits):
246 transformer_instance = transformer(config=self.config)
247 transformer_instance = transformer(config=self.config)
247 self.transformers.append(transformer_instance)
248 self.transformers.append(transformer_instance)
248 return transformer_instance
249 return transformer_instance
249 else:
250 else:
250 transformer_instance = transformer()
251 transformer_instance = transformer()
251 self.transformers.append(transformer_instance)
252 self.transformers.append(transformer_instance)
252 return transformer_instance
253 return transformer_instance
253
254
254
255
255 def register_filter(self, name, filter):
256 def register_filter(self, name, filter):
256 """
257 """
257 Register a filter.
258 Register a filter.
258 A filter is a function that accepts and acts on one string.
259 A filter is a function that accepts and acts on one string.
259 The filters are accesible within the Jinja templating engine.
260 The filters are accesible within the Jinja templating engine.
260
261
261 Parameters
262 Parameters
262 ----------
263 ----------
263 name : str
264 name : str
264 name to give the filter in the Jinja engine
265 name to give the filter in the Jinja engine
265 filter : filter
266 filter : filter
266 """
267 """
267 if inspect.isfunction(filter):
268 if inspect.isfunction(filter):
268 self.environment.filters[name] = filter
269 self.environment.filters[name] = filter
269 elif isinstance(filter, MetaHasTraits):
270 elif isinstance(filter, MetaHasTraits):
270 self.environment.filters[name] = filter(config=self.config)
271 self.environment.filters[name] = filter(config=self.config)
271 else:
272 else:
272 self.environment.filters[name] = filter()
273 self.environment.filters[name] = filter()
273 return self.environment.filters[name]
274 return self.environment.filters[name]
274
275
275
276
276 def _register_transformers(self):
277 def _register_transformers(self):
277 """
278 """
278 Register all of the transformers needed for this exporter.
279 Register all of the transformers needed for this exporter.
279 """
280 """
280
281
281 self.register_transformer(nbconvert.transformers.coalescestreams.coalesce_streams)
282 self.register_transformer(nbconvert.transformers.coalescestreams.coalesce_streams)
282
283
283 #Remember the figure extraction transformer so it can be enabled and
284 #Remember the figure extraction transformer so it can be enabled and
284 #disabled easily later.
285 #disabled easily later.
285 self.extract_figure_transformer = self.register_transformer(nbconvert.transformers.extractfigure.ExtractFigureTransformer)
286 self.extract_figure_transformer = self.register_transformer(nbconvert.transformers.extractfigure.ExtractFigureTransformer)
286
287
287
288
288 def _register_filters(self):
289 def _register_filters(self):
289 """
290 """
290 Register all of the filters required for the exporter.
291 Register all of the filters required for the exporter.
291 """
292 """
292 for k,v in default_filters.iteritems():
293 for k,v in default_filters.iteritems():
293 self.register_filter(k,v)
294 self.register_filter(k,v)
294
295
295
296
296 def _init_environment(self):
297 def _init_environment(self):
297 """
298 """
298 Create the Jinja templating environment.
299 Create the Jinja templating environment.
299 """
300 """
300
301
301 self.environment = Environment(
302 self.environment = Environment(
302 loader=FileSystemLoader([
303 loader=FileSystemLoader([
303 os.path.dirname(os.path.realpath(__file__)) + self.template_path,
304 os.path.dirname(os.path.realpath(__file__)) + self.template_path,
304 os.path.dirname(os.path.realpath(__file__)) + self.template_skeleton_path,
305 os.path.dirname(os.path.realpath(__file__)) + self.template_skeleton_path,
305 ]),
306 ]),
306 extensions=JINJA_EXTENSIONS
307 extensions=JINJA_EXTENSIONS
307 )
308 )
308
309
309 #Set special Jinja2 syntax that will not conflict with latex.
310 #Set special Jinja2 syntax that will not conflict with latex.
310 if self.jinja_logic_block_start:
311 if self.jinja_logic_block_start:
311 self.environment.block_start_string = self.jinja_logic_block_start
312 self.environment.block_start_string = self.jinja_logic_block_start
312 if self.jinja_logic_block_end:
313 if self.jinja_logic_block_end:
313 self.environment.block_end_string = self.jinja_logic_block_end
314 self.environment.block_end_string = self.jinja_logic_block_end
314 if self.jinja_variable_block_start:
315 if self.jinja_variable_block_start:
315 self.environment.variable_start_string = self.jinja_variable_block_start
316 self.environment.variable_start_string = self.jinja_variable_block_start
316 if self.jinja_variable_block_end:
317 if self.jinja_variable_block_end:
317 self.environment.variable_end_string = self.jinja_variable_block_end
318 self.environment.variable_end_string = self.jinja_variable_block_end
318 if self.jinja_comment_block_start:
319 if self.jinja_comment_block_start:
319 self.environment.comment_start_string = self.jinja_comment_block_start
320 self.environment.comment_start_string = self.jinja_comment_block_start
320 if self.jinja_comment_block_end:
321 if self.jinja_comment_block_end:
321 self.environment.comment_end_string = self.jinja_comment_block_end
322 self.environment.comment_end_string = self.jinja_comment_block_end
322
323
323
324
324 def _preprocess(self, nb, resources):
325 def _preprocess(self, nb, resources):
325 """
326 """
326 Preprocess the notebook before passing it into the Jinja engine.
327 Preprocess the notebook before passing it into the Jinja engine.
327 To preprocess the notebook is to apply all of the
328 To preprocess the notebook is to apply all of the
328
329
329 Parameters
330 Parameters
330 ----------
331 ----------
331 nb : notebook node
332 nb : notebook node
332 notebook that is being exported.
333 notebook that is being exported.
333 resources : a dict of additional resources that
334 resources : a dict of additional resources that
334 can be accessed read/write by transformers
335 can be accessed read/write by transformers
335 and filters.
336 and filters.
336 """
337 """
337
338
338 # Do a deepcopy first,
339 # Do a deepcopy first,
339 # we are never safe enough with what the transformers could do.
340 # we are never safe enough with what the transformers could do.
340 nbc = deepcopy(nb)
341 nbc = deepcopy(nb)
341 resc = deepcopy(resources)
342 resc = deepcopy(resources)
342 #Run each transformer on the notebook. Carry the output along
343 #Run each transformer on the notebook. Carry the output along
343 #to each transformer
344 #to each transformer
344 for transformer in self.transformers:
345 for transformer in self.transformers:
345 nb, resources = transformer(nbc, resc)
346 nb, resources = transformer(nbc, resc)
346 return nb, resources
347 return nb, resources
347
348
@@ -1,137 +1,137 b''
1 """
1 """
2 Exporter that allows Latex Jinja templates to work. Contains logic to
2 Exporter that allows Latex Jinja templates to work. Contains logic to
3 appropriately prepare IPYNB files for export to LaTeX. Including but
3 appropriately prepare IPYNB files for export to LaTeX. Including but
4 not limited to escaping LaTeX, fixing math region tags, using special
4 not limited to escaping LaTeX, fixing math region tags, using special
5 tags to circumvent Jinja/Latex syntax conflicts.
5 tags to circumvent Jinja/Latex syntax conflicts.
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 # Stdlib imports
19 # Stdlib imports
20 import os
20 import os
21
21
22 # IPython imports
22 # IPython imports
23 from IPython.utils.traitlets import Unicode
23 from IPython.utils.traitlets import Unicode
24 from IPython.config import Config
24 from IPython.config import Config
25
25
26 # other libs/dependencies
26 # other libs/dependencies
27 from jinja2 import Environment, FileSystemLoader
27 from jinja2 import Environment, FileSystemLoader
28
28
29 import nbconvert.filters.latex
29 import nbconvert.filters.latex
30 import nbconvert.filters.highlight
30 import nbconvert.filters.highlight
31 from nbconvert.transformers.latex import LatexTransformer
31 from nbconvert.transformers.latex import LatexTransformer
32
32
33 # local import
33 # local import
34 import exporter
34 import exporter
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Classes and functions
37 # Classes and functions
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 class LatexExporter(exporter.Exporter):
40 class LatexExporter(exporter.Exporter):
41 """
41 """
42 Exports to a Latex template. Inherit from this class if your template is
42 Exports to a Latex template. Inherit from this class if your template is
43 LaTeX based and you need custom tranformers/filters. Inherit from it if
43 LaTeX based and you need custom tranformers/filters. Inherit from it if
44 you are writing your own HTML template and need custom tranformers/filters.
44 you are writing your own HTML template and need custom tranformers/filters.
45 If you don't need custom tranformers/filters, just change the
45 If you don't need custom tranformers/filters, just change the
46 'template_file' config option. Place your template in the special "/latex"
46 'template_file' config option. Place your template in the special "/latex"
47 subfolder of the "../templates" folder.
47 subfolder of the "../templates" folder.
48 """
48 """
49
49
50 file_extension = Unicode(
50 file_extension = Unicode(
51 'tex', config=True,
51 'tex', config=True,
52 help="Extension of the file that should be written to disk")
52 help="Extension of the file that should be written to disk")
53
53
54 template_file = Unicode(
54 template_file = Unicode(
55 'base', config=True,
55 'base', config=True,
56 help="Name of the template file to use")
56 help="Name of the template file to use")
57
57
58 #Latex constants
58 #Latex constants
59 template_path = Unicode(
59 template_path = Unicode(
60 "/../templates/latex/", config=True,
60 "/../templates/latex/", config=True,
61 help="Path where the template files are located.")
61 help="Path where the template files are located.")
62
62
63 template_skeleton_path = Unicode(
63 template_skeleton_path = Unicode(
64 "/../templates/latex/skeleton/", config=True,
64 "/../templates/latex/skeleton/", config=True,
65 help="Path where the template skeleton files are located.")
65 help="Path where the template skeleton files are located.")
66
66
67 #Special Jinja2 syntax that will not conflict when exporting latex.
67 #Special Jinja2 syntax that will not conflict when exporting latex.
68 jinja_comment_block_start = Unicode("((=", config=True)
68 jinja_comment_block_start = Unicode("((=", config=True)
69 jinja_comment_block_end = Unicode("=))", config=True)
69 jinja_comment_block_end = Unicode("=))", config=True)
70 jinja_variable_block_start = Unicode("(((", config=True)
70 jinja_variable_block_start = Unicode("(((", config=True)
71 jinja_variable_block_end = Unicode(")))", config=True)
71 jinja_variable_block_end = Unicode(")))", config=True)
72 jinja_logic_block_start = Unicode("((*", config=True)
72 jinja_logic_block_start = Unicode("((*", config=True)
73 jinja_logic_block_end = Unicode("*))", config=True)
73 jinja_logic_block_end = Unicode("*))", config=True)
74
74
75 #Extension that the template files use.
75 #Extension that the template files use.
76 template_extension = Unicode(".tplx", config=True)
76 template_extension = Unicode(".tplx", config=True)
77
77
78 _default_config = Config({
78 _default_config = Config({
79 'display_data_priority' : ['latex', 'svg', 'png', 'jpg', 'jpeg' , 'text'],
79 'display_data_priority' : ['latex', 'svg', 'png', 'jpg', 'jpeg' , 'text'],
80 'extra_ext_map':{'svg':'pdf'},
80 'extra_ext_map':{'svg':'pdf'},
81 'ExtractFigureTransformer' : Config({'enabled':True})
81 'ExtractFigureTransformer' : Config({'enabled':True})
82 })
82 })
83
83
84 def __init__(self, transformers=None, filters=None, config=None, **kw):
84 def __init__(self, transformers=None, filters=None, config=None, **kw):
85 """
85 """
86 Public constructor
86 Public constructor
87
87
88 Parameters
88 Parameters
89 ----------
89 ----------
90 transformers : list[of transformer]
90 transformers : list[of transformer]
91 Custom transformers to apply to the notebook prior to engaging
91 Custom transformers to apply to the notebook prior to engaging
92 the Jinja template engine. Any transformers specified here
92 the Jinja template engine. Any transformers specified here
93 will override existing transformers if a naming conflict
93 will override existing transformers if a naming conflict
94 occurs.
94 occurs.
95 filters : list[of filter]
95 filters : list[of filter]
96 Custom filters to make accessible to the Jinja templates. Any
96 Custom filters to make accessible to the Jinja templates. Any
97 filters specified here will override existing filters if a
97 filters specified here will override existing filters if a
98 naming conflict occurs.
98 naming conflict occurs.
99 config : config
99 config : config
100 User configuration instance.
100 User configuration instance.
101 """
101 """
102
102
103 #Call base class constructor.
103 #Call base class constructor.
104
104
105 c = self.default_config
105 c = self.default_config
106 if config :
106 if config :
107 c._merge(Config(config))
107 c.merge(Config(config))
108
108
109 super(LatexExporter, self).__init__(transformers, filters, config=c, **kw)
109 super(LatexExporter, self).__init__(transformers, filters, config=c, **kw)
110
110
111 #self.extract_figure_transformer.extra_ext_map={'svg':'pdf'}
111 #self.extract_figure_transformer.extra_ext_map={'svg':'pdf'}
112
112
113
113
114 def _register_filters(self):
114 def _register_filters(self):
115 """
115 """
116 Register all of the filters required for the exporter.
116 Register all of the filters required for the exporter.
117 """
117 """
118
118
119 #Register the filters of the base class.
119 #Register the filters of the base class.
120 super(LatexExporter, self)._register_filters()
120 super(LatexExporter, self)._register_filters()
121
121
122 #Add latex filters to the Jinja2 environment
122 #Add latex filters to the Jinja2 environment
123 self.register_filter('escape_tex', nbconvert.filters.latex.escape_latex)
123 self.register_filter('escape_tex', nbconvert.filters.latex.escape_latex)
124 self.register_filter('highlight', nbconvert.filters.highlight.highlight2latex)
124 self.register_filter('highlight', nbconvert.filters.highlight.highlight2latex)
125
125
126
126
127 def _register_transformers(self):
127 def _register_transformers(self):
128 """
128 """
129 Register all of the transformers needed for this exporter.
129 Register all of the transformers needed for this exporter.
130 """
130 """
131
131
132 #Register the transformers of the base class.
132 #Register the transformers of the base class.
133 super(LatexExporter, self)._register_transformers()
133 super(LatexExporter, self)._register_transformers()
134
134
135 #Register latex transformer
135 #Register latex transformer
136 self.register_transformer(LatexTransformer)
136 self.register_transformer(LatexTransformer)
137
137
@@ -1,62 +1,59 b''
1 """
1 """
2 Python exporter which exports Notebook code into a PY file.
2 Python exporter which exports Notebook code into a PY file.
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.utils.traitlets import Unicode
16 from IPython.utils.traitlets import Unicode
17
17
18 # local import
18 # local import
19 import exporter
19 import exporter
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Classes
22 # Classes
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class PythonExporter(exporter.Exporter):
25 class PythonExporter(exporter.Exporter):
26 """
26 """
27 Exports a Python code file.
27 Exports a Python code file.
28 """
28 """
29
29
30 file_extension = Unicode(
30 file_extension = Unicode(
31 'py', config=True,
31 'py', config=True,
32 help="Extension of the file that should be written to disk")
32 help="Extension of the file that should be written to disk")
33
33
34 template_file = Unicode(
34 template_file = Unicode(
35 'python', config=True,
35 'python', config=True,
36 help="Name of the template file to use")
36 help="Name of the template file to use")
37
37
38 def __init__(self, transformers=None, filters=None, config=None, armor=False, **kw):
38
39 def __init__(self, transformers=None, filters=None, config=None, **kw):
39 """
40 """
40 Public constructor
41 Public constructor
41
42
42 Parameters
43 Parameters
43 ----------
44 ----------
44 transformers : list[of transformer]
45 transformers : list[of transformer]
45 Custom transformers to apply to the notebook prior to engaging
46 Custom transformers to apply to the notebook prior to engaging
46 the Jinja template engine. Any transformers specified here
47 the Jinja template engine. Any transformers specified here
47 will override existing transformers if a naming conflict
48 will override existing transformers if a naming conflict
48 occurs.
49 occurs.
49 filters : list[of filter]
50 filters : dict{of filter}
50 Custom filters to make accessible to the Jinja templates. Any
51 Custom filters to make accessible to the Jinja templates. Any
51 filters specified here will override existing filters if a
52 filters specified here will override existing filters if a
52 naming conflict occurs.
53 naming conflict occurs.
53 config : config
54 config : config
54 User configuration instance.
55 User configuration instance.
55 """
56 """
56
57
57 #Call base class constructor.
58 #Call base class constructor.
58 super(PythonExporter, self).__init__(transformers, filters, config, **kw)
59 super(PythonExporter, self).__init__(transformers, filters, config, **kw)
59
60 #Set defaults
61 self.extract_figure_transformer.enabled = False
62
@@ -1,52 +1,52 b''
1 """
1 """
2 Exporter for exporting notebooks to restructured text.
2 Exporter for exporting notebooks to restructured text.
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.utils.traitlets import Unicode
16 from IPython.utils.traitlets import Unicode
17 from IPython.config import Config
17 from IPython.config import Config
18
18
19 # local import
19 # local import
20 import exporter
20 import exporter
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Classes
23 # Classes
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 class RstExporter(exporter.Exporter):
26 class RstExporter(exporter.Exporter):
27 """
27 """
28 Exports restructured text documents.
28 Exports restructured text documents.
29 """
29 """
30
30
31 file_extension = Unicode(
31 file_extension = Unicode(
32 'rst', config=True,
32 'rst', config=True,
33 help="Extension of the file that should be written to disk")
33 help="Extension of the file that should be written to disk")
34
34
35 template_file = Unicode(
35 template_file = Unicode(
36 'rst', config=True,
36 'rst', config=True,
37 help="Name of the template file to use")
37 help="Name of the template file to use")
38
38
39 _default_config = Config({'ExtractFigureTransformer':{'enabled':True}})
39 _default_config = Config({'ExtractFigureTransformer':{'enabled':True}})
40
40
41
41
42 def __init__(self, transformers=None, filters=None, config=None, **kw):
42 def __init__(self, transformers=None, filters=None, config=None, **kw):
43
43
44 c = self.default_config
44 c = self.default_config
45 if config :
45 if config :
46 c._merge(config)
46 c.merge(config)
47
47
48 super(RstExporter, self).__init__(transformers=transformers,
48 super(RstExporter, self).__init__(transformers=transformers,
49 filters=filters,
49 filters=filters,
50 config=c,
50 config=c,
51 **kw)
51 **kw)
52
52
General Comments 0
You need to be logged in to leave comments. Login now