##// END OF EJS Templates
do a markdown converter
Matthias BUSSONNIER -
Show More
@@ -0,0 +1,12 b''
1 c = get_config()
2
3 c.ConverterTemplate.template_file='markdown'
4 c.ConverterTemplate.tex_environement=False
5
6 c.NbconvertApp.fileext='md'
7
8 c.GlobalConfigurable.display_data_priority=['svg', 'png', 'latex', 'jpg', 'jpeg','text']
9
10 c.ExtractFigureTransformer.enabled=True
11
12
@@ -0,0 +1,73 b''
1 {% extends 'display_priority.tpl' %}
2 {% block in_prompt %}
3 In[{{cell.prompt_number if cell.prompt_number else ' '}}]:{% endblock in_prompt %}
4
5 {% block output_prompt %}{% if cell.haspyout %}Out[{{cell.prompt_number}}]:
6 {%- endif %}{%- endblock output_prompt %}
7
8 {% block input %}
9 ```
10 {{ cell.input}}
11 ```
12 {% endblock input %}
13
14 {% block pyerr %}
15 {{ super() }}
16 {% endblock pyerr %}
17
18 {% block traceback_line %}
19 {{ line |indent| rm_ansi }}{% endblock traceback_line %}
20
21 {% block pyout %}
22 {% block data_priority scoped %}{{ super()}}{% endblock %}
23 {% endblock pyout %}
24
25 {% block stream %}
26 {{ output.text| indent }}
27 {% endblock stream %}
28
29
30
31
32 {% block data_svg %}
33 [!image]({{output.key_svg}})
34 {% endblock data_svg %}
35
36 {% block data_png %}
37 [!image]({{output.key_png}})
38 {% endblock data_png %}
39
40 {% block data_jpg %}
41 [!image]({{output.key_jpg}})
42 {% endblock data_jpg %}
43
44
45
46 {% block data_latex %}
47 $$
48 {{output.latex}}
49 $$
50 {% endblock data_latex %}
51
52 {% block data_text scoped %}
53
54 {{output.text | indent}}
55
56 {% endblock data_text %}
57
58 {% block markdowncell scoped %}
59 {{ cell.source | wrap(80)}}
60 {% endblock markdowncell %}
61
62 {% block headingcell scoped %}
63
64 {{ '#' * cell.level }} {{ cell.source}}
65
66 {% endblock headingcell %}
67
68 {% block rawcell scoped %}{{ cell.source }}
69 {% endblock rawcell %}
70
71 {% block unknowncell scoped %}
72 unknown type {{cell.type}}
73 {% endblock unknowncell %}
@@ -1,223 +1,234 b''
1 """Base classes for the notebook conversion pipeline.
1 """Base classes for the notebook conversion pipeline.
2
2
3 This module defines ConverterTemplate, a highly configurable converter
3 This module defines ConverterTemplate, a highly configurable converter
4 that uses Jinja2 to convert notebook files into different format.
4 that uses Jinja2 to convert 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 befor conversion and jinja filter that would then be availlable in the templates
7 befor conversion and jinja filter that would then be availlable in the templates
8 """
8 """
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (c) 2013, the IPython Development Team.
10 # Copyright (c) 2013, the IPython Development Team.
11 #
11 #
12 # Distributed under the terms of the Modified BSD License.
12 # Distributed under the terms of the Modified BSD License.
13 #
13 #
14 # The full license is in the file COPYING.txt, distributed with this software.
14 # The full license is in the file COPYING.txt, distributed with this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
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
25
26 # IPython imports
26 # IPython imports
27 from IPython.utils.traitlets import MetaHasTraits
27 from IPython.utils.traitlets import MetaHasTraits
28 from IPython.utils.traitlets import (Unicode, List, Bool)
28 from IPython.utils.traitlets import (Unicode, List, Bool)
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.nbformat import current as nbformat
30 from IPython.nbformat import current as nbformat
31
31
32
32 # other libs/dependencies
33 # other libs/dependencies
33 from jinja2 import Environment, FileSystemLoader
34 from jinja2 import Environment, FileSystemLoader
34
35
35
36
36 # local import (pre-transformers)
37 # local import (pre-transformers)
37 import converters.transformers as trans
38 import converters.transformers as trans
38
39
39 # some jinja filters
40 # some jinja filters
40 from converters.jinja_filters import (python_comment, indent,
41 from converters.jinja_filters import (python_comment, indent,
41 rm_fake, remove_ansi, markdown, highlight,
42 rm_fake, remove_ansi, markdown, highlight,
42 ansi2html, markdown2latex, escape_tex, FilterDataType)
43 ansi2html, markdown2latex, escape_tex, FilterDataType)
43
44
44 from converters.utils import markdown2rst
45 from converters.utils import markdown2rst
45
46
47 import textwrap
48
49 def wrap(text, width=100):
50 """ try to detect and wrap paragraph"""
51 splitt = text.split('\n')
52 wrp = map(lambda x:textwrap.wrap(x,width),splitt)
53 wrpd = map('\n'.join, wrp)
54 return '\n'.join(wrpd)
55
46
56
47
57
48 # define differents environemnt with different
58 # define differents environemnt with different
49 # delimiters not to conflict with languages inside
59 # delimiters not to conflict with languages inside
50
60
51 env = Environment(
61 env = Environment(
52 loader=FileSystemLoader([
62 loader=FileSystemLoader([
53 './templates/',
63 './templates/',
54 './templates/skeleton/',
64 './templates/skeleton/',
55 ]),
65 ]),
56 extensions=['jinja2.ext.loopcontrols']
66 extensions=['jinja2.ext.loopcontrols']
57 )
67 )
58
68
59 texenv = Environment(
69 texenv = Environment(
60 loader=FileSystemLoader([
70 loader=FileSystemLoader([
61 './templates/tex/',
71 './templates/tex/',
62 './templates/skeleton/tex/',
72 './templates/skeleton/tex/',
63 ]),
73 ]),
64 extensions=['jinja2.ext.loopcontrols']
74 extensions=['jinja2.ext.loopcontrols']
65 )
75 )
66
76
67
77
68 texenv.block_start_string = '((*'
78 texenv.block_start_string = '((*'
69 texenv.block_end_string = '*))'
79 texenv.block_end_string = '*))'
70
80
71 texenv.variable_start_string = '((('
81 texenv.variable_start_string = '((('
72 texenv.variable_end_string = ')))'
82 texenv.variable_end_string = ')))'
73
83
74 texenv.comment_start_string = '((='
84 texenv.comment_start_string = '((='
75 texenv.comment_end_string = '=))'
85 texenv.comment_end_string = '=))'
76
86
77 texenv.filters['escape_tex'] = escape_tex
87 texenv.filters['escape_tex'] = escape_tex
78
88
79 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
80 # Class declarations
90 # Class declarations
81 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
82 class ConversionException(Exception):
92 class ConversionException(Exception):
83 pass
93 pass
84
94
85 class ConverterTemplate(Configurable):
95 class ConverterTemplate(Configurable):
86 """ A Jinja2 base converter templates
96 """ A Jinja2 base converter templates
87
97
88 Preprocess the ipynb files, feed it throug jinja templates,
98 Preprocess the ipynb files, feed it throug jinja templates,
89 and spit an converted files and a data object with other data
99 and spit an converted files and a data object with other data
90
100
91 shoudl be mostly configurable
101 shoudl be mostly configurable
92 """
102 """
93
103
94 pre_transformer_order = List(['haspyout_transformer'],
104 pre_transformer_order = List(['haspyout_transformer'],
95 config=True,
105 config=True,
96 help= """
106 help= """
97 An ordered list of pre transformer to apply to the ipynb
107 An ordered list of pre transformer to apply to the ipynb
98 file befor running through templates
108 file befor running through templates
99 """
109 """
100 )
110 )
101
111
102 tex_environement = Bool(False,
112 tex_environement = Bool(False,
103 config=True,
113 config=True,
104 help=""" is this a tex environment or not """)
114 help=""" is this a tex environment or not """)
105
115
106 template_file = Unicode('',
116 template_file = Unicode('',
107 config=True,
117 config=True,
108 help=""" Name of the template file to use """ )
118 help=""" Name of the template file to use """ )
109 #-------------------------------------------------------------------------
119 #-------------------------------------------------------------------------
110 # Instance-level attributes that are set in the constructor for this
120 # Instance-level attributes that are set in the constructor for this
111 # class.
121 # class.
112 #-------------------------------------------------------------------------
122 #-------------------------------------------------------------------------
113
123
114
124
115 preprocessors = []
125 preprocessors = []
116
126
117 def __init__(self, preprocessors={}, jinja_filters={}, config=None, **kw):
127 def __init__(self, preprocessors={}, jinja_filters={}, config=None, **kw):
118 """ Init a new converter.
128 """ Init a new converter.
119
129
120 config: the Configurable config object to pass around.
130 config: the Configurable config object to pass around.
121
131
122 preprocessors: dict of **availlable** key/value function to run on
132 preprocessors: dict of **availlable** key/value function to run on
123 ipynb json data before conversion to extract/inline file.
133 ipynb json data before conversion to extract/inline file.
124 See `transformer.py` and `ConfigurableTransformers`
134 See `transformer.py` and `ConfigurableTransformers`
125
135
126 set the order in which the transformers should apply
136 set the order in which the transformers should apply
127 with the `pre_transformer_order` trait of this class
137 with the `pre_transformer_order` trait of this class
128
138
129 transformers registerd by this key will take precedence on
139 transformers registerd by this key will take precedence on
130 default one.
140 default one.
131
141
132
142
133 jinja_filters: dict of supplementary jinja filter that should be made
143 jinja_filters: dict of supplementary jinja filter that should be made
134 availlable in template. If those are of Configurable Class type,
144 availlable in template. If those are of Configurable Class type,
135 they will be instanciated with the config object as argument.
145 they will be instanciated with the config object as argument.
136
146
137 user defined filter will overwrite the one availlable by default.
147 user defined filter will overwrite the one availlable by default.
138 """
148 """
139 super(ConverterTemplate, self).__init__(config=config, **kw)
149 super(ConverterTemplate, self).__init__(config=config, **kw)
140
150
141 # variable parameters depending on the pype of jinja environement
151 # variable parameters depending on the pype of jinja environement
142 self.env = texenv if self.tex_environement else env
152 self.env = texenv if self.tex_environement else env
143 self.ext = '.tplx' if self.tex_environement else '.tpl'
153 self.ext = '.tplx' if self.tex_environement else '.tpl'
144
154
145 for name in self.pre_transformer_order:
155 for name in self.pre_transformer_order:
146 # get the user-defined transformer first
156 # get the user-defined transformer first
147 transformer = getattr(preprocessors, name, getattr(trans, name, None))
157 transformer = getattr(preprocessors, name, getattr(trans, name, None))
148 if isinstance(transformer, MetaHasTraits):
158 if isinstance(transformer, MetaHasTraits):
149 transformer = transformer(config=config)
159 transformer = transformer(config=config)
150 self.preprocessors.append(transformer)
160 self.preprocessors.append(transformer)
151
161
152 ## for compat, remove later
162 ## for compat, remove later
153 self.preprocessors.append(trans.coalesce_streams)
163 self.preprocessors.append(trans.coalesce_streams)
154 self.preprocessors.append(trans.ExtractFigureTransformer(config=config))
164 self.preprocessors.append(trans.ExtractFigureTransformer(config=config))
155 self.preprocessors.append(trans.RevealHelpTransformer(config=config))
165 self.preprocessors.append(trans.RevealHelpTransformer(config=config))
156 self.preprocessors.append(trans.CSSHtmlHeaderTransformer(config=config))
166 self.preprocessors.append(trans.CSSHtmlHeaderTransformer(config=config))
157
167
158 ##
168 ##
159 self.env.filters['filter_data_type'] = FilterDataType(config=config)
169 self.env.filters['filter_data_type'] = FilterDataType(config=config)
160 self.env.filters['pycomment'] = python_comment
170 self.env.filters['pycomment'] = python_comment
161 self.env.filters['indent'] = indent
171 self.env.filters['indent'] = indent
162 self.env.filters['rm_fake'] = rm_fake
172 self.env.filters['rm_fake'] = rm_fake
163 self.env.filters['rm_ansi'] = remove_ansi
173 self.env.filters['rm_ansi'] = remove_ansi
164 self.env.filters['markdown'] = markdown
174 self.env.filters['markdown'] = markdown
165 self.env.filters['highlight'] = highlight
175 self.env.filters['highlight'] = highlight
166 self.env.filters['ansi2html'] = ansi2html
176 self.env.filters['ansi2html'] = ansi2html
167 self.env.filters['markdown2latex'] = markdown2latex
177 self.env.filters['markdown2latex'] = markdown2latex
168 self.env.filters['markdown2rst'] = markdown2rst
178 self.env.filters['markdown2rst'] = markdown2rst
179 self.env.filters['wrap'] = wrap
169
180
170 ## user filter will overwrite
181 ## user filter will overwrite
171 for key, filtr in jinja_filters.iteritems():
182 for key, filtr in jinja_filters.iteritems():
172 if isinstance(filtr, MetaHasTraits):
183 if isinstance(filtr, MetaHasTraits):
173 self.env.filters[key] = filtr(config=config)
184 self.env.filters[key] = filtr(config=config)
174 else :
185 else :
175 self.env.filters[key] = filtr
186 self.env.filters[key] = filtr
176
187
177 self.template = self.env.get_template(self.template_file+self.ext)
188 self.template = self.env.get_template(self.template_file+self.ext)
178
189
179
190
180 def process(self, nb):
191 def process(self, nb):
181 """
192 """
182 preprocess the notebook json for easier use with the templates.
193 preprocess the notebook json for easier use with the templates.
183 will call all the `preprocessor`s in order before returning it.
194 will call all the `preprocessor`s in order before returning it.
184 """
195 """
185
196
186 # dict of 'resources' that could be made by the preprocessors
197 # dict of 'resources' that could be made by the preprocessors
187 # like key/value data to extract files from ipynb like in latex conversion
198 # like key/value data to extract files from ipynb like in latex conversion
188 resources = {}
199 resources = {}
189
200
190 for preprocessor in self.preprocessors:
201 for preprocessor in self.preprocessors:
191 nb, resources = preprocessor(nb, resources)
202 nb, resources = preprocessor(nb, resources)
192
203
193 return nb, resources
204 return nb, resources
194
205
195 def convert(self, nb):
206 def convert(self, nb):
196 """ convert the ipynb file
207 """ convert the ipynb file
197
208
198 return both the converted ipynb file and a dict containing potential
209 return both the converted ipynb file and a dict containing potential
199 other resources
210 other resources
200 """
211 """
201 nb, resources = self.process(nb)
212 nb, resources = self.process(nb)
202 return self.template.render(nb=nb, resources=resources), resources
213 return self.template.render(nb=nb, resources=resources), resources
203
214
204
215
205 def from_filename(self, filename):
216 def from_filename(self, filename):
206 """read and convert a notebook from a file name"""
217 """read and convert a notebook from a file name"""
207 with io.open(filename) as f:
218 with io.open(filename) as f:
208 return self.convert(nbformat.read(f, 'json'))
219 return self.convert(nbformat.read(f, 'json'))
209
220
210 def from_file(self, filelike):
221 def from_file(self, filelike):
211 """read and convert a notebook from a filelike object
222 """read and convert a notebook from a filelike object
212
223
213 filelike object will just be "read" and should be json format..
224 filelike object will just be "read" and should be json format..
214 """
225 """
215 return self.convert(nbformat.read(filelike, 'json'))
226 return self.convert(nbformat.read(filelike, 'json'))
216
227
217 def from_json(self, json):
228 def from_json(self, json):
218 """ not implemented
229 """ not implemented
219
230
220 Should convert from a json object
231 Should convert from a json object
221 """
232 """
222 raise NotImplementedError('not implemented (yet?)')
233 raise NotImplementedError('not implemented (yet?)')
223
234
General Comments 0
You need to be logged in to leave comments. Login now