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