##// END OF EJS Templates
Almost have nbconvert working again...
Jonathan Frederic -
Show More
@@ -1,155 +1,155 b''
1 1 #!/usr/bin/env python
2 2
3 3 """NBConvert is a utility for conversion of IPYNB files.
4 4
5 5 Commandline interface for the NBConvert conversion utility. Read the
6 6 readme.rst for usage information
7 7 """
8 8 #-----------------------------------------------------------------------------
9 9 #Copyright (c) 2013, the IPython Development Team.
10 10 #
11 11 #Distributed under the terms of the Modified BSD License.
12 12 #
13 13 #The full license is in the file COPYING.txt, distributed with this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 #Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #Stdlib imports
21 21 from __future__ import print_function
22 22 import sys
23 23 import io
24 24 import os
25 25
26 26 #From IPython
27 27 #All the stuff needed for the configurable things
28 28 from IPython.config.application import Application
29 29
30 30 #Local imports
31 31 from nbconvert.api.convert import export_by_name
32 32 from nbconvert.api.exporter import Exporter
33 33
34 34 #-----------------------------------------------------------------------------
35 35 #Globals and constants
36 36 #-----------------------------------------------------------------------------
37 37 NBCONVERT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
38 38
39 39 #'Keys in resources' user prompt.
40 40 KEYS_PROMPT_HEAD = "====================== Keys in Resources =================================="
41 41 KEYS_PROMPT_BODY = """
42 42 ===========================================================================
43 43 You are responsible for writting these files into the appropriate
44 44 directorie(s) if need be. If you do not want to see this message, enable
45 45 the 'write' (boolean) flag of the converter.
46 46 ===========================================================================
47 47 """
48 48
49 49 #Error Messages
50 50 ERROR_CONFIG_NOT_FOUND = "Config file for profile '%s' not found, giving up."
51 51
52 52 #-----------------------------------------------------------------------------
53 53 #Classes and functions
54 54 #-----------------------------------------------------------------------------
55 55 class NbconvertApp(Application):
56 56 """A basic application to convert ipynb files"""
57 57
58 58 aliases = {
59 59 'stdout':'NbconvertApp.stdout',
60 60 'write':'NbconvertApp.write'
61 61 }
62 62
63 63 flags = {}
64 64 flags['no-stdout'] = (
65 65 {'NbconvertApp' : {'stdout' : False}},
66 66 """Do not print converted file to stdout, equivalent to
67 67 --stdout=False"""
68 68 )
69 69
70 70 def __init__(self, **kwargs):
71 71 """Public constructor"""
72 72
73 73 #Call base class
74 74 super(NbconvertApp, self).__init__(**kwargs)
75 75
76 76 #Register class here to have help with help all
77 77 self.classes.insert(0, Exporter)
78 78
79 79
80 80 def start(self, argv=None):
81 81 """Convert a notebook in one step"""
82 82
83 83 #Parse the commandline options.
84 84 self.parse_command_line(argv)
85 85
86 86 #Call base
87 87 super(NbconvertApp, self).start()
88 88
89 89 #The last arguments in chain of arguments will be used as conversion type
90 90 ipynb_file = (self.extra_args)[2]
91 91 export_type = (self.extra_args)[1]
92 92
93 93 #Export
94 94 output, resources, exporter = export_by_name(ipynb_file, export_type)
95
95
96 96 destination_filename = None
97 97 destination_directory = None
98 98 if exporter.write:
99 99
100 100 #Get the file name without the '.ipynb' (6 chars) extension and then
101 101 #remove any addition periods and spaces. The resulting name will
102 102 #be used to create the directory that the files will be exported
103 103 #into.
104 104 out_root = ipynb_file[:-6].replace('.', '_').replace(' ', '_')
105 105 destination_filename = os.path.join(out_root+'.'+exporter.fileext)
106 106
107 107 destination_directory = out_root+'_files'
108 108 if not os.path.exists(destination_directory):
109 109 os.mkdir(destination_directory)
110 110
111 111 #Write the results
112 112 if exporter.stdout or exporter.write:
113 113 self._write_results(exporter.stdout, destination_filename, destination_directory, output, resources)
114 114
115 115
116 116 def _write_results(self, stdout, destination_filename, destination_directory, output, resources):
117 117 if stdout:
118 118 print(output.encode('utf-8'))
119 119
120 120 #Write file output from conversion.
121 121 if not destination_filename is None:
122 122 with io.open(destination_filename, 'w') as f:
123 123 f.write(output)
124 124
125 125 #Output any associate figures into the same "root" directory.
126 126 binkeys = resources.get('figures', {}).get('binary',{}).keys()
127 127 textkeys = resources.get('figures', {}).get('text',{}).keys()
128 128 if binkeys or textkeys :
129 129 if not destination_directory is None:
130 130 for key in binkeys:
131 131 with io.open(os.path.join(destination_directory, key), 'wb') as f:
132 132 f.write(resources['figures']['binary'][key])
133 133 for key in textkeys:
134 134 with io.open(os.path.join(destination_directory, key), 'w') as f:
135 135 f.write(resources['figures']['text'][key])
136 136
137 137 #Figures that weren't exported which will need to be created by the
138 138 #user. Tell the user what figures these are.
139 139 if stdout:
140 140 print(KEYS_PROMPT_HEAD)
141 141 print(resources['figures'].keys())
142 142 print(KEYS_PROMPT_BODY)
143 143
144 144 #-----------------------------------------------------------------------------
145 145 #Script main
146 146 #-----------------------------------------------------------------------------
147 147 def main():
148 148 """Convert a notebook in one step"""
149 149
150 150 app = NbconvertApp.instance()
151 151 app.description = __doc__
152 app.run(argv=sys.argv)
152 app.start(argv=sys.argv)
153 153
154 154 if __name__ == '__main__':
155 155 main() No newline at end of file
@@ -1,219 +1,219 b''
1 1 """Exporter for the notebook conversion pipeline.
2 2
3 3 This module defines Exporter, a highly configurable converter
4 4 that uses Jinja2 to export notebook files into different format.
5 5
6 6 You can register both pre-transformers that will act on the notebook format
7 7 before conversion and jinja filter that would then be available in the templates
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (c) 2013, the IPython Development Team.
12 12 #
13 13 # Distributed under the terms of the Modified BSD License.
14 14 #
15 15 # The full license is in the file COPYING.txt, distributed with this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21 from __future__ import print_function, absolute_import
22 22
23 23 # Stdlib imports
24 24 import io
25 25 import os
26 26
27 27 # IPython imports
28 28 from IPython.config.configurable import Configurable
29 29 from IPython.nbformat import current as nbformat
30 30 from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool
31 31 from IPython.utils.text import indent
32 32
33 33 # other libs/dependencies
34 34 from jinja2 import Environment, FileSystemLoader
35 35 from markdown import markdown
36 36
37 37 # local import
38 38 import nbconvert.filters.strings
39 39 import nbconvert.filters.markdown
40 40 import nbconvert.filters.latex
41 41 import nbconvert.filters.datatypefilter
42 import nbconvert.filters.pygments
42 import nbconvert.filters.highlight
43 43 import nbconvert.filters.ansi
44 44
45 45 import nbconvert.transformers.extractfigure
46 46 import nbconvert.transformers.coalescestreams
47 47
48 48
49 49 #-----------------------------------------------------------------------------
50 50 # Globals and constants
51 51 #-----------------------------------------------------------------------------
52 52
53 53 #Standard Jinja2 environment constants
54 54 TEMPLATE_PATH = "/../templates/"
55 55 TEMPLATE_SKELETON_PATH = "/../templates/skeleton/"
56 56
57 57 #Jinja2 extensions to load.
58 58 JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
59 59
60 60 #-----------------------------------------------------------------------------
61 61 # Classes and functions
62 62 #-----------------------------------------------------------------------------
63 63 class Exporter(Configurable):
64 64 pre_transformer_order = List(['haspyout_transformer'],
65 65 config=True,
66 66 help= """
67 67 An ordered list of pre-transformer to apply to the IPYNB
68 68 file before running through templates
69 69 """
70 70 )
71 71
72 72 template_file = Unicode(
73 73 '', config=True,
74 74 help="Name of the template file to use")
75 75
76 76 file_extension = Unicode(
77 77 'txt', config=True,
78 78 help="Extension of the file that should be written to disk"
79 79 )
80 80
81 81 stdout = Bool(
82 82 True, config=True,
83 83 help="""Whether to print the converted IPYNB file to stdout
84 84 use full do diff files without actually writing a new file"""
85 85 )
86 86
87 87 write = Bool(
88 88 False, config=True,
89 89 help="""Should the converted notebook file be written to disk
90 90 along with potential extracted resources."""
91 91 )
92 92
93 93 #Extension that the template files use.
94 94 template_extension = ".tpl"
95 95
96 96 #Processors that process the input data prior to the export, set in the
97 97 #constructor for this class.
98 98 preprocessors = []
99 99
100 100 # Public Constructor #####################################################
101 101
102 102 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
103 103
104 104 #Call the base class constructor
105 105 super(Exporter, self).__init__(config=config, **kw)
106 106
107 107 #Standard environment
108 108 self._init_environment()
109 109
110 110 #TODO: Implement reflection style methods to get user transformers.
111 111 #if not preprocessors is None:
112 112 # for name in self.pre_transformer_order:
113 113 # # get the user-defined transformer first
114 114 # transformer = preprocessors.get(name, getattr(trans, name, None))
115 115 # if isinstance(transformer, MetaHasTraits):
116 116 # transformer = transformer(config=config)
117 117 # self.preprocessors.append(transformer)
118 118
119 119 #Add transformers
120 120 self._register_transformers()
121 121
122 122 #Add filters to the Jinja2 environment
123 123 self._register_filters()
124 124
125 125 #Load user filters. Overwrite existing filters if need be.
126 126 if not jinja_filters is None:
127 127 for key, user_filter in jinja_filters.iteritems():
128 128 if issubclass(user_filter, MetaHasTraits):
129 129 self.environment.filters[key] = user_filter(config=config)
130 130 else:
131 131 self.environment.filters[key] = user_filter
132 132
133 133 # Public methods #########################################
134 134
135 135 def from_notebook_node(self, nb):
136 136 nb, resources = self._preprocess(nb)
137 137
138 138 #Load the template file.
139 139 self.template = self.environment.get_template(self.template_file+self.template_extension)
140 140
141 141 return self.template.render(nb=nb, resources=resources), resources
142 142
143 143
144 144 def from_filename(self, filename):
145 145 with io.open(filename) as f:
146 146 return self.from_notebook_node(nbformat.read(f, 'json'))
147 147
148 148
149 149 def from_file(self, file_stream):
150 150 return self.from_notebook_node(nbformat.read(file_stream, 'json'))
151 151
152 152
153 153 def register_transformer(self, transformer):
154 154 if isinstance(transformer, MetaHasTraits):
155 155 transformer_instance = transformer(config=self.config)
156 156 self.preprocessors.append(transformer_instance)
157 157 return transformer_instance
158 158 else:
159 159 self.preprocessors.append(transformer)
160 160 return transformer
161 161
162 162
163 163 def register_filter(self, name, filter):
164 164 if isinstance(filter, MetaHasTraits):
165 165 self.environment.filters[name] = filter(config=self.config)
166 166 else:
167 167 self.environment.filters[name] = filter
168 168 return self.environment.filters[name]
169 169
170 170
171 171 # Protected and Private methods #########################################
172 172
173 173 def _register_transformers(self):
174 174 self.register_transformer(nbconvert.transformers.coalescestreams.coalesce_streams)
175 175
176 176 #Remember the figure extraction transformer so it can be enabled and
177 177 #disabled easily later.
178 178 self.extract_figure_transformer = self.register_transformer(nbconvert.transformers.extractfigure.ExtractFigureTransformer)
179 179
180 180
181 181 def _register_filters(self):
182 182 self.register_filter('indent', indent)
183 183 self.register_filter('markdown', markdown)
184 184 self.register_filter('ansi2html', nbconvert.filters.ansi.ansi2html)
185 185 self.register_filter('filter_data_type', nbconvert.filters.datatypefilter.DataTypeFilter)
186 186 self.register_filter('get_lines', nbconvert.filters.strings.get_lines)
187 self.register_filter('highlight', nbconvert.filters.pygments.highlight)
188 self.register_filter('highlight2html', nbconvert.filters.pygments.highlight)
189 self.register_filter('highlight2latex', nbconvert.filters.pygments.highlight2latex)
187 self.register_filter('highlight', nbconvert.filters.highlight.highlight)
188 self.register_filter('highlight2html', nbconvert.filters.highlight.highlight)
189 self.register_filter('highlight2latex', nbconvert.filters.highlight.highlight2latex)
190 190 self.register_filter('markdown2latex', nbconvert.filters.markdown.markdown2latex)
191 191 self.register_filter('markdown2rst', nbconvert.filters.markdown.markdown2rst)
192 192 self.register_filter('pycomment', nbconvert.filters.strings.python_comment)
193 193 self.register_filter('rm_ansi', nbconvert.filters.ansi.remove_ansi)
194 194 self.register_filter('rm_dollars', nbconvert.filters.strings.strip_dollars)
195 195 self.register_filter('rm_fake', nbconvert.filters.strings.rm_fake)
196 196 self.register_filter('rm_math_space', nbconvert.filters.latex.rm_math_space)
197 197 self.register_filter('wrap', nbconvert.filters.strings.wrap)
198 198
199 199
200 200 def _init_environment(self):
201 201 self.environment = Environment(
202 202 loader=FileSystemLoader([
203 203 os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_PATH,
204 204 os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_SKELETON_PATH,
205 205 ]),
206 206 extensions=JINJA_EXTENSIONS
207 207 )
208 208
209 209
210 210 def _preprocess(self, nb):
211 211
212 212 #Dict of 'resources' that can be filled by the preprocessors.
213 213 resources = {}
214 214
215 215 #Run each transformer on the notebook. Carry the output along
216 216 #to each transformer
217 217 for transformer in self.preprocessors:
218 218 nb, resources = transformer(nb, resources)
219 219 return nb, resources
@@ -1,42 +1,42 b''
1 1 """TODO: Docstring
2 2 """
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2013, the IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # local import
17 17 import exporter
18 18 import nbconvert.transformers.csshtmlheader
19 19 from IPython.utils.traitlets import Unicode
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Classes
23 23 #-----------------------------------------------------------------------------
24 24 class HtmlExporter(exporter.Exporter):
25 25
26 26 file_extension = Unicode(
27 27 'html', config=True,
28 28 help="Extension of the file that should be written to disk"
29 29 )
30 30
31 31 template_file = Unicode(
32 32 'fullhtml', config=True,
33 33 help="Name of the template file to use")
34 34
35 35 def _register_transformers(self):
36 36
37 37 #Register the transformers of the base class.
38 super(exporter.Exporter, self)._register_transformers()
38 super(HtmlExporter, self)._register_transformers()
39 39
40 40 #Register latex transformer
41 41 self.register_transformer(nbconvert.transformers.csshtmlheader.CSSHtmlHeaderTransformer)
42 42 No newline at end of file
@@ -1,99 +1,99 b''
1 1 #-----------------------------------------------------------------------------
2 2 # Copyright (c) 2013, the IPython Development Team.
3 3 #
4 4 # Distributed under the terms of the Modified BSD License.
5 5 #
6 6 # The full license is in the file COPYING.txt, distributed with this software.
7 7 #-----------------------------------------------------------------------------
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Imports
11 11 #-----------------------------------------------------------------------------
12 12
13 13 # Stdlib imports
14 14 import os
15 15
16 16 # IPython imports
17 17 from IPython.utils.traitlets import Unicode
18 18
19 19 # other libs/dependencies
20 20 from jinja2 import Environment, FileSystemLoader
21 21
22 22 # local import
23 23 import exporter
24 24 import nbconvert.filters.latex
25 import nbconvert.filters.pygments
25 import nbconvert.filters.highlight
26 26 from nbconvert.transformers.latex import LatexTransformer
27 27 #-----------------------------------------------------------------------------
28 28 # Globals and constants
29 29 #-----------------------------------------------------------------------------
30 30
31 31 #Latex Jinja2 constants
32 LATEX_TEMPLATE_PATH = "/../templates/tex/"
33 LATEX_TEMPLATE_SKELETON_PATH = "/../templates/tex/skeleton/"
32 LATEX_TEMPLATE_PATH = "/../templates/latex/"
33 LATEX_TEMPLATE_SKELETON_PATH = "/../templates/latex/skeleton/"
34 34
35 35 #Special Jinja2 syntax that will not conflict when exporting latex.
36 36 LATEX_JINJA_COMMENT_BLOCK = ["((=", "=))"]
37 37 LATEX_JINJA_VARIABLE_BLOCK = ["(((", ")))"]
38 38 LATEX_JINJA_LOGIC_BLOCK = ["((*", "*))"]
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Classes and functions
42 42 #-----------------------------------------------------------------------------
43 43 class LatexExporter(exporter.Exporter):
44 44
45 45 #Extension that the template files use.
46 46 template_extension = ".tplx"
47 47
48 48 file_extension = Unicode(
49 49 'tex', config=True,
50 50 help="Extension of the file that should be written to disk")
51 51
52 52 template_file = Unicode(
53 'latex_base', config=True,
53 'base', config=True,
54 54 help="Name of the template file to use")
55 55
56 56 def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw):
57 57
58 58 #Call base class constructor.
59 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
59 super(LatexExporter, self).__init__(preprocessors, jinja_filters, config, **kw)
60 60
61 61 self.extract_figure_transformer.display_data_priority = ['latex', 'svg', 'png', 'jpg', 'jpeg' , 'text']
62 62 self.extract_figure_transformer.extra_ext_map={'svg':'pdf'}
63 63
64 64
65 65 def _init_environment(self):
66 66 self.environment = Environment(
67 67 loader=FileSystemLoader([
68 68 os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_PATH,
69 69 os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_SKELETON_PATH,
70 70 ]),
71 71 extensions=exporter.JINJA_EXTENSIONS
72 72 )
73 73
74 74 #Set special Jinja2 syntax that will not conflict with latex.
75 75 self.environment.block_start_string = LATEX_JINJA_LOGIC_BLOCK[0]
76 76 self.environment.block_end_string = LATEX_JINJA_LOGIC_BLOCK[1]
77 77 self.environment.variable_start_string = LATEX_JINJA_VARIABLE_BLOCK[0]
78 78 self.environment.variable_end_string = LATEX_JINJA_VARIABLE_BLOCK[1]
79 79 self.environment.comment_start_string = LATEX_JINJA_COMMENT_BLOCK[0]
80 80 self.environment.comment_end_string = LATEX_JINJA_COMMENT_BLOCK[1]
81 81
82 82
83 83 def _register_filters(self):
84 84
85 85 #Register the filters of the base class.
86 super(exporter.Exporter, self)._register_filters()
86 super(LatexExporter, self)._register_filters()
87 87
88 88 #Add latex filters to the Jinja2 environment
89 self.register_filter('escape_tex', filters.latex.escape_tex)
90 self.register_filter('highlight', filters.pygments.highlight2latex)
89 self.register_filter('escape_tex', nbconvert.filters.latex.escape_tex)
90 self.register_filter('highlight', nbconvert.filters.highlight.highlight2latex)
91 91
92 92 def _register_transformers(self):
93 93
94 94 #Register the transformers of the base class.
95 super(exporter.Exporter, self)._register_transformers()
95 super(LatexExporter, self)._register_transformers()
96 96
97 97 #Register latex transformer
98 98 self.register_transformer(LatexTransformer)
99 99 No newline at end of file
@@ -1,40 +1,40 b''
1 1 """TODO: Docstring
2 2 """
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2013, the IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # local import
17 17 import exporter
18 18 from IPython.utils.traitlets import Unicode
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Classes
22 22 #-----------------------------------------------------------------------------
23 23 class PythonExporter(exporter.Exporter):
24 24
25 25 file_extension = Unicode(
26 26 'py', config=True,
27 27 help="Extension of the file that should be written to disk")
28 28
29 29 template_file = Unicode(
30 30 'python', config=True,
31 31 help="Name of the template file to use")
32 32
33 33 def __init__(self, preprocessors=None, jinja_filters=None, config=None, armor=False, **kw):
34 34
35 35 #Call base class constructor.
36 super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw)
36 super(PythonExporter, self).__init__(preprocessors, jinja_filters, config, **kw)
37 37
38 38 #Set defaults
39 39 self.extract_figure_transformer.enabled = False
40 40
@@ -1,41 +1,41 b''
1 1 """TODO: Docstring
2 2 """
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2013, the IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # local import
17 17 import html
18 18 import nbconvert.transformers.revealhelp
19 19 from IPython.utils.traitlets import Unicode
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Classes
23 23 #-----------------------------------------------------------------------------
24 24 class RevealExporter(html.HtmlExporter):
25 25
26 26 file_extension = Unicode(
27 27 'reveal.html', config=True,
28 28 help="Extension of the file that should be written to disk")
29 29
30 30 template_file = Unicode(
31 31 'reveal', config=True,
32 32 help="Name of the template file to use")
33 33
34 34 def _register_transformers(self):
35 35
36 36 #Register the transformers of the base class.
37 super(html_exporter.HtmlExporter, self)._register_transformers()
37 super(RevealExporter, self)._register_transformers()
38 38
39 39 #Register reveal help transformer
40 self.register_transformer(transformers.revealhelp.RevealHelpTransformer)
40 self.register_transformer(nbconvert.transformers.revealhelp.RevealHelpTransformer)
41 41 No newline at end of file
@@ -1,34 +1,34 b''
1 1
2 2 #-----------------------------------------------------------------------------
3 3 # Copyright (c) 2013, the IPython Development Team.
4 4 #
5 5 # Distributed under the terms of the Modified BSD License.
6 6 #
7 7 # The full license is in the file COPYING.txt, distributed with this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13
14 14 # local import
15 15 import latex
16 16 from IPython.utils.traitlets import Unicode
17 17 from nbconvert.transformers.sphinx import SphinxTransformer
18 18 #-----------------------------------------------------------------------------
19 19 # Classes
20 20 #-----------------------------------------------------------------------------
21 21 class SphinxExporter(latex.LatexExporter):
22 22
23 23 template_file = Unicode(
24 'sphinxhowto', config=True,
24 'sphinx_howto', config=True,
25 25 help="Name of the template file to use")
26 26
27 27 def _register_transformers(self):
28 28
29 29 #Register the transformers of the base class.
30 super(latex.LatexExporter, self)._register_transformers()
30 super(SphinxExporter, self)._register_transformers()
31 31
32 32 #Register sphinx latex transformer
33 33 self.register_transformer(SphinxTransformer)
34 34
@@ -1,40 +1,39 b''
1 1 """Filter used to select the first preferred output format available.
2 2
3 3 The filter contained in the file allows the converter templates to select
4 4 the output format that is most valuable to the active export format. The
5 5 value of the different formats is set via
6 6 GlobalConfigurable.display_data_priority
7 7 """
8 8 #-----------------------------------------------------------------------------
9 9 # Copyright (c) 2013, the IPython Development Team.
10 10 #
11 11 # Distributed under the terms of the Modified BSD License.
12 12 #
13 13 # The full license is in the file COPYING.txt, distributed with this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Classes and functions
18 18 #-----------------------------------------------------------------------------
19 19 class DataTypeFilter(object):
20 20 """ Returns the preferred display format """
21 21
22 22 display_data_priority = None
23 23
24 24 def __init__(self, display_data_priority):
25 super(object, self).__init__()
26 25
27 26 #Make sure that the display data priority variably is not None.
28 if self.display_data_priority is None:
27 if display_data_priority is None:
29 28 raise TypeError
30 29 else:
31 30 self.display_data_priority = display_data_priority
32 31
33 32
34 33 def __call__(self, output):
35 34 """ Return the first available format in the priority """
36 35
37 36 for fmt in self.display_data_priority:
38 37 if fmt in output:
39 38 return [fmt]
40 39 return [] No newline at end of file
@@ -1,39 +1,41 b''
1
2 from pygments import highlight as pygements_highlight
3 from pygments.lexers import get_lexer_by_name
4 from pygments.formatters import HtmlFormatter
5 from pygments.formatters import LatexFormatter
6
1 7 # Our own imports
2 8 from nbconvert.utils.lexers import IPythonLexer
3 9
4 10 #-----------------------------------------------------------------------------
5 11 # Globals and constants
6 12 #-----------------------------------------------------------------------------
7 13 _multiline_outputs = ['text', 'html', 'svg', 'latex', 'javascript', 'json']
8 14
9 15
10 16 #-----------------------------------------------------------------------------
11 17 # Utility functions
12 18 #-----------------------------------------------------------------------------
13 19 def highlight(src, lang='ipython'):
14 20 """
15 21 Return a syntax-highlighted version of the input source as html output.
16 22 """
17 from pygments.formatters import HtmlFormatter
18 return pygment_highlight(src, HtmlFormatter(), lang)
23
24 return _pygment_highlight(src, HtmlFormatter(), lang)
19 25
20 26 def highlight2latex(src, lang='ipython'):
21 27 """
22 28 Return a syntax-highlighted version of the input source as latex output.
23 29 """
24 from pygments.formatters import LatexFormatter
25 return pygment_highlight(src, LatexFormatter(), lang)
30 return _pygment_highlight(src, LatexFormatter(), lang)
26 31
27 def pygment_highlight(src, output_formatter, lang='ipython'):
32 def _pygment_highlight(src, output_formatter, lang='ipython'):
28 33 """
29 34 Return a syntax-highlighted version of the input source
30 35 """
31 from pygments import highlight
32 from pygments.lexers import get_lexer_by_name
33
34 36 if lang == 'ipython':
35 37 lexer = IPythonLexer()
36 38 else:
37 39 lexer = get_lexer_by_name(lang, stripall=True)
38 40
39 return highlight(src, lexer, output_formatter)
41 return pygements_highlight(src, lexer, output_formatter)
@@ -1,92 +1,92 b''
1 1 ((= autogenerated file do not edit =))
2 2 ((=
3 3
4 4 DO NOT USE THIS AS A BASE WORK,
5 5 IF YOU ARE COPY AND PASTING THIS FILE
6 6 YOU ARE PROBABLY DOING THINGS WRONG.
7 7
8 8 Null template, Does nothing except defining a basic structure
9 9 To layout the different blocks of a notebook.
10 10
11 11 Subtemplates can override blocks to define their custom representation.
12 12
13 13 If one of the block you do overwrite is not a leave block, consider
14 14 calling super.
15 15
16 16 ((*- block nonLeaveBlock -*))
17 17 #add stuff at beginning
18 18 ((( super() )))
19 19 #add stuff at end
20 20 ((*- endblock nonLeaveBlock -*))
21 21
22 22 consider calling super even if it is a leave block, we might insert more blocks later.
23 23
24 24 =))
25 25 ((*- block header -*))
26 26 ((*- endblock header -*))
27 27 ((*- block body -*))
28 28 ((*- for worksheet in nb.worksheets -*))
29 29 ((*- for cell in worksheet.cells -*))
30 30 ((*- block any_cell scoped -*))
31 ((*- if cell.type in ['code'] -*))
31 ((*- if cell.cell_type in ['code'] -*))
32 32 ((*- block codecell scoped -*))
33 33 ((*- block input_group -*))
34 34 ((*- block in_prompt -*))((*- endblock in_prompt -*))
35 35 ((*- block input -*))((*- endblock input -*))
36 36 ((*- endblock input_group -*))
37 37 ((*- if cell.outputs -*))
38 38 ((*- block output_group -*))
39 39 ((*- block output_prompt -*))((*- endblock output_prompt -*))
40 40 ((*- block outputs scoped -*))
41 41 ((*- for output in cell.outputs -*))
42 42 ((*- block output scoped -*))
43 43 ((*- if output.output_type in ['pyout'] -*))
44 44 ((*- block pyout scoped -*))((*- endblock pyout -*))
45 45 ((*- elif output.output_type in ['stream'] -*))
46 46 ((*- block stream scoped -*))
47 47 ((*- if output.stream in ['stdout'] -*))
48 48 ((*- block stream_stdout scoped -*))
49 49 ((*- endblock stream_stdout -*))
50 50 ((*- elif output.stream in ['stderr'] -*))
51 51 ((*- block stream_stderr scoped -*))
52 52 ((*- endblock stream_stderr -*))
53 53 ((*- endif -*))
54 54 ((*- endblock stream -*))
55 55 ((*- elif output.output_type in ['display_data'] -*))
56 56 ((*- block display_data scoped -*))
57 57 ((*- block data_priority scoped -*))
58 58 ((*- endblock data_priority -*))
59 59 ((*- endblock display_data -*))
60 60 ((*- elif output.output_type in ['pyerr'] -*))
61 61 ((*- block pyerr scoped -*))
62 62 ((*- for line in output.traceback -*))
63 63 ((*- block traceback_line scoped -*))((*- endblock traceback_line -*))
64 64 ((*- endfor -*))
65 65 ((*- endblock pyerr -*))
66 66 ((*- endif -*))
67 67 ((*- endblock output -*))
68 68 ((*- endfor -*))
69 69 ((*- endblock outputs -*))
70 70 ((*- endblock output_group -*))
71 71 ((*- endif -*))
72 72 ((*- endblock codecell -*))
73 ((*- elif cell.type in ['markdown'] -*))
73 ((*- elif cell.cell_type in ['markdown'] -*))
74 74 ((*- block markdowncell scoped-*))
75 75 ((*- endblock markdowncell -*))
76 ((*- elif cell.type in ['heading'] -*))
76 ((*- elif cell.cell_type in ['heading'] -*))
77 77 ((*- block headingcell scoped-*))
78 78 ((*- endblock headingcell -*))
79 ((*- elif cell.type in ['raw'] -*))
79 ((*- elif cell.cell_type in ['raw'] -*))
80 80 ((*- block rawcell scoped-*))
81 81 ((*- endblock rawcell -*))
82 82 ((*- else -*))
83 83 ((*- block unknowncell scoped-*))
84 84 ((*- endblock unknowncell -*))
85 85 ((*- endif -*))
86 86 ((*- endblock any_cell -*))
87 87 ((*- endfor -*))
88 88 ((*- endfor -*))
89 89 ((*- endblock body -*))
90 90
91 91 ((*- block footer -*))
92 92 ((*- endblock footer -*))
@@ -1,439 +1,439 b''
1 1 ((= NBConvert Sphinx-Latex Template
2 2
3 3 Purpose: Allow export of PDF friendly Latex inspired by Sphinx. Most of the
4 4 template is derived directly from Sphinx source.
5 5
6 Inheritance: null>display_priority>latex_base
6 Inheritance: null>display_priority
7 7
8 8 Note: For best display, use latex syntax highlighting. =))
9 9
10 10 ((*- extends 'display_priority.tplx' -*))
11 11
12 12 %==============================================================================
13 13 % Declarations
14 14 %==============================================================================
15 15
16 16 % In order to make sure that the input/output header follows the code it
17 17 % preceeds, the needspace package is used to request that a certain
18 18 % amount of lines (specified by this variable) are reserved. If those
19 19 % lines aren't available on the current page, the documenter will break
20 20 % to the next page and the header along with accomanying lines will be
21 21 % rendered together. This value specifies the number of lines that
22 22 % the header will be forced to group with without a page break.
23 23 ((*- set min_header_lines = 4 -*))
24 24
25 25 % This is the number of characters that are permitted per line. It's
26 26 % important that this limit is set so characters do not run off the
27 27 % edges of latex pages (since latex does not always seem smart enough
28 28 % to prevent this in some cases.) This is only applied to textual output
29 29 ((* if resources.sphinx.outputstyle == 'simple' *))
30 30 ((*- set wrap_size = 85 -*))
31 31 ((* elif resources.sphinx.outputstyle == 'notebook' *))
32 32 ((*- set wrap_size = 70 -*))
33 33 ((* endif *))
34 34
35 35 %==============================================================================
36 36 % Header
37 37 %==============================================================================
38 38 ((* block header *))
39 39
40 40 % Header, overrides base
41 41
42 42 % Make sure that the sphinx doc style knows who it inherits from.
43 43 \def\sphinxdocclass{(((parentdocumentclass)))}
44 44
45 45 % Declare the document class
46 46 \documentclass[letterpaper,10pt,english]{((( resources.sphinx.texinputs )))/sphinx(((documentclass)))}
47 47
48 48 % Imports
49 49 \usepackage[utf8]{inputenc}
50 50 \DeclareUnicodeCharacter{00A0}{\\nobreakspace}
51 51 \usepackage[T1]{fontenc}
52 52 \usepackage{babel}
53 53 \usepackage{times}
54 54 \usepackage{import}
55 55 \usepackage[((( resources.sphinx.chapterstyle )))]{((( resources.sphinx.texinputs )))/fncychap}
56 56 \usepackage{longtable}
57 57 \usepackage{((( resources.sphinx.texinputs )))/sphinx}
58 58 \usepackage{multirow}
59 59
60 60 \usepackage{amsmath}
61 61 \usepackage{amssymb}
62 62 \usepackage{ucs}
63 63 \usepackage{enumerate}
64 64
65 65 % Used to make the Input/Output rules follow around the contents.
66 66 \usepackage{needspace}
67 67
68 68 % Pygments requirements
69 69 \usepackage{fancyvrb}
70 70 \usepackage{color}
71 71
72 72 % Needed to box output/input
73 73 \usepackage{tikz}
74 74 \usetikzlibrary{calc,arrows,shadows}
75 75 \usepackage[framemethod=tikz]{mdframed}
76 76
77 77 \usepackage{alltt}
78 78
79 79 % Used to load and display graphics
80 80 \usepackage{graphicx}
81 81 \graphicspath{ {figs/} }
82 82 \usepackage[Export]{adjustbox} % To resize
83 83
84 84
85 85 % For formatting output while also word wrapping.
86 86 \usepackage{listings}
87 87 \lstset{breaklines=true}
88 88 \lstset{basicstyle=\small\ttfamily}
89 89 \def\smaller{\fontsize{9.5pt}{9.5pt}\selectfont}
90 90
91 91 %Pygments definitions
92 92 ((( resources.sphinx.pygment_definitions )))
93 93
94 94 %Set pygments styles if needed...
95 95 ((* if resources.sphinx.outputstyle == 'notebook' *))
96 96 \definecolor{nbframe-border}{rgb}{0.867,0.867,0.867}
97 97 \definecolor{nbframe-bg}{rgb}{0.969,0.969,0.969}
98 98 \definecolor{nbframe-in-prompt}{rgb}{0.0,0.0,0.502}
99 99 \definecolor{nbframe-out-prompt}{rgb}{0.545,0.0,0.0}
100 100
101 101 \newenvironment{ColorVerbatim}
102 102 {\begin{mdframed}[%
103 103 roundcorner=1.0pt, %
104 104 backgroundcolor=nbframe-bg, %
105 105 userdefinedwidth=1\linewidth, %
106 106 leftmargin=0.1\linewidth, %
107 107 innerleftmargin=0pt, %
108 108 innerrightmargin=0pt, %
109 109 linecolor=nbframe-border, %
110 110 linewidth=1pt, %
111 111 usetwoside=false, %
112 112 everyline=true, %
113 113 innerlinewidth=3pt, %
114 114 innerlinecolor=nbframe-bg, %
115 115 middlelinewidth=1pt, %
116 116 middlelinecolor=nbframe-bg, %
117 117 outerlinewidth=0.5pt, %
118 118 outerlinecolor=nbframe-border, %
119 119 needspace=0pt
120 120 ]}
121 121 {\end{mdframed}}
122 122
123 123 \newenvironment{InvisibleVerbatim}
124 124 {\begin{mdframed}[leftmargin=0.1\linewidth,innerleftmargin=3pt,innerrightmargin=3pt, userdefinedwidth=1\linewidth, linewidth=0pt, linecolor=white, usetwoside=false]}
125 125 {\end{mdframed}}
126 126
127 127 \renewenvironment{Verbatim}[1][\unskip]
128 128 {\begin{alltt}\smaller}
129 129 {\end{alltt}}
130 130 ((* endif *))
131 131
132 132 % Help prevent overflowing lines due to urls and other hard-to-break
133 133 % entities. This doesn't catch everything...
134 134 \sloppy
135 135
136 136 % Document level variables
137 137 \title{((( nb.metadata.name | escape_tex )))}
138 138 \date{((( nb.metadata._draft.date | escape_tex )))}
139 139 \release{((( nb.metadata._draft.version | escape_tex )))}
140 140 \author{((( nb.metadata._draft.author | escape_tex )))}
141 141 \renewcommand{\releasename}{((( nb.metadata._draft.release | escape_tex )))}
142 142
143 143 % TODO: Add option for the user to specify a logo for his/her export.
144 144 \newcommand{\sphinxlogo}{}
145 145
146 146 % Make the index page of the document.
147 147 \makeindex
148 148
149 149 % Import sphinx document type specifics.
150 150 ((* block sphinxheader *))((* endblock sphinxheader *))
151 151 ((* endblock header *))
152 152
153 153 %==============================================================================
154 154 % Body
155 155 %==============================================================================
156 156 ((* block body *))
157 157 ((* block bodyBegin *))
158 158 % Body
159 159
160 160 % Start of the document
161 161 \begin{document}
162 162
163 163 ((* if resources.sphinx.header *))
164 164 \maketitle
165 165 ((* endif *))
166 166
167 167 ((* block toc *))
168 168 \tableofcontents
169 169 ((* endblock toc *))
170 170
171 171 ((* endblock bodyBegin *))((( super() )))((* block bodyEnd *))
172 172
173 173 \renewcommand{\indexname}{Index}
174 174 \printindex
175 175
176 176 % End of document
177 177 \end{document}
178 178 ((* endblock bodyEnd *))
179 179 ((* endblock body *))
180 180
181 181 %==============================================================================
182 182 % Footer
183 183 %==============================================================================
184 184 ((* block footer *))
185 185 ((* endblock footer *))
186 186
187 187 %==============================================================================
188 188 % Headings
189 189 %
190 190 % Purpose: Format pynb headers as sphinx headers. Depending on the Sphinx
191 191 % style that is active, this will change. Thus sphinx styles will
192 192 % override the values here.
193 193 %==============================================================================
194 194 ((* block headingcell -*))
195 195 \
196 196 ((*- if cell.level == 1 -*))
197 197 ((* block h1 -*))part((* endblock h1 -*))
198 198 ((*- elif cell.level == 2 -*))
199 199 ((* block h2 -*))chapter((* endblock h2 -*))
200 200 ((*- elif cell.level == 3 -*))
201 201 ((* block h3 -*))section((* endblock h3 -*))
202 202 ((*- elif cell.level == 4 -*))
203 203 ((* block h4 -*))subsection((* endblock h4 -*))
204 204 ((*- elif cell.level == 5 -*))
205 205 ((* block h5 -*))subsubsection((* endblock h5 -*))
206 206 ((*- elif cell.level == 6 -*))
207 207 ((* block h6 -*))paragraph((* endblock h6 -*))
208 208
209 209 ((= It's important to make sure that underscores (which tend to be common
210 210 in IPYNB file titles) do not make their way into latex. Sometimes this
211 211 causes latex to barf. =))
212 212 ((*- endif -*)){((( escape_underscores(cell.source | markdown2latex ) )))}
213 213 ((*- endblock headingcell *))
214 214
215 215 %==============================================================================
216 216 % Markdown
217 217 %
218 218 % Purpose: Convert markdown to latex. Here markdown2latex is explicitly
219 219 % called since we know we want latex output.
220 220 %==============================================================================
221 221 ((*- block markdowncell scoped-*))
222 222 ((( cell.source | markdown2latex )))
223 223 ((*- endblock markdowncell -*))
224 224
225 225 %==============================================================================
226 226 % Rawcell
227 227 %
228 228 % Purpose: Raw text cells allow the user to manually inject document code that
229 229 % will not get touched by the templating system.
230 230 %==============================================================================
231 231 ((*- block rawcell *))
232 232 ((( cell.source | wrap(wrap_size) )))
233 233 ((* endblock rawcell -*))
234 234
235 235 %==============================================================================
236 236 % Unknowncell
237 237 %
238 238 % Purpose: This is the catch anything unhandled. To display this data, we
239 239 % remove all possible latex conflicts and wrap the characters so they
240 240 % can't flow off of the page.
241 241 %==============================================================================
242 242 ((* block unknowncell scoped*))
243 243
244 244 % Unsupported cell type, no formatting
245 245 ((( cell.source | wrap | escape_tex )))
246 246 ((* endblock unknowncell *))
247 247
248 248 %==============================================================================
249 249 % Input
250 250 %==============================================================================
251 251 ((* block input *))
252 252
253 253 % Make sure that atleast 4 lines are below the HR
254 254 \needspace{((( min_header_lines )))\baselineskip}
255 255
256 256 ((* if resources.sphinx.outputstyle == 'simple' *))
257 257
258 258 % Add a horizantal break, along with break title.
259 259 \vspace{10pt}
260 260 {\scriptsize Input}\\*
261 261 \rule[10pt]{\linewidth}{0.5pt}
262 262 \vspace{-25pt}
263 263
264 264 % Add contents below.
265 265 ((( cell.input | highlight )))
266 266
267 267 ((* elif resources.sphinx.outputstyle == 'notebook' *))
268 268 \vspace{6pt}
269 269 ((( write_prompt("In", cell.prompt_number, "nbframe-in-prompt") )))
270 270 \vspace{-2.65\baselineskip}
271 271 \begin{ColorVerbatim}
272 272 \vspace{-0.7\baselineskip}
273 273 ((( cell.input | highlight )))
274 274 ((* if cell.input == None or cell.input == '' *))
275 275 \vspace{0.3\baselineskip}
276 276 ((* else *))
277 277 \vspace{-0.2\baselineskip}
278 278 ((* endif *))
279 279 \end{ColorVerbatim}
280 280 ((* endif *))
281 281 ((* endblock input *))
282 282
283 283 %==============================================================================
284 284 % Output_Group
285 285 %
286 286 % Purpose: Make sure that only one header bar only attaches to the output
287 287 % once. By keeping track of when an input group is started
288 288 %==============================================================================
289 289 ((* block output_group *))
290 290 ((* if cell.outputs.__len__() > 0 *))
291 291
292 292 % If the first block is an image, minipage the image. Else
293 293 % request a certain amount of space for the input text.
294 294 ((( iff_figure(cell.outputs[0], "\\begin{minipage}{1.0\\textwidth}", "\\needspace{" ~ min_header_lines ~ "\\baselineskip}") )))
295 295
296 296 ((* if resources.sphinx.outputstyle == 'simple' *))
297 297
298 298 % Add a horizantal break, along with break title.
299 299 \vspace{10pt}
300 300 {\scriptsize Output}\\*
301 301 \rule[10pt]{\linewidth}{0.5pt}
302 302 \vspace{-20pt}
303 303
304 304 % Add the contents of the first block.
305 305 ((( render_output(cell.outputs[0]) )))
306 306
307 307 % Close the minipage.
308 308 ((( iff_figure(cell.outputs[0], "\\end{minipage}", "") )))
309 309
310 310 % Add remainer of the document contents below.
311 311 ((* for output in cell.outputs[1:] *))
312 312 ((( render_output(output, cell.prompt_number) )))
313 313 ((* endfor *))
314 314 ((* elif resources.sphinx.outputstyle == 'notebook' *))
315 315
316 316 % Add document contents.
317 317 ((* for output in cell.outputs *))
318 318 ((( render_output(output, cell.prompt_number) )))
319 319 ((* endfor *))
320 320 ((* endif *))
321 321 ((* endif *))
322 322 ((* endblock *))
323 323
324 324 %==============================================================================
325 325 % Additional formating
326 326 %==============================================================================
327 327 ((* block data_text *))
328 328 ((( custom_verbatim(output.text) )))
329 329 ((* endblock *))
330 330
331 331 ((* block traceback_line *))
332 332 ((( conditionally_center_output(line | indent| rm_ansi) )))
333 333 ((* endblock traceback_line *))
334 334
335 335 %==============================================================================
336 336 % Supported image formats
337 337 %==============================================================================
338 338 ((*- block data_png -*))
339 339 ((( conditionally_center_output(insert_graphics(output.key_png)) )))
340 340 ((*- endblock -*))
341 341
342 342 ((*- block data_svg -*))
343 343 ((( conditionally_center_output(insert_graphics(output.key_svg)) )))
344 344 ((*- endblock -*))
345 345
346 346 ((*- block data_latex *))
347 347 ((* if resources.sphinx.centeroutput *))\begin{center}((* endif -*))((( output.latex | rm_math_space )))((*- if resources.sphinx.centeroutput *))\end{center} ((* endif -*))
348 348 ((*- endblock -*))
349 349
350 350 %==============================================================================
351 351 % Support Macros
352 352 %==============================================================================
353 353
354 354 % Name: write_prompt
355 355 % Purpose: Renders an output/input prompt for notebook style pdfs
356 356 ((* macro write_prompt(prompt, number, color) -*))
357 357 \makebox[0.1\linewidth]{\smaller\hfill\tt\color{((( color )))}((( prompt )))\hspace{4pt}{[}((( number ))){]}:\hspace{4pt}}\\*
358 358 ((*- endmacro *))
359 359
360 360 % Name: render_output
361 361 % Purpose: Renders an output block appropriately.
362 362 ((* macro render_output(output, prompt_number) -*))
363 363 ((*- if output.output_type == 'pyerr' -*))
364 364 ((*- block pyerr scoped *))
365 365 ((( custom_verbatim(super()) )))
366 366 ((* endblock pyerr -*))
367 367 ((*- else -*))
368 368
369 369 ((* if resources.sphinx.outputstyle == 'notebook' *))
370 370 ((*- if output.output_type == 'pyout' -*))
371 371 ((( write_prompt("Out", prompt_number, "nbframe-out-prompt") )))
372 372 \vspace{-2.55\baselineskip}
373 373 ((*- endif -*))
374 374
375 375 \begin{InvisibleVerbatim}
376 376 \vspace{-0.5\baselineskip}
377 377 ((*- endif -*))
378 378
379 379 ((*- block display_data scoped -*))
380 380 ((( super() )))
381 381 ((*- endblock display_data -*))
382 382
383 383 ((* if resources.sphinx.outputstyle == 'notebook' *))
384 384 \end{InvisibleVerbatim}
385 385 ((*- endif -*))
386 386 ((*- endif -*))
387 387 ((*- endmacro *))
388 388
389 389 % Name: iff_figure
390 390 % Purpose: If the output block provided is a figure type, the 'true_content'
391 391 % parameter will be returned. Else, the 'false_content'.
392 392 ((* macro iff_figure(output, true_content, false_content) -*))
393 393 ((*- set is_figure = false -*))
394 394 ((*- for type in output | filter_data_type -*))
395 395 ((*- if type in ['pdf', 'svg', 'png', 'jpeg','html']*))
396 396 ((*- set is_figure = true -*))
397 397 ((*- endif -*))
398 398 ((*- endfor -*))
399 399
400 400 ((* if is_figure -*))
401 401 ((( true_content )))
402 402 ((*- else -*))
403 403 ((( false_content )))
404 404 ((*- endif *))
405 405 ((*- endmacro *))
406 406
407 407 % Name: custom_verbatim
408 408 % Purpose: This macro creates a verbatim style block that fits the existing
409 409 % sphinx style more readily than standard verbatim blocks.
410 410 ((* macro custom_verbatim(text) -*))
411 411 \begin{alltt}
412 412 ((*- if resources.sphinx.centeroutput *))\begin{center} ((* endif -*))
413 413 ((( text | wrap(wrap_size) )))
414 414 ((*- if resources.sphinx.centeroutput *))\end{center}((* endif -*))
415 415 \end{alltt}
416 416 ((*- endmacro *))
417 417
418 418 % Name: conditionally_center_output
419 419 % Purpose: This macro centers the output if the output centering is enabled.
420 420 ((* macro conditionally_center_output(text) -*))
421 421 ((* if resources.sphinx.centeroutput *)){\centering ((* endif *))((( text )))((* if resources.sphinx.centeroutput *))}((* endif *))
422 422 ((*- endmacro *))
423 423
424 424 % Name: insert_graphics
425 425 % Purpose: This macro will insert an image in the latex document given a path.
426 426 ((* macro insert_graphics(path) -*))
427 427 \begin{center}
428 428 \includegraphics[max size={\textwidth}{\textheight}]{(((path)))}
429 429 \par
430 430 \end{center}
431 431 ((*- endmacro *))
432 432
433 433 % Name: escape_underscores
434 434 % Purpose: Underscores cause a problem in latex. It's important that we
435 435 % escape any underscores that appear.
436 436 ((* macro escape_underscores(text) -*))
437 437 ((*- set text = text|replace("_","\\_") -*))
438 438 ((( text )))
439 439 ((*- endmacro *)) No newline at end of file
@@ -1,25 +1,25 b''
1 1 ((============================================================================
2 2 NBConvert Sphinx-Latex HowTo Template
3 3
4 4 Purpose: Allow export of PDF friendly Latex inspired by Sphinx HowTo
5 5 document style. Most of the is derived directly from Sphinx source.
6 6
7 7 Inheritance: null>display_priority>latex_base->latex_sphinx_base
8 8
9 9 ==========================================================================))
10 10
11 ((*- extends 'latex_sphinx_base.tplx' -*))
11 ((*- extends 'sphinx_base.tplx' -*))
12 12
13 13 ((* set parentdocumentclass = 'article' *))
14 14 ((* set documentclass = 'howto' *))
15 15
16 16 ((* block h1 -*))part((* endblock h1 -*))
17 17 ((* block h2 -*))section((* endblock h2 -*))
18 18 ((* block h3 -*))subsection((* endblock h3 -*))
19 19 ((* block h4 -*))subsubsection((* endblock h4 -*))
20 20 ((* block h5 -*))paragraph((* endblock h5 -*))
21 21 ((* block h6 -*))subparagraph((* endblock h6 -*))
22 22
23 23 % Diasble table of contents for howto
24 24 ((* block toc *))
25 25 ((* endblock toc *))
@@ -1,21 +1,21 b''
1 1 ((============================================================================
2 2 NBConvert Sphinx-Latex Manual Template
3 3
4 4 Purpose: Allow export of PDF friendly Latex inspired by Sphinx Manual
5 5 document style. Most of the is derived directly from Sphinx source.
6 6
7 7 Inheritance: null>display_priority>latex_base->latex_sphinx_base
8 8
9 9 ==========================================================================))
10 10
11 ((*- extends 'latex_sphinx_base.tplx' -*))
11 ((*- extends 'sphinx_base.tplx' -*))
12 12
13 13 ((* set parentdocumentclass = 'report' *))
14 14 ((* set documentclass = 'manual' *))
15 15
16 16 ((* block h1 -*))part((* endblock h1 -*))
17 17 ((* block h2 -*))chapter((* endblock h2 -*))
18 18 ((* block h3 -*))section((* endblock h3 -*))
19 19 ((* block h4 -*))subsection((* endblock h4 -*))
20 20 ((* block h5 -*))subsubsection((* endblock h5 -*))
21 21 ((* block h6 -*))paragraph((* endblock h6 -*))
@@ -1,91 +1,91 b''
1 1 {#
2 2
3 3 DO NOT USE THIS AS A BASE WORK,
4 4 IF YOU ARE COPY AND PASTING THIS FILE
5 5 YOU ARE PROBABLY DOING THINGS WRONG.
6 6
7 7 Null template, Does nothing except defining a basic structure
8 8 To layout the different blocks of a notebook.
9 9
10 10 Subtemplates can override blocks to define their custom representation.
11 11
12 12 If one of the block you do overwrite is not a leave block, consider
13 13 calling super.
14 14
15 15 {%- block nonLeaveBlock -%}
16 16 #add stuff at beginning
17 17 {{ super() }}
18 18 #add stuff at end
19 19 {%- endblock nonLeaveBlock -%}
20 20
21 21 consider calling super even if it is a leave block, we might insert more blocks later.
22 22
23 23 #}
24 24 {%- block header -%}
25 25 {%- endblock header -%}
26 26 {%- block body -%}
27 27 {%- for worksheet in nb.worksheets -%}
28 28 {%- for cell in worksheet.cells -%}
29 29 {%- block any_cell scoped -%}
30 {%- if cell.type in ['code'] -%}
30 {%- if cell.cell_type in ['code'] -%}
31 31 {%- block codecell scoped -%}
32 32 {%- block input_group -%}
33 33 {%- block in_prompt -%}{%- endblock in_prompt -%}
34 34 {%- block input -%}{%- endblock input -%}
35 35 {%- endblock input_group -%}
36 36 {%- if cell.outputs -%}
37 37 {%- block output_group -%}
38 38 {%- block output_prompt -%}{%- endblock output_prompt -%}
39 39 {%- block outputs scoped -%}
40 40 {%- for output in cell.outputs -%}
41 41 {%- block output scoped -%}
42 42 {%- if output.output_type in ['pyout'] -%}
43 43 {%- block pyout scoped -%}{%- endblock pyout -%}
44 44 {%- elif output.output_type in ['stream'] -%}
45 45 {%- block stream scoped -%}
46 46 {%- if output.stream in ['stdout'] -%}
47 47 {%- block stream_stdout scoped -%}
48 48 {%- endblock stream_stdout -%}
49 49 {%- elif output.stream in ['stderr'] -%}
50 50 {%- block stream_stderr scoped -%}
51 51 {%- endblock stream_stderr -%}
52 52 {%- endif -%}
53 53 {%- endblock stream -%}
54 54 {%- elif output.output_type in ['display_data'] -%}
55 55 {%- block display_data scoped -%}
56 56 {%- block data_priority scoped -%}
57 57 {%- endblock data_priority -%}
58 58 {%- endblock display_data -%}
59 59 {%- elif output.output_type in ['pyerr'] -%}
60 60 {%- block pyerr scoped -%}
61 61 {%- for line in output.traceback -%}
62 62 {%- block traceback_line scoped -%}{%- endblock traceback_line -%}
63 63 {%- endfor -%}
64 64 {%- endblock pyerr -%}
65 65 {%- endif -%}
66 66 {%- endblock output -%}
67 67 {%- endfor -%}
68 68 {%- endblock outputs -%}
69 69 {%- endblock output_group -%}
70 70 {%- endif -%}
71 71 {%- endblock codecell -%}
72 {%- elif cell.type in ['markdown'] -%}
72 {%- elif cell.cell_type in ['markdown'] -%}
73 73 {%- block markdowncell scoped-%}
74 74 {%- endblock markdowncell -%}
75 {%- elif cell.type in ['heading'] -%}
75 {%- elif cell.cell_type in ['heading'] -%}
76 76 {%- block headingcell scoped-%}
77 77 {%- endblock headingcell -%}
78 {%- elif cell.type in ['raw'] -%}
78 {%- elif cell.cell_type in ['raw'] -%}
79 79 {%- block rawcell scoped-%}
80 80 {%- endblock rawcell -%}
81 81 {%- else -%}
82 82 {%- block unknowncell scoped-%}
83 83 {%- endblock unknowncell -%}
84 84 {%- endif -%}
85 85 {%- endblock any_cell -%}
86 86 {%- endfor -%}
87 87 {%- endfor -%}
88 88 {%- endblock body -%}
89 89
90 90 {%- block footer -%}
91 91 {%- endblock footer -%}
@@ -1,19 +1,19 b''
1 1 from .base import ConfigurableTransformer
2 2 from IPython.utils.traitlets import (Bool)
3 3
4 4 class ActivatableTransformer(ConfigurableTransformer):
5 5 """A simple ConfigurableTransformers that have an enabled flag
6 6
7 7 Inherit from that if you just want to have a transformer which is
8 8 no-op by default but can be activated in profiles with
9 9
10 10 c.YourTransformerName.enabled = True
11 11 """
12 12
13 enabled = Bool(False, config=True)
13 enabled = Bool(True, config=True)
14 14
15 15 def __call__(self, nb, other):
16 16 if not self.enabled :
17 17 return nb, other
18 18 else :
19 19 return super(ActivatableTransformer, self).__call__(nb, other)
General Comments 0
You need to be logged in to leave comments. Login now