##// END OF EJS Templates
Finished a rough draft of the exporters.
Jonathan Frederic -
Show More
@@ -0,0 +1,47
1 """TODO: Docstring
2 """
3
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 # local import
17 import exporter
18 import transformers.csshtmlheader
19
20 #-----------------------------------------------------------------------------
21 # Classes
22 #-----------------------------------------------------------------------------
23 class HtmlExporter(exporter.Exporter):
24
25 def __init__(self, preprocessors=None, jinja_filters=None, config=None, full_html=True, **kw):
26
27 #Call base class constructor.
28 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
29
30 #Set defaults
31 self.file_extension = "html"
32 self.extract_figure_transformer.enabled = True
33
34 #Load the correct template
35 if full_html:
36 self.template_file = "fullhtml"
37 else:
38 self.template_file = "basichtml"
39
40 def _register_transformers(self):
41
42 #Register the transformers of the base class.
43 super(exporter.Exporter, self)._register_transformers()
44
45 #Register latex transformer
46 self.register_transformer(transformers.csshtmlheader.CSSHtmlHeaderTransformer)
47 No newline at end of file
@@ -0,0 +1,32
1 """TODO: Docstring
2 """
3
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 # local import
17 import exporter
18
19 #-----------------------------------------------------------------------------
20 # Classes
21 #-----------------------------------------------------------------------------
22 class MarkdownExporter(exporter.Exporter):
23
24 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
25
26 #Call base class constructor.
27 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
28
29 #Set defaults
30 self.file_extension = "md"
31 self.extract_figure_transformer.enabled = True
32 self.template_file = "markdown"
@@ -0,0 +1,34
1 """TODO: Docstring
2 """
3
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 # local import
17 import exporter
18
19 #-----------------------------------------------------------------------------
20 # Classes
21 #-----------------------------------------------------------------------------
22 class PythonExporter(exporter.Exporter):
23
24 def __init__(self, preprocessors=None, jinja_filters=None, config=None, armor=False, **kw):
25
26 #Call base class constructor.
27 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
28
29 #Set defaults
30 self.file_extension = "py"
31 if armor:
32 self.template_file = "python-armor"
33 else:
34 self.template_file = "python"
@@ -0,0 +1,41
1 """TODO: Docstring
2 """
3
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 # local import
17 import html_exporter
18 import transformers.revealhelp
19
20 #-----------------------------------------------------------------------------
21 # Classes
22 #-----------------------------------------------------------------------------
23 class RevealExporter(html_exporter.HtmlExporter):
24
25 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
26
27 #Call base class constructor.
28 super(html_exporter.HtmlExporter, self).__init__(preprocessors, jinja_filters, config, **kw)
29
30 #Set defaults
31 self.file_extension = "reveal.html"
32 self.template_file = "reveal"
33
34 def _register_transformers(self):
35
36 #Register the transformers of the base class.
37 super(html_exporter.HtmlExporter, self)._register_transformers()
38
39 #Register reveal help transformer
40 self.register_transformer(transformers.revealhelp.RevealHelpTransformer)
41 No newline at end of file
@@ -0,0 +1,51
1 """TODO: Docstring
2 """
3
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 # local import
17 import exporter
18
19 #-----------------------------------------------------------------------------
20 # Classes
21 #-----------------------------------------------------------------------------
22 class RstExporter(exporter.Exporter):
23
24 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
25
26 #Call base class constructor.
27 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
28
29 #Set defaults
30 self.file_extension = "rst"
31 self.template_file = "rst"
32 self.extract_figure_transformer.enabled = True
33
34
35 def _register_filters(self):
36
37 #Register the filters of the base class.
38 super(exporter.Exporter, self)._register_filters()
39
40 #Add latex filters to the Jinja2 environment
41 #self.register_filter('escape_tex', filters.latex.escape_tex)
42
43
44 def _register_transformers(self):
45
46 #Register the transformers of the base class.
47 super(exporter.Exporter, self)._register_transformers()
48
49 #Register latex transformer
50 #self.register_transformer(LatexTransformer)
51
@@ -0,0 +1,48
1 """TODO: Docstring
2 """
3
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 # local import
17 import latex_exporter
18
19 #-----------------------------------------------------------------------------
20 # Classes
21 #-----------------------------------------------------------------------------
22 class SphinxExporter(latex_exporter.LatexExporter):
23
24 def __init__(self, preprocessors=None, jinja_filters=None, config=None, sphinx_type="howto", **kw):
25
26 #Call base class constructor.
27 super(latex_exporter.LatexExporter, self).__init__(preprocessors, jinja_filters, config, **kw)
28
29 #Defaults
30 self.template_file = "latex_sphinx_" + sphinx_type
31
32 def _register_filters(self):
33
34 #Register the filters of the base class.
35 super(latex_exporter.LatexExporter, self)._register_filters()
36
37 #Add latex filters to the Jinja2 environment
38 #self.register_filter('escape_tex', filters.latex.escape_tex)
39
40
41 def _register_transformers(self):
42
43 #Register the transformers of the base class.
44 super(latex_exporter.LatexExporter, self)._register_transformers()
45
46 #Register latex transformer
47 #self.register_transformer(LatexTransformer)
48
@@ -1,23 +1,21
1 """Latex transformer.
1 """Latex transformer.
2
2
3 Module that allows latex output notebooks to be conditioned before
3 Module that allows latex output notebooks to be conditioned before
4 they are converted.
4 they are converted.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2013, the IPython Development Team.
7 # Copyright (c) 2013, the IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Functions
15 # Functions
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17 def export_sphinx_report(nb, config=None):
18 def export_sphinx_report(nb, config=None):
18 pass
19 pass
19 def export_sphinx_report(nb, fileName, config=None):
20 pass
21
20
22 #TODO: Add basic export/import utility functions.
21 #TODO: Add basic export/import utility functions.
23 __author__ = 'root'
@@ -1,268 +1,285
1 """Exporter for the notebook conversion pipeline.
1 """Exporter for the notebook conversion pipeline.
2
2
3 This module defines Exporter, a highly configurable converter
3 This module defines Exporter, a highly configurable converter
4 that uses Jinja2 to export notebook files into different format.
4 that uses Jinja2 to export notebook files into different format.
5
5
6 You can register both pre-transformers that will act on the notebook format
6 You can register both pre-transformers that will act on the notebook format
7 before conversion and jinja filter that would then be available in the templates
7 before conversion and jinja filter that would then be available in the templates
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (c) 2013, the IPython Development Team.
11 # Copyright (c) 2013, the IPython Development Team.
12 #
12 #
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14 #
14 #
15 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 from __future__ import print_function, absolute_import
21 from __future__ import print_function, absolute_import
22
22
23 # Stdlib imports
23 # Stdlib imports
24 import io
24 import io
25 import os
25 import os
26 import copy
26
27
27 # IPython imports
28 # IPython imports
28 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
29 from IPython.nbformat import current as nbformat
30 from IPython.nbformat import current as nbformat
30 from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool
31 from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool
31 from IPython.utils.text import indent
32 from IPython.utils.text import indent
32
33
33 # other libs/dependencies
34 # other libs/dependencies
34 from jinja2 import Environment, FileSystemLoader
35 from jinja2 import Environment, FileSystemLoader
35 from markdown import markdown
36 from markdown import markdown
36
37
37 # local import
38 # local import
38 import filters.strings
39 import filters.strings
39 import filters.markdown
40 import filters.markdown
40 import filters.latex
41 import filters.latex
41 import filters.datatypefilter
42 import filters.datatypefilter
42 import filters.pygments
43 import filters.pygments
43 import filters.ansi
44 import filters.ansi
44
45
45 import transformers.extractfigure
46 import transformers.extractfigure
46 import transformers.csshtmlheader
47 import transformers.revealhelp
48 import transformers.coalescestreams
47 import transformers.coalescestreams
49
48
50
49
51 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
52 # Globals and constants
51 # Globals and constants
53 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
54
53
55 #Standard Jinja2 environment constants
54 #Standard Jinja2 environment constants
56 TEMPLATE_PATH = "/../templates/"
55 TEMPLATE_PATH = "/../templates/"
57 TEMPLATE_SKELETON_PATH = "/../templates/skeleton/"
56 TEMPLATE_SKELETON_PATH = "/../templates/skeleton/"
58 TEMPLATE_EXTENSION = ".tpl"
57 TEMPLATE_EXTENSION = ".tpl"
59
58
60 #Jinja2 extensions to load.
59 #Jinja2 extensions to load.
61 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
60 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
62
61
63 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
64 # Classes and functions
63 # Classes and functions
65 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
66 class Exporter(Configurable):
65 class Exporter(Configurable):
67 """ A Jinja2 base converter templates
66 """ A Jinja2 base converter templates
68
67
69 Pre-process the IPYNB files, feed it through Jinja2 templates,
68 Pre-process the IPYNB files, feed it through Jinja2 templates,
70 and spit an converted files and a data object with other data
69 and spit an converted files and a data object with other data
71 should be mostly configurable
70 should be mostly configurable
72 """
71 """
73
72
74 pre_transformer_order = List(['haspyout_transformer'],
73 pre_transformer_order = List(['haspyout_transformer'],
75 config=True,
74 config=True,
76 help= """
75 help= """
77 An ordered list of pre-transformer to apply to the IPYNB
76 An ordered list of pre-transformer to apply to the IPYNB
78 file before running through templates
77 file before running through templates
79 """
78 """
80 )
79 )
81
80
82 template_file = Unicode(
81 template_file = Unicode(
83 '', config=True,
82 '', config=True,
84 help="Name of the template file to use")
83 help="Name of the template file to use")
85
84
86 file_extension = Unicode(
85 file_extension = Unicode(
87 'txt', config=True,
86 'txt', config=True,
88 help="Extension of the file that should be written to disk"
87 help="Extension of the file that should be written to disk"
89 )
88 )
90
89
91 stdout = Bool(
90 stdout = Bool(
92 True, config=True,
91 True, config=True,
93 help="""Whether to print the converted IPYNB file to stdout
92 help="""Whether to print the converted IPYNB file to stdout
94 "use full do diff files without actually writing a new file"""
93 "use full do diff files without actually writing a new file"""
95 )
94 )
96
95
97 write = Bool(
96 write = Bool(
98 False, config=True,
97 False, config=True,
99 help="""Should the converted notebook file be written to disk
98 help="""Should the converted notebook file be written to disk
100 along with potential extracted resources."""
99 along with potential extracted resources."""
101 )
100 )
102
101
103 #Processors that process the input data prior to the export, set in the
102 #Processors that process the input data prior to the export, set in the
104 #constructor for this class.
103 #constructor for this class.
105 preprocessors = []
104 preprocessors = []
106
105
106 # Public Constructor #####################################################
107
107 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
108 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
108 """ Init a new converter.
109 """ Init a new converter.
109
110
110 config: the Configurable config object to pass around.
111 config: the Configurable config object to pass around.
111
112
112 preprocessors: dict of **available** key/value function to run on
113 preprocessors: dict of **available** key/value function to run on
113 ipynb json data before conversion to extract/in-line file.
114 ipynb json data before conversion to extract/in-line file.
114 See `transformer.py` and `ConfigurableTransformers`
115 See `transformer.py` and `ConfigurableTransformers`
115
116
116 set the order in which the transformers should apply
117 set the order in which the transformers should apply
117 with the `pre_transformer_order` trait of this class
118 with the `pre_transformer_order` trait of this class
118
119
119 transformers registered by this key will take precedence on
120 transformers registered by this key will take precedence on
120 default one.
121 default one.
121
122
122 jinja_filters: dict of supplementary jinja filter that should be made
123 jinja_filters: dict of supplementary jinja filter that should be made
123 available in template. If those are of Configurable Class type,
124 available in template. If those are of Configurable Class type,
124 they will be instanciated with the config object as argument.
125 they will be instanciated with the config object as argument.
125
126
126 user defined filter will overwrite the one available by default.
127 user defined filter will overwrite the one available by default.
127 """
128 """
128
129
129 #Call the base class constructor
130 #Call the base class constructor
130 super(Exporter, self).__init__(config=config, **kw)
131 super(Exporter, self).__init__(config=config, **kw)
131
132
132 #Standard environment
133 #Standard environment
133 self.ext = TEMPLATE_EXTENSION
134 self.ext = TEMPLATE_EXTENSION
134 self._init_environment()
135 self._init_environment()
135
136
136 #TODO: Implement reflection style methods to get user transformers.
137 #TODO: Implement reflection style methods to get user transformers.
137 #if not preprocessors is None:
138 #if not preprocessors is None:
138 # for name in self.pre_transformer_order:
139 # for name in self.pre_transformer_order:
139 # # get the user-defined transformer first
140 # # get the user-defined transformer first
140 # transformer = preprocessors.get(name, getattr(trans, name, None))
141 # transformer = preprocessors.get(name, getattr(trans, name, None))
141 # if isinstance(transformer, MetaHasTraits):
142 # if isinstance(transformer, MetaHasTraits):
142 # transformer = transformer(config=config)
143 # transformer = transformer(config=config)
143 # self.preprocessors.append(transformer)
144 # self.preprocessors.append(transformer)
144
145
145 #Add transformers
146 #Add transformers
146 self._register_transformers()
147 self._register_transformers()
147
148
148 #Add filters to the Jinja2 environment
149 #Add filters to the Jinja2 environment
149 self._register_filters()
150 self._register_filters()
150
151
151 #Load user filters. Overwrite existing filters if need be.
152 #Load user filters. Overwrite existing filters if need be.
152 if not jinja_filters is None:
153 if not jinja_filters is None:
153 for key, user_filter in jinja_filters.iteritems():
154 for key, user_filter in jinja_filters.iteritems():
154 if isinstance(user_filter, MetaHasTraits):
155 if isinstance(user_filter, MetaHasTraits):
155 self.environment.filters[key] = user_filter(config=config)
156 self.environment.filters[key] = user_filter(config=config)
156 else:
157 else:
157 self.environment.filters[key] = user_filter
158 self.environment.filters[key] = user_filter
158
159
159 #Load the template file.
160 self.template = self.environment.get_template(self.template_file+self.ext)
161
160
161 #Set the default datatype priority.
162 self._set_datatype_priority(['svg', 'png', 'latex', 'jpg', 'jpeg','text'])
163
164
165 # Public methods #########################################
162
166
163 def from_notebook_node(self, nb):
167 def from_notebook_node(self, nb):
164 """Export NotebookNode instance
168 """Export NotebookNode instance
165
169
166 nb: NotebookNode to export.
170 nb: NotebookNode to export.
167
171
168 Returns both the converted ipynb file and a dict containing the
172 Returns both the converted ipynb file and a dict containing the
169 resources created along the way via the transformers and Jinja2
173 resources created along the way via the transformers and Jinja2
170 processing.
174 processing.
171 """
175 """
172
176
173 nb, resources = self._preprocess(nb)
177 nb, resources = self._preprocess(nb)
178
179 #Load the template file.
180 self.template = self.environment.get_template(self.template_file+self.ext)
181
174 return self.template.render(nb=nb, resources=resources), resources
182 return self.template.render(nb=nb, resources=resources), resources
175
183
176
184
177 def from_filename(self, filename):
185 def from_filename(self, filename):
178 """Read and export a notebook from a filename
186 """Read and export a notebook from a filename
179
187
180 filename: Filename of the notebook file to export.
188 filename: Filename of the notebook file to export.
181
189
182 Returns both the converted ipynb file and a dict containing the
190 Returns both the converted ipynb file and a dict containing the
183 resources created along the way via the transformers and Jinja2
191 resources created along the way via the transformers and Jinja2
184 processing.
192 processing.
185 """
193 """
186 with io.open(filename) as f:
194 with io.open(filename) as f:
187 return self.from_notebook_node(nbformat.read(f, 'json'))
195 return self.from_notebook_node(nbformat.read(f, 'json'))
188
196
189
197
190 def from_file(self, file_stream):
198 def from_file(self, file_stream):
191 """Read and export a notebook from a file stream
199 """Read and export a notebook from a file stream
192
200
193 file_stream: File handle of file that contains notebook data.
201 file_stream: File handle of file that contains notebook data.
194
202
195 Returns both the converted ipynb file and a dict containing the
203 Returns both the converted ipynb file and a dict containing the
196 resources created along the way via the transformers and Jinja2
204 resources created along the way via the transformers and Jinja2
197 processing.
205 processing.
198 """
206 """
199
207
200 return self.from_notebook_node(nbformat.read(file_stream, 'json'))
208 return self.from_notebook_node(nbformat.read(file_stream, 'json'))
201
209
202
210
203 def register_transformer(self, transformer):
211 def register_transformer(self, transformer):
204 if MetaHasTraits(transformer):
212 if MetaHasTraits(transformer):
205 self.preprocessors.append(transformer(config=self.config))
213 self.preprocessors.append(transformer(config=self.config))
206 else:
214 else:
207 self.preprocessors.append(transformer)
215 self.preprocessors.append(transformer)
208
216
209
217
210 def register_filter(self, name, filter):
218 def register_filter(self, name, filter):
211 if MetaHasTraits(filter):
219 if MetaHasTraits(filter):
212 self.environment.filters[name] = filter(config=self.config)
220 self.environment.filters[name] = filter(config=self.config)
213 else:
221 else:
214 self.environment.filters[name] = filter
222 self.environment.filters[name] = filter
223 return self.environment.filters[name]
215
224
225 # Protected and Private methods #########################################
216
226
217 def _register_transformers(self):
227 def _register_transformers(self):
218 self.register_transformer(transformers.coalescestreams.coalesce_streams)
228 self.register_transformer(transformers.coalescestreams.coalesce_streams)
219 self.register_transformer(transformers.extractfigure.ExtractFigureTransformer)
229
220 self.register_transformer(transformers.revealhelp.RevealHelpTransformer)
230 #Remember the figure extraction transformer so it can be enabled and
221 self.register_transformer(transformers.csshtmlheader.CSSHtmlHeaderTransformer)
231 #disabled easily later.
232 self.extract_figure_transformer = self.register_transformer(transformers.extractfigure.ExtractFigureTransformer)
233 self.extract_figure_transformer.enabled = False
222
234
223
235
224 def _register_filters(self):
236 def _register_filters(self):
225 self.register_filter('indent', indent)
237 self.register_filter('indent', indent)
226 self.register_filter('markdown', markdown)
238 self.register_filter('markdown', markdown)
227 self.register_filter('ansi2html', filters.ansi.ansi2html)
239 self.register_filter('ansi2html', filters.ansi.ansi2html)
228 self.register_filter('filter_data_type', filters.datatypefilter.DataTypeFilter)
240 self.register_filter('filter_data_type', filters.datatypefilter.DataTypeFilter)
229 self.register_filter('get_lines', filters.strings.get_lines)
241 self.register_filter('get_lines', filters.strings.get_lines)
230 self.register_filter('highlight', filters.pygments.highlight)
242 self.register_filter('highlight', filters.pygments.highlight)
231 self.register_filter('highlight2html', filters.pygments.highlight)
243 self.register_filter('highlight2html', filters.pygments.highlight)
232 self.register_filter('highlight2latex', filters.pygments.highlight2latex)
244 self.register_filter('highlight2latex', filters.pygments.highlight2latex)
233 self.register_filter('markdown2latex', filters.markdown.markdown2latex)
245 self.register_filter('markdown2latex', filters.markdown.markdown2latex)
234 self.register_filter('markdown2rst', filters.markdown.markdown2rst)
246 self.register_filter('markdown2rst', filters.markdown.markdown2rst)
235 self.register_filter('pycomment', filters.strings.python_comment)
247 self.register_filter('pycomment', filters.strings.python_comment)
236 self.register_filter('rm_ansi', filters.ansi.remove_ansi)
248 self.register_filter('rm_ansi', filters.ansi.remove_ansi)
237 self.register_filter('rm_dollars', filters.strings.strip_dollars)
249 self.register_filter('rm_dollars', filters.strings.strip_dollars)
238 self.register_filter('rm_fake', filters.strings.rm_fake)
250 self.register_filter('rm_fake', filters.strings.rm_fake)
239 self.register_filter('rm_math_space', filters.latex.rm_math_space)
251 self.register_filter('rm_math_space', filters.latex.rm_math_space)
240 self.register_filter('wrap', filters.strings.wrap)
252 self.register_filter('wrap', filters.strings.wrap)
241
253
242
254
255 def _set_datatype_priority(self, priority):
256 self.extract_figure_transformer.display_data_priority=copy.copy(priority)
257 self.display_data_priority=copy.copy(priority)
258
259
243 def _init_environment(self):
260 def _init_environment(self):
244 self.environment = Environment(
261 self.environment = Environment(
245 loader=FileSystemLoader([
262 loader=FileSystemLoader([
246 os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_PATH,
263 os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_PATH,
247 os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_SKELETON_PATH,
264 os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_SKELETON_PATH,
248 ]),
265 ]),
249 extensions=JINJA_EXTENSIONS
266 extensions=JINJA_EXTENSIONS
250 )
267 )
251
268
252
269
253 def _preprocess(self, nb):
270 def _preprocess(self, nb):
254 """ Preprocess the notebook using the transformers specific
271 """ Preprocess the notebook using the transformers specific
255 for the current export format.
272 for the current export format.
256
273
257 nb: Notebook to preprocess
274 nb: Notebook to preprocess
258 """
275 """
259
276
260 #Dict of 'resources' that can be filled by the preprocessors.
277 #Dict of 'resources' that can be filled by the preprocessors.
261 resources = {}
278 resources = {}
262
279
263 #Run each transformer on the notebook. Carry the output along
280 #Run each transformer on the notebook. Carry the output along
264 #to each transformer
281 #to each transformer
265 for transformer in self.preprocessors:
282 for transformer in self.preprocessors:
266 nb, resources = transformer(nb, resources)
283 nb, resources = transformer(nb, resources)
267 return nb, resources
284 return nb, resources
268
285
@@ -1,127 +1,114
1 """Latex exporter for the notebook conversion pipeline.
1 """Latex exporter for the notebook conversion pipeline.
2
2
3 This module defines Exporter, a highly configurable converter
3 This module defines Exporter, a highly configurable converter
4 that uses Jinja2 to export notebook files into different format.
4 that uses Jinja2 to export notebook files into different format.
5
5
6 You can register both pre-transformers that will act on the notebook format
6 You can register both pre-transformers that will act on the notebook format
7 before conversion and jinja filter that would then be available in the templates
7 before conversion and jinja filter that would then be available in the templates
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (c) 2013, the IPython Development Team.
11 # Copyright (c) 2013, the IPython Development Team.
12 #
12 #
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14 #
14 #
15 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # Stdlib imports
22 # Stdlib imports
23 import io
23 import io
24 import os
24 import os
25
25
26 # IPython imports
26 # IPython imports
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
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 exporter
37 import exporter
38 import filters.latex
38 import filters.latex
39 import filters.pygments
39 import filters.pygments
40 from transformers.latex import LatexTransformer
40 from transformers.latex import LatexTransformer
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Globals and constants
42 # Globals and constants
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45 #Latex Jinja2 constants
45 #Latex Jinja2 constants
46 LATEX_TEMPLATE_PATH = "/../templates/tex/"
46 LATEX_TEMPLATE_PATH = "/../templates/tex/"
47 LATEX_TEMPLATE_SKELETON_PATH = "/../templates/tex/skeleton/"
47 LATEX_TEMPLATE_SKELETON_PATH = "/../templates/tex/skeleton/"
48 LATEX_TEMPLATE_EXTENSION = ".tplx"
48 LATEX_TEMPLATE_EXTENSION = ".tplx"
49
49
50 #Special Jinja2 syntax that will not conflict when exporting latex.
50 #Special Jinja2 syntax that will not conflict when exporting latex.
51 LATEX_JINJA_COMMENT_BLOCK = ["((=", "=))"]
51 LATEX_JINJA_COMMENT_BLOCK = ["((=", "=))"]
52 LATEX_JINJA_VARIABLE_BLOCK = ["(((", ")))"]
52 LATEX_JINJA_VARIABLE_BLOCK = ["(((", ")))"]
53 LATEX_JINJA_LOGIC_BLOCK = ["((*", "*))"]
53 LATEX_JINJA_LOGIC_BLOCK = ["((*", "*))"]
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Classes and functions
56 # Classes and functions
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 class LatexExporter(exporter.Exporter):
58 class LatexExporter(exporter.Exporter):
59 """ A Jinja2 latex exporter
59 """ A Jinja2 latex exporter
60
60
61 Preprocess the ipynb files, feed it through jinja templates,
61 Preprocess the ipynb files, feed it through jinja templates,
62 and spit an converted files and a data object with other data
62 and spit an converted files and a data object with other data
63 should be mostly configurable
63 should be mostly configurable
64 """
64 """
65
65
66 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
66 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
67 """ Init a new converter.
68
67
69 config: the Configurable config object to pass around.
68 #Call base class constructor.
70
71 preprocessors: dict of **available** key/value function to run on
72 ipynb json data before conversion to extract/inline file.
73 See `transformer.py` and `ConfigurableTransformers`
74
75 set the order in which the transformers should apply
76 with the `pre_transformer_order` trait of this class
77
78 transformers registerd by this key will take precedence on
79 default one.
80
81 jinja_filters: dict of supplementary jinja filter that should be made
82 available in template. If those are of Configurable Class type,
83 they will be instanciated with the config object as argument.
84
85 user defined filter will overwrite the one available by default.
86 """
87
88 #Call the base class constructor
89 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
69 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
90
70
71 #Set defaults
72 self.file_extension = "tex"
73 self._set_datatype_priority(['latex', 'svg', 'png', 'jpg', 'jpeg' , 'text'])
74 self.extract_figure_transformer.enabled = True
75 self.extract_figure_transformer.extra_ext_map={'svg':'pdf'}
76 self.template_file = "latex_base"
77
91
78
92 def _init_environment(self):
79 def _init_environment(self):
93 self.ext = LATEX_TEMPLATE_EXTENSION
80 self.ext = LATEX_TEMPLATE_EXTENSION
94 self.environment = Environment(
81 self.environment = Environment(
95 loader=FileSystemLoader([
82 loader=FileSystemLoader([
96 os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_PATH,
83 os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_PATH,
97 os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_SKELETON_PATH,
84 os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_SKELETON_PATH,
98 ]),
85 ]),
99 extensions=exporter.JINJA_EXTENSIONS
86 extensions=exporter.JINJA_EXTENSIONS
100 )
87 )
101
88
102 #Set special Jinja2 syntax that will not conflict with latex.
89 #Set special Jinja2 syntax that will not conflict with latex.
103 self.environment.block_start_string = LATEX_JINJA_LOGIC_BLOCK[0]
90 self.environment.block_start_string = LATEX_JINJA_LOGIC_BLOCK[0]
104 self.environment.block_end_string = LATEX_JINJA_LOGIC_BLOCK[1]
91 self.environment.block_end_string = LATEX_JINJA_LOGIC_BLOCK[1]
105 self.environment.variable_start_string = LATEX_JINJA_VARIABLE_BLOCK[0]
92 self.environment.variable_start_string = LATEX_JINJA_VARIABLE_BLOCK[0]
106 self.environment.variable_end_string = LATEX_JINJA_VARIABLE_BLOCK[1]
93 self.environment.variable_end_string = LATEX_JINJA_VARIABLE_BLOCK[1]
107 self.environment.comment_start_string = LATEX_JINJA_COMMENT_BLOCK[0]
94 self.environment.comment_start_string = LATEX_JINJA_COMMENT_BLOCK[0]
108 self.environment.comment_end_string = LATEX_JINJA_COMMENT_BLOCK[1]
95 self.environment.comment_end_string = LATEX_JINJA_COMMENT_BLOCK[1]
109
96
110
97
111 def _register_filters(self):
98 def _register_filters(self):
112
99
113 #Register the filters of the base class.
100 #Register the filters of the base class.
114 super(exporter.Exporter, self)._register_filters()
101 super(exporter.Exporter, self)._register_filters()
115
102
116 #Add latex filters to the Jinja2 environment
103 #Add latex filters to the Jinja2 environment
117 self.register_filter('escape_tex', filters.latex.escape_tex)
104 self.register_filter('escape_tex', filters.latex.escape_tex)
118 self.register_filter('highlight', filters.pygments.highlight2latex)
105 self.register_filter('highlight', filters.pygments.highlight2latex)
119
106
120 def _register_transformers(self):
107 def _register_transformers(self):
121
108
122 #Register the transformers of the base class.
109 #Register the transformers of the base class.
123 super(exporter.Exporter, self)._register_transformers()
110 super(exporter.Exporter, self)._register_transformers()
124
111
125 #Register latex transformer
112 #Register latex transformer
126 self.register_transformer(LatexTransformer)
113 self.register_transformer(LatexTransformer)
127 No newline at end of file
114
General Comments 0
You need to be logged in to leave comments. Login now