##// END OF EJS Templates
Fixed, don't check using in since resources is a default dict.
Jonathan Frederic -
Show More
@@ -1,112 +1,108 b''
1 """
1 """
2 Module with tests for exporter.py
2 Module with tests for exporter.py
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from IPython.config import Config
17 from IPython.config import Config
18
18
19 from .base import ExportersTestsBase
19 from .base import ExportersTestsBase
20 from .cheese import CheeseTransformer
20 from .cheese import CheeseTransformer
21 from ..exporter import Exporter
21 from ..exporter import Exporter
22
22
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Class
25 # Class
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 class TestExporter(ExportersTestsBase):
28 class TestExporter(ExportersTestsBase):
29 """Contains test functions for exporter.py"""
29 """Contains test functions for exporter.py"""
30
30
31
31
32 def test_constructor(self):
32 def test_constructor(self):
33 """
33 """
34 Can an Exporter be constructed?
34 Can an Exporter be constructed?
35 """
35 """
36 Exporter()
36 Exporter()
37
37
38
38
39 def test_export(self):
39 def test_export(self):
40 """
40 """
41 Can an Exporter export something?
41 Can an Exporter export something?
42 """
42 """
43 exporter = self._make_exporter()
43 exporter = self._make_exporter()
44 (output, resources) = exporter.from_filename(self._get_notebook())
44 (output, resources) = exporter.from_filename(self._get_notebook())
45 assert len(output) > 0
45 assert len(output) > 0
46
46
47
47
48 def test_extract_outputs(self):
48 def test_extract_outputs(self):
49 """
49 """
50 If the ExtractOutputTransformer is enabled, are outputs extracted?
50 If the ExtractOutputTransformer is enabled, are outputs extracted?
51 """
51 """
52 config = Config({'ExtractOutputTransformer': {'enabled': True}})
52 config = Config({'ExtractOutputTransformer': {'enabled': True}})
53 exporter = self._make_exporter(config=config)
53 exporter = self._make_exporter(config=config)
54 (output, resources) = exporter.from_filename(self._get_notebook())
54 (output, resources) = exporter.from_filename(self._get_notebook())
55 assert resources is not None
55 assert resources is not None
56 assert 'outputs' in resources
56 assert isinstance(resources['outputs'], dict)
57 assert len(resources['outputs']) > 0
57 assert len(resources['outputs']) > 0
58
58
59
59
60 def test_transformer_class(self):
60 def test_transformer_class(self):
61 """
61 """
62 Can a transformer be added to the transformers list by class type?
62 Can a transformer be added to the transformers list by class type?
63 """
63 """
64 config = Config({'Exporter': {'transformers': [CheeseTransformer]}})
64 config = Config({'Exporter': {'transformers': [CheeseTransformer]}})
65 exporter = self._make_exporter(config=config)
65 exporter = self._make_exporter(config=config)
66 (output, resources) = exporter.from_filename(self._get_notebook())
66 (output, resources) = exporter.from_filename(self._get_notebook())
67 assert resources is not None
67 assert resources is not None
68 assert 'cheese' in resources
69 assert resources['cheese'] == 'real'
68 assert resources['cheese'] == 'real'
70
69
71
70
72 def test_transformer_instance(self):
71 def test_transformer_instance(self):
73 """
72 """
74 Can a transformer be added to the transformers list by instance?
73 Can a transformer be added to the transformers list by instance?
75 """
74 """
76 config = Config({'Exporter': {'transformers': [CheeseTransformer()]}})
75 config = Config({'Exporter': {'transformers': [CheeseTransformer()]}})
77 exporter = self._make_exporter(config=config)
76 exporter = self._make_exporter(config=config)
78 (output, resources) = exporter.from_filename(self._get_notebook())
77 (output, resources) = exporter.from_filename(self._get_notebook())
79 assert resources is not None
78 assert resources is not None
80 assert 'cheese' in resources
81 assert resources['cheese'] == 'real'
79 assert resources['cheese'] == 'real'
82
80
83
81
84 def test_transformer_dottedobjectname(self):
82 def test_transformer_dottedobjectname(self):
85 """
83 """
86 Can a transformer be added to the transformers list by dotted object name?
84 Can a transformer be added to the transformers list by dotted object name?
87 """
85 """
88 config = Config({'Exporter': {'transformers': ['IPython.nbconvert.exporters.tests.cheese.CheeseTransformer']}})
86 config = Config({'Exporter': {'transformers': ['IPython.nbconvert.exporters.tests.cheese.CheeseTransformer']}})
89 exporter = self._make_exporter(config=config)
87 exporter = self._make_exporter(config=config)
90 (output, resources) = exporter.from_filename(self._get_notebook())
88 (output, resources) = exporter.from_filename(self._get_notebook())
91 assert resources is not None
89 assert resources is not None
92 assert 'cheese' in resources
93 assert resources['cheese'] == 'real'
90 assert resources['cheese'] == 'real'
94
91
95
92
96 def test_transformer_via_method(self):
93 def test_transformer_via_method(self):
97 """
94 """
98 Can a transformer be added via the Exporter convenience method?
95 Can a transformer be added via the Exporter convenience method?
99 """
96 """
100 exporter = self._make_exporter()
97 exporter = self._make_exporter()
101 exporter.register_transformer(CheeseTransformer, enabled=True)
98 exporter.register_transformer(CheeseTransformer, enabled=True)
102 (output, resources) = exporter.from_filename(self._get_notebook())
99 (output, resources) = exporter.from_filename(self._get_notebook())
103 assert resources is not None
100 assert resources is not None
104 assert 'cheese' in resources
105 assert resources['cheese'] == 'real'
101 assert resources['cheese'] == 'real'
106
102
107
103
108 def _make_exporter(self, config=None):
104 def _make_exporter(self, config=None):
109 #Create the exporter instance, make sure to set a template name since
105 #Create the exporter instance, make sure to set a template name since
110 #the base Exporter doesn't have a template associated with it.
106 #the base Exporter doesn't have a template associated with it.
111 exporter = Exporter(config=config, template_file='python')
107 exporter = Exporter(config=config, template_file='python')
112 return exporter No newline at end of file
108 return exporter
@@ -1,102 +1,102 b''
1 """Module containing a transformer that extracts all of the outputs from the
1 """Module containing a transformer that extracts all of the outputs from the
2 notebook file. The extracted outputs are returned in the 'resources' dictionary.
2 notebook file. The extracted outputs are returned in the 'resources' dictionary.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
5 # Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # 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.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import base64
16 import base64
17 import sys
17 import sys
18 import os
18 import os
19
19
20 from IPython.utils.traitlets import Unicode
20 from IPython.utils.traitlets import Unicode
21 from .base import Transformer
21 from .base import Transformer
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Classes
25 # Classes
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 class ExtractOutputTransformer(Transformer):
28 class ExtractOutputTransformer(Transformer):
29 """
29 """
30 Extracts all of the outputs from the notebook file. The extracted
30 Extracts all of the outputs from the notebook file. The extracted
31 outputs are returned in the 'resources' dictionary.
31 outputs are returned in the 'resources' dictionary.
32 """
32 """
33
33
34 output_filename_template = Unicode(
34 output_filename_template = Unicode(
35 "{unique_key}_{cell_index}_{index}.{extension}", config=True)
35 "{unique_key}_{cell_index}_{index}.{extension}", config=True)
36
36
37
37
38 def transform_cell(self, cell, resources, cell_index):
38 def transform_cell(self, cell, resources, cell_index):
39 """
39 """
40 Apply a transformation on each cell,
40 Apply a transformation on each cell,
41
41
42 Parameters
42 Parameters
43 ----------
43 ----------
44 cell : NotebookNode cell
44 cell : NotebookNode cell
45 Notebook cell being processed
45 Notebook cell being processed
46 resources : dictionary
46 resources : dictionary
47 Additional resources used in the conversion process. Allows
47 Additional resources used in the conversion process. Allows
48 transformers to pass variables into the Jinja engine.
48 transformers to pass variables into the Jinja engine.
49 cell_index : int
49 cell_index : int
50 Index of the cell being processed (see base.py)
50 Index of the cell being processed (see base.py)
51 """
51 """
52
52
53 #Get the unique key from the resource dict if it exists. If it does not
53 #Get the unique key from the resource dict if it exists. If it does not
54 #exist, use 'output' as the default. Also, get files directory if it
54 #exist, use 'output' as the default. Also, get files directory if it
55 #has been specified
55 #has been specified
56 unique_key = resources.get('unique_key', 'output')
56 unique_key = resources.get('unique_key', 'output')
57 output_files_dir = resources.get('output_files_dir', None)
57 output_files_dir = resources.get('output_files_dir', None)
58
58
59 #Make sure outputs key exists
59 #Make sure outputs key exists
60 if not 'outputs' in resources:
60 if not isinstance(resources['outputs'], dict):
61 resources['outputs'] = {}
61 resources['outputs'] = {}
62
62
63 #Loop through all of the outputs in the cell
63 #Loop through all of the outputs in the cell
64 for index, out in enumerate(cell.get('outputs', [])):
64 for index, out in enumerate(cell.get('outputs', [])):
65
65
66 #Get the output in data formats that the template is interested in.
66 #Get the output in data formats that the template is interested in.
67 for out_type in self.display_data_priority:
67 for out_type in self.display_data_priority:
68 if out.hasattr(out_type):
68 if out.hasattr(out_type):
69 data = out[out_type]
69 data = out[out_type]
70
70
71 #Binary files are base64-encoded, SVG is already XML
71 #Binary files are base64-encoded, SVG is already XML
72 if out_type in ('png', 'jpg', 'jpeg', 'pdf'):
72 if out_type in ('png', 'jpg', 'jpeg', 'pdf'):
73
73
74 # data is b64-encoded as text (str, unicode)
74 # data is b64-encoded as text (str, unicode)
75 # decodestring only accepts bytes
75 # decodestring only accepts bytes
76 data = py3compat.cast_bytes(data)
76 data = py3compat.cast_bytes(data)
77 data = base64.decodestring(data)
77 data = base64.decodestring(data)
78 elif sys.platform == 'win32':
78 elif sys.platform == 'win32':
79 data = data.replace('\n', '\r\n').encode("UTF-8")
79 data = data.replace('\n', '\r\n').encode("UTF-8")
80 else:
80 else:
81 data = data.encode("UTF-8")
81 data = data.encode("UTF-8")
82
82
83 #Build an output name
83 #Build an output name
84 filename = self.output_filename_template.format(
84 filename = self.output_filename_template.format(
85 unique_key=unique_key,
85 unique_key=unique_key,
86 cell_index=cell_index,
86 cell_index=cell_index,
87 index=index,
87 index=index,
88 extension=out_type)
88 extension=out_type)
89
89
90 #On the cell, make the figure available via
90 #On the cell, make the figure available via
91 # cell.outputs[i].svg_filename ... etc (svg in example)
91 # cell.outputs[i].svg_filename ... etc (svg in example)
92 # Where
92 # Where
93 # cell.outputs[i].svg contains the data
93 # cell.outputs[i].svg contains the data
94 if output_files_dir is not None:
94 if output_files_dir is not None:
95 filename = os.path.join(output_files_dir, filename)
95 filename = os.path.join(output_files_dir, filename)
96 out[out_type + '_filename'] = filename
96 out[out_type + '_filename'] = filename
97
97
98 #In the resources, make the figure available via
98 #In the resources, make the figure available via
99 # resources['outputs']['filename'] = data
99 # resources['outputs']['filename'] = data
100 resources['outputs'][filename] = data
100 resources['outputs'][filename] = data
101
101
102 return cell, resources
102 return cell, resources
@@ -1,61 +1,61 b''
1 """Module that pre-processes the notebook for export via Reveal.
1 """Module that pre-processes the notebook for export via Reveal.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, the IPython Development Team.
4 # Copyright (c) 2013, the IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 from .base import Transformer
15 from .base import Transformer
16 from IPython.utils.traitlets import Unicode
16 from IPython.utils.traitlets import Unicode
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Classes and functions
19 # Classes and functions
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 class RevealHelpTransformer(Transformer):
22 class RevealHelpTransformer(Transformer):
23
23
24 url_prefix = Unicode('//cdn.jsdelivr.net/reveal.js/2.4.0',
24 url_prefix = Unicode('//cdn.jsdelivr.net/reveal.js/2.4.0',
25 config=True,
25 config=True,
26 help="""If you want to use a local reveal.js library,
26 help="""If you want to use a local reveal.js library,
27 use 'url_prefix':'reveal.js' in your config object.""")
27 use 'url_prefix':'reveal.js' in your config object.""")
28
28
29 def call(self, nb, resources):
29 def call(self, nb, resources):
30 """
30 """
31 Called once to 'transform' contents of the notebook.
31 Called once to 'transform' contents of the notebook.
32
32
33 Parameters
33 Parameters
34 ----------
34 ----------
35 nb : NotebookNode
35 nb : NotebookNode
36 Notebook being converted
36 Notebook being converted
37 resources : dictionary
37 resources : dictionary
38 Additional resources used in the conversion process. Allows
38 Additional resources used in the conversion process. Allows
39 transformers to pass variables into the Jinja engine.
39 transformers to pass variables into the Jinja engine.
40 """
40 """
41
41
42 for worksheet in nb.worksheets :
42 for worksheet in nb.worksheets :
43 for index, cell in enumerate(worksheet.cells):
43 for index, cell in enumerate(worksheet.cells):
44
44
45 #Make sure the cell has slideshow metadata.
45 #Make sure the cell has slideshow metadata.
46 cell.metadata.align_type = cell.get('metadata', {}).get('slideshow', {}).get('align_type', 'Left')
46 cell.metadata.align_type = cell.get('metadata', {}).get('slideshow', {}).get('align_type', 'Left')
47 cell.metadata.slide_type = cell.get('metadata', {}).get('slideshow', {}).get('slide_type', '-')
47 cell.metadata.slide_type = cell.get('metadata', {}).get('slideshow', {}).get('slide_type', '-')
48
48
49 #Get the slide type. If type is start of subslide or slide,
49 #Get the slide type. If type is start of subslide or slide,
50 #end the last subslide/slide.
50 #end the last subslide/slide.
51 if cell.metadata.slide_type in ['slide']:
51 if cell.metadata.slide_type in ['slide']:
52 worksheet.cells[index - 1].metadata.slide_helper = 'slide_end'
52 worksheet.cells[index - 1].metadata.slide_helper = 'slide_end'
53 if cell.metadata.slide_type in ['subslide']:
53 if cell.metadata.slide_type in ['subslide']:
54 worksheet.cells[index - 1].metadata.slide_helper = 'subslide_end'
54 worksheet.cells[index - 1].metadata.slide_helper = 'subslide_end'
55
55
56
56
57 if 'reveal' not in resources:
57 if not isinstance(resources['reveal'], dict):
58 resources['reveal'] = {}
58 resources['reveal'] = {}
59 resources['reveal']['url_prefix'] = self.url_prefix
59 resources['reveal']['url_prefix'] = self.url_prefix
60
60
61 return nb, resources
61 return nb, resources
@@ -1,264 +1,264 b''
1 """Module that allows custom Sphinx parameters to be set on the notebook and
1 """Module that allows custom Sphinx parameters to be set on the notebook and
2 on the 'other' object passed into Jinja. Called prior to Jinja conversion
2 on the 'other' object passed into Jinja. Called prior to Jinja conversion
3 process.
3 process.
4 """
4 """
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import print_function, absolute_import
17 from __future__ import print_function, absolute_import
18
18
19 # Stdlib imports
19 # Stdlib imports
20 # Used to find Sphinx package location
20 # Used to find Sphinx package location
21 import sphinx
21 import sphinx
22 import os.path
22 import os.path
23
23
24 # Used to set the default date to today's date
24 # Used to set the default date to today's date
25 from datetime import date
25 from datetime import date
26
26
27 # Third-party imports
27 # Third-party imports
28 # Needed for Pygments latex definitions.
28 # Needed for Pygments latex definitions.
29 from pygments.formatters import LatexFormatter
29 from pygments.formatters import LatexFormatter
30
30
31 # Our own imports
31 # Our own imports
32 # Configurable traitlets
32 # Configurable traitlets
33 from IPython.utils.traitlets import Unicode, Bool
33 from IPython.utils.traitlets import Unicode, Bool
34
34
35 # Needed to override transformer
35 # Needed to override transformer
36 from .base import (Transformer)
36 from .base import (Transformer)
37
37
38 from IPython.nbconvert.utils import console
38 from IPython.nbconvert.utils import console
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Classes and functions
41 # Classes and functions
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class SphinxTransformer(Transformer):
44 class SphinxTransformer(Transformer):
45 """
45 """
46 Sphinx utility transformer.
46 Sphinx utility transformer.
47
47
48 This transformer is used to set variables needed by the latex to build
48 This transformer is used to set variables needed by the latex to build
49 Sphinx stylized templates.
49 Sphinx stylized templates.
50 """
50 """
51
51
52 interactive = Bool(False, config=True, help="""
52 interactive = Bool(False, config=True, help="""
53 Allows you to define whether or not the Sphinx exporter will prompt
53 Allows you to define whether or not the Sphinx exporter will prompt
54 you for input during the conversion process. If this is set to false,
54 you for input during the conversion process. If this is set to false,
55 the author, version, release, date, and chapter_style traits should
55 the author, version, release, date, and chapter_style traits should
56 be set.
56 be set.
57 """)
57 """)
58
58
59 author = Unicode("Unknown Author", config=True, help="Author name")
59 author = Unicode("Unknown Author", config=True, help="Author name")
60
60
61 version = Unicode("", config=True, help="""
61 version = Unicode("", config=True, help="""
62 Version number
62 Version number
63 You can leave this blank if you do not want to render a version number.
63 You can leave this blank if you do not want to render a version number.
64 Example: "1.0.0"
64 Example: "1.0.0"
65 """)
65 """)
66
66
67 release = Unicode("", config=True, help="""
67 release = Unicode("", config=True, help="""
68 Release name
68 Release name
69 You can leave this blank if you do not want to render a release name.
69 You can leave this blank if you do not want to render a release name.
70 Example: "Rough Draft"
70 Example: "Rough Draft"
71 """)
71 """)
72
72
73 publish_date = Unicode("", config=True, help="""
73 publish_date = Unicode("", config=True, help="""
74 Publish date
74 Publish date
75 This is the date to render on the document as the publish date.
75 This is the date to render on the document as the publish date.
76 Leave this blank to default to todays date.
76 Leave this blank to default to todays date.
77 Example: "June 12, 1990"
77 Example: "June 12, 1990"
78 """)
78 """)
79
79
80 chapter_style = Unicode("Bjarne", config=True, help="""
80 chapter_style = Unicode("Bjarne", config=True, help="""
81 Sphinx chapter style
81 Sphinx chapter style
82 This is the style to use for the chapter headers in the document.
82 This is the style to use for the chapter headers in the document.
83 You may choose one of the following:
83 You may choose one of the following:
84 "Bjarne" (default)
84 "Bjarne" (default)
85 "Lenny"
85 "Lenny"
86 "Glenn"
86 "Glenn"
87 "Conny"
87 "Conny"
88 "Rejne"
88 "Rejne"
89 "Sonny" (used for international documents)
89 "Sonny" (used for international documents)
90 """)
90 """)
91
91
92 output_style = Unicode("notebook", config=True, help="""
92 output_style = Unicode("notebook", config=True, help="""
93 Nbconvert Ipython
93 Nbconvert Ipython
94 notebook input/output formatting style.
94 notebook input/output formatting style.
95 You may choose one of the following:
95 You may choose one of the following:
96 "simple (recommended for long code segments)"
96 "simple (recommended for long code segments)"
97 "notebook" (default)
97 "notebook" (default)
98 """)
98 """)
99
99
100 center_output = Bool(False, config=True, help="""
100 center_output = Bool(False, config=True, help="""
101 Optional attempt to center all output. If this is false, no additional
101 Optional attempt to center all output. If this is false, no additional
102 formatting is applied.
102 formatting is applied.
103 """)
103 """)
104
104
105 use_headers = Bool(True, config=True, help="""
105 use_headers = Bool(True, config=True, help="""
106 Whether not a header should be added to the document.
106 Whether not a header should be added to the document.
107 """)
107 """)
108
108
109 #Allow the user to override the title of the notebook (useful for
109 #Allow the user to override the title of the notebook (useful for
110 #fancy document titles that the file system doesn't support.)
110 #fancy document titles that the file system doesn't support.)
111 overridetitle = Unicode("", config=True, help="")
111 overridetitle = Unicode("", config=True, help="")
112
112
113
113
114 def call(self, nb, resources):
114 def call(self, nb, resources):
115 """
115 """
116 Sphinx transformation to apply on each notebook.
116 Sphinx transformation to apply on each notebook.
117
117
118 Parameters
118 Parameters
119 ----------
119 ----------
120 nb : NotebookNode
120 nb : NotebookNode
121 Notebook being converted
121 Notebook being converted
122 resources : dictionary
122 resources : dictionary
123 Additional resources used in the conversion process. Allows
123 Additional resources used in the conversion process. Allows
124 transformers to pass variables into the Jinja engine.
124 transformers to pass variables into the Jinja engine.
125 """
125 """
126
126
127 # TODO: Add versatile method of additional notebook metadata. Include
127 # TODO: Add versatile method of additional notebook metadata. Include
128 # handling of multiple files. For now use a temporay namespace,
128 # handling of multiple files. For now use a temporay namespace,
129 # '_draft' to signify that this needs to change.
129 # '_draft' to signify that this needs to change.
130 if not "sphinx" in resources:
130 if not isinstance(resources["sphinx"], dict):
131 resources["sphinx"] = {}
131 resources["sphinx"] = {}
132
132
133 if self.interactive:
133 if self.interactive:
134
134
135 # Prompt the user for additional meta data that doesn't exist currently
135 # Prompt the user for additional meta data that doesn't exist currently
136 # but would be usefull for Sphinx.
136 # but would be usefull for Sphinx.
137 resources["sphinx"]["author"] = self._prompt_author()
137 resources["sphinx"]["author"] = self._prompt_author()
138 resources["sphinx"]["version"] = self._prompt_version()
138 resources["sphinx"]["version"] = self._prompt_version()
139 resources["sphinx"]["release"] = self._prompt_release()
139 resources["sphinx"]["release"] = self._prompt_release()
140 resources["sphinx"]["date"] = self._prompt_date()
140 resources["sphinx"]["date"] = self._prompt_date()
141
141
142 # Prompt the user for the document style.
142 # Prompt the user for the document style.
143 resources["sphinx"]["chapterstyle"] = self._prompt_chapter_title_style()
143 resources["sphinx"]["chapterstyle"] = self._prompt_chapter_title_style()
144 resources["sphinx"]["outputstyle"] = self._prompt_output_style()
144 resources["sphinx"]["outputstyle"] = self._prompt_output_style()
145
145
146 # Small options
146 # Small options
147 resources["sphinx"]["centeroutput"] = console.prompt_boolean("Do you want to center the output? (false)", False)
147 resources["sphinx"]["centeroutput"] = console.prompt_boolean("Do you want to center the output? (false)", False)
148 resources["sphinx"]["header"] = console.prompt_boolean("Should a Sphinx document header be used? (true)", True)
148 resources["sphinx"]["header"] = console.prompt_boolean("Should a Sphinx document header be used? (true)", True)
149 else:
149 else:
150
150
151 # Try to use the traitlets.
151 # Try to use the traitlets.
152 resources["sphinx"]["author"] = self.author
152 resources["sphinx"]["author"] = self.author
153 resources["sphinx"]["version"] = self.version
153 resources["sphinx"]["version"] = self.version
154 resources["sphinx"]["release"] = self.release
154 resources["sphinx"]["release"] = self.release
155
155
156 # Use todays date if none is provided.
156 # Use todays date if none is provided.
157 if self.publish_date:
157 if self.publish_date:
158 resources["sphinx"]["date"] = self.publish_date
158 resources["sphinx"]["date"] = self.publish_date
159 elif len(resources['metadata']['modified_date'].strip()) == 0:
159 elif len(resources['metadata']['modified_date'].strip()) == 0:
160 resources["sphinx"]["date"] = date.today().strftime("%B %-d, %Y")
160 resources["sphinx"]["date"] = date.today().strftime("%B %-d, %Y")
161 else:
161 else:
162 resources["sphinx"]["date"] = resources['metadata']['modified_date']
162 resources["sphinx"]["date"] = resources['metadata']['modified_date']
163
163
164 # Sphinx traitlets.
164 # Sphinx traitlets.
165 resources["sphinx"]["chapterstyle"] = self.chapter_style
165 resources["sphinx"]["chapterstyle"] = self.chapter_style
166 resources["sphinx"]["outputstyle"] = self.output_style
166 resources["sphinx"]["outputstyle"] = self.output_style
167 resources["sphinx"]["centeroutput"] = self.center_output
167 resources["sphinx"]["centeroutput"] = self.center_output
168 resources["sphinx"]["header"] = self.use_headers
168 resources["sphinx"]["header"] = self.use_headers
169
169
170 # Find and pass in the path to the Sphinx dependencies.
170 # Find and pass in the path to the Sphinx dependencies.
171 resources["sphinx"]["texinputs"] = os.path.realpath(os.path.join(sphinx.__file__, "..", "texinputs"))
171 resources["sphinx"]["texinputs"] = os.path.realpath(os.path.join(sphinx.__file__, "..", "texinputs"))
172
172
173 # Generate Pygments definitions for Latex
173 # Generate Pygments definitions for Latex
174 resources["sphinx"]["pygment_definitions"] = self._generate_pygments_latex_def()
174 resources["sphinx"]["pygment_definitions"] = self._generate_pygments_latex_def()
175
175
176 if not (self.overridetitle == None or len(self.overridetitle.strip()) == 0):
176 if not (self.overridetitle == None or len(self.overridetitle.strip()) == 0):
177 resources['metadata']['name'] = self.overridetitle
177 resources['metadata']['name'] = self.overridetitle
178
178
179 # End
179 # End
180 return nb, resources
180 return nb, resources
181
181
182
182
183 def _generate_pygments_latex_def(self):
183 def _generate_pygments_latex_def(self):
184 """
184 """
185 Generate the pygments latex definitions that allows pygments
185 Generate the pygments latex definitions that allows pygments
186 to work in latex.
186 to work in latex.
187 """
187 """
188
188
189 return LatexFormatter().get_style_defs()
189 return LatexFormatter().get_style_defs()
190
190
191
191
192 def _prompt_author(self):
192 def _prompt_author(self):
193 """
193 """
194 Prompt the user to input an Author name
194 Prompt the user to input an Author name
195 """
195 """
196 return console.input("Author name: ")
196 return console.input("Author name: ")
197
197
198
198
199 def _prompt_version(self):
199 def _prompt_version(self):
200 """
200 """
201 prompt the user to enter a version number
201 prompt the user to enter a version number
202 """
202 """
203 return console.input("Version (ie ""1.0.0""): ")
203 return console.input("Version (ie ""1.0.0""): ")
204
204
205
205
206 def _prompt_release(self):
206 def _prompt_release(self):
207 """
207 """
208 Prompt the user to input a release name
208 Prompt the user to input a release name
209 """
209 """
210
210
211 return console.input("Release Name (ie ""Rough draft""): ")
211 return console.input("Release Name (ie ""Rough draft""): ")
212
212
213
213
214 def _prompt_date(self, resources):
214 def _prompt_date(self, resources):
215 """
215 """
216 Prompt the user to enter a date
216 Prompt the user to enter a date
217 """
217 """
218
218
219 if resources['metadata']['modified_date']:
219 if resources['metadata']['modified_date']:
220 default_date = resources['metadata']['modified_date']
220 default_date = resources['metadata']['modified_date']
221 else:
221 else:
222 default_date = date.today().strftime("%B %-d, %Y")
222 default_date = date.today().strftime("%B %-d, %Y")
223
223
224 user_date = console.input("Date (deafults to \"" + default_date + "\"): ")
224 user_date = console.input("Date (deafults to \"" + default_date + "\"): ")
225 if len(user_date.strip()) == 0:
225 if len(user_date.strip()) == 0:
226 user_date = default_date
226 user_date = default_date
227 return user_date
227 return user_date
228
228
229
229
230 def _prompt_output_style(self):
230 def _prompt_output_style(self):
231 """
231 """
232 Prompts the user to pick an IPython output style.
232 Prompts the user to pick an IPython output style.
233 """
233 """
234
234
235 # Dictionary of available output styles
235 # Dictionary of available output styles
236 styles = {1: "simple",
236 styles = {1: "simple",
237 2: "notebook"}
237 2: "notebook"}
238
238
239 #Append comments to the menu when displaying it to the user.
239 #Append comments to the menu when displaying it to the user.
240 comments = {1: "(recommended for long code segments)",
240 comments = {1: "(recommended for long code segments)",
241 2: "(default)"}
241 2: "(default)"}
242
242
243 return console.prompt_dictionary(styles, default_style=2, menu_comments=comments)
243 return console.prompt_dictionary(styles, default_style=2, menu_comments=comments)
244
244
245
245
246 def _prompt_chapter_title_style(self):
246 def _prompt_chapter_title_style(self):
247 """
247 """
248 Prompts the user to pick a Sphinx chapter style
248 Prompts the user to pick a Sphinx chapter style
249 """
249 """
250
250
251 # Dictionary of available Sphinx styles
251 # Dictionary of available Sphinx styles
252 styles = {1: "Bjarne",
252 styles = {1: "Bjarne",
253 2: "Lenny",
253 2: "Lenny",
254 3: "Glenn",
254 3: "Glenn",
255 4: "Conny",
255 4: "Conny",
256 5: "Rejne",
256 5: "Rejne",
257 6: "Sonny"}
257 6: "Sonny"}
258
258
259 #Append comments to the menu when displaying it to the user.
259 #Append comments to the menu when displaying it to the user.
260 comments = {1: "(default)",
260 comments = {1: "(default)",
261 6: "(for international documents)"}
261 6: "(for international documents)"}
262
262
263 return console.prompt_dictionary(styles, menu_comments=comments)
263 return console.prompt_dictionary(styles, menu_comments=comments)
264
264
@@ -1,48 +1,47 b''
1 """
1 """
2 Module with tests for the csshtmlheader transformer
2 Module with tests for the csshtmlheader transformer
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from .base import TransformerTestsBase
17 from .base import TransformerTestsBase
18 from ..csshtmlheader import CSSHTMLHeaderTransformer
18 from ..csshtmlheader import CSSHTMLHeaderTransformer
19
19
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Class
22 # Class
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class TestCSSHTMLHeader(TransformerTestsBase):
25 class TestCSSHTMLHeader(TransformerTestsBase):
26 """Contains test functions for csshtmlheader.py"""
26 """Contains test functions for csshtmlheader.py"""
27
27
28
28
29 def build_transformer(self):
29 def build_transformer(self):
30 """Make an instance of a transformer"""
30 """Make an instance of a transformer"""
31 transformer = CSSHTMLHeaderTransformer()
31 transformer = CSSHTMLHeaderTransformer()
32 transformer.enabled = True
32 transformer.enabled = True
33 return transformer
33 return transformer
34
34
35
35
36 def test_constructor(self):
36 def test_constructor(self):
37 """Can a CSSHTMLHeaderTransformer be constructed?"""
37 """Can a CSSHTMLHeaderTransformer be constructed?"""
38 self.build_transformer()
38 self.build_transformer()
39
39
40
40
41 def test_output(self):
41 def test_output(self):
42 """Test the output of the CSSHTMLHeaderTransformer"""
42 """Test the output of the CSSHTMLHeaderTransformer"""
43 nb = self.build_notebook()
43 nb = self.build_notebook()
44 res = self.build_resources()
44 res = self.build_resources()
45 transformer = self.build_transformer()
45 transformer = self.build_transformer()
46 nb, res = transformer(nb, res)
46 nb, res = transformer(nb, res)
47 assert 'inlining' in res
48 assert 'css' in res['inlining'] No newline at end of file
47 assert 'css' in res['inlining']
@@ -1,65 +1,62 b''
1 """
1 """
2 Module with tests for the extractoutput transformer
2 Module with tests for the extractoutput transformer
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from .base import TransformerTestsBase
17 from .base import TransformerTestsBase
18 from ..extractoutput import ExtractOutputTransformer
18 from ..extractoutput import ExtractOutputTransformer
19
19
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Class
22 # Class
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class TestExtractOutput(TransformerTestsBase):
25 class TestExtractOutput(TransformerTestsBase):
26 """Contains test functions for extractoutput.py"""
26 """Contains test functions for extractoutput.py"""
27
27
28
28
29 def build_transformer(self):
29 def build_transformer(self):
30 """Make an instance of a transformer"""
30 """Make an instance of a transformer"""
31 transformer = ExtractOutputTransformer()
31 transformer = ExtractOutputTransformer()
32 transformer.enabled = True
32 transformer.enabled = True
33 return transformer
33 return transformer
34
34
35
35
36 def test_constructor(self):
36 def test_constructor(self):
37 """Can a ExtractOutputTransformer be constructed?"""
37 """Can a ExtractOutputTransformer be constructed?"""
38 self.build_transformer()
38 self.build_transformer()
39
39
40
40
41 def test_output(self):
41 def test_output(self):
42 """Test the output of the ExtractOutputTransformer"""
42 """Test the output of the ExtractOutputTransformer"""
43 nb = self.build_notebook()
43 nb = self.build_notebook()
44 res = self.build_resources()
44 res = self.build_resources()
45 transformer = self.build_transformer()
45 transformer = self.build_transformer()
46 nb, res = transformer(nb, res)
46 nb, res = transformer(nb, res)
47
47
48 # Check if text was extracted.
48 # Check if text was extracted.
49 assert 'text_filename' in nb.worksheets[0].cells[0].outputs[1]
49 assert 'text_filename' in nb.worksheets[0].cells[0].outputs[1]
50 text_filename = nb.worksheets[0].cells[0].outputs[1]['text_filename']
50 text_filename = nb.worksheets[0].cells[0].outputs[1]['text_filename']
51
51
52 # Check if png was extracted.
52 # Check if png was extracted.
53 assert 'png_filename' in nb.worksheets[0].cells[0].outputs[6]
53 assert 'png_filename' in nb.worksheets[0].cells[0].outputs[6]
54 png_filename = nb.worksheets[0].cells[0].outputs[6]['png_filename']
54 png_filename = nb.worksheets[0].cells[0].outputs[6]['png_filename']
55
55
56 # Make sure an entry to the resources was added.
57 assert 'outputs' in res
58
59 # Verify text output
56 # Verify text output
60 assert text_filename in res['outputs']
57 assert text_filename in res['outputs']
61 self.assertEqual(res['outputs'][text_filename], b'b')
58 self.assertEqual(res['outputs'][text_filename], b'b')
62
59
63 # Verify png output
60 # Verify png output
64 assert png_filename in res['outputs']
61 assert png_filename in res['outputs']
65 self.assertEqual(res['outputs'][png_filename], b'g')
62 self.assertEqual(res['outputs'][png_filename], b'g')
@@ -1,58 +1,57 b''
1 """
1 """
2 Module with tests for the sphinx transformer
2 Module with tests for the sphinx transformer
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from .base import TransformerTestsBase
17 from .base import TransformerTestsBase
18 from ..sphinx import SphinxTransformer
18 from ..sphinx import SphinxTransformer
19
19
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Class
22 # Class
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class TestSphinx(TransformerTestsBase):
25 class TestSphinx(TransformerTestsBase):
26 """Contains test functions for sphinx.py"""
26 """Contains test functions for sphinx.py"""
27
27
28
28
29 def build_transformer(self):
29 def build_transformer(self):
30 """Make an instance of a transformer"""
30 """Make an instance of a transformer"""
31 transformer = SphinxTransformer()
31 transformer = SphinxTransformer()
32 transformer.enabled = True
32 transformer.enabled = True
33 return transformer
33 return transformer
34
34
35
35
36 def test_constructor(self):
36 def test_constructor(self):
37 """Can a SphinxTransformer be constructed?"""
37 """Can a SphinxTransformer be constructed?"""
38 self.build_transformer()
38 self.build_transformer()
39
39
40
40
41 def test_resources(self):
41 def test_resources(self):
42 """Make sure the SphinxTransformer adds the appropriate resources to the
42 """Make sure the SphinxTransformer adds the appropriate resources to the
43 resources dict."""
43 resources dict."""
44 nb = self.build_notebook()
44 nb = self.build_notebook()
45 res = self.build_resources()
45 res = self.build_resources()
46 transformer = self.build_transformer()
46 transformer = self.build_transformer()
47 nb, res = transformer(nb, res)
47 nb, res = transformer(nb, res)
48 assert 'sphinx' in res
49 assert "author" in res['sphinx']
48 assert "author" in res['sphinx']
50 assert "version" in res['sphinx']
49 assert "version" in res['sphinx']
51 assert "release" in res['sphinx']
50 assert "release" in res['sphinx']
52 assert "date" in res['sphinx']
51 assert "date" in res['sphinx']
53 assert "chapterstyle" in res['sphinx']
52 assert "chapterstyle" in res['sphinx']
54 assert "outputstyle" in res['sphinx']
53 assert "outputstyle" in res['sphinx']
55 assert "centeroutput" in res['sphinx']
54 assert "centeroutput" in res['sphinx']
56 assert "header" in res['sphinx']
55 assert "header" in res['sphinx']
57 assert "texinputs" in res['sphinx']
56 assert "texinputs" in res['sphinx']
58 assert "pygment_definitions" in res['sphinx']
57 assert "pygment_definitions" in res['sphinx']
@@ -1,42 +1,42 b''
1 """
1 """
2 Contains debug writer.
2 Contains debug writer.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 #Distributed under the terms of the Modified BSD License.
7 #Distributed under the terms of the Modified BSD License.
8 #
8 #
9 #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.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 from .base import WriterBase
16 from .base import WriterBase
17 from pprint import pprint
17 from pprint import pprint
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Classes
20 # Classes
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 class DebugWriter(WriterBase):
23 class DebugWriter(WriterBase):
24 """Consumes output from nbconvert export...() methods and writes usefull
24 """Consumes output from nbconvert export...() methods and writes usefull
25 debugging information to the stdout. The information includes a list of
25 debugging information to the stdout. The information includes a list of
26 resources that were extracted from the notebook(s) during export."""
26 resources that were extracted from the notebook(s) during export."""
27
27
28
28
29 def write(self, output, resources, notebook_name='notebook', **kw):
29 def write(self, output, resources, notebook_name='notebook', **kw):
30 """
30 """
31 Consume and write Jinja output.
31 Consume and write Jinja output.
32
32
33 See base for more...
33 See base for more...
34 """
34 """
35
35
36 if 'outputs' in resources:
36 if isinstance(resources['outputs'], dict):
37 print("outputs extracted from %s" % notebook_name)
37 print("outputs extracted from %s" % notebook_name)
38 print('-' * 80)
38 print('-' * 80)
39 pprint(resources['outputs'], indent=2, width=70)
39 pprint(resources['outputs'], indent=2, width=70)
40 else:
40 else:
41 print("no outputs extracted from %s" % notebook_name)
41 print("no outputs extracted from %s" % notebook_name)
42 print('=' * 80)
42 print('=' * 80)
General Comments 0
You need to be logged in to leave comments. Login now