##// END OF EJS Templates
Merge pull request #3784 from jdfreder/export_flavors...
Jonathan Frederic -
r11769:a9c0f491 merge
parent child Browse files
Show More
@@ -0,0 +1,2 b''
1 from .base import PostProcessorBase
2 from .pdf import PDFPostProcessor
@@ -0,0 +1,51 b''
1 """
2 Contains writer for writing nbconvert output to PDF.
3 """
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
6 #
7 #Distributed under the terms of the Modified BSD License.
8 #
9 #The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 import subprocess
17 import os
18
19 from IPython.utils.traitlets import Integer, Unicode, Bool
20
21 from .base import PostProcessorBase
22
23 #-----------------------------------------------------------------------------
24 # Classes
25 #-----------------------------------------------------------------------------
26 class PDFPostProcessor(PostProcessorBase):
27 """Writer designed to write to PDF files"""
28
29 iteration_count = Integer(3, config=True, help="""
30 How many times pdflatex will be called.
31 """)
32
33 compiler = Unicode(u'pdflatex {0}', config=True, help="""
34 Shell command used to compile PDF.""")
35
36 verbose = Bool(False, config=True, help="""
37 Whether or not to display the output of the compile call.
38 """)
39
40 def call(self, input):
41 """
42 Consume and write Jinja output a PDF.
43 See files.py for more...
44 """
45 command = self.compiler.format(input)
46 for index in range(self.iteration_count):
47 if self.verbose:
48 subprocess.Popen(command, shell=True)
49 else:
50 with open(os.devnull, 'wb') as null:
51 subprocess.Popen(command, shell=True, stdout=null)
@@ -3,4 +3,5 b''
3 from .exporters import *
3 from .exporters import *
4 import filters
4 import filters
5 import transformers
5 import transformers
6 import post_processors
6 import writers
7 import writers
@@ -1,11 +1,8 b''
1 from .basichtml import BasicHTMLExporter
2 from .export import *
1 from .export import *
2 from .html import HTMLExporter
3 from .slides import SlidesExporter
3 from .exporter import Exporter
4 from .exporter import Exporter
4 from .fullhtml import FullHTMLExporter
5 from .reveal import RevealExporter
6 from .latex import LatexExporter
5 from .latex import LatexExporter
7 from .markdown import MarkdownExporter
6 from .markdown import MarkdownExporter
8 from .python import PythonExporter
7 from .python import PythonExporter
9 from .rst import RSTExporter
8 from .rst import RSTExporter
10 from .sphinx_howto import SphinxHowtoExporter
11 from .sphinx_manual import SphinxManualExporter
@@ -19,15 +19,12 b' from IPython.nbformat.v3.nbbase import NotebookNode'
19 from IPython.config import Config
19 from IPython.config import Config
20
20
21 from .exporter import Exporter
21 from .exporter import Exporter
22 from .basichtml import BasicHTMLExporter
22 from .html import HTMLExporter
23 from .fullhtml import FullHTMLExporter
23 from .slides import SlidesExporter
24 from .latex import LatexExporter
24 from .latex import LatexExporter
25 from .markdown import MarkdownExporter
25 from .markdown import MarkdownExporter
26 from .python import PythonExporter
26 from .python import PythonExporter
27 from .reveal import RevealExporter
28 from .rst import RSTExporter
27 from .rst import RSTExporter
29 from .sphinx_howto import SphinxHowtoExporter
30 from .sphinx_manual import SphinxManualExporter
31
28
32 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
33 # Classes
30 # Classes
@@ -54,7 +51,10 b' def DocDecorator(f):'
54 exporter_instance : Exporter
51 exporter_instance : Exporter
55 Instance of the Exporter class used to export the document. Useful
52 Instance of the Exporter class used to export the document. Useful
56 to caller because it provides a 'file_extension' property which
53 to caller because it provides a 'file_extension' property which
57 specifies what extension the output should be saved as."""
54 specifies what extension the output should be saved as.
55
56 WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT
57 """
58
58
59 @wraps(f)
59 @wraps(f)
60 def decorator(*args, **kwargs):
60 def decorator(*args, **kwargs):
@@ -69,14 +69,12 b' def DocDecorator(f):'
69
69
70 __all__ = [
70 __all__ = [
71 'export',
71 'export',
72 'export_sphinx_manual',
72 'export_html',
73 'export_sphinx_howto',
73 'export_custom',
74 'export_basic_html',
74 'export_slides',
75 'export_full_html',
76 'export_latex',
75 'export_latex',
77 'export_markdown',
76 'export_markdown',
78 'export_python',
77 'export_python',
79 'export_reveal',
80 'export_rst',
78 'export_rst',
81 'export_by_name',
79 'export_by_name',
82 'get_export_names',
80 'get_export_names',
@@ -126,35 +124,27 b' def export(exporter, nb, **kw):'
126
124
127
125
128 @DocDecorator
126 @DocDecorator
129 def export_sphinx_manual(nb, **kw):
127 def export_custom(nb, **kw):
130 """
131 Export a notebook object to Sphinx Manual LaTeX
132 """
133 return export(SphinxManualExporter, nb, **kw)
134
135
136 @DocDecorator
137 def export_sphinx_howto(nb, **kw):
138 """
128 """
139 Export a notebook object to Sphinx HowTo LaTeX
129 Export a notebook object to a custom format
140 """
130 """
141 return export(SphinxHowtoExporter, nb, **kw)
131 return export(Exporter, nb, **kw)
142
132
143
133
144 @DocDecorator
134 @DocDecorator
145 def export_basic_html(nb, **kw):
135 def export_html(nb, **kw):
146 """
136 """
147 Export a notebook object to Basic HTML
137 Export a notebook object to HTML
148 """
138 """
149 return export(BasicHTMLExporter, nb, **kw)
139 return export(HTMLExporter, nb, **kw)
150
140
151
141
152 @DocDecorator
142 @DocDecorator
153 def export_full_html(nb, **kw):
143 def export_slides(nb, **kw):
154 """
144 """
155 Export a notebook object to Full HTML
145 Export a notebook object to Slides
156 """
146 """
157 return export(FullHTMLExporter, nb, **kw)
147 return export(SlidesExporter, nb, **kw)
158
148
159
149
160 @DocDecorator
150 @DocDecorator
@@ -182,14 +172,6 b' def export_python(nb, **kw):'
182
172
183
173
184 @DocDecorator
174 @DocDecorator
185 def export_reveal(nb, **kw):
186 """
187 Export a notebook object to a Reveal.js presentation
188 """
189 return export(RevealExporter, nb, **kw)
190
191
192 @DocDecorator
193 def export_rst(nb, **kw):
175 def export_rst(nb, **kw):
194 """
176 """
195 Export a notebook object to reStructuredText
177 Export a notebook object to reStructuredText
@@ -217,7 +199,10 b' def export_by_name(format_name, nb, **kw):'
217
199
218
200
219 def get_export_names():
201 def get_export_names():
220 "Return a list of the currently supported export targets"
202 """Return a list of the currently supported export targets
203
204 WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT"""
205
221 # grab everything after 'export_'
206 # grab everything after 'export_'
222 l = [x[len('export_'):] for x in __all__ if x.startswith('export_')]
207 l = [x[len('export_'):] for x in __all__ if x.startswith('export_')]
223
208
@@ -25,7 +25,7 b' import collections'
25 import datetime
25 import datetime
26
26
27 # other libs/dependencies
27 # other libs/dependencies
28 from jinja2 import Environment, FileSystemLoader, ChoiceLoader
28 from jinja2 import Environment, FileSystemLoader, ChoiceLoader, TemplateNotFound
29
29
30 # IPython imports
30 # IPython imports
31 from IPython.config.configurable import Configurable
31 from IPython.config.configurable import Configurable
@@ -86,7 +86,7 b' class Exporter(Configurable):'
86 transformers provided by default suffice, there is no need to inherit from
86 transformers provided by default suffice, there is no need to inherit from
87 this class. Instead, override the template_file and file_extension
87 this class. Instead, override the template_file and file_extension
88 traits via a config file.
88 traits via a config file.
89
89
90 {filters}
90 {filters}
91 """
91 """
92
92
@@ -94,9 +94,15 b' class Exporter(Configurable):'
94 __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
94 __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
95
95
96
96
97 template_file = Unicode(
97 template_file = Unicode(u'default',
98 '', config=True,
98 config=True,
99 help="Name of the template file to use")
99 help="Name of the template file to use")
100 def _template_file_changed(self, name, old, new):
101 if new=='default':
102 self.template_file = self.default_template
103 else:
104 self.template_file = new
105 default_template = Unicode(u'')
100
106
101 file_extension = Unicode(
107 file_extension = Unicode(
102 'txt', config=True,
108 'txt', config=True,
@@ -155,6 +161,8 b' class Exporter(Configurable):'
155 extra_loaders : list[of Jinja Loaders]
161 extra_loaders : list[of Jinja Loaders]
156 ordered list of Jinja loder to find templates. Will be tried in order
162 ordered list of Jinja loder to find templates. Will be tried in order
157 before the default FileSysteme ones.
163 before the default FileSysteme ones.
164 template : str (optional, kw arg)
165 Template to use when exporting.
158 """
166 """
159
167
160 #Call the base class constructor
168 #Call the base class constructor
@@ -165,6 +173,7 b' class Exporter(Configurable):'
165 super(Exporter, self).__init__(config=c, **kw)
173 super(Exporter, self).__init__(config=c, **kw)
166
174
167 #Init
175 #Init
176 self._init_template(**kw)
168 self._init_environment(extra_loaders=extra_loaders)
177 self._init_environment(extra_loaders=extra_loaders)
169 self._init_transformers()
178 self._init_transformers()
170 self._init_filters()
179 self._init_filters()
@@ -189,12 +198,29 b' class Exporter(Configurable):'
189 nb_copy = copy.deepcopy(nb)
198 nb_copy = copy.deepcopy(nb)
190 resources = self._init_resources(resources)
199 resources = self._init_resources(resources)
191
200
192 #Preprocess
201 # Preprocess
193 nb_copy, resources = self._transform(nb_copy, resources)
202 nb_copy, resources = self._transform(nb_copy, resources)
194
203
195 #Convert
204 # Try different template names during conversion. First try to load the
196 self.template = self.environment.get_template(self.template_file + self.template_extension)
205 # template by name with extension added, then try loading the template
197 output = self.template.render(nb=nb_copy, resources=resources)
206 # as if the name is explicitly specified, then try the name as a
207 # 'flavor', and lastly just try to load the template by module name.
208 module_name = self.__module__.split('.')[-1]
209 try_names = [self.template_file + self.template_extension,
210 self.template_file,
211 module_name + '_' + self.template_file + self.template_extension,
212 module_name + self.template_extension]
213 for try_name in try_names:
214 try:
215 self.template = self.environment.get_template(try_name)
216 break
217 except TemplateNotFound:
218 pass
219
220 if hasattr(self, 'template'):
221 output = self.template.render(nb=nb_copy, resources=resources)
222 else:
223 raise IOError('template file "%s" could not be found' % self.template_file)
198 return output, resources
224 return output, resources
199
225
200
226
@@ -329,6 +355,16 b' class Exporter(Configurable):'
329 raise TypeError('filter')
355 raise TypeError('filter')
330
356
331
357
358 def _init_template(self, **kw):
359 """
360 Make sure a template name is specified. If one isn't specified, try to
361 build one from the information we know.
362 """
363 self._template_file_changed('template_file', self.template_file, self.template_file)
364 if 'template' in kw:
365 self.template_file = kw['template']
366
367
332 def _init_environment(self, extra_loaders=None):
368 def _init_environment(self, extra_loaders=None):
333 """
369 """
334 Create the Jinja templating environment.
370 Create the Jinja templating environment.
@@ -17,6 +17,7 b' Exporter that exports Basic HTML.'
17 from IPython.utils.traitlets import Unicode, List
17 from IPython.utils.traitlets import Unicode, List
18
18
19 from IPython.nbconvert import transformers
19 from IPython.nbconvert import transformers
20 from IPython.config import Config
20
21
21 from .exporter import Exporter
22 from .exporter import Exporter
22
23
@@ -24,7 +25,7 b' from .exporter import Exporter'
24 # Classes
25 # Classes
25 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
26
27
27 class BasicHTMLExporter(Exporter):
28 class HTMLExporter(Exporter):
28 """
29 """
29 Exports a basic HTML document. This exporter assists with the export of
30 Exports a basic HTML document. This exporter assists with the export of
30 HTML. Inherit from it if you are writing your own HTML template and need
31 HTML. Inherit from it if you are writing your own HTML template and need
@@ -37,6 +38,15 b' class BasicHTMLExporter(Exporter):'
37 help="Extension of the file that should be written to disk"
38 help="Extension of the file that should be written to disk"
38 )
39 )
39
40
40 template_file = Unicode(
41 default_template = Unicode('full', config=True, help="""Flavor of the data
41 'basichtml', config=True,
42 format to use. I.E. 'full' or 'basic'""")
42 help="Name of the template file to use")
43
44 @property
45 def default_config(self):
46 c = Config({
47 'CSSHTMLHeaderTransformer':{
48 'enabled':True
49 }
50 })
51 c.merge(super(HTMLExporter,self).default_config)
52 return c
@@ -44,9 +44,8 b' class LatexExporter(Exporter):'
44 'tex', config=True,
44 'tex', config=True,
45 help="Extension of the file that should be written to disk")
45 help="Extension of the file that should be written to disk")
46
46
47 template_file = Unicode(
47 default_template = Unicode('article', config=True, help="""Template of the
48 'base', config=True,
48 data format to use. I.E. 'full' or 'basic'""")
49 help="Name of the template file to use")
50
49
51 #Latex constants
50 #Latex constants
52 default_template_path = Unicode(
51 default_template_path = Unicode(
@@ -68,6 +67,7 b' class LatexExporter(Exporter):'
68 #Extension that the template files use.
67 #Extension that the template files use.
69 template_extension = Unicode(".tplx", config=True)
68 template_extension = Unicode(".tplx", config=True)
70
69
70
71 @property
71 @property
72 def default_config(self):
72 def default_config(self):
73 c = Config({
73 c = Config({
@@ -82,6 +82,9 b' class LatexExporter(Exporter):'
82 },
82 },
83 'LatexTransformer': {
83 'LatexTransformer': {
84 'enabled':True
84 'enabled':True
85 },
86 'SphinxTransformer': {
87 'enabled':True
85 }
88 }
86 })
89 })
87 c.merge(super(LatexExporter,self).default_config)
90 c.merge(super(LatexExporter,self).default_config)
@@ -29,7 +29,3 b' class MarkdownExporter(Exporter):'
29 file_extension = Unicode(
29 file_extension = Unicode(
30 'md', config=True,
30 'md', config=True,
31 help="Extension of the file that should be written to disk")
31 help="Extension of the file that should be written to disk")
32
33 template_file = Unicode(
34 'markdown', config=True,
35 help="Name of the template file to use")
@@ -29,7 +29,3 b' class PythonExporter(Exporter):'
29 file_extension = Unicode(
29 file_extension = Unicode(
30 'py', config=True,
30 'py', config=True,
31 help="Extension of the file that should be written to disk")
31 help="Extension of the file that should be written to disk")
32
33 template_file = Unicode(
34 'python', config=True,
35 help="Name of the template file to use")
@@ -31,10 +31,6 b' class RSTExporter(Exporter):'
31 'rst', config=True,
31 'rst', config=True,
32 help="Extension of the file that should be written to disk")
32 help="Extension of the file that should be written to disk")
33
33
34 template_file = Unicode(
35 'rst', config=True,
36 help="Name of the template file to use")
37
38 @property
34 @property
39 def default_config(self):
35 def default_config(self):
40 c = Config({'ExtractOutputTransformer':{'enabled':True}})
36 c = Config({'ExtractOutputTransformer':{'enabled':True}})
@@ -1,6 +1,7 b''
1 """
1 """
2 Reveal slide show exporter.
2 Contains slide show exporter
3 """
3 """
4
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
6 #
7 #
@@ -13,29 +14,29 b' Reveal slide show exporter.'
13 # Imports
14 # Imports
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15
16
16 from IPython.utils.traitlets import Unicode, List
17 from IPython.utils.traitlets import Unicode
17 from IPython.config import Config
18
18
19 from .basichtml import BasicHTMLExporter
20 from IPython.nbconvert import transformers
19 from IPython.nbconvert import transformers
20 from IPython.config import Config
21
22 from .exporter import Exporter
21
23
22 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
23 # Classes
25 # Classes
24 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
25
27
26 class RevealExporter(BasicHTMLExporter):
28 class SlidesExporter(Exporter):
27 """
29 """
28 Exports a Reveal slide show (.HTML) which may be rendered in a web browser.
30 Exports slides
29 """
31 """
30
32
31 file_extension = Unicode(
33 file_extension = Unicode(
32 'reveal.html', config=True,
34 'slides.html', config=True,
33 help="Extension of the file that should be written to disk")
35 help="Extension of the file that should be written to disk"
34
36 )
35 template_file = Unicode(
36 'reveal', config=True,
37 help="Name of the template file to use")
38
37
38 default_template = Unicode('reveal', config=True, help="""Template of the
39 data format to use. I.E. 'reveal'""")
39
40
40 @property
41 @property
41 def default_config(self):
42 def default_config(self):
@@ -47,5 +48,5 b' class RevealExporter(BasicHTMLExporter):'
47 'enabled':True,
48 'enabled':True,
48 },
49 },
49 })
50 })
50 c.merge(super(RevealExporter,self).default_config)
51 c.merge(super(SlidesExporter,self).default_config)
51 return c
52 return c
@@ -1,5 +1,5 b''
1 """
1 """
2 Module with tests for fullhtml.py
2 Module with tests for html.py
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
@@ -15,26 +15,45 b' Module with tests for fullhtml.py'
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from .base import ExportersTestsBase
17 from .base import ExportersTestsBase
18 from ..fullhtml import FullHTMLExporter
18 from ..html import HTMLExporter
19 from IPython.testing.decorators import onlyif_cmds_exist
19 from IPython.testing.decorators import onlyif_cmds_exist
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Class
22 # Class
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class TestFullHTMLExporter(ExportersTestsBase):
25 class TestHTMLExporter(ExportersTestsBase):
26 """Contains test functions for fullhtml.py"""
26 """Contains test functions for html.py"""
27
27
28 def test_constructor(self):
28 def test_constructor(self):
29 """
29 """
30 Can a FullHTMLExporter be constructed?
30 Can a HTMLExporter be constructed?
31 """
31 """
32 FullHTMLExporter()
32 HTMLExporter()
33
33
34
34 @onlyif_cmds_exist('pandoc')
35 @onlyif_cmds_exist('pandoc')
35 def test_export(self):
36 def test_export(self):
36 """
37 """
37 Can a FullHTMLExporter export something?
38 Can a HTMLExporter export something?
39 """
40 (output, resources) = HTMLExporter().from_filename(self._get_notebook())
41 assert len(output) > 0
42
43
44 @onlyif_cmds_exist('pandoc')
45 def test_export_basic(self):
46 """
47 Can a HTMLExporter export using the 'basic' template?
48 """
49 (output, resources) = HTMLExporter(template='basic').from_filename(self._get_notebook())
50 assert len(output) > 0
51
52
53 @onlyif_cmds_exist('pandoc')
54 def test_export_full(self):
55 """
56 Can a HTMLExporter export using the 'full' template?
38 """
57 """
39 (output, resources) = FullHTMLExporter().from_filename(self._get_notebook())
58 (output, resources) = HTMLExporter(template='full').from_filename(self._get_notebook())
40 assert len(output) > 0
59 assert len(output) > 0
@@ -39,3 +39,30 b' class TestLatexExporter(ExportersTestsBase):'
39 """
39 """
40 (output, resources) = LatexExporter().from_filename(self._get_notebook())
40 (output, resources) = LatexExporter().from_filename(self._get_notebook())
41 assert len(output) > 0
41 assert len(output) > 0
42
43
44 @onlyif_cmds_exist('pandoc')
45 def test_export_book(self):
46 """
47 Can a LatexExporter export using 'book' template?
48 """
49 (output, resources) = LatexExporter(template='book').from_filename(self._get_notebook())
50 assert len(output) > 0
51
52
53 @onlyif_cmds_exist('pandoc')
54 def test_export_basic(self):
55 """
56 Can a LatexExporter export using 'basic' template?
57 """
58 (output, resources) = LatexExporter(template='basic').from_filename(self._get_notebook())
59 assert len(output) > 0
60
61
62 @onlyif_cmds_exist('pandoc')
63 def test_export_article(self):
64 """
65 Can a LatexExporter export using 'article' template?
66 """
67 (output, resources) = LatexExporter(template='article').from_filename(self._get_notebook())
68 assert len(output) > 0 No newline at end of file
@@ -1,5 +1,5 b''
1 """
1 """
2 Module with tests for basichtml.py
2 Module with tests for slides.py
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
@@ -15,26 +15,33 b' Module with tests for basichtml.py'
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from .base import ExportersTestsBase
17 from .base import ExportersTestsBase
18 from ..basichtml import BasicHTMLExporter
18 from ..slides import SlidesExporter
19 from IPython.testing.decorators import onlyif_cmds_exist
20
19
21 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
22 # Class
21 # Class
23 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
24
23
25 class TestBasicHTMLExporter(ExportersTestsBase):
24 class TestSlidesExporter(ExportersTestsBase):
26 """Contains test functions for basichtml.py"""
25 """Contains test functions for slides.py"""
27
26
28 def test_constructor(self):
27 def test_constructor(self):
29 """
28 """
30 Can a BasicHTMLExporter be constructed?
29 Can a SlidesExporter be constructed?
31 """
30 """
32 BasicHTMLExporter()
31 SlidesExporter()
32
33
33
34 @onlyif_cmds_exist('pandoc')
35 def test_export(self):
34 def test_export(self):
36 """
35 """
37 Can a BasicHTMLExporter export something?
36 Can a SlidesExporter export something?
37 """
38 (output, resources) = SlidesExporter().from_filename(self._get_notebook())
39 assert len(output) > 0
40
41
42 def test_export_reveal(self):
43 """
44 Can a SlidesExporter export using the 'reveal' template?
38 """
45 """
39 (output, resources) = BasicHTMLExporter().from_filename(self._get_notebook())
46 (output, resources) = SlidesExporter(template='reveal').from_filename(self._get_notebook())
40 assert len(output) > 0
47 assert len(output) > 0
@@ -30,7 +30,7 b' from IPython.utils.traitlets import ('
30 from IPython.utils.importstring import import_item
30 from IPython.utils.importstring import import_item
31
31
32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
33 from IPython.nbconvert import exporters, transformers, writers
33 from IPython.nbconvert import exporters, transformers, writers, post_processors
34 from .utils.base import NbConvertBase
34 from .utils.base import NbConvertBase
35 from .utils.exceptions import ConversionException
35 from .utils.exceptions import ConversionException
36
36
@@ -38,12 +38,27 b' from .utils.exceptions import ConversionException'
38 #Classes and functions
38 #Classes and functions
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 class DottedOrNone(DottedObjectName):
42 """
43 A string holding a valid dotted object name in Python, such as A.b3._c
44 Also allows for None type."""
45
46 default_value = u''
47
48 def validate(self, obj, value):
49 if value is not None and len(value) > 0:
50 return super(DottedOrNone, self).validate(obj, value)
51 else:
52 return value
53
41 nbconvert_aliases = {}
54 nbconvert_aliases = {}
42 nbconvert_aliases.update(base_aliases)
55 nbconvert_aliases.update(base_aliases)
43 nbconvert_aliases.update({
56 nbconvert_aliases.update({
44 'format' : 'NbConvertApp.export_format',
57 'to' : 'NbConvertApp.export_format',
58 'template' : 'Exporter.template_file',
45 'notebooks' : 'NbConvertApp.notebooks',
59 'notebooks' : 'NbConvertApp.notebooks',
46 'writer' : 'NbConvertApp.writer_class',
60 'writer' : 'NbConvertApp.writer_class',
61 'post': 'NbConvertApp.post_processor_class'
47 })
62 })
48
63
49 nbconvert_flags = {}
64 nbconvert_flags = {}
@@ -74,7 +89,9 b' class NbConvertApp(BaseIPythonApplication):'
74
89
75 description = Unicode(
90 description = Unicode(
76 u"""This application is used to convert notebook files (*.ipynb)
91 u"""This application is used to convert notebook files (*.ipynb)
77 to various other formats.""")
92 to various other formats.
93
94 WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.""")
78
95
79 examples = Unicode(u"""
96 examples = Unicode(u"""
80 The simplest way to use nbconvert is
97 The simplest way to use nbconvert is
@@ -83,14 +100,24 b' class NbConvertApp(BaseIPythonApplication):'
83
100
84 which will convert mynotebook.ipynb to the default format (probably HTML).
101 which will convert mynotebook.ipynb to the default format (probably HTML).
85
102
86 You can specify the export format with `--format`.
103 You can specify the export format with `--to`.
87 Options include {0}
104 Options include {0}
88
105
89 > ipython nbconvert --format latex mynotebook.ipnynb
106 > ipython nbconvert --to latex mynotebook.ipnynb
107
108 Both HTML and LaTeX support multiple output templates. LaTeX includes
109 'basic', 'book', and 'article'. HTML includes 'basic' and 'full'. You
110 can specify the flavor of the format used.
111
112 > ipython nbconvert --to html --template basic mynotebook.ipynb
90
113
91 You can also pipe the output to stdout, rather than a file
114 You can also pipe the output to stdout, rather than a file
92
115
93 > ipython nbconvert mynotebook.ipynb --stdout
116 > ipython nbconvert mynotebook.ipynb --stdout
117
118 A post-processor can be used to compile a PDF
119
120 > ipython nbconvert mynotebook.ipynb --to latex --post PDF
94
121
95 Multiple notebooks can be given at the command line in a couple of
122 Multiple notebooks can be given at the command line in a couple of
96 different ways:
123 different ways:
@@ -104,6 +131,7 b' class NbConvertApp(BaseIPythonApplication):'
104
131
105 > ipython nbconvert --config mycfg.py
132 > ipython nbconvert --config mycfg.py
106 """.format(get_export_names()))
133 """.format(get_export_names()))
134
107 # Writer specific variables
135 # Writer specific variables
108 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
136 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
109 help="""Instance of the writer class used to write the
137 help="""Instance of the writer class used to write the
@@ -121,10 +149,27 b' class NbConvertApp(BaseIPythonApplication):'
121 new = self.writer_aliases[new]
149 new = self.writer_aliases[new]
122 self.writer_factory = import_item(new)
150 self.writer_factory = import_item(new)
123
151
152 # Post-processor specific variables
153 post_processor = Instance('IPython.nbconvert.post_processors.base.PostProcessorBase',
154 help="""Instance of the PostProcessor class used to write the
155 results of the conversion.""")
156
157 post_processor_class = DottedOrNone(config=True,
158 help="""PostProcessor class used to write the
159 results of the conversion""")
160 post_processor_aliases = {'PDF': 'IPython.nbconvert.post_processors.pdf.PDFPostProcessor'}
161 post_processor_factory = Type()
162
163 def _post_processor_class_changed(self, name, old, new):
164 if new in self.post_processor_aliases:
165 new = self.post_processor_aliases[new]
166 if new:
167 self.post_processor_factory = import_item(new)
168
124
169
125 # Other configurable variables
170 # Other configurable variables
126 export_format = CaselessStrEnum(get_export_names(),
171 export_format = CaselessStrEnum(get_export_names(),
127 default_value="full_html",
172 default_value="html",
128 config=True,
173 config=True,
129 help="""The export format to be used."""
174 help="""The export format to be used."""
130 )
175 )
@@ -140,6 +185,8 b' class NbConvertApp(BaseIPythonApplication):'
140 self.init_syspath()
185 self.init_syspath()
141 self.init_notebooks()
186 self.init_notebooks()
142 self.init_writer()
187 self.init_writer()
188 self.init_post_processor()
189
143
190
144
191
145 def init_syspath(self):
192 def init_syspath(self):
@@ -184,6 +231,15 b' class NbConvertApp(BaseIPythonApplication):'
184 self._writer_class_changed(None, self.writer_class, self.writer_class)
231 self._writer_class_changed(None, self.writer_class, self.writer_class)
185 self.writer = self.writer_factory(parent=self)
232 self.writer = self.writer_factory(parent=self)
186
233
234 def init_post_processor(self):
235 """
236 Initialize the post_processor (which is stateless)
237 """
238 self._post_processor_class_changed(None, self.post_processor_class,
239 self.post_processor_class)
240 if self.post_processor_factory:
241 self.post_processor = self.post_processor_factory(parent=self)
242
187 def start(self):
243 def start(self):
188 """
244 """
189 Ran after initialization completed
245 Ran after initialization completed
@@ -225,7 +281,11 b' class NbConvertApp(BaseIPythonApplication):'
225 file=sys.stderr)
281 file=sys.stderr)
226 self.exit(1)
282 self.exit(1)
227 else:
283 else:
228 self.writer.write(output, resources, notebook_name=notebook_name)
284 write_resultes = self.writer.write(output, resources, notebook_name=notebook_name)
285
286 #Post-process if post processor has been defined.
287 if hasattr(self, 'post_processor') and self.post_processor:
288 self.post_processor(write_resultes)
229 conversion_success += 1
289 conversion_success += 1
230
290
231 # If nothing was converted successfully, help the user.
291 # If nothing was converted successfully, help the user.
@@ -1,34 +1,35 b''
1 """
1 """
2 Exporter for exporting notebooks to Sphinx 'Manual' style latex. Latex
2 Basic post processor
3 formatted for use with PDFLatex.
4 """
3 """
5 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, the IPython Development Team.
7 #
6 #
8 # Distributed under the terms of the Modified BSD License.
7 #Distributed under the terms of the Modified BSD License.
9 #
8 #
10 # The full license is in the file COPYING.txt, distributed with this software.
9 #The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
12
11
13 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
14 # Imports
13 # Imports
15 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
16
15
17 from IPython.utils.traitlets import Unicode
16 from ..utils.base import NbConvertBase
18
17
19 from .sphinx_howto import SphinxHowtoExporter
20
18
21 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
22 # Classes
20 # Classes
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 class PostProcessorBase(NbConvertBase):
24
23
25 class SphinxManualExporter(SphinxHowtoExporter):
24 def __call__(self, input):
26 """
25 """
27 Exports Sphinx "Manual" LaTeX documents. The Sphinx "Manual" exporter
26 See def call() ...
28 produces book like latex output for use with PDFLatex.
27 """
29 """
28 self.call(input)
30
29
31 template_file = Unicode(
30
32 'sphinx_manual', config=True,
31 def call(self, input):
33 help="Name of the template file to use")
32 """
34 No newline at end of file
33 Post-process output from a writer.
34 """
35 raise NotImplementedError('call')
1 NO CONTENT: file renamed from IPython/nbconvert/templates/basichtml.tpl to IPython/nbconvert/templates/html_basic.tpl
NO CONTENT: file renamed from IPython/nbconvert/templates/basichtml.tpl to IPython/nbconvert/templates/html_basic.tpl
@@ -1,4 +1,4 b''
1 {%- extends 'basichtml.tpl' -%}
1 {%- extends 'html_basic.tpl' -%}
2
2
3 {%- block header -%}<!DOCTYPE html>
3 {%- block header -%}<!DOCTYPE html>
4 <html>
4 <html>
@@ -4,11 +4,11 b''
4 Purpose: Allow export of PDF friendly Latex inspired by Sphinx HowTo
4 Purpose: Allow export of PDF friendly Latex inspired by Sphinx HowTo
5 document style. Most of the is derived directly from Sphinx source.
5 document style. Most of the is derived directly from Sphinx source.
6
6
7 Inheritance: null>display_priority>latex_base->latex_sphinx_base
7 Inheritance: null>display_priority>sphinx
8
8
9 ==========================================================================))
9 ==========================================================================))
10
10
11 ((*- extends 'sphinx_base.tplx' -*))
11 ((*- extends 'sphinx.tplx' -*))
12
12
13 ((* set parentdocumentclass = 'article' *))
13 ((* set parentdocumentclass = 'article' *))
14 ((* set documentclass = 'howto' *))
14 ((* set documentclass = 'howto' *))
@@ -1,5 +1,7 b''
1 ((*- extends 'display_priority.tplx' -*))
1 ((*- extends 'display_priority.tplx' -*))
2
2
3 \nonstopmode
4
3 ((* block in_prompt *))((* endblock in_prompt *))
5 ((* block in_prompt *))((* endblock in_prompt *))
4
6
5 ((* block output_prompt *))((* endblock output_prompt *))
7 ((* block output_prompt *))((* endblock output_prompt *))
@@ -4,11 +4,11 b''
4 Purpose: Allow export of PDF friendly Latex inspired by Sphinx Manual
4 Purpose: Allow export of PDF friendly Latex inspired by Sphinx Manual
5 document style. Most of the is derived directly from Sphinx source.
5 document style. Most of the is derived directly from Sphinx source.
6
6
7 Inheritance: null>display_priority>latex_base->latex_sphinx_base
7 Inheritance: null>display_priority>sphinx
8
8
9 ==========================================================================))
9 ==========================================================================))
10
10
11 ((*- extends 'sphinx_base.tplx' -*))
11 ((*- extends 'sphinx.tplx' -*))
12
12
13 ((* set parentdocumentclass = 'report' *))
13 ((* set parentdocumentclass = 'report' *))
14 ((* set documentclass = 'manual' *))
14 ((* set documentclass = 'manual' *))
@@ -9,6 +9,8 b' Note: For best display, use latex syntax highlighting. =))'
9
9
10 ((*- extends 'display_priority.tplx' -*))
10 ((*- extends 'display_priority.tplx' -*))
11
11
12 \nonstopmode
13
12 %==============================================================================
14 %==============================================================================
13 % Declarations
15 % Declarations
14 %==============================================================================
16 %==============================================================================
@@ -1,4 +1,4 b''
1 {%- extends 'basichtml.tpl' -%}
1 {%- extends 'html_basic.tpl' -%}
2
2
3
3
4
4
1 NO CONTENT: file renamed from IPython/nbconvert/templates/reveal.tpl to IPython/nbconvert/templates/slides_reveal.tpl
NO CONTENT: file renamed from IPython/nbconvert/templates/reveal.tpl to IPython/nbconvert/templates/slides_reveal.tpl
@@ -1,4 +1,3 b''
1 #!/usr/bin/env python
2 """
1 """
3 Contains base test class for nbconvert
2 Contains base test class for nbconvert
4 """
3 """
@@ -17,6 +17,7 b' import os'
17 from .base import TestsBase
17 from .base import TestsBase
18
18
19 from IPython.utils import py3compat
19 from IPython.utils import py3compat
20 from IPython.testing import decorators as dec
20
21
21
22
22 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
@@ -52,7 +53,7 b' class TestNbConvertApp(TestsBase):'
52 """
53 """
53 with self.create_temp_cwd(['notebook*.ipynb']):
54 with self.create_temp_cwd(['notebook*.ipynb']):
54 assert not 'error' in self.call([IPYTHON, 'nbconvert',
55 assert not 'error' in self.call([IPYTHON, 'nbconvert',
55 '--format="python"', '--notebooks=["*.ipynb"]']).lower()
56 '--to="python"', '--notebooks=["*.ipynb"]']).lower()
56 assert os.path.isfile('notebook1.py')
57 assert os.path.isfile('notebook1.py')
57 assert os.path.isfile('notebook2.py')
58 assert os.path.isfile('notebook2.py')
58
59
@@ -63,7 +64,7 b' class TestNbConvertApp(TestsBase):'
63 """
64 """
64 with self.create_temp_cwd() as cwd:
65 with self.create_temp_cwd() as cwd:
65 self.copy_files_to(['notebook*.ipynb'], 'subdir/')
66 self.copy_files_to(['notebook*.ipynb'], 'subdir/')
66 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--format="python"',
67 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
67 '--notebooks=["%s"]' % os.path.join('subdir', '*.ipynb')]).lower()
68 '--notebooks=["%s"]' % os.path.join('subdir', '*.ipynb')]).lower()
68 assert os.path.isfile('notebook1.py')
69 assert os.path.isfile('notebook1.py')
69 assert os.path.isfile('notebook2.py')
70 assert os.path.isfile('notebook2.py')
@@ -74,18 +75,43 b' class TestNbConvertApp(TestsBase):'
74 Do explicit notebook names work?
75 Do explicit notebook names work?
75 """
76 """
76 with self.create_temp_cwd(['notebook*.ipynb']):
77 with self.create_temp_cwd(['notebook*.ipynb']):
77 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--format="python"',
78 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
78 '--notebooks=["notebook2.ipynb"]']).lower()
79 '--notebooks=["notebook2.ipynb"]']).lower()
79 assert not os.path.isfile('notebook1.py')
80 assert not os.path.isfile('notebook1.py')
80 assert os.path.isfile('notebook2.py')
81 assert os.path.isfile('notebook2.py')
81
82
82
83
84 @dec.onlyif_cmds_exist('pdflatex')
85 def test_post_processor(self):
86 """
87 Do post processors work?
88 """
89 with self.create_temp_cwd(['notebook1.ipynb']):
90 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="latex"',
91 'notebook1', '--post="PDF"', '--PDFPostProcessor.verbose=True']).lower()
92 assert os.path.isfile('notebook1.tex')
93 print("\n\n\t" + "\n\t".join([f for f in os.listdir('.') if os.path.isfile(f)]) + "\n\n")
94 assert os.path.isfile('notebook1.pdf')
95
96
97 def test_template(self):
98 """
99 Do export templates work?
100 """
101 with self.create_temp_cwd(['notebook2.ipynb']):
102 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to=slides',
103 '--notebooks=["notebook2.ipynb"]', '--template=reveal']).lower()
104 assert os.path.isfile('notebook2.slides.html')
105 with open('notebook2.slides.html') as f:
106 assert '/reveal.css' in f.read()
107
108
83 def test_glob_explicit(self):
109 def test_glob_explicit(self):
84 """
110 """
85 Can a search pattern be used along with matching explicit notebook names?
111 Can a search pattern be used along with matching explicit notebook names?
86 """
112 """
87 with self.create_temp_cwd(['notebook*.ipynb']):
113 with self.create_temp_cwd(['notebook*.ipynb']):
88 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--format="python"',
114 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
89 '--notebooks=["*.ipynb", "notebook1.ipynb", "notebook2.ipynb"]']).lower()
115 '--notebooks=["*.ipynb", "notebook1.ipynb", "notebook2.ipynb"]']).lower()
90 assert os.path.isfile('notebook1.py')
116 assert os.path.isfile('notebook1.py')
91 assert os.path.isfile('notebook2.py')
117 assert os.path.isfile('notebook2.py')
@@ -96,7 +122,7 b' class TestNbConvertApp(TestsBase):'
96 Can explicit notebook names be used and then a matching search pattern?
122 Can explicit notebook names be used and then a matching search pattern?
97 """
123 """
98 with self.create_temp_cwd(['notebook*.ipynb']):
124 with self.create_temp_cwd(['notebook*.ipynb']):
99 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--format="python"',
125 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
100 '--notebooks=["notebook1.ipynb", "notebook2.ipynb", "*.ipynb"]']).lower()
126 '--notebooks=["notebook1.ipynb", "notebook2.ipynb", "*.ipynb"]']).lower()
101 assert os.path.isfile('notebook1.py')
127 assert os.path.isfile('notebook1.py')
102 assert os.path.isfile('notebook2.py')
128 assert os.path.isfile('notebook2.py')
@@ -1,2 +1,3 b''
1 from .files import FilesWriter
1 from .files import FilesWriter
2 from .stdout import StdoutWriter
2 from .stdout import StdoutWriter
3 from .base import WriterBase
@@ -1,4 +1,3 b''
1 #!/usr/bin/env python
2 """
1 """
3 Contains writer base class.
2 Contains writer base class.
4 """
3 """
@@ -1,4 +1,3 b''
1 #!/usr/bin/env python
2 """
1 """
3 Contains debug writer.
2 Contains debug writer.
4 """
3 """
@@ -1,4 +1,3 b''
1 #!/usr/bin/env python
2 """
1 """
3 Contains writer for writing nbconvert output to filesystem.
2 Contains writer for writing nbconvert output to filesystem.
4 """
3 """
@@ -100,3 +99,4 b' class FilesWriter(WriterBase):'
100 # Write conversion results.
99 # Write conversion results.
101 with io.open(dest, 'w') as f:
100 with io.open(dest, 'w') as f:
102 f.write(output)
101 f.write(output)
102 return dest No newline at end of file
@@ -1,4 +1,3 b''
1 #!/usr/bin/env python
2 """
1 """
3 Contains Stdout writer
2 Contains Stdout writer
4 """
3 """
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now