Show More
@@ -1,315 +1,315 | |||||
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 os |
|
20 | import os | |
21 |
|
21 | |||
22 | # other libs/dependencies |
|
22 | # other libs/dependencies | |
23 | from jinja2 import Environment, FileSystemLoader, ChoiceLoader, TemplateNotFound |
|
23 | from jinja2 import Environment, FileSystemLoader, ChoiceLoader, TemplateNotFound | |
24 |
|
24 | |||
25 | # IPython imports |
|
25 | # IPython imports | |
26 | from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Dict, Any |
|
26 | from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Dict, Any | |
27 | from IPython.utils.importstring import import_item |
|
27 | from IPython.utils.importstring import import_item | |
28 | from IPython.utils import py3compat, text |
|
28 | from IPython.utils import py3compat, text | |
29 |
|
29 | |||
30 | from IPython.nbconvert import filters |
|
30 | from IPython.nbconvert import filters | |
31 | from .exporter import Exporter |
|
31 | from .exporter import Exporter | |
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # Globals and constants |
|
34 | # Globals and constants | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
36 | |||
37 | #Jinja2 extensions to load. |
|
37 | #Jinja2 extensions to load. | |
38 | JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols'] |
|
38 | JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols'] | |
39 |
|
39 | |||
40 | default_filters = { |
|
40 | default_filters = { | |
41 | 'indent': text.indent, |
|
41 | 'indent': text.indent, | |
42 | 'markdown2html': filters.markdown2html, |
|
42 | 'markdown2html': filters.markdown2html, | |
43 | 'ansi2html': filters.ansi2html, |
|
43 | 'ansi2html': filters.ansi2html, | |
44 | 'filter_data_type': filters.DataTypeFilter, |
|
44 | 'filter_data_type': filters.DataTypeFilter, | |
45 | 'get_lines': filters.get_lines, |
|
45 | 'get_lines': filters.get_lines, | |
46 | 'highlight2html': filters.Highlight2Html, |
|
46 | 'highlight2html': filters.Highlight2Html, | |
47 |
'highlight2latex': filters. |
|
47 | 'highlight2latex': filters.Highlight2Latex, | |
48 | 'ipython2python': filters.ipython2python, |
|
48 | 'ipython2python': filters.ipython2python, | |
49 | 'posix_path': filters.posix_path, |
|
49 | 'posix_path': filters.posix_path, | |
50 | 'markdown2latex': filters.markdown2latex, |
|
50 | 'markdown2latex': filters.markdown2latex, | |
51 | 'markdown2rst': filters.markdown2rst, |
|
51 | 'markdown2rst': filters.markdown2rst, | |
52 | 'comment_lines': filters.comment_lines, |
|
52 | 'comment_lines': filters.comment_lines, | |
53 | 'strip_ansi': filters.strip_ansi, |
|
53 | 'strip_ansi': filters.strip_ansi, | |
54 | 'strip_dollars': filters.strip_dollars, |
|
54 | 'strip_dollars': filters.strip_dollars, | |
55 | 'strip_files_prefix': filters.strip_files_prefix, |
|
55 | 'strip_files_prefix': filters.strip_files_prefix, | |
56 | 'html2text' : filters.html2text, |
|
56 | 'html2text' : filters.html2text, | |
57 | 'add_anchor': filters.add_anchor, |
|
57 | 'add_anchor': filters.add_anchor, | |
58 | 'ansi2latex': filters.ansi2latex, |
|
58 | 'ansi2latex': filters.ansi2latex, | |
59 | 'wrap_text': filters.wrap_text, |
|
59 | 'wrap_text': filters.wrap_text, | |
60 | 'escape_latex': filters.escape_latex, |
|
60 | 'escape_latex': filters.escape_latex, | |
61 | 'citation2latex': filters.citation2latex, |
|
61 | 'citation2latex': filters.citation2latex, | |
62 | 'path2url': filters.path2url, |
|
62 | 'path2url': filters.path2url, | |
63 | 'add_prompts': filters.add_prompts, |
|
63 | 'add_prompts': filters.add_prompts, | |
64 | } |
|
64 | } | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Class |
|
67 | # Class | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | class TemplateExporter(Exporter): |
|
70 | class TemplateExporter(Exporter): | |
71 | """ |
|
71 | """ | |
72 | Exports notebooks into other file formats. Uses Jinja 2 templating engine |
|
72 | Exports notebooks into other file formats. Uses Jinja 2 templating engine | |
73 | to output new formats. Inherit from this class if you are creating a new |
|
73 | to output new formats. Inherit from this class if you are creating a new | |
74 | template type along with new filters/preprocessors. If the filters/ |
|
74 | template type along with new filters/preprocessors. If the filters/ | |
75 | preprocessors provided by default suffice, there is no need to inherit from |
|
75 | preprocessors provided by default suffice, there is no need to inherit from | |
76 | this class. Instead, override the template_file and file_extension |
|
76 | this class. Instead, override the template_file and file_extension | |
77 | traits via a config file. |
|
77 | traits via a config file. | |
78 |
|
78 | |||
79 | {filters} |
|
79 | {filters} | |
80 | """ |
|
80 | """ | |
81 |
|
81 | |||
82 | # finish the docstring |
|
82 | # finish the docstring | |
83 | __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys())) |
|
83 | __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys())) | |
84 |
|
84 | |||
85 |
|
85 | |||
86 | template_file = Unicode(u'default', |
|
86 | template_file = Unicode(u'default', | |
87 | config=True, |
|
87 | config=True, | |
88 | help="Name of the template file to use") |
|
88 | help="Name of the template file to use") | |
89 | def _template_file_changed(self, name, old, new): |
|
89 | def _template_file_changed(self, name, old, new): | |
90 | if new == 'default': |
|
90 | if new == 'default': | |
91 | self.template_file = self.default_template |
|
91 | self.template_file = self.default_template | |
92 | else: |
|
92 | else: | |
93 | self.template_file = new |
|
93 | self.template_file = new | |
94 | self.template = None |
|
94 | self.template = None | |
95 | self._load_template() |
|
95 | self._load_template() | |
96 |
|
96 | |||
97 | default_template = Unicode(u'') |
|
97 | default_template = Unicode(u'') | |
98 | template = Any() |
|
98 | template = Any() | |
99 | environment = Any() |
|
99 | environment = Any() | |
100 |
|
100 | |||
101 | template_path = List(['.'], config=True) |
|
101 | template_path = List(['.'], config=True) | |
102 | def _template_path_changed(self, name, old, new): |
|
102 | def _template_path_changed(self, name, old, new): | |
103 | self._load_template() |
|
103 | self._load_template() | |
104 |
|
104 | |||
105 | default_template_path = Unicode( |
|
105 | default_template_path = Unicode( | |
106 | os.path.join("..", "templates"), |
|
106 | os.path.join("..", "templates"), | |
107 | help="Path where the template files are located.") |
|
107 | help="Path where the template files are located.") | |
108 |
|
108 | |||
109 | template_skeleton_path = Unicode( |
|
109 | template_skeleton_path = Unicode( | |
110 | os.path.join("..", "templates", "skeleton"), |
|
110 | os.path.join("..", "templates", "skeleton"), | |
111 | help="Path where the template skeleton files are located.") |
|
111 | help="Path where the template skeleton files are located.") | |
112 |
|
112 | |||
113 | #Jinja block definitions |
|
113 | #Jinja block definitions | |
114 | jinja_comment_block_start = Unicode("", config=True) |
|
114 | jinja_comment_block_start = Unicode("", config=True) | |
115 | jinja_comment_block_end = Unicode("", config=True) |
|
115 | jinja_comment_block_end = Unicode("", config=True) | |
116 | jinja_variable_block_start = Unicode("", config=True) |
|
116 | jinja_variable_block_start = Unicode("", config=True) | |
117 | jinja_variable_block_end = Unicode("", config=True) |
|
117 | jinja_variable_block_end = Unicode("", config=True) | |
118 | jinja_logic_block_start = Unicode("", config=True) |
|
118 | jinja_logic_block_start = Unicode("", config=True) | |
119 | jinja_logic_block_end = Unicode("", config=True) |
|
119 | jinja_logic_block_end = Unicode("", config=True) | |
120 |
|
120 | |||
121 | #Extension that the template files use. |
|
121 | #Extension that the template files use. | |
122 | template_extension = Unicode(".tpl", config=True) |
|
122 | template_extension = Unicode(".tpl", config=True) | |
123 |
|
123 | |||
124 | filters = Dict(config=True, |
|
124 | filters = Dict(config=True, | |
125 | help="""Dictionary of filters, by name and namespace, to add to the Jinja |
|
125 | help="""Dictionary of filters, by name and namespace, to add to the Jinja | |
126 | environment.""") |
|
126 | environment.""") | |
127 |
|
127 | |||
128 |
|
128 | |||
129 | def __init__(self, config=None, extra_loaders=None, **kw): |
|
129 | def __init__(self, config=None, extra_loaders=None, **kw): | |
130 | """ |
|
130 | """ | |
131 | Public constructor |
|
131 | Public constructor | |
132 |
|
132 | |||
133 | Parameters |
|
133 | Parameters | |
134 | ---------- |
|
134 | ---------- | |
135 | config : config |
|
135 | config : config | |
136 | User configuration instance. |
|
136 | User configuration instance. | |
137 | extra_loaders : list[of Jinja Loaders] |
|
137 | extra_loaders : list[of Jinja Loaders] | |
138 | ordered list of Jinja loader to find templates. Will be tried in order |
|
138 | ordered list of Jinja loader to find templates. Will be tried in order | |
139 | before the default FileSystem ones. |
|
139 | before the default FileSystem ones. | |
140 | template : str (optional, kw arg) |
|
140 | template : str (optional, kw arg) | |
141 | Template to use when exporting. |
|
141 | Template to use when exporting. | |
142 | """ |
|
142 | """ | |
143 | if not config: |
|
143 | if not config: | |
144 | config = self.default_config |
|
144 | config = self.default_config | |
145 |
|
145 | |||
146 | super(Exporter, self).__init__(config=config, **kw) |
|
146 | super(Exporter, self).__init__(config=config, **kw) | |
147 |
|
147 | |||
148 | #Init |
|
148 | #Init | |
149 | self._init_template() |
|
149 | self._init_template() | |
150 | self._init_environment(extra_loaders=extra_loaders) |
|
150 | self._init_environment(extra_loaders=extra_loaders) | |
151 | self._init_preprocessors() |
|
151 | self._init_preprocessors() | |
152 | self._init_filters() |
|
152 | self._init_filters() | |
153 |
|
153 | |||
154 |
|
154 | |||
155 | def _load_template(self): |
|
155 | def _load_template(self): | |
156 | """Load the Jinja template object from the template file |
|
156 | """Load the Jinja template object from the template file | |
157 |
|
157 | |||
158 | This is a no-op if the template attribute is already defined, |
|
158 | This is a no-op if the template attribute is already defined, | |
159 | or the Jinja environment is not setup yet. |
|
159 | or the Jinja environment is not setup yet. | |
160 |
|
160 | |||
161 | This is triggered by various trait changes that would change the template. |
|
161 | This is triggered by various trait changes that would change the template. | |
162 | """ |
|
162 | """ | |
163 | if self.template is not None: |
|
163 | if self.template is not None: | |
164 | return |
|
164 | return | |
165 | # called too early, do nothing |
|
165 | # called too early, do nothing | |
166 | if self.environment is None: |
|
166 | if self.environment is None: | |
167 | return |
|
167 | return | |
168 | # Try different template names during conversion. First try to load the |
|
168 | # Try different template names during conversion. First try to load the | |
169 | # template by name with extension added, then try loading the template |
|
169 | # template by name with extension added, then try loading the template | |
170 | # as if the name is explicitly specified, then try the name as a |
|
170 | # as if the name is explicitly specified, then try the name as a | |
171 | # 'flavor', and lastly just try to load the template by module name. |
|
171 | # 'flavor', and lastly just try to load the template by module name. | |
172 | module_name = self.__module__.rsplit('.', 1)[-1] |
|
172 | module_name = self.__module__.rsplit('.', 1)[-1] | |
173 | try_names = [] |
|
173 | try_names = [] | |
174 | if self.template_file: |
|
174 | if self.template_file: | |
175 | try_names.extend([ |
|
175 | try_names.extend([ | |
176 | self.template_file + self.template_extension, |
|
176 | self.template_file + self.template_extension, | |
177 | self.template_file, |
|
177 | self.template_file, | |
178 | module_name + '_' + self.template_file + self.template_extension, |
|
178 | module_name + '_' + self.template_file + self.template_extension, | |
179 | ]) |
|
179 | ]) | |
180 | try_names.append(module_name + self.template_extension) |
|
180 | try_names.append(module_name + self.template_extension) | |
181 | for try_name in try_names: |
|
181 | for try_name in try_names: | |
182 | self.log.debug("Attempting to load template %s", try_name) |
|
182 | self.log.debug("Attempting to load template %s", try_name) | |
183 | try: |
|
183 | try: | |
184 | self.template = self.environment.get_template(try_name) |
|
184 | self.template = self.environment.get_template(try_name) | |
185 | except (TemplateNotFound, IOError): |
|
185 | except (TemplateNotFound, IOError): | |
186 | pass |
|
186 | pass | |
187 | except Exception as e: |
|
187 | except Exception as e: | |
188 | self.log.warn("Unexpected exception loading template: %s", try_name, exc_info=True) |
|
188 | self.log.warn("Unexpected exception loading template: %s", try_name, exc_info=True) | |
189 | else: |
|
189 | else: | |
190 | self.log.info("Loaded template %s", try_name) |
|
190 | self.log.info("Loaded template %s", try_name) | |
191 | break |
|
191 | break | |
192 |
|
192 | |||
193 | def from_notebook_node(self, nb, resources=None, **kw): |
|
193 | def from_notebook_node(self, nb, resources=None, **kw): | |
194 | """ |
|
194 | """ | |
195 | Convert a notebook from a notebook node instance. |
|
195 | Convert a notebook from a notebook node instance. | |
196 |
|
196 | |||
197 | Parameters |
|
197 | Parameters | |
198 | ---------- |
|
198 | ---------- | |
199 | nb : Notebook node |
|
199 | nb : Notebook node | |
200 | resources : dict (**kw) |
|
200 | resources : dict (**kw) | |
201 | of additional resources that can be accessed read/write by |
|
201 | of additional resources that can be accessed read/write by | |
202 | preprocessors and filters. |
|
202 | preprocessors and filters. | |
203 | """ |
|
203 | """ | |
204 | nb_copy, resources = super(TemplateExporter, self).from_notebook_node(nb, resources, **kw) |
|
204 | nb_copy, resources = super(TemplateExporter, self).from_notebook_node(nb, resources, **kw) | |
205 |
|
205 | |||
206 | self._load_template() |
|
206 | self._load_template() | |
207 |
|
207 | |||
208 | if self.template is not None: |
|
208 | if self.template is not None: | |
209 | output = self.template.render(nb=nb_copy, resources=resources) |
|
209 | output = self.template.render(nb=nb_copy, resources=resources) | |
210 | else: |
|
210 | else: | |
211 | raise IOError('template file "%s" could not be found' % self.template_file) |
|
211 | raise IOError('template file "%s" could not be found' % self.template_file) | |
212 | return output, resources |
|
212 | return output, resources | |
213 |
|
213 | |||
214 |
|
214 | |||
215 | def register_filter(self, name, jinja_filter): |
|
215 | def register_filter(self, name, jinja_filter): | |
216 | """ |
|
216 | """ | |
217 | Register a filter. |
|
217 | Register a filter. | |
218 | A filter is a function that accepts and acts on one string. |
|
218 | A filter is a function that accepts and acts on one string. | |
219 | The filters are accesible within the Jinja templating engine. |
|
219 | The filters are accesible within the Jinja templating engine. | |
220 |
|
220 | |||
221 | Parameters |
|
221 | Parameters | |
222 | ---------- |
|
222 | ---------- | |
223 | name : str |
|
223 | name : str | |
224 | name to give the filter in the Jinja engine |
|
224 | name to give the filter in the Jinja engine | |
225 | filter : filter |
|
225 | filter : filter | |
226 | """ |
|
226 | """ | |
227 | if jinja_filter is None: |
|
227 | if jinja_filter is None: | |
228 | raise TypeError('filter') |
|
228 | raise TypeError('filter') | |
229 | isclass = isinstance(jinja_filter, type) |
|
229 | isclass = isinstance(jinja_filter, type) | |
230 | constructed = not isclass |
|
230 | constructed = not isclass | |
231 |
|
231 | |||
232 | #Handle filter's registration based on it's type |
|
232 | #Handle filter's registration based on it's type | |
233 | if constructed and isinstance(jinja_filter, py3compat.string_types): |
|
233 | if constructed and isinstance(jinja_filter, py3compat.string_types): | |
234 | #filter is a string, import the namespace and recursively call |
|
234 | #filter is a string, import the namespace and recursively call | |
235 | #this register_filter method |
|
235 | #this register_filter method | |
236 | filter_cls = import_item(jinja_filter) |
|
236 | filter_cls = import_item(jinja_filter) | |
237 | return self.register_filter(name, filter_cls) |
|
237 | return self.register_filter(name, filter_cls) | |
238 |
|
238 | |||
239 | if constructed and hasattr(jinja_filter, '__call__'): |
|
239 | if constructed and hasattr(jinja_filter, '__call__'): | |
240 | #filter is a function, no need to construct it. |
|
240 | #filter is a function, no need to construct it. | |
241 | self.environment.filters[name] = jinja_filter |
|
241 | self.environment.filters[name] = jinja_filter | |
242 | return jinja_filter |
|
242 | return jinja_filter | |
243 |
|
243 | |||
244 | elif isclass and isinstance(jinja_filter, MetaHasTraits): |
|
244 | elif isclass and isinstance(jinja_filter, MetaHasTraits): | |
245 | #filter is configurable. Make sure to pass in new default for |
|
245 | #filter is configurable. Make sure to pass in new default for | |
246 | #the enabled flag if one was specified. |
|
246 | #the enabled flag if one was specified. | |
247 | filter_instance = jinja_filter(parent=self) |
|
247 | filter_instance = jinja_filter(parent=self) | |
248 | self.register_filter(name, filter_instance ) |
|
248 | self.register_filter(name, filter_instance ) | |
249 |
|
249 | |||
250 | elif isclass: |
|
250 | elif isclass: | |
251 | #filter is not configurable, construct it |
|
251 | #filter is not configurable, construct it | |
252 | filter_instance = jinja_filter() |
|
252 | filter_instance = jinja_filter() | |
253 | self.register_filter(name, filter_instance) |
|
253 | self.register_filter(name, filter_instance) | |
254 |
|
254 | |||
255 | else: |
|
255 | else: | |
256 | #filter is an instance of something without a __call__ |
|
256 | #filter is an instance of something without a __call__ | |
257 | #attribute. |
|
257 | #attribute. | |
258 | raise TypeError('filter') |
|
258 | raise TypeError('filter') | |
259 |
|
259 | |||
260 |
|
260 | |||
261 | def _init_template(self): |
|
261 | def _init_template(self): | |
262 | """ |
|
262 | """ | |
263 | Make sure a template name is specified. If one isn't specified, try to |
|
263 | Make sure a template name is specified. If one isn't specified, try to | |
264 | build one from the information we know. |
|
264 | build one from the information we know. | |
265 | """ |
|
265 | """ | |
266 | self._template_file_changed('template_file', self.template_file, self.template_file) |
|
266 | self._template_file_changed('template_file', self.template_file, self.template_file) | |
267 |
|
267 | |||
268 |
|
268 | |||
269 | def _init_environment(self, extra_loaders=None): |
|
269 | def _init_environment(self, extra_loaders=None): | |
270 | """ |
|
270 | """ | |
271 | Create the Jinja templating environment. |
|
271 | Create the Jinja templating environment. | |
272 | """ |
|
272 | """ | |
273 | here = os.path.dirname(os.path.realpath(__file__)) |
|
273 | here = os.path.dirname(os.path.realpath(__file__)) | |
274 | loaders = [] |
|
274 | loaders = [] | |
275 | if extra_loaders: |
|
275 | if extra_loaders: | |
276 | loaders.extend(extra_loaders) |
|
276 | loaders.extend(extra_loaders) | |
277 |
|
277 | |||
278 | paths = self.template_path |
|
278 | paths = self.template_path | |
279 | paths.extend([os.path.join(here, self.default_template_path), |
|
279 | paths.extend([os.path.join(here, self.default_template_path), | |
280 | os.path.join(here, self.template_skeleton_path)]) |
|
280 | os.path.join(here, self.template_skeleton_path)]) | |
281 | loaders.append(FileSystemLoader(paths)) |
|
281 | loaders.append(FileSystemLoader(paths)) | |
282 |
|
282 | |||
283 | self.environment = Environment( |
|
283 | self.environment = Environment( | |
284 | loader= ChoiceLoader(loaders), |
|
284 | loader= ChoiceLoader(loaders), | |
285 | extensions=JINJA_EXTENSIONS |
|
285 | extensions=JINJA_EXTENSIONS | |
286 | ) |
|
286 | ) | |
287 |
|
287 | |||
288 | #Set special Jinja2 syntax that will not conflict with latex. |
|
288 | #Set special Jinja2 syntax that will not conflict with latex. | |
289 | if self.jinja_logic_block_start: |
|
289 | if self.jinja_logic_block_start: | |
290 | self.environment.block_start_string = self.jinja_logic_block_start |
|
290 | self.environment.block_start_string = self.jinja_logic_block_start | |
291 | if self.jinja_logic_block_end: |
|
291 | if self.jinja_logic_block_end: | |
292 | self.environment.block_end_string = self.jinja_logic_block_end |
|
292 | self.environment.block_end_string = self.jinja_logic_block_end | |
293 | if self.jinja_variable_block_start: |
|
293 | if self.jinja_variable_block_start: | |
294 | self.environment.variable_start_string = self.jinja_variable_block_start |
|
294 | self.environment.variable_start_string = self.jinja_variable_block_start | |
295 | if self.jinja_variable_block_end: |
|
295 | if self.jinja_variable_block_end: | |
296 | self.environment.variable_end_string = self.jinja_variable_block_end |
|
296 | self.environment.variable_end_string = self.jinja_variable_block_end | |
297 | if self.jinja_comment_block_start: |
|
297 | if self.jinja_comment_block_start: | |
298 | self.environment.comment_start_string = self.jinja_comment_block_start |
|
298 | self.environment.comment_start_string = self.jinja_comment_block_start | |
299 | if self.jinja_comment_block_end: |
|
299 | if self.jinja_comment_block_end: | |
300 | self.environment.comment_end_string = self.jinja_comment_block_end |
|
300 | self.environment.comment_end_string = self.jinja_comment_block_end | |
301 |
|
301 | |||
302 |
|
302 | |||
303 | def _init_filters(self): |
|
303 | def _init_filters(self): | |
304 | """ |
|
304 | """ | |
305 | Register all of the filters required for the exporter. |
|
305 | Register all of the filters required for the exporter. | |
306 | """ |
|
306 | """ | |
307 |
|
307 | |||
308 | #Add default filters to the Jinja2 environment |
|
308 | #Add default filters to the Jinja2 environment | |
309 | for key, value in default_filters.items(): |
|
309 | for key, value in default_filters.items(): | |
310 | self.register_filter(key, value) |
|
310 | self.register_filter(key, value) | |
311 |
|
311 | |||
312 | #Load user filters. Overwrite existing filters if need be. |
|
312 | #Load user filters. Overwrite existing filters if need be. | |
313 | if self.filters: |
|
313 | if self.filters: | |
314 | for key, user_filter in self.filters.items(): |
|
314 | for key, user_filter in self.filters.items(): | |
315 | self.register_filter(key, user_filter) |
|
315 | self.register_filter(key, user_filter) |
@@ -1,118 +1,121 | |||||
1 | """ |
|
1 | """ | |
2 | Module containing filter functions that allow code to be highlighted |
|
2 | Module containing filter functions that allow code to be highlighted | |
3 | from within Jinja templates. |
|
3 | from within Jinja templates. | |
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 pygments import highlight as pygements_highlight |
|
17 | from pygments import highlight as pygements_highlight | |
18 | from pygments.lexers import get_lexer_by_name |
|
18 | from pygments.lexers import get_lexer_by_name | |
19 | from pygments.formatters import HtmlFormatter |
|
19 | from pygments.formatters import HtmlFormatter | |
20 | from pygments.formatters import LatexFormatter |
|
20 | from pygments.formatters import LatexFormatter | |
21 | from IPython.config import catch_config_error, Configurable |
|
21 | ||
22 | from IPython.utils.traitlets import Unicode |
|
|||
23 |
|
22 | |||
24 | # Our own imports |
|
23 | # Our own imports | |
25 | from IPython.nbconvert.utils.lexers import IPythonLexer |
|
24 | from IPython.nbconvert.utils.lexers import IPythonLexer | |
|
25 | from IPython.nbconvert.utils.base import NbConvertBase | |||
26 |
|
26 | |||
27 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
28 | # Globals and constants |
|
28 | # Globals and constants | |
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 |
|
30 | |||
31 | MULTILINE_OUTPUTS = ['text', 'html', 'svg', 'latex', 'javascript', 'json'] |
|
31 | MULTILINE_OUTPUTS = ['text', 'html', 'svg', 'latex', 'javascript', 'json'] | |
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # Utility functions |
|
34 | # Utility functions | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
36 | |||
37 | __all__ = [ |
|
37 | __all__ = [ | |
38 | 'Highlight2Html', |
|
38 | 'Highlight2Html', | |
39 |
' |
|
39 | 'Highlight2Latex' | |
40 | ] |
|
40 | ] | |
41 |
|
41 | |||
42 |
|
42 | |||
43 |
class Highlight2Html( |
|
43 | class Highlight2Html(NbConvertBase): | |
44 |
|
||||
45 | language = Unicode('ipython', config=True, help='default highlight language') |
|
|||
46 |
|
44 | |||
47 | def __call__(self, source, language=None, metadata=None): |
|
45 | def __call__(self, source, language=None, metadata=None): | |
48 | """ |
|
46 | """ | |
49 | Return a syntax-highlighted version of the input source as html output. |
|
47 | Return a syntax-highlighted version of the input source as html output. | |
50 |
|
48 | |||
51 | Parameters |
|
49 | Parameters | |
52 | ---------- |
|
50 | ---------- | |
53 | source : str |
|
51 | source : str | |
54 | source of the cell to highlight |
|
52 | source of the cell to highlight | |
55 | language : str |
|
53 | language : str | |
56 | language to highlight the syntax of |
|
54 | language to highlight the syntax of | |
57 | metadata : NotebookNode cell metadata |
|
55 | metadata : NotebookNode cell metadata | |
58 | metadata of the cell to highlight |
|
56 | metadata of the cell to highlight | |
59 | """ |
|
57 | """ | |
60 | if not language: |
|
58 | if not language: | |
61 | language=self.language |
|
59 | language=self.default_language | |
62 |
|
60 | |||
63 | return _pygment_highlight(source, HtmlFormatter(), language, metadata) |
|
61 | return _pygment_highlight(source, HtmlFormatter(), language, metadata) | |
64 |
|
62 | |||
65 |
|
63 | |||
66 | def highlight2latex(source, language='ipython', metadata=None, strip_verbatim=False): |
|
64 | class Highlight2Latex(NbConvertBase): | |
67 | """ |
|
|||
68 | Return a syntax-highlighted version of the input source as latex output. |
|
|||
69 |
|
65 | |||
70 | Parameters |
|
66 | def __call__(self, source, language=None, metadata=None, strip_verbatim=False): | |
71 | ---------- |
|
67 | """ | |
72 | source : str |
|
68 | Return a syntax-highlighted version of the input source as latex output. | |
73 | source of the cell to highlight |
|
69 | ||
74 | language : str |
|
70 | Parameters | |
75 | language to highlight the syntax of |
|
71 | ---------- | |
76 | metadata : NotebookNode cell metadata |
|
72 | source : str | |
77 |
|
|
73 | source of the cell to highlight | |
78 | strip_verbatim : bool |
|
74 | language : str | |
79 | remove the Verbatim environment that pygments provides by default |
|
75 | language to highlight the syntax of | |
80 | """ |
|
76 | metadata : NotebookNode cell metadata | |
81 | latex = _pygment_highlight(source, LatexFormatter(), language, metadata) |
|
77 | metadata of the cell to highlight | |
82 |
|
|
78 | strip_verbatim : bool | |
83 | latex = latex.replace(r'\begin{Verbatim}[commandchars=\\\{\}]' + '\n', '') |
|
79 | remove the Verbatim environment that pygments provides by default | |
84 | return latex.replace('\n\\end{Verbatim}\n', '') |
|
80 | """ | |
85 | else: |
|
81 | if not language: | |
86 | return latex |
|
82 | language=self.default_language | |
|
83 | ||||
|
84 | latex = _pygment_highlight(source, LatexFormatter(), language, metadata) | |||
|
85 | if strip_verbatim: | |||
|
86 | latex = latex.replace(r'\begin{Verbatim}[commandchars=\\\{\}]' + '\n', '') | |||
|
87 | return latex.replace('\n\\end{Verbatim}\n', '') | |||
|
88 | else: | |||
|
89 | return latex | |||
87 |
|
90 | |||
88 |
|
91 | |||
89 |
|
92 | |||
90 | def _pygment_highlight(source, output_formatter, language='ipython', metadata=None): |
|
93 | def _pygment_highlight(source, output_formatter, language='ipython', metadata=None): | |
91 | """ |
|
94 | """ | |
92 | Return a syntax-highlighted version of the input source |
|
95 | Return a syntax-highlighted version of the input source | |
93 |
|
96 | |||
94 | Parameters |
|
97 | Parameters | |
95 | ---------- |
|
98 | ---------- | |
96 | source : str |
|
99 | source : str | |
97 | source of the cell to highlight |
|
100 | source of the cell to highlight | |
98 | output_formatter : Pygments formatter |
|
101 | output_formatter : Pygments formatter | |
99 | language : str |
|
102 | language : str | |
100 | language to highlight the syntax of |
|
103 | language to highlight the syntax of | |
101 | metadata : NotebookNode cell metadata |
|
104 | metadata : NotebookNode cell metadata | |
102 | metadata of the cell to highlight |
|
105 | metadata of the cell to highlight | |
103 | """ |
|
106 | """ | |
104 |
|
107 | |||
105 | # If the cell uses a magic extension language, |
|
108 | # If the cell uses a magic extension language, | |
106 | # use the magic language instead. |
|
109 | # use the magic language instead. | |
107 | if language == 'ipython' \ |
|
110 | if language == 'ipython' \ | |
108 | and metadata \ |
|
111 | and metadata \ | |
109 | and 'magics_language' in metadata: |
|
112 | and 'magics_language' in metadata: | |
110 |
|
113 | |||
111 | language = metadata['magics_language'] |
|
114 | language = metadata['magics_language'] | |
112 |
|
115 | |||
113 | if language == 'ipython': |
|
116 | if language == 'ipython': | |
114 | lexer = IPythonLexer() |
|
117 | lexer = IPythonLexer() | |
115 | else: |
|
118 | else: | |
116 | lexer = get_lexer_by_name(language, stripall=True) |
|
119 | lexer = get_lexer_by_name(language, stripall=True) | |
117 |
|
120 | |||
118 | return pygements_highlight(source, lexer, output_formatter) |
|
121 | return pygements_highlight(source, lexer, output_formatter) |
@@ -1,67 +1,88 | |||||
1 | """ |
|
1 | """ | |
2 | Module with tests for Highlight |
|
2 | Module with tests for Highlight | |
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 ...tests.base import TestsBase |
|
17 | from ...tests.base import TestsBase | |
18 |
from ..highlight import Highlight2Html, |
|
18 | from ..highlight import Highlight2Html, Highlight2Latex | |
19 |
|
19 | from IPython.config import Config | ||
|
20 | import xml | |||
20 |
|
21 | |||
21 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
22 | # Class |
|
23 | # Class | |
23 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
24 |
|
25 | |||
25 | highlight2html = Highlight2Html() |
|
26 | highlight2html = Highlight2Html() | |
|
27 | highlight2latex = Highlight2Latex() | |||
|
28 | c = Config() | |||
|
29 | c.Highlight2Html.default_language='ruby' | |||
|
30 | highlight2html_ruby = Highlight2Html(config=c) | |||
26 |
|
31 | |||
27 | class TestHighlight(TestsBase): |
|
32 | class TestHighlight(TestsBase): | |
28 | """Contains test functions for highlight.py""" |
|
33 | """Contains test functions for highlight.py""" | |
29 |
|
34 | |||
30 | #Hello world test, magics test, blank string test |
|
35 | #Hello world test, magics test, blank string test | |
31 | tests = [ |
|
36 | tests = [ | |
32 | """ |
|
37 | """ | |
33 | #Hello World Example |
|
38 | #Hello World Example | |
34 |
|
39 | |||
35 | def say(text): |
|
40 | def say(text): | |
36 | print(text) |
|
41 | print(text) | |
37 |
|
42 | |||
|
43 | end | |||
|
44 | ||||
38 | say('Hello World!') |
|
45 | say('Hello World!') | |
39 | """, |
|
46 | """, | |
40 | """ |
|
47 | """ | |
41 | %%pylab |
|
48 | %%pylab | |
42 | plot(x,y, 'r') |
|
49 | plot(x,y, 'r') | |
43 | """ |
|
50 | """ | |
44 | ] |
|
51 | ] | |
45 |
|
52 | |||
46 | tokens = [ |
|
53 | tokens = [ | |
47 | ['Hello World Example', 'say', 'text', 'print', 'def'], |
|
54 | ['Hello World Example', 'say', 'text', 'print', 'def'], | |
48 | ['pylab', 'plot']] |
|
55 | ['pylab', 'plot']] | |
49 |
|
56 | |||
50 |
|
57 | |||
51 | def test_highlight2html(self): |
|
58 | def test_highlight2html(self): | |
52 | """highlight2html test""" |
|
59 | """highlight2html test""" | |
53 | for index, test in enumerate(self.tests): |
|
60 | for index, test in enumerate(self.tests): | |
54 | self._try_highlight(highlight2html, test, self.tokens[index]) |
|
61 | self._try_highlight(highlight2html, test, self.tokens[index]) | |
55 |
|
62 | |||
56 |
|
63 | |||
57 | def test_highlight2latex(self): |
|
64 | def test_highlight2latex(self): | |
58 | """highlight2latex test""" |
|
65 | """highlight2latex test""" | |
59 | for index, test in enumerate(self.tests): |
|
66 | for index, test in enumerate(self.tests): | |
60 | self._try_highlight(highlight2latex, test, self.tokens[index]) |
|
67 | self._try_highlight(highlight2latex, test, self.tokens[index]) | |
61 |
|
68 | |||
|
69 | def test_parse_html_many_lang(self): | |||
|
70 | ||||
|
71 | ht = highlight2html(self.tests[0]) | |||
|
72 | rb = highlight2html_ruby(self.tests[0]) | |||
|
73 | ||||
|
74 | for lang,tkns in [ | |||
|
75 | ( ht, ('def','print') ), | |||
|
76 | ( rb, ('def','end' ) ) | |||
|
77 | ]: | |||
|
78 | root = xml.etree.ElementTree.fromstring(lang) | |||
|
79 | assert self._extract_tokens(root,'k') == set(tkns) | |||
|
80 | ||||
|
81 | def _extract_tokens(self, root, cls): | |||
|
82 | return set(map(lambda x:x.text,root.findall(".//*[@class='"+cls+"']"))) | |||
62 |
|
83 | |||
63 | def _try_highlight(self, method, test, tokens): |
|
84 | def _try_highlight(self, method, test, tokens): | |
64 | """Try highlighting source, look for key tokens""" |
|
85 | """Try highlighting source, look for key tokens""" | |
65 | results = method(test) |
|
86 | results = method(test) | |
66 | for token in tokens: |
|
87 | for token in tokens: | |
67 | assert token in results |
|
88 | assert token in results |
@@ -1,37 +1,40 | |||||
1 | """Global configuration class.""" |
|
1 | """Global configuration class.""" | |
2 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
3 | # Copyright (c) 2013, the IPython Development Team. |
|
3 | # Copyright (c) 2013, the IPython Development Team. | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 | # |
|
6 | # | |
7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | from IPython.utils.traitlets import List |
|
14 | from IPython.utils.traitlets import List | |
15 | from IPython.config.configurable import LoggingConfigurable |
|
15 | from IPython.config.configurable import LoggingConfigurable | |
|
16 | from IPython.utils.traitlets import Unicode | |||
16 |
|
17 | |||
17 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
18 | # Classes and functions |
|
19 | # Classes and functions | |
19 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
20 |
|
21 | |||
21 | class NbConvertBase(LoggingConfigurable): |
|
22 | class NbConvertBase(LoggingConfigurable): | |
22 | """Global configurable class for shared config |
|
23 | """Global configurable class for shared config | |
23 |
|
24 | |||
24 | Usefull for display data priority that might be use by many trasnformers |
|
25 | Usefull for display data priority that might be use by many trasnformers | |
25 | """ |
|
26 | """ | |
26 |
|
27 | |||
27 | display_data_priority = List(['html', 'pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'], |
|
28 | display_data_priority = List(['html', 'pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'], | |
28 | config=True, |
|
29 | config=True, | |
29 | help= """ |
|
30 | help= """ | |
30 | An ordered list of prefered output type, the first |
|
31 | An ordered list of prefered output type, the first | |
31 | encounterd will usually be used when converting discarding |
|
32 | encounterd will usually be used when converting discarding | |
32 | the others. |
|
33 | the others. | |
33 | """ |
|
34 | """ | |
34 | ) |
|
35 | ) | |
35 |
|
36 | |||
|
37 | default_language = Unicode('ipython', config=True, help='default highlight language') | |||
|
38 | ||||
36 | def __init__(self, **kw): |
|
39 | def __init__(self, **kw): | |
37 | super(NbConvertBase, self).__init__(**kw) |
|
40 | super(NbConvertBase, self).__init__(**kw) |
General Comments 0
You need to be logged in to leave comments.
Login now