Show More
@@ -1,154 +1,155 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | |||
3 | """NBConvert is a utility for conversion of IPYNB files. |
|
3 | """NBConvert is a utility for conversion of IPYNB files. | |
4 |
|
4 | |||
5 | Commandline interface for the NBConvert conversion utility. Read the |
|
5 | Commandline interface for the NBConvert conversion utility. Read the | |
6 | readme.rst for usage information |
|
6 | readme.rst for usage information | |
7 | """ |
|
7 | """ | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 | #Copyright (c) 2013, the IPython Development Team. |
|
9 | #Copyright (c) 2013, the IPython Development Team. | |
10 | # |
|
10 | # | |
11 | #Distributed under the terms of the Modified BSD License. |
|
11 | #Distributed under the terms of the Modified BSD License. | |
12 | # |
|
12 | # | |
13 | #The full license is in the file COPYING.txt, distributed with this software. |
|
13 | #The full license is in the file COPYING.txt, distributed with this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | #Imports |
|
17 | #Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | #Stdlib imports |
|
20 | #Stdlib imports | |
21 | from __future__ import print_function |
|
21 | from __future__ import print_function | |
22 | import sys |
|
22 | import sys | |
23 | import io |
|
23 | import io | |
24 | import os |
|
24 | import os | |
25 |
|
25 | |||
26 | #From IPython |
|
26 | #From IPython | |
27 | #All the stuff needed for the configurable things |
|
27 | #All the stuff needed for the configurable things | |
28 | from IPython.config.application import Application |
|
28 | from IPython.config.application import Application | |
29 | from IPython.config.loader import ConfigFileNotFound |
|
|||
30 | from IPython.utils.traitlets import Unicode, Bool |
|
|||
31 |
|
29 | |||
32 | #Local imports |
|
30 | #Local imports | |
33 |
from api.e |
|
31 | from nbconvert.api.convert import export_by_name | |
34 | from converters.config import GlobalConfigurable #TODO |
|
32 | from nbconvert.api.exporter import Exporter | |
35 | from converters.transformers import (ExtractFigureTransformer) #TODO |
|
|||
36 |
|
33 | |||
37 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
38 | #Globals and constants |
|
35 | #Globals and constants | |
39 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
40 | NBCONVERT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__))) |
|
37 | NBCONVERT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__))) | |
41 |
|
38 | |||
42 | #'Keys in resources' user prompt. |
|
39 | #'Keys in resources' user prompt. | |
43 | KEYS_PROMPT_HEAD = "====================== Keys in Resources ==================================" |
|
40 | KEYS_PROMPT_HEAD = "====================== Keys in Resources ==================================" | |
44 | KEYS_PROMPT_BODY = """ |
|
41 | KEYS_PROMPT_BODY = """ | |
45 | =========================================================================== |
|
42 | =========================================================================== | |
46 | You are responsible for writting these files into the appropriate |
|
43 | You are responsible for writting these files into the appropriate | |
47 | directorie(s) if need be. If you do not want to see this message, enable |
|
44 | directorie(s) if need be. If you do not want to see this message, enable | |
48 | the 'write' (boolean) flag of the converter. |
|
45 | the 'write' (boolean) flag of the converter. | |
49 | =========================================================================== |
|
46 | =========================================================================== | |
50 | """ |
|
47 | """ | |
51 |
|
48 | |||
52 | #Error Messages |
|
49 | #Error Messages | |
53 | ERROR_CONFIG_NOT_FOUND = "Config file for profile '%s' not found, giving up." |
|
50 | ERROR_CONFIG_NOT_FOUND = "Config file for profile '%s' not found, giving up." | |
54 |
|
51 | |||
55 | #----------------------------------------------------------------------------- |
|
52 | #----------------------------------------------------------------------------- | |
56 | #Classes and functions |
|
53 | #Classes and functions | |
57 | #----------------------------------------------------------------------------- |
|
54 | #----------------------------------------------------------------------------- | |
58 | class NbconvertApp(Application): |
|
55 | class NbconvertApp(Application): | |
59 | """A basic application to convert ipynb files""" |
|
56 | """A basic application to convert ipynb files""" | |
60 |
|
57 | |||
61 | aliases = { |
|
58 | aliases = { | |
62 | 'stdout':'NbconvertApp.stdout', |
|
59 | 'stdout':'NbconvertApp.stdout', | |
63 | 'write':'NbconvertApp.write' |
|
60 | 'write':'NbconvertApp.write' | |
64 | } |
|
61 | } | |
65 |
|
62 | |||
66 | flags = {} |
|
63 | flags = {} | |
67 | flags['no-stdout'] = ( |
|
64 | flags['no-stdout'] = ( | |
68 | {'NbconvertApp' : {'stdout' : False}}, |
|
65 | {'NbconvertApp' : {'stdout' : False}}, | |
69 | """Do not print converted file to stdout, equivalent to |
|
66 | """Do not print converted file to stdout, equivalent to | |
70 | --stdout=False""" |
|
67 | --stdout=False""" | |
71 | ) |
|
68 | ) | |
72 |
|
69 | |||
73 | def __init__(self, **kwargs): |
|
70 | def __init__(self, **kwargs): | |
74 | """Public constructor""" |
|
71 | """Public constructor""" | |
75 |
|
72 | |||
76 | #Call base class |
|
73 | #Call base class | |
77 | super(NbconvertApp, self).__init__(**kwargs) |
|
74 | super(NbconvertApp, self).__init__(**kwargs) | |
78 |
|
75 | |||
79 | #Register class here to have help with help all |
|
76 | #Register class here to have help with help all | |
80 | self.classes.insert(0, Exporter) |
|
77 | self.classes.insert(0, Exporter) | |
81 | self.classes.insert(0, ExtractFigureTransformer) |
|
|||
82 | self.classes.insert(0, GlobalConfigurable) |
|
|||
83 |
|
78 | |||
84 |
|
79 | |||
85 | def start(self, argv=None): |
|
80 | def start(self, argv=None): | |
86 | """Convert a notebook in one step""" |
|
81 | """Convert a notebook in one step""" | |
87 |
|
82 | |||
88 | #Parse the commandline options. |
|
83 | #Parse the commandline options. | |
89 | self.parse_command_line(argv) |
|
84 | self.parse_command_line(argv) | |
90 |
|
85 | |||
91 | #Call base |
|
86 | #Call base | |
92 | super(NbconvertApp, self).start() |
|
87 | super(NbconvertApp, self).start() | |
93 |
|
88 | |||
94 | #The last arguments in chain of arguments will be used as conversion |
|
89 | #The last arguments in chain of arguments will be used as conversion type | |
95 |
ipynb_file = (self.extra_args |
|
90 | ipynb_file = (self.extra_args)[2] | |
96 |
|
91 | export_type = (self.extra_args)[1] | ||
97 | #If you are writting a custom transformer, append it to the dictionary |
|
|||
98 | #below. |
|
|||
99 | userpreprocessors = {} |
|
|||
100 |
|
||||
101 | #Create the Jinja template exporter. TODO: Add ability to |
|
|||
102 | #import in IPYNB aswell |
|
|||
103 | exporter = Exporter(config=self.config, preprocessors=userpreprocessors,export_format=export_format) |
|
|||
104 |
|
92 | |||
105 | #Export |
|
93 | #Export | |
106 |
output, resources = export |
|
94 | output, resources, exporter = export_by_name(ipynb_file, export_type) | |
107 | if exporter.stdout : |
|
95 | ||
|
96 | destination_filename = None | |||
|
97 | destination_directory = None | |||
|
98 | if exporter.write: | |||
|
99 | ||||
|
100 | #Get the file name without the '.ipynb' (6 chars) extension and then | |||
|
101 | #remove any addition periods and spaces. The resulting name will | |||
|
102 | #be used to create the directory that the files will be exported | |||
|
103 | #into. | |||
|
104 | out_root = ipynb_file[:-6].replace('.', '_').replace(' ', '_') | |||
|
105 | destination_filename = os.path.join(out_root+'.'+exporter.fileext) | |||
|
106 | ||||
|
107 | destination_directory = out_root+'_files' | |||
|
108 | if not os.path.exists(destination_directory): | |||
|
109 | os.mkdir(destination_directory) | |||
|
110 | ||||
|
111 | #Write the results | |||
|
112 | if exporter.stdout or exporter.write: | |||
|
113 | self._write_results(exporter.stdout, destination_filename, destination_directory, output, resources) | |||
|
114 | ||||
|
115 | ||||
|
116 | def _write_results(self, stdout, destination_filename, destination_directory, output, resources): | |||
|
117 | if stdout: | |||
108 | print(output.encode('utf-8')) |
|
118 | print(output.encode('utf-8')) | |
109 |
|
119 | |||
110 | #Get the file name without the '.ipynb' (6 chars) extension and then |
|
|||
111 | #remove any addition periods and spaces. The resulting name will |
|
|||
112 | #be used to create the directory that the files will be exported |
|
|||
113 | #into. |
|
|||
114 | out_root = ipynb_file[:-6].replace('.', '_').replace(' ', '_') |
|
|||
115 |
|
||||
116 | #Write file output from conversion. |
|
120 | #Write file output from conversion. | |
117 | if exporter.write : |
|
121 | if not destination_filename is None: | |
118 |
with io.open( |
|
122 | with io.open(destination_filename, 'w') as f: | |
119 | f.write(output) |
|
123 | f.write(output) | |
120 |
|
124 | |||
121 | #Output any associate figures into the same "root" directory. |
|
125 | #Output any associate figures into the same "root" directory. | |
122 | binkeys = resources.get('figures', {}).get('binary',{}).keys() |
|
126 | binkeys = resources.get('figures', {}).get('binary',{}).keys() | |
123 | textkeys = resources.get('figures', {}).get('text',{}).keys() |
|
127 | textkeys = resources.get('figures', {}).get('text',{}).keys() | |
124 | if binkeys or textkeys : |
|
128 | if binkeys or textkeys : | |
125 | if exporter.write: |
|
129 | if not destination_directory is None: | |
126 | files_dir = out_root+'_files' |
|
|||
127 | if not os.path.exists(out_root+'_files'): |
|
|||
128 | os.mkdir(files_dir) |
|
|||
129 | for key in binkeys: |
|
130 | for key in binkeys: | |
130 |
with io.open(os.path.join( |
|
131 | with io.open(os.path.join(destination_directory, key), 'wb') as f: | |
131 | f.write(resources['figures']['binary'][key]) |
|
132 | f.write(resources['figures']['binary'][key]) | |
132 | for key in textkeys: |
|
133 | for key in textkeys: | |
133 |
with io.open(os.path.join( |
|
134 | with io.open(os.path.join(destination_directory, key), 'w') as f: | |
134 | f.write(resources['figures']['text'][key]) |
|
135 | f.write(resources['figures']['text'][key]) | |
135 |
|
136 | |||
136 | #Figures that weren't exported which will need to be created by the |
|
137 | #Figures that weren't exported which will need to be created by the | |
137 | #user. Tell the user what figures these are. |
|
138 | #user. Tell the user what figures these are. | |
138 |
|
|
139 | if stdout: | |
139 | print(KEYS_PROMPT_HEAD) |
|
140 | print(KEYS_PROMPT_HEAD) | |
140 | print(resources['figures'].keys()) |
|
141 | print(resources['figures'].keys()) | |
141 | print(KEYS_PROMPT_BODY) |
|
142 | print(KEYS_PROMPT_BODY) | |
142 |
|
143 | |||
143 | #----------------------------------------------------------------------------- |
|
144 | #----------------------------------------------------------------------------- | |
144 | #Script main |
|
145 | #Script main | |
145 | #----------------------------------------------------------------------------- |
|
146 | #----------------------------------------------------------------------------- | |
146 | def main(): |
|
147 | def main(): | |
147 | """Convert a notebook in one step""" |
|
148 | """Convert a notebook in one step""" | |
148 |
|
149 | |||
149 | app = NbconvertApp.instance() |
|
150 | app = NbconvertApp.instance() | |
150 | app.description = __doc__ |
|
151 | app.description = __doc__ | |
151 | app.run(argv=sys.argv) |
|
152 | app.run(argv=sys.argv) | |
152 |
|
153 | |||
153 | if __name__ == '__main__': |
|
154 | if __name__ == '__main__': | |
154 | main() No newline at end of file |
|
155 | main() |
@@ -1,21 +1,83 b'' | |||||
1 | """Latex transformer. |
|
1 | """Latex transformer. | |
2 |
|
2 | |||
3 | Module that allows latex output notebooks to be conditioned before |
|
3 | Module that allows latex output notebooks to be conditioned before | |
4 | they are converted. |
|
4 | they are converted. | |
5 | """ |
|
5 | """ | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (c) 2013, the IPython Development Team. |
|
7 | # Copyright (c) 2013, the IPython Development Team. | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the Modified BSD License. |
|
9 | # Distributed under the terms of the Modified BSD License. | |
10 | # |
|
10 | # | |
11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
11 | # The full license is in the file COPYING.txt, distributed with this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
|
14 | from .exporter import Exporter | |||
|
15 | ||||
|
16 | from .html import HtmlExporter | |||
|
17 | from .latex import LatexExporter | |||
|
18 | from .markdown import MarkdownExporter | |||
|
19 | from .python import PythonExporter | |||
|
20 | from .reveal import RevealExporter | |||
|
21 | from .rst import RstExporter | |||
|
22 | from .sphinx import SphinxExporter | |||
|
23 | ||||
|
24 | from IPython.nbformat.v3.nbbase import NotebookNode | |||
|
25 | ||||
14 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
15 | # Functions |
|
27 | # Functions | |
16 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
17 |
|
29 | |||
18 | def export_sphinx_report(nb, config=None): |
|
30 | def export(nb, config=None, transformers=None, filters=None, exporter_type=Exporter): | |
19 |
|
|
31 | ||
|
32 | #Check arguments | |||
|
33 | if exporter_type is None: | |||
|
34 | raise TypeError("Exporter is None") | |||
|
35 | elif not isinstance(exporter_type, Exporter): | |||
|
36 | raise TypeError("Exporter type does not inherit from Exporter (base)") | |||
|
37 | ||||
|
38 | if nb is None: | |||
|
39 | raise TypeError("nb is None") | |||
|
40 | ||||
|
41 | #Create the exporter | |||
|
42 | exporter_instance = exporter_type(transformers, filters, config) | |||
|
43 | ||||
|
44 | #Try to convert the notebook using the appropriate conversion function. | |||
|
45 | if isinstance(nb, NotebookNode): | |||
|
46 | return exporter_instance.from_notebook_node(nb), exporter_instance | |||
|
47 | elif isinstance(nb, str): | |||
|
48 | return exporter_instance.from_filename(nb), exporter_instance | |||
|
49 | else: | |||
|
50 | return exporter_instance.from_file(nb), exporter_instance | |||
|
51 | ||||
|
52 | ||||
|
53 | def export_sphinx(nb, config=None, transformers=None, filters=None): | |||
|
54 | return export(nb, config, transformers, filters, SphinxExporter) | |||
|
55 | ||||
|
56 | def export_html(nb, config=None, transformers=None, filters=None): | |||
|
57 | return export(nb, config, transformers, filters, HtmlExporter) | |||
|
58 | ||||
|
59 | def export_latex(nb, config=None, transformers=None, filters=None): | |||
|
60 | return export(nb, config, transformers, filters, LatexExporter) | |||
|
61 | ||||
|
62 | def export_markdown(nb, config=None, transformers=None, filters=None): | |||
|
63 | return export(nb, config, transformers, filters, MarkdownExporter) | |||
|
64 | ||||
|
65 | def export_python(nb, config=None, transformers=None, filters=None): | |||
|
66 | return export(nb, config, transformers, filters, PythonExporter) | |||
|
67 | ||||
|
68 | def export_reveal(nb, config=None, transformers=None, filters=None): | |||
|
69 | return export(nb, config, transformers, filters, RevealExporter) | |||
|
70 | ||||
|
71 | def export_rst(nb, config=None, transformers=None, filters=None): | |||
|
72 | return export(nb, config, transformers, filters, RstExporter) | |||
|
73 | ||||
|
74 | EXPORT_FUNCTIONS = {"sphinx": export_sphinx, | |||
|
75 | "html": export_html, | |||
|
76 | "latex": export_latex, | |||
|
77 | "markdown": export_markdown, | |||
|
78 | "python": export_python, | |||
|
79 | "reveal": export_reveal, | |||
|
80 | "rst": export_rst} | |||
20 |
|
81 | |||
21 | #TODO: Add basic export/import utility functions. |
|
82 | def export_by_name(nb, template_name, config=None, transformers=None, filters=None): | |
|
83 | return EXPORT_FUNCTIONS[template_name](nb, config, transformers, filters) No newline at end of file |
@@ -1,285 +1,219 b'' | |||||
1 | """Exporter for the notebook conversion pipeline. |
|
1 | """Exporter for the notebook conversion pipeline. | |
2 |
|
2 | |||
3 | This module defines Exporter, a highly configurable converter |
|
3 | This module defines Exporter, a highly configurable converter | |
4 | that uses Jinja2 to export notebook files into different format. |
|
4 | that uses Jinja2 to export notebook files into different format. | |
5 |
|
5 | |||
6 | You can register both pre-transformers that will act on the notebook format |
|
6 | You can register both pre-transformers that will act on the notebook format | |
7 | before conversion and jinja filter that would then be available in the templates |
|
7 | before conversion and jinja filter that would then be available in the templates | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (c) 2013, the IPython Development Team. |
|
11 | # Copyright (c) 2013, the IPython Development Team. | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the Modified BSD License. |
|
13 | # Distributed under the terms of the Modified BSD License. | |
14 | # |
|
14 | # | |
15 | # The full license is in the file COPYING.txt, distributed with this software. |
|
15 | # The full license is in the file COPYING.txt, distributed with this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | from __future__ import print_function, absolute_import |
|
21 | from __future__ import print_function, absolute_import | |
22 |
|
22 | |||
23 | # Stdlib imports |
|
23 | # Stdlib imports | |
24 | import io |
|
24 | import io | |
25 | import os |
|
25 | import os | |
26 | import copy |
|
|||
27 |
|
26 | |||
28 | # IPython imports |
|
27 | # IPython imports | |
29 | from IPython.config.configurable import Configurable |
|
28 | from IPython.config.configurable import Configurable | |
30 | from IPython.nbformat import current as nbformat |
|
29 | from IPython.nbformat import current as nbformat | |
31 | from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool |
|
30 | from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool | |
32 | from IPython.utils.text import indent |
|
31 | from IPython.utils.text import indent | |
33 |
|
32 | |||
34 | # other libs/dependencies |
|
33 | # other libs/dependencies | |
35 | from jinja2 import Environment, FileSystemLoader |
|
34 | from jinja2 import Environment, FileSystemLoader | |
36 | from markdown import markdown |
|
35 | from markdown import markdown | |
37 |
|
36 | |||
38 | # local import |
|
37 | # local import | |
39 | import filters.strings |
|
38 | import filters.strings | |
40 | import filters.markdown |
|
39 | import filters.markdown | |
41 | import filters.latex |
|
40 | import filters.latex | |
42 | import filters.datatypefilter |
|
41 | import filters.datatypefilter | |
43 | import filters.pygments |
|
42 | import filters.pygments | |
44 | import filters.ansi |
|
43 | import filters.ansi | |
45 |
|
44 | |||
46 | import transformers.extractfigure |
|
45 | import transformers.extractfigure | |
47 | import transformers.coalescestreams |
|
46 | import transformers.coalescestreams | |
48 |
|
47 | |||
49 |
|
48 | |||
50 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
51 | # Globals and constants |
|
50 | # Globals and constants | |
52 | #----------------------------------------------------------------------------- |
|
51 | #----------------------------------------------------------------------------- | |
53 |
|
52 | |||
54 | #Standard Jinja2 environment constants |
|
53 | #Standard Jinja2 environment constants | |
55 | TEMPLATE_PATH = "/../templates/" |
|
54 | TEMPLATE_PATH = "/../templates/" | |
56 | TEMPLATE_SKELETON_PATH = "/../templates/skeleton/" |
|
55 | TEMPLATE_SKELETON_PATH = "/../templates/skeleton/" | |
57 | TEMPLATE_EXTENSION = ".tpl" |
|
|||
58 |
|
56 | |||
59 | #Jinja2 extensions to load. |
|
57 | #Jinja2 extensions to load. | |
60 | JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols'] |
|
58 | JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols'] | |
61 |
|
59 | |||
62 | #----------------------------------------------------------------------------- |
|
60 | #----------------------------------------------------------------------------- | |
63 | # Classes and functions |
|
61 | # Classes and functions | |
64 | #----------------------------------------------------------------------------- |
|
62 | #----------------------------------------------------------------------------- | |
65 | class Exporter(Configurable): |
|
63 | class Exporter(Configurable): | |
66 | """ A Jinja2 base converter templates |
|
|||
67 |
|
||||
68 | Pre-process the IPYNB files, feed it through Jinja2 templates, |
|
|||
69 | and spit an converted files and a data object with other data |
|
|||
70 | should be mostly configurable |
|
|||
71 | """ |
|
|||
72 |
|
||||
73 | pre_transformer_order = List(['haspyout_transformer'], |
|
64 | pre_transformer_order = List(['haspyout_transformer'], | |
74 | config=True, |
|
65 | config=True, | |
75 | help= """ |
|
66 | help= """ | |
76 | An ordered list of pre-transformer to apply to the IPYNB |
|
67 | An ordered list of pre-transformer to apply to the IPYNB | |
77 | file before running through templates |
|
68 | file before running through templates | |
78 | """ |
|
69 | """ | |
79 | ) |
|
70 | ) | |
80 |
|
71 | |||
81 | template_file = Unicode( |
|
72 | template_file = Unicode( | |
82 | '', config=True, |
|
73 | '', config=True, | |
83 | help="Name of the template file to use") |
|
74 | help="Name of the template file to use") | |
84 |
|
75 | |||
85 | file_extension = Unicode( |
|
76 | file_extension = Unicode( | |
86 | 'txt', config=True, |
|
77 | 'txt', config=True, | |
87 | help="Extension of the file that should be written to disk" |
|
78 | help="Extension of the file that should be written to disk" | |
88 | ) |
|
79 | ) | |
89 |
|
80 | |||
90 | stdout = Bool( |
|
81 | stdout = Bool( | |
91 | True, config=True, |
|
82 | True, config=True, | |
92 | help="""Whether to print the converted IPYNB file to stdout |
|
83 | help="""Whether to print the converted IPYNB file to stdout | |
93 | "use full do diff files without actually writing a new file""" |
|
84 | "use full do diff files without actually writing a new file""" | |
94 | ) |
|
85 | ) | |
95 |
|
86 | |||
96 | write = Bool( |
|
87 | write = Bool( | |
97 | False, config=True, |
|
88 | False, config=True, | |
98 | help="""Should the converted notebook file be written to disk |
|
89 | help="""Should the converted notebook file be written to disk | |
99 | along with potential extracted resources.""" |
|
90 | along with potential extracted resources.""" | |
100 | ) |
|
91 | ) | |
101 |
|
92 | |||
|
93 | #Extension that the template files use. | |||
|
94 | template_extension = ".tpl" | |||
|
95 | ||||
102 | #Processors that process the input data prior to the export, set in the |
|
96 | #Processors that process the input data prior to the export, set in the | |
103 | #constructor for this class. |
|
97 | #constructor for this class. | |
104 | preprocessors = [] |
|
98 | preprocessors = [] | |
105 |
|
99 | |||
106 | # Public Constructor ##################################################### |
|
100 | # Public Constructor ##################################################### | |
107 |
|
101 | |||
108 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): |
|
102 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): | |
109 | """ Init a new converter. |
|
|||
110 |
|
||||
111 | config: the Configurable config object to pass around. |
|
|||
112 |
|
||||
113 | preprocessors: dict of **available** key/value function to run on |
|
|||
114 | ipynb json data before conversion to extract/in-line file. |
|
|||
115 | See `transformer.py` and `ConfigurableTransformers` |
|
|||
116 |
|
||||
117 | set the order in which the transformers should apply |
|
|||
118 | with the `pre_transformer_order` trait of this class |
|
|||
119 |
|
||||
120 | transformers registered by this key will take precedence on |
|
|||
121 | default one. |
|
|||
122 |
|
||||
123 | jinja_filters: dict of supplementary jinja filter that should be made |
|
|||
124 | available in template. If those are of Configurable Class type, |
|
|||
125 | they will be instanciated with the config object as argument. |
|
|||
126 |
|
||||
127 | user defined filter will overwrite the one available by default. |
|
|||
128 | """ |
|
|||
129 |
|
103 | |||
130 | #Call the base class constructor |
|
104 | #Call the base class constructor | |
131 | super(Exporter, self).__init__(config=config, **kw) |
|
105 | super(Exporter, self).__init__(config=config, **kw) | |
132 |
|
106 | |||
133 | #Standard environment |
|
107 | #Standard environment | |
134 | self.ext = TEMPLATE_EXTENSION |
|
|||
135 | self._init_environment() |
|
108 | self._init_environment() | |
136 |
|
109 | |||
137 | #TODO: Implement reflection style methods to get user transformers. |
|
110 | #TODO: Implement reflection style methods to get user transformers. | |
138 | #if not preprocessors is None: |
|
111 | #if not preprocessors is None: | |
139 | # for name in self.pre_transformer_order: |
|
112 | # for name in self.pre_transformer_order: | |
140 | # # get the user-defined transformer first |
|
113 | # # get the user-defined transformer first | |
141 | # transformer = preprocessors.get(name, getattr(trans, name, None)) |
|
114 | # transformer = preprocessors.get(name, getattr(trans, name, None)) | |
142 | # if isinstance(transformer, MetaHasTraits): |
|
115 | # if isinstance(transformer, MetaHasTraits): | |
143 | # transformer = transformer(config=config) |
|
116 | # transformer = transformer(config=config) | |
144 | # self.preprocessors.append(transformer) |
|
117 | # self.preprocessors.append(transformer) | |
145 |
|
118 | |||
146 | #Add transformers |
|
119 | #Add transformers | |
147 | self._register_transformers() |
|
120 | self._register_transformers() | |
148 |
|
121 | |||
149 | #Add filters to the Jinja2 environment |
|
122 | #Add filters to the Jinja2 environment | |
150 | self._register_filters() |
|
123 | self._register_filters() | |
151 |
|
124 | |||
152 | #Load user filters. Overwrite existing filters if need be. |
|
125 | #Load user filters. Overwrite existing filters if need be. | |
153 | if not jinja_filters is None: |
|
126 | if not jinja_filters is None: | |
154 | for key, user_filter in jinja_filters.iteritems(): |
|
127 | for key, user_filter in jinja_filters.iteritems(): | |
155 | if isinstance(user_filter, MetaHasTraits): |
|
128 | if isinstance(user_filter, MetaHasTraits): | |
156 | self.environment.filters[key] = user_filter(config=config) |
|
129 | self.environment.filters[key] = user_filter(config=config) | |
157 | else: |
|
130 | else: | |
158 | self.environment.filters[key] = user_filter |
|
131 | self.environment.filters[key] = user_filter | |
159 |
|
||||
160 |
|
||||
161 | #Set the default datatype priority. |
|
|||
162 | self._set_datatype_priority(['svg', 'png', 'latex', 'jpg', 'jpeg','text']) |
|
|||
163 |
|
||||
164 |
|
132 | |||
165 | # Public methods ######################################### |
|
133 | # Public methods ######################################### | |
166 |
|
134 | |||
167 | def from_notebook_node(self, nb): |
|
135 | def from_notebook_node(self, nb): | |
168 | """Export NotebookNode instance |
|
|||
169 |
|
||||
170 | nb: NotebookNode to export. |
|
|||
171 |
|
||||
172 | Returns both the converted ipynb file and a dict containing the |
|
|||
173 | resources created along the way via the transformers and Jinja2 |
|
|||
174 | processing. |
|
|||
175 | """ |
|
|||
176 |
|
||||
177 | nb, resources = self._preprocess(nb) |
|
136 | nb, resources = self._preprocess(nb) | |
178 |
|
137 | |||
179 | #Load the template file. |
|
138 | #Load the template file. | |
180 | self.template = self.environment.get_template(self.template_file+self.ext) |
|
139 | self.template = self.environment.get_template(self.template_file+self.template_extension) | |
181 |
|
140 | |||
182 | return self.template.render(nb=nb, resources=resources), resources |
|
141 | return self.template.render(nb=nb, resources=resources), resources | |
183 |
|
142 | |||
184 |
|
143 | |||
185 | def from_filename(self, filename): |
|
144 | def from_filename(self, filename): | |
186 | """Read and export a notebook from a filename |
|
|||
187 |
|
||||
188 | filename: Filename of the notebook file to export. |
|
|||
189 |
|
||||
190 | Returns both the converted ipynb file and a dict containing the |
|
|||
191 | resources created along the way via the transformers and Jinja2 |
|
|||
192 | processing. |
|
|||
193 | """ |
|
|||
194 | with io.open(filename) as f: |
|
145 | with io.open(filename) as f: | |
195 | return self.from_notebook_node(nbformat.read(f, 'json')) |
|
146 | return self.from_notebook_node(nbformat.read(f, 'json')) | |
196 |
|
147 | |||
197 |
|
148 | |||
198 | def from_file(self, file_stream): |
|
149 | def from_file(self, file_stream): | |
199 | """Read and export a notebook from a file stream |
|
|||
200 |
|
||||
201 | file_stream: File handle of file that contains notebook data. |
|
|||
202 |
|
||||
203 | Returns both the converted ipynb file and a dict containing the |
|
|||
204 | resources created along the way via the transformers and Jinja2 |
|
|||
205 | processing. |
|
|||
206 | """ |
|
|||
207 |
|
||||
208 | return self.from_notebook_node(nbformat.read(file_stream, 'json')) |
|
150 | return self.from_notebook_node(nbformat.read(file_stream, 'json')) | |
209 |
|
151 | |||
210 |
|
152 | |||
211 | def register_transformer(self, transformer): |
|
153 | def register_transformer(self, transformer): | |
212 | if MetaHasTraits(transformer): |
|
154 | if MetaHasTraits(transformer): | |
213 |
|
|
155 | transformer_instance = transformer(config=self.config) | |
|
156 | self.preprocessors.append(transformer_instance) | |||
|
157 | return transformer_instance | |||
214 | else: |
|
158 | else: | |
215 | self.preprocessors.append(transformer) |
|
159 | self.preprocessors.append(transformer) | |
|
160 | return transformer | |||
216 |
|
161 | |||
217 |
|
162 | |||
218 | def register_filter(self, name, filter): |
|
163 | def register_filter(self, name, filter): | |
219 | if MetaHasTraits(filter): |
|
164 | if MetaHasTraits(filter): | |
220 | self.environment.filters[name] = filter(config=self.config) |
|
165 | self.environment.filters[name] = filter(config=self.config) | |
221 | else: |
|
166 | else: | |
222 | self.environment.filters[name] = filter |
|
167 | self.environment.filters[name] = filter | |
223 | return self.environment.filters[name] |
|
168 | return self.environment.filters[name] | |
224 |
|
169 | |||
|
170 | ||||
225 | # Protected and Private methods ######################################### |
|
171 | # Protected and Private methods ######################################### | |
226 |
|
172 | |||
227 | def _register_transformers(self): |
|
173 | def _register_transformers(self): | |
228 | self.register_transformer(transformers.coalescestreams.coalesce_streams) |
|
174 | self.register_transformer(transformers.coalescestreams.coalesce_streams) | |
229 |
|
175 | |||
230 | #Remember the figure extraction transformer so it can be enabled and |
|
176 | #Remember the figure extraction transformer so it can be enabled and | |
231 | #disabled easily later. |
|
177 | #disabled easily later. | |
232 | self.extract_figure_transformer = self.register_transformer(transformers.extractfigure.ExtractFigureTransformer) |
|
178 | self.extract_figure_transformer = self.register_transformer(transformers.extractfigure.ExtractFigureTransformer) | |
233 | self.extract_figure_transformer.enabled = False |
|
|||
234 |
|
179 | |||
235 |
|
180 | |||
236 | def _register_filters(self): |
|
181 | def _register_filters(self): | |
237 | self.register_filter('indent', indent) |
|
182 | self.register_filter('indent', indent) | |
238 | self.register_filter('markdown', markdown) |
|
183 | self.register_filter('markdown', markdown) | |
239 | self.register_filter('ansi2html', filters.ansi.ansi2html) |
|
184 | self.register_filter('ansi2html', filters.ansi.ansi2html) | |
240 | self.register_filter('filter_data_type', filters.datatypefilter.DataTypeFilter) |
|
185 | self.register_filter('filter_data_type', filters.datatypefilter.DataTypeFilter) | |
241 | self.register_filter('get_lines', filters.strings.get_lines) |
|
186 | self.register_filter('get_lines', filters.strings.get_lines) | |
242 | self.register_filter('highlight', filters.pygments.highlight) |
|
187 | self.register_filter('highlight', filters.pygments.highlight) | |
243 | self.register_filter('highlight2html', filters.pygments.highlight) |
|
188 | self.register_filter('highlight2html', filters.pygments.highlight) | |
244 | self.register_filter('highlight2latex', filters.pygments.highlight2latex) |
|
189 | self.register_filter('highlight2latex', filters.pygments.highlight2latex) | |
245 | self.register_filter('markdown2latex', filters.markdown.markdown2latex) |
|
190 | self.register_filter('markdown2latex', filters.markdown.markdown2latex) | |
246 | self.register_filter('markdown2rst', filters.markdown.markdown2rst) |
|
191 | self.register_filter('markdown2rst', filters.markdown.markdown2rst) | |
247 | self.register_filter('pycomment', filters.strings.python_comment) |
|
192 | self.register_filter('pycomment', filters.strings.python_comment) | |
248 | self.register_filter('rm_ansi', filters.ansi.remove_ansi) |
|
193 | self.register_filter('rm_ansi', filters.ansi.remove_ansi) | |
249 | self.register_filter('rm_dollars', filters.strings.strip_dollars) |
|
194 | self.register_filter('rm_dollars', filters.strings.strip_dollars) | |
250 | self.register_filter('rm_fake', filters.strings.rm_fake) |
|
195 | self.register_filter('rm_fake', filters.strings.rm_fake) | |
251 | self.register_filter('rm_math_space', filters.latex.rm_math_space) |
|
196 | self.register_filter('rm_math_space', filters.latex.rm_math_space) | |
252 | self.register_filter('wrap', filters.strings.wrap) |
|
197 | self.register_filter('wrap', filters.strings.wrap) | |
253 |
|
||||
254 |
|
||||
255 | def _set_datatype_priority(self, priority): |
|
|||
256 | self.extract_figure_transformer.display_data_priority=copy.copy(priority) |
|
|||
257 | self.display_data_priority=copy.copy(priority) |
|
|||
258 |
|
198 | |||
259 |
|
199 | |||
260 | def _init_environment(self): |
|
200 | def _init_environment(self): | |
261 | self.environment = Environment( |
|
201 | self.environment = Environment( | |
262 | loader=FileSystemLoader([ |
|
202 | loader=FileSystemLoader([ | |
263 | os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_PATH, |
|
203 | os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_PATH, | |
264 | os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_SKELETON_PATH, |
|
204 | os.path.dirname(os.path.realpath(__file__)) + TEMPLATE_SKELETON_PATH, | |
265 | ]), |
|
205 | ]), | |
266 | extensions=JINJA_EXTENSIONS |
|
206 | extensions=JINJA_EXTENSIONS | |
267 | ) |
|
207 | ) | |
268 |
|
208 | |||
269 |
|
209 | |||
270 | def _preprocess(self, nb): |
|
210 | def _preprocess(self, nb): | |
271 | """ Preprocess the notebook using the transformers specific |
|
|||
272 | for the current export format. |
|
|||
273 |
|
||||
274 | nb: Notebook to preprocess |
|
|||
275 | """ |
|
|||
276 |
|
211 | |||
277 | #Dict of 'resources' that can be filled by the preprocessors. |
|
212 | #Dict of 'resources' that can be filled by the preprocessors. | |
278 | resources = {} |
|
213 | resources = {} | |
279 |
|
214 | |||
280 | #Run each transformer on the notebook. Carry the output along |
|
215 | #Run each transformer on the notebook. Carry the output along | |
281 | #to each transformer |
|
216 | #to each transformer | |
282 | for transformer in self.preprocessors: |
|
217 | for transformer in self.preprocessors: | |
283 | nb, resources = transformer(nb, resources) |
|
218 | nb, resources = transformer(nb, resources) | |
284 | return nb, resources |
|
219 | return nb, resources | |
285 |
|
@@ -1,47 +1,42 b'' | |||||
1 |
|
|
1 | """TODO: Docstring | |
2 | """ |
|
2 | """ | |
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 | # local import |
|
16 | # local import | |
17 | import exporter |
|
17 | import exporter | |
18 | import transformers.csshtmlheader |
|
18 | import transformers.csshtmlheader | |
|
19 | from IPython.utils.traitlets import Unicode | |||
19 |
|
20 | |||
20 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
21 | # Classes |
|
22 | # Classes | |
22 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
23 | class HtmlExporter(exporter.Exporter): |
|
24 | class HtmlExporter(exporter.Exporter): | |
24 |
|
25 | |||
25 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, full_html=True, **kw): |
|
26 | file_extension = Unicode( | |
26 |
|
27 | 'html', config=True, | ||
27 | #Call base class constructor. |
|
28 | help="Extension of the file that should be written to disk" | |
28 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
29 | ) | |
|
30 | ||||
|
31 | template_file = Unicode( | |||
|
32 | 'fullhtml', config=True, | |||
|
33 | help="Name of the template file to use") | |||
29 |
|
34 | |||
30 | #Set defaults |
|
|||
31 | self.file_extension = "html" |
|
|||
32 | self.extract_figure_transformer.enabled = True |
|
|||
33 |
|
||||
34 | #Load the correct template |
|
|||
35 | if full_html: |
|
|||
36 | self.template_file = "fullhtml" |
|
|||
37 | else: |
|
|||
38 | self.template_file = "basichtml" |
|
|||
39 |
|
||||
40 | def _register_transformers(self): |
|
35 | def _register_transformers(self): | |
41 |
|
36 | |||
42 | #Register the transformers of the base class. |
|
37 | #Register the transformers of the base class. | |
43 | super(exporter.Exporter, self)._register_transformers() |
|
38 | super(exporter.Exporter, self)._register_transformers() | |
44 |
|
39 | |||
45 | #Register latex transformer |
|
40 | #Register latex transformer | |
46 | self.register_transformer(transformers.csshtmlheader.CSSHtmlHeaderTransformer) |
|
41 | self.register_transformer(transformers.csshtmlheader.CSSHtmlHeaderTransformer) | |
47 | No newline at end of file |
|
42 |
@@ -1,114 +1,99 b'' | |||||
1 | """Latex exporter for the notebook conversion pipeline. |
|
|||
2 |
|
||||
3 | This module defines Exporter, a highly configurable converter |
|
|||
4 | that uses Jinja2 to export notebook files into different format. |
|
|||
5 |
|
||||
6 | You can register both pre-transformers that will act on the notebook format |
|
|||
7 | before conversion and jinja filter that would then be available in the templates |
|
|||
8 | """ |
|
|||
9 |
|
||||
10 |
|
|
1 | #----------------------------------------------------------------------------- | |
11 | # Copyright (c) 2013, the IPython Development Team. |
|
2 | # Copyright (c) 2013, the IPython Development Team. | |
12 | # |
|
3 | # | |
13 | # Distributed under the terms of the Modified BSD License. |
|
4 | # Distributed under the terms of the Modified BSD License. | |
14 | # |
|
5 | # | |
15 | # The full license is in the file COPYING.txt, distributed with this software. |
|
6 | # The full license is in the file COPYING.txt, distributed with this software. | |
16 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
17 |
|
8 | |||
18 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
10 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
21 |
|
12 | |||
22 | # Stdlib imports |
|
13 | # Stdlib imports | |
23 | import io |
|
|||
24 | import os |
|
14 | import os | |
25 |
|
15 | |||
26 | # IPython imports |
|
16 | # IPython imports | |
27 |
from IPython. |
|
17 | from IPython.utils.traitlets import Unicode | |
28 | from IPython.nbformat import current as nbformat |
|
|||
29 | from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Bool |
|
|||
30 | from IPython.utils.text import indent |
|
|||
31 |
|
18 | |||
32 | # other libs/dependencies |
|
19 | # other libs/dependencies | |
33 | from jinja2 import Environment, FileSystemLoader |
|
20 | from jinja2 import Environment, FileSystemLoader | |
34 | from markdown import markdown |
|
|||
35 |
|
21 | |||
36 | # local import |
|
22 | # local import | |
37 | import exporter |
|
23 | import exporter | |
38 | import filters.latex |
|
24 | import filters.latex | |
39 | import filters.pygments |
|
25 | import filters.pygments | |
40 | from transformers.latex import LatexTransformer |
|
26 | from transformers.latex import LatexTransformer | |
41 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
42 | # Globals and constants |
|
28 | # Globals and constants | |
43 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
44 |
|
30 | |||
45 | #Latex Jinja2 constants |
|
31 | #Latex Jinja2 constants | |
46 | LATEX_TEMPLATE_PATH = "/../templates/tex/" |
|
32 | LATEX_TEMPLATE_PATH = "/../templates/tex/" | |
47 | LATEX_TEMPLATE_SKELETON_PATH = "/../templates/tex/skeleton/" |
|
33 | LATEX_TEMPLATE_SKELETON_PATH = "/../templates/tex/skeleton/" | |
48 | LATEX_TEMPLATE_EXTENSION = ".tplx" |
|
|||
49 |
|
34 | |||
50 | #Special Jinja2 syntax that will not conflict when exporting latex. |
|
35 | #Special Jinja2 syntax that will not conflict when exporting latex. | |
51 | LATEX_JINJA_COMMENT_BLOCK = ["((=", "=))"] |
|
36 | LATEX_JINJA_COMMENT_BLOCK = ["((=", "=))"] | |
52 | LATEX_JINJA_VARIABLE_BLOCK = ["(((", ")))"] |
|
37 | LATEX_JINJA_VARIABLE_BLOCK = ["(((", ")))"] | |
53 | LATEX_JINJA_LOGIC_BLOCK = ["((*", "*))"] |
|
38 | LATEX_JINJA_LOGIC_BLOCK = ["((*", "*))"] | |
54 |
|
39 | |||
55 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
56 | # Classes and functions |
|
41 | # Classes and functions | |
57 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
58 | class LatexExporter(exporter.Exporter): |
|
43 | class LatexExporter(exporter.Exporter): | |
59 | """ A Jinja2 latex exporter |
|
|||
60 |
|
44 | |||
61 | Preprocess the ipynb files, feed it through jinja templates, |
|
45 | #Extension that the template files use. | |
62 | and spit an converted files and a data object with other data |
|
46 | template_extension = ".tplx" | |
63 | should be mostly configurable |
|
47 | ||
64 | """ |
|
48 | file_extension = Unicode( | |
|
49 | 'tex', config=True, | |||
|
50 | help="Extension of the file that should be written to disk") | |||
65 |
|
51 | |||
|
52 | template_file = Unicode( | |||
|
53 | 'latex_base', config=True, | |||
|
54 | help="Name of the template file to use") | |||
|
55 | ||||
66 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): |
|
56 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): | |
67 |
|
57 | |||
68 | #Call base class constructor. |
|
58 | #Call base class constructor. | |
69 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
59 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) | |
70 |
|
60 | |||
71 | #Set defaults |
|
61 | self.extract_figure_transformer.display_data_priority = ['latex', 'svg', 'png', 'jpg', 'jpeg' , 'text'] | |
72 | self.file_extension = "tex" |
|
|||
73 | self._set_datatype_priority(['latex', 'svg', 'png', 'jpg', 'jpeg' , 'text']) |
|
|||
74 | self.extract_figure_transformer.enabled = True |
|
|||
75 | self.extract_figure_transformer.extra_ext_map={'svg':'pdf'} |
|
62 | self.extract_figure_transformer.extra_ext_map={'svg':'pdf'} | |
76 | self.template_file = "latex_base" |
|
|||
77 |
|
63 | |||
78 |
|
64 | |||
79 | def _init_environment(self): |
|
65 | def _init_environment(self): | |
80 | self.ext = LATEX_TEMPLATE_EXTENSION |
|
|||
81 | self.environment = Environment( |
|
66 | self.environment = Environment( | |
82 | loader=FileSystemLoader([ |
|
67 | loader=FileSystemLoader([ | |
83 | os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_PATH, |
|
68 | os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_PATH, | |
84 | os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_SKELETON_PATH, |
|
69 | os.path.dirname(os.path.realpath(__file__)) + LATEX_TEMPLATE_SKELETON_PATH, | |
85 | ]), |
|
70 | ]), | |
86 | extensions=exporter.JINJA_EXTENSIONS |
|
71 | extensions=exporter.JINJA_EXTENSIONS | |
87 | ) |
|
72 | ) | |
88 |
|
73 | |||
89 | #Set special Jinja2 syntax that will not conflict with latex. |
|
74 | #Set special Jinja2 syntax that will not conflict with latex. | |
90 | self.environment.block_start_string = LATEX_JINJA_LOGIC_BLOCK[0] |
|
75 | self.environment.block_start_string = LATEX_JINJA_LOGIC_BLOCK[0] | |
91 | self.environment.block_end_string = LATEX_JINJA_LOGIC_BLOCK[1] |
|
76 | self.environment.block_end_string = LATEX_JINJA_LOGIC_BLOCK[1] | |
92 | self.environment.variable_start_string = LATEX_JINJA_VARIABLE_BLOCK[0] |
|
77 | self.environment.variable_start_string = LATEX_JINJA_VARIABLE_BLOCK[0] | |
93 | self.environment.variable_end_string = LATEX_JINJA_VARIABLE_BLOCK[1] |
|
78 | self.environment.variable_end_string = LATEX_JINJA_VARIABLE_BLOCK[1] | |
94 | self.environment.comment_start_string = LATEX_JINJA_COMMENT_BLOCK[0] |
|
79 | self.environment.comment_start_string = LATEX_JINJA_COMMENT_BLOCK[0] | |
95 | self.environment.comment_end_string = LATEX_JINJA_COMMENT_BLOCK[1] |
|
80 | self.environment.comment_end_string = LATEX_JINJA_COMMENT_BLOCK[1] | |
96 |
|
81 | |||
97 |
|
82 | |||
98 | def _register_filters(self): |
|
83 | def _register_filters(self): | |
99 |
|
84 | |||
100 | #Register the filters of the base class. |
|
85 | #Register the filters of the base class. | |
101 | super(exporter.Exporter, self)._register_filters() |
|
86 | super(exporter.Exporter, self)._register_filters() | |
102 |
|
87 | |||
103 | #Add latex filters to the Jinja2 environment |
|
88 | #Add latex filters to the Jinja2 environment | |
104 | self.register_filter('escape_tex', filters.latex.escape_tex) |
|
89 | self.register_filter('escape_tex', filters.latex.escape_tex) | |
105 | self.register_filter('highlight', filters.pygments.highlight2latex) |
|
90 | self.register_filter('highlight', filters.pygments.highlight2latex) | |
106 |
|
91 | |||
107 | def _register_transformers(self): |
|
92 | def _register_transformers(self): | |
108 |
|
93 | |||
109 | #Register the transformers of the base class. |
|
94 | #Register the transformers of the base class. | |
110 | super(exporter.Exporter, self)._register_transformers() |
|
95 | super(exporter.Exporter, self)._register_transformers() | |
111 |
|
96 | |||
112 | #Register latex transformer |
|
97 | #Register latex transformer | |
113 | self.register_transformer(LatexTransformer) |
|
98 | self.register_transformer(LatexTransformer) | |
114 | No newline at end of file |
|
99 |
@@ -1,32 +1,29 b'' | |||||
1 | """TODO: Docstring |
|
|||
2 | """ |
|
|||
3 |
|
|
1 | ||
4 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
5 | # Copyright (c) 2013, the IPython Development Team. |
|
3 | # Copyright (c) 2013, the IPython Development Team. | |
6 | # |
|
4 | # | |
7 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
8 | # |
|
6 | # | |
9 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
10 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
11 |
|
9 | |||
12 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
11 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
15 |
|
13 | |||
16 | # local import |
|
14 | # local import | |
17 | import exporter |
|
15 | import exporter | |
|
16 | from IPython.utils.traitlets import Unicode | |||
18 |
|
17 | |||
19 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
20 | # Classes |
|
19 | # Classes | |
21 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
22 | class MarkdownExporter(exporter.Exporter): |
|
21 | class MarkdownExporter(exporter.Exporter): | |
23 |
|
22 | |||
24 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): |
|
23 | file_extension = Unicode( | |
25 |
|
24 | 'md', config=True, | ||
26 | #Call base class constructor. |
|
25 | help="Extension of the file that should be written to disk") | |
27 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
|||
28 |
|
26 | |||
29 | #Set defaults |
|
27 | template_file = Unicode( | |
30 | self.file_extension = "md" |
|
28 | 'markdown', config=True, | |
31 | self.extract_figure_transformer.enabled = True |
|
29 | help="Name of the template file to use") | |
32 | self.template_file = "markdown" |
|
@@ -1,34 +1,40 b'' | |||||
1 | """TODO: Docstring |
|
1 | """TODO: Docstring | |
2 | """ |
|
2 | """ | |
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 | # local import |
|
16 | # local import | |
17 | import exporter |
|
17 | import exporter | |
|
18 | from IPython.utils.traitlets import Unicode | |||
18 |
|
19 | |||
19 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
20 | # Classes |
|
21 | # Classes | |
21 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
22 | class PythonExporter(exporter.Exporter): |
|
23 | class PythonExporter(exporter.Exporter): | |
23 |
|
24 | |||
|
25 | file_extension = Unicode( | |||
|
26 | 'py', config=True, | |||
|
27 | help="Extension of the file that should be written to disk") | |||
|
28 | ||||
|
29 | template_file = Unicode( | |||
|
30 | 'python', config=True, | |||
|
31 | help="Name of the template file to use") | |||
|
32 | ||||
24 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, armor=False, **kw): |
|
33 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, armor=False, **kw): | |
25 |
|
34 | |||
26 | #Call base class constructor. |
|
35 | #Call base class constructor. | |
27 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
36 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) | |
28 |
|
37 | |||
29 | #Set defaults |
|
38 | #Set defaults | |
30 | self.file_extension = "py" |
|
39 | self.extract_figure_transformer.enabled = False | |
31 |
|
|
40 | ||
32 | self.template_file = "python-armor" |
|
|||
33 | else: |
|
|||
34 | self.template_file = "python" |
|
@@ -1,41 +1,41 b'' | |||||
1 |
|
|
1 | """TODO: Docstring | |
2 | """ |
|
2 | """ | |
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 | # local import |
|
16 | # local import | |
17 | import html_exporter |
|
17 | import html_exporter | |
18 | import transformers.revealhelp |
|
18 | import transformers.revealhelp | |
|
19 | from IPython.utils.traitlets import Unicode | |||
19 |
|
20 | |||
20 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
21 | # Classes |
|
22 | # Classes | |
22 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
23 | class RevealExporter(html_exporter.HtmlExporter): |
|
24 | class RevealExporter(html_exporter.HtmlExporter): | |
24 |
|
25 | |||
25 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): |
|
26 | file_extension = Unicode( | |
26 |
|
27 | 'reveal.html', config=True, | ||
27 | #Call base class constructor. |
|
28 | help="Extension of the file that should be written to disk") | |
28 | super(html_exporter.HtmlExporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
|||
29 |
|
||||
30 | #Set defaults |
|
|||
31 | self.file_extension = "reveal.html" |
|
|||
32 | self.template_file = "reveal" |
|
|||
33 |
|
29 | |||
|
30 | template_file = Unicode( | |||
|
31 | 'reveal', config=True, | |||
|
32 | help="Name of the template file to use") | |||
|
33 | ||||
34 | def _register_transformers(self): |
|
34 | def _register_transformers(self): | |
35 |
|
35 | |||
36 | #Register the transformers of the base class. |
|
36 | #Register the transformers of the base class. | |
37 | super(html_exporter.HtmlExporter, self)._register_transformers() |
|
37 | super(html_exporter.HtmlExporter, self)._register_transformers() | |
38 |
|
38 | |||
39 | #Register reveal help transformer |
|
39 | #Register reveal help transformer | |
40 | self.register_transformer(transformers.revealhelp.RevealHelpTransformer) |
|
40 | self.register_transformer(transformers.revealhelp.RevealHelpTransformer) | |
41 | No newline at end of file |
|
41 |
@@ -1,51 +1,49 b'' | |||||
1 |
|
|
1 | """TODO: Docstring | |
2 | """ |
|
2 | """ | |
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 | # local import |
|
16 | # local import | |
17 | import exporter |
|
17 | import exporter | |
|
18 | from IPython.utils.traitlets import Unicode | |||
18 |
|
19 | |||
19 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
20 | # Classes |
|
21 | # Classes | |
21 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
22 | class RstExporter(exporter.Exporter): |
|
23 | class RstExporter(exporter.Exporter): | |
23 |
|
24 | |||
24 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, **kw): |
|
25 | file_extension = Unicode( | |
25 |
|
26 | 'rst', config=True, | ||
26 | #Call base class constructor. |
|
27 | help="Extension of the file that should be written to disk") | |
27 | super(exporter.Exporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
|||
28 |
|
||||
29 | #Set defaults |
|
|||
30 | self.file_extension = "rst" |
|
|||
31 | self.template_file = "rst" |
|
|||
32 | self.extract_figure_transformer.enabled = True |
|
|||
33 |
|
||||
34 |
|
28 | |||
|
29 | template_file = Unicode( | |||
|
30 | 'rst', config=True, | |||
|
31 | help="Name of the template file to use") | |||
|
32 | ||||
35 | def _register_filters(self): |
|
33 | def _register_filters(self): | |
36 |
|
34 | |||
37 | #Register the filters of the base class. |
|
35 | #Register the filters of the base class. | |
38 | super(exporter.Exporter, self)._register_filters() |
|
36 | super(exporter.Exporter, self)._register_filters() | |
39 |
|
37 | |||
40 | #Add latex filters to the Jinja2 environment |
|
38 | #Add latex filters to the Jinja2 environment | |
41 | #self.register_filter('escape_tex', filters.latex.escape_tex) |
|
39 | #self.register_filter('escape_tex', filters.latex.escape_tex) | |
42 |
|
40 | |||
43 |
|
41 | |||
44 | def _register_transformers(self): |
|
42 | def _register_transformers(self): | |
45 |
|
43 | |||
46 | #Register the transformers of the base class. |
|
44 | #Register the transformers of the base class. | |
47 | super(exporter.Exporter, self)._register_transformers() |
|
45 | super(exporter.Exporter, self)._register_transformers() | |
48 |
|
46 | |||
49 | #Register latex transformer |
|
47 | #Register latex transformer | |
50 | #self.register_transformer(LatexTransformer) |
|
48 | #self.register_transformer(LatexTransformer) | |
51 |
|
49 |
@@ -1,48 +1,34 b'' | |||||
1 | """TODO: Docstring |
|
|||
2 | """ |
|
|||
3 |
|
|
1 | ||
4 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
5 | # Copyright (c) 2013, the IPython Development Team. |
|
3 | # Copyright (c) 2013, the IPython Development Team. | |
6 | # |
|
4 | # | |
7 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
8 | # |
|
6 | # | |
9 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
10 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
11 |
|
9 | |||
12 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
11 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
15 |
|
13 | |||
16 | # local import |
|
14 | # local import | |
17 |
import latex |
|
15 | import latex | |
18 |
|
16 | from IPython.utils.traitlets import Unicode | ||
|
17 | from transformers.sphinx import SphinxTransformer | |||
19 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
20 | # Classes |
|
19 | # Classes | |
21 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
22 |
class SphinxExporter(latex |
|
21 | class SphinxExporter(latex.LatexExporter): | |
23 |
|
||||
24 | def __init__(self, preprocessors=None, jinja_filters=None, config=None, sphinx_type="howto", **kw): |
|
|||
25 |
|
||||
26 | #Call base class constructor. |
|
|||
27 | super(latex_exporter.LatexExporter, self).__init__(preprocessors, jinja_filters, config, **kw) |
|
|||
28 |
|
||||
29 | #Defaults |
|
|||
30 | self.template_file = "latex_sphinx_" + sphinx_type |
|
|||
31 |
|
||||
32 | def _register_filters(self): |
|
|||
33 |
|
||||
34 | #Register the filters of the base class. |
|
|||
35 | super(latex_exporter.LatexExporter, self)._register_filters() |
|
|||
36 |
|
||||
37 | #Add latex filters to the Jinja2 environment |
|
|||
38 | #self.register_filter('escape_tex', filters.latex.escape_tex) |
|
|||
39 |
|
22 | |||
|
23 | template_file = Unicode( | |||
|
24 | 'sphinxhowto', config=True, | |||
|
25 | help="Name of the template file to use") | |||
40 |
|
26 | |||
41 | def _register_transformers(self): |
|
27 | def _register_transformers(self): | |
42 |
|
28 | |||
43 | #Register the transformers of the base class. |
|
29 | #Register the transformers of the base class. | |
44 |
super(latex |
|
30 | super(latex.LatexExporter, self)._register_transformers() | |
45 |
|
31 | |||
46 | #Register latex transformer |
|
32 | #Register sphinx latex transformer | |
47 |
|
|
33 | self.register_transformer(SphinxTransformer) | |
48 |
|
34 |
@@ -1,82 +1,61 b'' | |||||
1 | # ANSI color functions: |
|
|||
2 |
|
|
1 | import re | |
3 | def remove_ansi(src): |
|
|||
4 | """Strip all ANSI color escape sequences from input string. |
|
|||
5 |
|
||||
6 | Parameters |
|
|||
7 | ---------- |
|
|||
8 | src : string |
|
|||
9 |
|
2 | |||
10 | Returns |
|
3 | def remove_ansi(src): | |
11 | ------- |
|
|||
12 | string |
|
|||
13 | """ |
|
|||
14 | return re.sub(r'\033\[(0|\d;\d\d)m', '', src) |
|
4 | return re.sub(r'\033\[(0|\d;\d\d)m', '', src) | |
15 |
|
5 | |||
16 |
|
6 | |||
17 | def ansi2html(txt): |
|
7 | def ansi2html(txt): | |
18 | """Render ANSI colors as HTML colors |
|
|||
19 |
|
||||
20 | This is equivalent to util.fixConsole in utils.js |
|
|||
21 |
|
||||
22 | Parameters |
|
|||
23 | ---------- |
|
|||
24 | txt : string |
|
|||
25 |
|
||||
26 | Returns |
|
|||
27 | ------- |
|
|||
28 | string |
|
|||
29 | """ |
|
|||
30 |
|
||||
31 | ansi_colormap = { |
|
8 | ansi_colormap = { | |
32 | '30': 'ansiblack', |
|
9 | '30': 'ansiblack', | |
33 | '31': 'ansired', |
|
10 | '31': 'ansired', | |
34 | '32': 'ansigreen', |
|
11 | '32': 'ansigreen', | |
35 | '33': 'ansiyellow', |
|
12 | '33': 'ansiyellow', | |
36 | '34': 'ansiblue', |
|
13 | '34': 'ansiblue', | |
37 | '35': 'ansipurple', |
|
14 | '35': 'ansipurple', | |
38 | '36': 'ansicyan', |
|
15 | '36': 'ansicyan', | |
39 | '37': 'ansigrey', |
|
16 | '37': 'ansigrey', | |
40 | '01': 'ansibold', |
|
17 | '01': 'ansibold', | |
41 | } |
|
18 | } | |
42 |
|
19 | |||
43 | # do ampersand first |
|
20 | # do ampersand first | |
44 | txt = txt.replace('&', '&') |
|
21 | txt = txt.replace('&', '&') | |
45 | html_escapes = { |
|
22 | html_escapes = { | |
46 | '<': '<', |
|
23 | '<': '<', | |
47 | '>': '>', |
|
24 | '>': '>', | |
48 | "'": ''', |
|
25 | "'": ''', | |
49 | '"': '"', |
|
26 | '"': '"', | |
50 | '`': '`', |
|
27 | '`': '`', | |
51 | } |
|
28 | } | |
|
29 | ||||
52 | for c, escape in html_escapes.iteritems(): |
|
30 | for c, escape in html_escapes.iteritems(): | |
53 | txt = txt.replace(c, escape) |
|
31 | txt = txt.replace(c, escape) | |
54 |
|
32 | |||
55 | ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m') |
|
33 | ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m') | |
56 | m = ansi_re.search(txt) |
|
34 | m = ansi_re.search(txt) | |
57 | opened = False |
|
35 | opened = False | |
58 | cmds = [] |
|
36 | cmds = [] | |
59 | opener = '' |
|
37 | opener = '' | |
60 | closer = '' |
|
38 | closer = '' | |
61 | while m: |
|
39 | while m: | |
62 | cmds = m.groups()[0].split(';') |
|
40 | cmds = m.groups()[0].split(';') | |
63 | closer = '</span>' if opened else '' |
|
41 | closer = '</span>' if opened else '' | |
|
42 | ||||
64 | # True if there is there more than one element in cmds, *or* |
|
43 | # True if there is there more than one element in cmds, *or* | |
65 | # if there is only one but it is not equal to a string of zeroes. |
|
44 | # if there is only one but it is not equal to a string of zeroes. | |
66 | opened = len(cmds) > 1 or cmds[0] != '0' * len(cmds[0]) |
|
45 | opened = len(cmds) > 1 or cmds[0] != '0' * len(cmds[0]) | |
67 | classes = [] |
|
46 | classes = [] | |
68 | for cmd in cmds: |
|
47 | for cmd in cmds: | |
69 | if cmd in ansi_colormap: |
|
48 | if cmd in ansi_colormap: | |
70 | classes.append(ansi_colormap.get(cmd)) |
|
49 | classes.append(ansi_colormap.get(cmd)) | |
71 |
|
50 | |||
72 | if classes: |
|
51 | if classes: | |
73 | opener = '<span class="%s">' % (' '.join(classes)) |
|
52 | opener = '<span class="%s">' % (' '.join(classes)) | |
74 | else: |
|
53 | else: | |
75 | opener = '' |
|
54 | opener = '' | |
76 | txt = re.sub(ansi_re, closer + opener, txt, 1) |
|
55 | txt = re.sub(ansi_re, closer + opener, txt, 1) | |
77 |
|
56 | |||
78 | m = ansi_re.search(txt) |
|
57 | m = ansi_re.search(txt) | |
79 |
|
58 | |||
80 | if opened: |
|
59 | if opened: | |
81 | txt += '</span>' |
|
60 | txt += '</span>' | |
82 |
return txt |
|
61 | return txt No newline at end of file |
@@ -1,31 +1,40 b'' | |||||
1 | """Filter used to select the first prefered output format available. |
|
1 | """Filter used to select the first preferred output format available. | |
2 |
|
2 | |||
3 | The filter contained in the file allows the converter templates to select |
|
3 | The filter contained in the file allows the converter templates to select | |
4 | the output format that is most valuable to the active export format. The |
|
4 | the output format that is most valuable to the active export format. The | |
5 | value of the different formats is set via |
|
5 | value of the different formats is set via | |
6 | GlobalConfigurable.display_data_priority |
|
6 | GlobalConfigurable.display_data_priority | |
7 | """ |
|
7 | """ | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 | # Copyright (c) 2013, the IPython Development Team. |
|
9 | # Copyright (c) 2013, the IPython Development Team. | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the Modified BSD License. |
|
11 | # Distributed under the terms of the Modified BSD License. | |
12 | # |
|
12 | # | |
13 | # The full license is in the file COPYING.txt, distributed with this software. |
|
13 | # The full license is in the file COPYING.txt, distributed with this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Classes and functions |
|
17 | # Classes and functions | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
class DataTypeFilter( |
|
19 | class DataTypeFilter(object): | |
20 | """ Returns the prefered display format """ |
|
20 | """ Returns the preferred display format """ | |
21 |
|
21 | |||
22 | def __init__(self, config=None, **kw): |
|
22 | display_data_priority = None | |
23 | super(DataTypeFilter, self).__init__(config=config, **kw) |
|
23 | ||
|
24 | def __init__(self, display_data_priority): | |||
|
25 | super(object, self).__init__() | |||
|
26 | ||||
|
27 | #Make sure that the display data priority variably is not None. | |||
|
28 | if self.display_data_priority is None: | |||
|
29 | raise TypeError | |||
|
30 | else: | |||
|
31 | self.display_data_priority = display_data_priority | |||
|
32 | ||||
24 |
|
33 | |||
25 | def __call__(self, output): |
|
34 | def __call__(self, output): | |
26 | """ Return the first available format in the priority """ |
|
35 | """ Return the first available format in the priority """ | |
27 |
|
36 | |||
28 | for fmt in self.display_data_priority: |
|
37 | for fmt in self.display_data_priority: | |
29 | if fmt in output: |
|
38 | if fmt in output: | |
30 | return [fmt] |
|
39 | return [fmt] | |
31 | return [] No newline at end of file |
|
40 | return [] |
@@ -1,95 +1,93 b'' | |||||
1 | """Latex transformer. |
|
1 | """Latex transformer. | |
2 |
|
2 | |||
3 | Module that allows latex output notebooks to be conditioned before |
|
3 | Module that allows latex output notebooks to be conditioned before | |
4 | they are converted. |
|
4 | they are converted. | |
5 | """ |
|
5 | """ | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (c) 2013, the IPython Development Team. |
|
7 | # Copyright (c) 2013, the IPython Development Team. | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the Modified BSD License. |
|
9 | # Distributed under the terms of the Modified BSD License. | |
10 | # |
|
10 | # | |
11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
11 | # The full license is in the file COPYING.txt, distributed with this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | import re |
|
17 | import re | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Globals and constants |
|
20 | # Globals and constants | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | #Latex substitutions for escaping latex. |
|
23 | #Latex substitutions for escaping latex. | |
24 | LATEX_SUBS = ( |
|
24 | LATEX_SUBS = ( | |
25 | (re.compile(r'\\'), r'\\textbackslash'), |
|
25 | (re.compile(r'\\'), r'\\textbackslash'), | |
26 | (re.compile(r'([{}_#%&$])'), r'\\\1'), |
|
26 | (re.compile(r'([{}_#%&$])'), r'\\\1'), | |
27 | (re.compile(r'~'), r'\~{}'), |
|
27 | (re.compile(r'~'), r'\~{}'), | |
28 | (re.compile(r'\^'), r'\^{}'), |
|
28 | (re.compile(r'\^'), r'\^{}'), | |
29 | (re.compile(r'"'), r"''"), |
|
29 | (re.compile(r'"'), r"''"), | |
30 | (re.compile(r'\.\.\.+'), r'\\ldots'), |
|
30 | (re.compile(r'\.\.\.+'), r'\\ldots'), | |
31 | ) |
|
31 | ) | |
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # Functions |
|
34 | # Functions | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
||||
37 | #TODO: Comment me. |
|
|||
38 | def escape_tex(value): |
|
36 | def escape_tex(value): | |
39 | newval = value |
|
37 | newval = value | |
40 | for pattern, replacement in LATEX_SUBS: |
|
38 | for pattern, replacement in LATEX_SUBS: | |
41 | newval = pattern.sub(replacement, newval) |
|
39 | newval = pattern.sub(replacement, newval) | |
42 | return newval |
|
40 | return newval | |
43 |
|
41 | |||
44 |
|
42 | |||
45 | def rm_math_space(text): |
|
43 | def rm_math_space(text): | |
46 | """ |
|
44 | """ | |
47 | Remove the space between latex math commands and enclosing $ symbols. |
|
45 | Remove the space between latex math commands and enclosing $ symbols. | |
48 | """ |
|
46 | """ | |
49 |
|
47 | |||
50 | # First, scan through the markdown looking for $. If |
|
48 | # First, scan through the markdown looking for $. If | |
51 | # a $ symbol is found, without a preceding \, assume |
|
49 | # a $ symbol is found, without a preceding \, assume | |
52 | # it is the start of a math block. UNLESS that $ is |
|
50 | # it is the start of a math block. UNLESS that $ is | |
53 | # not followed by another within two math_lines. |
|
51 | # not followed by another within two math_lines. | |
54 | math_regions = [] |
|
52 | math_regions = [] | |
55 | math_lines = 0 |
|
53 | math_lines = 0 | |
56 | within_math = False |
|
54 | within_math = False | |
57 | math_start_index = 0 |
|
55 | math_start_index = 0 | |
58 | ptext = '' |
|
56 | ptext = '' | |
59 | last_character = "" |
|
57 | last_character = "" | |
60 | skip = False |
|
58 | skip = False | |
61 | for index, char in enumerate(text): |
|
59 | for index, char in enumerate(text): | |
62 |
|
60 | |||
63 | #Make sure the character isn't preceeded by a backslash |
|
61 | #Make sure the character isn't preceeded by a backslash | |
64 | if (char == "$" and last_character != "\\"): |
|
62 | if (char == "$" and last_character != "\\"): | |
65 |
|
63 | |||
66 | # Close the math region if this is an ending $ |
|
64 | # Close the math region if this is an ending $ | |
67 | if within_math: |
|
65 | if within_math: | |
68 | within_math = False |
|
66 | within_math = False | |
69 | skip = True |
|
67 | skip = True | |
70 | ptext = ptext+'$'+text[math_start_index+1:index].strip()+'$' |
|
68 | ptext = ptext+'$'+text[math_start_index+1:index].strip()+'$' | |
71 | math_regions.append([math_start_index, index+1]) |
|
69 | math_regions.append([math_start_index, index+1]) | |
72 | else: |
|
70 | else: | |
73 |
|
71 | |||
74 | # Start a new math region |
|
72 | # Start a new math region | |
75 | within_math = True |
|
73 | within_math = True | |
76 | math_start_index = index |
|
74 | math_start_index = index | |
77 | math_lines = 0 |
|
75 | math_lines = 0 | |
78 |
|
76 | |||
79 | # If we are in a math region, count the number of lines parsed. |
|
77 | # If we are in a math region, count the number of lines parsed. | |
80 | # Cancel the math region if we find two line breaks! |
|
78 | # Cancel the math region if we find two line breaks! | |
81 | elif char == "\n": |
|
79 | elif char == "\n": | |
82 | if within_math: |
|
80 | if within_math: | |
83 | math_lines += 1 |
|
81 | math_lines += 1 | |
84 | if math_lines > 1: |
|
82 | if math_lines > 1: | |
85 | within_math = False |
|
83 | within_math = False | |
86 | ptext = ptext+text[math_start_index:index] |
|
84 | ptext = ptext+text[math_start_index:index] | |
87 |
|
85 | |||
88 | # Remember the last character so we can easily watch |
|
86 | # Remember the last character so we can easily watch | |
89 | # for backslashes |
|
87 | # for backslashes | |
90 | last_character = char |
|
88 | last_character = char | |
91 | if not within_math and not skip: |
|
89 | if not within_math and not skip: | |
92 | ptext = ptext+char |
|
90 | ptext = ptext+char | |
93 | if skip: |
|
91 | if skip: | |
94 | skip = False |
|
92 | skip = False | |
95 | return ptext |
|
93 | return ptext |
@@ -1,57 +1,57 b'' | |||||
1 | """String utilities. |
|
1 | """String utilities. | |
2 |
|
2 | |||
3 |
Contains a collection of useful |
|
3 | Contains a collection of useful string manipulations functions. | |
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 | # Our own imports |
|
17 | # Our own imports | |
18 | import textwrap #TODO |
|
18 | import textwrap #TODO | |
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Functions |
|
21 | # Functions | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | def wrap(text, width=100): |
|
23 | def wrap(text, width=100): | |
24 | """ Intelligently wrap text""" |
|
24 | """ Intelligently wrap text""" | |
25 |
|
25 | |||
26 | splitt = text.split('\n') |
|
26 | splitt = text.split('\n') | |
27 | wrp = map(lambda x:textwrap.wrap(x,width),splitt) |
|
27 | wrp = map(lambda x:textwrap.wrap(x,width),splitt) | |
28 | wrpd = map('\n'.join, wrp) |
|
28 | wrpd = map('\n'.join, wrp) | |
29 | return '\n'.join(wrpd) |
|
29 | return '\n'.join(wrpd) | |
30 |
|
30 | |||
31 |
|
31 | |||
32 | def strip_dollars(text): |
|
32 | def strip_dollars(text): | |
33 | """Remove all dollar symbols from text""" |
|
33 | """Remove all dollar symbols from text""" | |
34 |
|
34 | |||
35 | return text.strip('$') |
|
35 | return text.strip('$') | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | #TODO: Comment me. |
|
38 | #TODO: Comment me. | |
39 | def rm_fake(strng): |
|
39 | def rm_fake(strng): | |
40 | return strng.replace('/files/', '') |
|
40 | return strng.replace('/files/', '') | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | #TODO: Comment me. |
|
43 | #TODO: Comment me. | |
44 | def python_comment(string): |
|
44 | def python_comment(string): | |
45 | return '# '+'\n# '.join(string.split('\n')) |
|
45 | return '# '+'\n# '.join(string.split('\n')) | |
46 |
|
46 | |||
47 | def get_lines(src, start=None,end=None): |
|
47 | def get_lines(src, start=None,end=None): | |
48 | """ |
|
48 | """ | |
49 | Split the input text into separate lines and then return the |
|
49 | Split the input text into separate lines and then return the | |
50 | lines that the caller is interested in. |
|
50 | lines that the caller is interested in. | |
51 | """ |
|
51 | """ | |
52 |
|
52 | |||
53 | # Split the input into lines. |
|
53 | # Split the input into lines. | |
54 | lines = src.split("\n") |
|
54 | lines = src.split("\n") | |
55 |
|
55 | |||
56 | # Return the right lines. |
|
56 | # Return the right lines. | |
57 | return "\n".join(lines[start:end]) #re-join |
|
57 | return "\n".join(lines[start:end]) #re-join |
1 | NO CONTENT: file renamed from nbconvert/templates/latex/latex_base.tplx to nbconvert/templates/latex/base.tplx |
|
NO CONTENT: file renamed from nbconvert/templates/latex/latex_base.tplx to nbconvert/templates/latex/base.tplx |
1 | NO CONTENT: file renamed from nbconvert/templates/latex/latex_sphinx_base.tplx to nbconvert/templates/latex/sphinx_base.tplx |
|
NO CONTENT: file renamed from nbconvert/templates/latex/latex_sphinx_base.tplx to nbconvert/templates/latex/sphinx_base.tplx |
1 | NO CONTENT: file renamed from nbconvert/templates/latex/latex_sphinx_howto.tplx to nbconvert/templates/latex/sphinx_howto.tplx |
|
NO CONTENT: file renamed from nbconvert/templates/latex/latex_sphinx_howto.tplx to nbconvert/templates/latex/sphinx_howto.tplx |
1 | NO CONTENT: file renamed from nbconvert/templates/latex/latex_sphinx_manual.tplx to nbconvert/templates/latex/sphinx_manual.tplx |
|
NO CONTENT: file renamed from nbconvert/templates/latex/latex_sphinx_manual.tplx to nbconvert/templates/latex/sphinx_manual.tplx |
@@ -1,19 +1,19 b'' | |||||
1 |
from |
|
1 | from .base import ConfigurableTransformer | |
|
2 | from IPython.utils.traitlets import (Bool) | |||
2 |
|
3 | |||
3 |
|
4 | class ActivatableTransformer(ConfigurableTransformer): | ||
4 | class ActivatableTransformer(ConfigurableTransformers): |
|
|||
5 | """A simple ConfigurableTransformers that have an enabled flag |
|
5 | """A simple ConfigurableTransformers that have an enabled flag | |
6 |
|
6 | |||
7 | Inherit from that if you just want to have a transformer which is |
|
7 | Inherit from that if you just want to have a transformer which is | |
8 | no-op by default but can be activated in profiles with |
|
8 | no-op by default but can be activated in profiles with | |
9 |
|
9 | |||
10 | c.YourTransformerName.enabled = True |
|
10 | c.YourTransformerName.enabled = True | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | enabled = Bool(False, config=True) |
|
13 | enabled = Bool(False, config=True) | |
14 |
|
14 | |||
15 | def __call__(self, nb, other): |
|
15 | def __call__(self, nb, other): | |
16 | if not self.enabled : |
|
16 | if not self.enabled : | |
17 | return nb, other |
|
17 | return nb, other | |
18 | else : |
|
18 | else : | |
19 | return super(ActivatableTransformer, self).__call__(nb, other) |
|
19 | return super(ActivatableTransformer, self).__call__(nb, other) |
@@ -1,121 +1,59 b'' | |||||
1 | """ |
|
1 | """ | |
2 | Module that regroups transformer that woudl be applied to ipynb files |
|
2 | Module that regroups transformer that woudl be applied to ipynb files | |
3 | before going through the templating machinery. |
|
3 | before going through the templating machinery. | |
4 |
|
4 | |||
5 | It exposes convenient classes to inherit from to access configurability |
|
5 | It exposes convenient classes to inherit from to access configurability | |
6 | as well as decorator to simplify tasks. |
|
6 | as well as decorator to simplify tasks. | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | from __future__ import print_function, absolute_import |
|
9 | from __future__ import print_function, absolute_import | |
10 |
|
10 | |||
11 | from IPython.config.configurable import Configurable |
|
11 | from IPython.config.configurable import Configurable | |
12 | from IPython.utils.traitlets import Unicode, Bool, Dict, List |
|
|||
13 |
|
12 | |||
14 | from .config import GlobalConfigurable |
|
13 | class ConfigurableTransformer(Configurable): | |
15 |
|
||||
16 | class ConfigurableTransformers(GlobalConfigurable): |
|
|||
17 | """ A configurable transformer |
|
14 | """ A configurable transformer | |
18 |
|
15 | |||
19 | Inherit from this class if you wish to have configurability for your |
|
16 | Inherit from this class if you wish to have configurability for your | |
20 | transformer. |
|
17 | transformer. | |
21 |
|
18 | |||
22 | Any configurable traitlets this class exposed will be configurable in profiles |
|
19 | Any configurable traitlets this class exposed will be configurable in profiles | |
23 | using c.SubClassName.atribute=value |
|
20 | using c.SubClassName.atribute=value | |
24 |
|
21 | |||
25 | you can overwrite cell_transform to apply a transformation independently on each cell |
|
22 | you can overwrite cell_transform to apply a transformation independently on each cell | |
26 | or __call__ if you prefer your own logic. See orresponding docstring for informations. |
|
23 | or __call__ if you prefer your own logic. See orresponding docstring for informations. | |
27 |
|
24 | |||
28 |
|
25 | |||
29 | """ |
|
26 | """ | |
30 |
|
27 | |||
31 | def __init__(self, config=None, **kw): |
|
28 | def __init__(self, config=None, **kw): | |
32 |
super(ConfigurableTransformer |
|
29 | super(ConfigurableTransformer, self).__init__(config=config, **kw) | |
33 |
|
30 | |||
34 | def __call__(self, nb, other): |
|
31 | def __call__(self, nb, other): | |
35 | """transformation to apply on each notebook. |
|
32 | """transformation to apply on each notebook. | |
36 |
|
33 | |||
37 | received a handle to the current notebook as well as a dict of resources |
|
34 | received a handle to the current notebook as well as a dict of resources | |
38 | which structure depends on the transformer. |
|
35 | which structure depends on the transformer. | |
39 |
|
36 | |||
40 | You should return modified nb, other. |
|
37 | You should return modified nb, other. | |
41 |
|
38 | |||
42 | If you wish to apply on each cell, you might want to overwrite cell_transform method. |
|
39 | If you wish to apply on each cell, you might want to overwrite cell_transform method. | |
43 | """ |
|
40 | """ | |
44 | try : |
|
41 | try : | |
45 | for worksheet in nb.worksheets : |
|
42 | for worksheet in nb.worksheets : | |
46 | for index, cell in enumerate(worksheet.cells): |
|
43 | for index, cell in enumerate(worksheet.cells): | |
47 | worksheet.cells[index], other = self.cell_transform(cell, other, 100*index) |
|
44 | worksheet.cells[index], other = self.cell_transform(cell, other, 100*index) | |
48 | return nb, other |
|
45 | return nb, other | |
49 | except NotImplementedError: |
|
46 | except NotImplementedError: | |
50 | raise NotImplementedError('should be implemented by subclass') |
|
47 | raise NotImplementedError('should be implemented by subclass') | |
51 |
|
48 | |||
52 | def cell_transform(self, cell, other, index): |
|
49 | def cell_transform(self, cell, other, index): | |
53 | """ |
|
50 | """ | |
54 | Overwrite if you want to apply a transformation on each cell, |
|
51 | Overwrite if you want to apply a transformation on each cell, | |
55 |
|
52 | |||
56 | receive the current cell, the resource dict and the index of current cell as parameter. |
|
53 | receive the current cell, the resource dict and the index of current cell as parameter. | |
57 |
|
54 | |||
58 | You should return modified cell and resource dict. |
|
55 | You should return modified cell and resource dict. | |
59 | """ |
|
56 | """ | |
60 |
|
57 | |||
61 | raise NotImplementedError('should be implemented by subclass') |
|
58 | raise NotImplementedError('should be implemented by subclass') | |
62 | return cell, other |
|
59 | return cell, other | |
63 |
|
||||
64 | def cell_preprocessor(function): |
|
|||
65 | """ wrap a function to be executed on all cells of a notebook |
|
|||
66 |
|
||||
67 | wrapped function parameters : |
|
|||
68 | cell : the cell |
|
|||
69 | other : external resources |
|
|||
70 | index : index of the cell |
|
|||
71 | """ |
|
|||
72 | def wrappedfunc(nb, other): |
|
|||
73 | for worksheet in nb.worksheets : |
|
|||
74 | for index, cell in enumerate(worksheet.cells): |
|
|||
75 | worksheet.cells[index], other = function(cell, other, index) |
|
|||
76 | return nb, other |
|
|||
77 | return wrappedfunc |
|
|||
78 |
|
||||
79 |
|
||||
80 | @cell_preprocessor |
|
|||
81 | def haspyout_transformer(cell, other, count): |
|
|||
82 | """ |
|
|||
83 | Add a haspyout flag to cell that have it |
|
|||
84 |
|
||||
85 | Easier for templating, where you can't know in advance |
|
|||
86 | wether to write the out prompt |
|
|||
87 |
|
||||
88 | """ |
|
|||
89 | cell.type = cell.cell_type |
|
|||
90 | cell.haspyout = False |
|
|||
91 | for out in cell.get('outputs', []): |
|
|||
92 | if out.output_type == 'pyout': |
|
|||
93 | cell.haspyout = True |
|
|||
94 | break |
|
|||
95 | return cell, other |
|
|||
96 |
|
||||
97 | @cell_preprocessor |
|
|||
98 | def coalesce_streams(cell, other, count): |
|
|||
99 | """merge consecutive sequences of stream output into single stream |
|
|||
100 |
|
||||
101 | to prevent extra newlines inserted at flush calls |
|
|||
102 |
|
||||
103 | TODO: handle \r deletion |
|
|||
104 | """ |
|
|||
105 | outputs = cell.get('outputs', []) |
|
|||
106 | if not outputs: |
|
|||
107 | return cell, other |
|
|||
108 | new_outputs = [] |
|
|||
109 | last = outputs[0] |
|
|||
110 | new_outputs = [last] |
|
|||
111 | for output in outputs[1:]: |
|
|||
112 | if (output.output_type == 'stream' and |
|
|||
113 | last.output_type == 'stream' and |
|
|||
114 | last.stream == output.stream |
|
|||
115 | ): |
|
|||
116 | last.text += output.text |
|
|||
117 | else: |
|
|||
118 | new_outputs.append(output) |
|
|||
119 |
|
||||
120 | cell.outputs = new_outputs |
|
|||
121 | return cell, other |
|
@@ -1,43 +1,42 b'' | |||||
1 |
|
1 | |||
2 | def cell_preprocessor(function): |
|
2 | def cell_preprocessor(function): | |
3 | """ wrap a function to be executed on all cells of a notebook |
|
3 | """ wrap a function to be executed on all cells of a notebook | |
4 |
|
4 | |||
5 | wrapped function parameters : |
|
5 | wrapped function parameters : | |
6 | cell : the cell |
|
6 | cell : the cell | |
7 | other : external resources |
|
7 | other : external resources | |
8 | index : index of the cell |
|
8 | index : index of the cell | |
9 | """ |
|
9 | """ | |
10 | def wrappedfunc(nb, other): |
|
10 | def wrappedfunc(nb, other): | |
11 | for worksheet in nb.worksheets : |
|
11 | for worksheet in nb.worksheets : | |
12 | for index, cell in enumerate(worksheet.cells): |
|
12 | for index, cell in enumerate(worksheet.cells): | |
13 | worksheet.cells[index], other = function(cell, other, index) |
|
13 | worksheet.cells[index], other = function(cell, other, index) | |
14 | return nb, other |
|
14 | return nb, other | |
15 | return wrappedfunc |
|
15 | return wrappedfunc | |
16 |
|
16 | |||
17 |
|
17 | |||
18 | @cell_preprocessor |
|
18 | @cell_preprocessor | |
19 | def coalesce_streams(cell, other, count): |
|
19 | def coalesce_streams(cell, other, count): | |
20 | """merge consecutive sequences of stream output into single stream |
|
20 | """merge consecutive sequences of stream output into single stream | |
21 |
|
21 | |||
22 | to prevent extra newlines inserted at flush calls |
|
22 | to prevent extra newlines inserted at flush calls | |
23 |
|
23 | |||
24 | TODO: handle \r deletion |
|
24 | TODO: handle \r deletion | |
25 | """ |
|
25 | """ | |
26 | outputs = cell.get('outputs', []) |
|
26 | outputs = cell.get('outputs', []) | |
27 | if not outputs: |
|
27 | if not outputs: | |
28 | return cell, other |
|
28 | return cell, other | |
29 | new_outputs = [] |
|
|||
30 | last = outputs[0] |
|
29 | last = outputs[0] | |
31 | new_outputs = [last] |
|
30 | new_outputs = [last] | |
32 | for output in outputs[1:]: |
|
31 | for output in outputs[1:]: | |
33 | if (output.output_type == 'stream' and |
|
32 | if (output.output_type == 'stream' and | |
34 | last.output_type == 'stream' and |
|
33 | last.output_type == 'stream' and | |
35 | last.stream == output.stream |
|
34 | last.stream == output.stream | |
36 | ): |
|
35 | ): | |
37 | last.text += output.text |
|
36 | last.text += output.text | |
38 | else: |
|
37 | else: | |
39 | new_outputs.append(output) |
|
38 | new_outputs.append(output) | |
40 |
|
39 | |||
41 | cell.outputs = new_outputs |
|
40 | cell.outputs = new_outputs | |
42 | return cell, other |
|
41 | return cell, other | |
43 |
|
42 |
@@ -1,58 +1,57 b'' | |||||
1 |
|
1 | from .activatable import ActivatableTransformer | ||
2 |
|
2 | |||
3 | class CSSHtmlHeaderTransformer(ActivatableTransformer): |
|
3 | class CSSHtmlHeaderTransformer(ActivatableTransformer): | |
4 |
|
4 | |||
5 | def __call__(self, nb, resources): |
|
5 | def __call__(self, nb, resources): | |
6 | """Fetch and add css to the resource dict |
|
6 | """Fetch and add css to the resource dict | |
7 |
|
7 | |||
8 | Fetch css from IPython adn Pygment to add at the beginning |
|
8 | Fetch css from IPython adn Pygment to add at the beginning | |
9 | of the html files. |
|
9 | of the html files. | |
10 |
|
10 | |||
11 | Add this css in resources in the "inlining.css" key |
|
11 | Add this css in resources in the "inlining.css" key | |
12 | """ |
|
12 | """ | |
13 | resources['inlining'] = {} |
|
13 | resources['inlining'] = {} | |
14 | resources['inlining']['css'] = self.header |
|
14 | resources['inlining']['css'] = self.header | |
15 | return nb, resources |
|
15 | return nb, resources | |
16 |
|
16 | |||
17 | header = [] |
|
17 | header = [] | |
18 |
|
18 | |||
19 | def __init__(self, config=None, **kw): |
|
19 | def __init__(self, config=None, **kw): | |
20 | super(CSSHtmlHeaderTransformer, self).__init__(config=config, **kw) |
|
20 | super(CSSHtmlHeaderTransformer, self).__init__(config=config, **kw) | |
21 | if self.enabled : |
|
21 | if self.enabled : | |
22 | self.regen_header() |
|
22 | self.regen_header() | |
23 |
|
23 | |||
24 | def regen_header(self): |
|
24 | def regen_header(self): | |
25 | ## lazy load asa this might not be use in many transformers |
|
25 | ## lazy load asa this might not be use in many transformers | |
26 | import os |
|
26 | import os | |
27 | from IPython.utils import path |
|
27 | from IPython.utils import path | |
28 | import io |
|
28 | import io | |
29 | from pygments.formatters import HtmlFormatter |
|
29 | from pygments.formatters import HtmlFormatter | |
30 | header = [] |
|
30 | header = [] | |
31 | static = os.path.join(path.get_ipython_package_dir(), |
|
31 | static = os.path.join(path.get_ipython_package_dir(), | |
32 | 'frontend', 'html', 'notebook', 'static', |
|
32 | 'frontend', 'html', 'notebook', 'static', | |
33 | ) |
|
33 | ) | |
34 | here = os.path.split(os.path.realpath(__file__))[0] |
|
|||
35 | css = os.path.join(static, 'css') |
|
34 | css = os.path.join(static, 'css') | |
36 | for sheet in [ |
|
35 | for sheet in [ | |
37 | # do we need jquery and prettify? |
|
36 | # do we need jquery and prettify? | |
38 | # os.path.join(static, 'jquery', 'css', 'themes', 'base', |
|
37 | # os.path.join(static, 'jquery', 'css', 'themes', 'base', | |
39 | # 'jquery-ui.min.css'), |
|
38 | # 'jquery-ui.min.css'), | |
40 | # os.path.join(static, 'prettify', 'prettify.css'), |
|
39 | # os.path.join(static, 'prettify', 'prettify.css'), | |
41 | os.path.join(css, 'boilerplate.css'), |
|
40 | os.path.join(css, 'boilerplate.css'), | |
42 | os.path.join(css, 'fbm.css'), |
|
41 | os.path.join(css, 'fbm.css'), | |
43 | os.path.join(css, 'notebook.css'), |
|
42 | os.path.join(css, 'notebook.css'), | |
44 | os.path.join(css, 'renderedhtml.css'), |
|
43 | os.path.join(css, 'renderedhtml.css'), | |
45 | os.path.join(css, 'style.min.css'), |
|
44 | os.path.join(css, 'style.min.css'), | |
46 | ]: |
|
45 | ]: | |
47 | try: |
|
46 | try: | |
48 | with io.open(sheet, encoding='utf-8') as f: |
|
47 | with io.open(sheet, encoding='utf-8') as f: | |
49 | s = f.read() |
|
48 | s = f.read() | |
50 | header.append(s) |
|
49 | header.append(s) | |
51 | except IOError: |
|
50 | except IOError: | |
52 | # new version of ipython with style.min.css, pass |
|
51 | # new version of ipython with style.min.css, pass | |
53 | pass |
|
52 | pass | |
54 |
|
53 | |||
55 | pygments_css = HtmlFormatter().get_style_defs('.highlight') |
|
54 | pygments_css = HtmlFormatter().get_style_defs('.highlight') | |
56 | header.append(pygments_css) |
|
55 | header.append(pygments_css) | |
57 | self.header = header |
|
56 | self.header = header | |
58 |
|
57 |
@@ -1,64 +1,66 b'' | |||||
1 |
|
1 | from IPython.utils.traitlets import (Dict, List, Unicode) | ||
|
2 | from .activatable import ActivatableTransformer | |||
2 |
|
3 | |||
3 | class ExtractFigureTransformer(ActivatableTransformer): |
|
4 | class ExtractFigureTransformer(ActivatableTransformer): | |
4 |
|
5 | |||
5 |
|
6 | |||
6 | extra_ext_map = Dict({}, |
|
7 | extra_ext_map = Dict({}, | |
7 | config=True, |
|
8 | config=True, | |
8 | help="""extra map to override extension based on type. |
|
9 | help="""extra map to override extension based on type. | |
9 | Usefull for latex where svg will be converted to pdf before inclusion |
|
10 | Usefull for latex where svg will be converted to pdf before inclusion | |
10 | """ |
|
11 | """ | |
11 | ) |
|
12 | ) | |
12 |
|
13 | |||
13 | key_format_map = Dict({}, |
|
14 | key_format_map = Dict({}, | |
14 | config=True, |
|
15 | config=True, | |
15 | ) |
|
16 | ) | |
16 |
|
17 | |||
17 | figname_format_map = Dict({}, |
|
18 | figname_format_map = Dict({}, | |
18 | config=True, |
|
19 | config=True, | |
19 | ) |
|
20 | ) | |
20 |
|
21 | |||
|
22 | display_data_priority = List(['svg', 'png', 'latex', 'jpg', 'jpeg','text']) | |||
21 |
|
23 | |||
22 | #to do change this to .format {} syntax |
|
24 | #to do change this to .format {} syntax | |
23 | default_key_tpl = Unicode('_fig_{count:02d}.{ext}', config=True) |
|
25 | default_key_tpl = Unicode('_fig_{count:02d}.{ext}', config=True) | |
24 |
|
26 | |||
25 | def _get_ext(self, ext): |
|
27 | def _get_ext(self, ext): | |
26 | if ext in self.extra_ext_map : |
|
28 | if ext in self.extra_ext_map : | |
27 | return self.extra_ext_map[ext] |
|
29 | return self.extra_ext_map[ext] | |
28 | return ext |
|
30 | return ext | |
29 |
|
31 | |||
30 | def _new_figure(self, data, fmt, count): |
|
32 | def _new_figure(self, data, fmt, count): | |
31 | """Create a new figure file in the given format. |
|
33 | """Create a new figure file in the given format. | |
32 |
|
34 | |||
33 | """ |
|
35 | """ | |
34 | tplf = self.figname_format_map.get(fmt, self.default_key_tpl) |
|
36 | tplf = self.figname_format_map.get(fmt, self.default_key_tpl) | |
35 | tplk = self.key_format_map.get(fmt, self.default_key_tpl) |
|
37 | tplk = self.key_format_map.get(fmt, self.default_key_tpl) | |
36 |
|
38 | |||
37 | # option to pass the hash as data ? |
|
39 | # option to pass the hash as data ? | |
38 | figname = tplf.format(count=count, ext=self._get_ext(fmt)) |
|
40 | figname = tplf.format(count=count, ext=self._get_ext(fmt)) | |
39 | key = tplk.format(count=count, ext=self._get_ext(fmt)) |
|
41 | key = tplk.format(count=count, ext=self._get_ext(fmt)) | |
40 |
|
42 | |||
41 | # Binary files are base64-encoded, SVG is already XML |
|
43 | # Binary files are base64-encoded, SVG is already XML | |
42 | binary = False |
|
44 | binary = False | |
43 | if fmt in ('png', 'jpg', 'pdf'): |
|
45 | if fmt in ('png', 'jpg', 'pdf'): | |
44 | data = data.decode('base64') |
|
46 | data = data.decode('base64') | |
45 | binary = True |
|
47 | binary = True | |
46 |
|
48 | |||
47 | return figname, key, data, binary |
|
49 | return figname, key, data, binary | |
48 |
|
50 | |||
49 |
|
51 | |||
50 | def cell_transform(self, cell, other, count): |
|
52 | def cell_transform(self, cell, other, count): | |
51 | if other.get('figures', None) is None : |
|
53 | if other.get('figures', None) is None : | |
52 | other['figures'] = {'text':{},'binary':{}} |
|
54 | other['figures'] = {'text':{},'binary':{}} | |
53 | for out in cell.get('outputs', []): |
|
55 | for out in cell.get('outputs', []): | |
54 | for out_type in self.display_data_priority: |
|
56 | for out_type in self.display_data_priority: | |
55 | if out.hasattr(out_type): |
|
57 | if out.hasattr(out_type): | |
56 | figname, key, data, binary = self._new_figure(out[out_type], out_type, count) |
|
58 | figname, key, data, binary = self._new_figure(out[out_type], out_type, count) | |
57 | out['key_'+out_type] = figname |
|
59 | out['key_'+out_type] = figname | |
58 | if binary : |
|
60 | if binary : | |
59 | other['figures']['binary'][key] = data |
|
61 | other['figures']['binary'][key] = data | |
60 | else : |
|
62 | else : | |
61 | other['figures']['text'][key] = data |
|
63 | other['figures']['text'][key] = data | |
62 | count = count+1 |
|
64 | count = count+1 | |
63 | return cell, other |
|
65 | return cell, other | |
64 |
|
66 |
@@ -1,42 +1,43 b'' | |||||
1 | """Latex transformer. |
|
1 | """Latex transformer. | |
2 |
|
2 | |||
3 | Module that allows latex output notebooks to be conditioned before |
|
3 | Module that allows latex output notebooks to be conditioned before | |
4 | they are converted. |
|
4 | they are converted. | |
5 | """ |
|
5 | """ | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (c) 2013, the IPython Development Team. |
|
7 | # Copyright (c) 2013, the IPython Development Team. | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the Modified BSD License. |
|
9 | # Distributed under the terms of the Modified BSD License. | |
10 | # |
|
10 | # | |
11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
11 | # The full license is in the file COPYING.txt, distributed with this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | from __future__ import print_function, absolute_import |
|
17 | from __future__ import print_function, absolute_import | |
18 |
|
18 | |||
19 | # Our own imports |
|
19 | # Our own imports | |
20 | # Needed to override transformer |
|
20 | # Needed to override transformer | |
21 |
from . |
|
21 | from .activatable import (ActivatableTransformer) | |
|
22 | from filters import latex | |||
22 |
|
23 | |||
23 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
24 | # Classes |
|
25 | # Classes | |
25 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
26 | class LatexTransformer(ActivatableTransformer): |
|
27 | class LatexTransformer(ActivatableTransformer): | |
27 | """ |
|
28 | """ | |
28 | Converter for latex destined documents. |
|
29 | Converter for latex destined documents. | |
29 | """ |
|
30 | """ | |
30 |
|
31 | |||
31 | def cell_transform(self, cell, other, index): |
|
32 | def cell_transform(self, cell, other, index): | |
32 | """ |
|
33 | """ | |
33 | Apply a transformation on each cell, |
|
34 | Apply a transformation on each cell, | |
34 |
|
35 | |||
35 | receive the current cell, the resource dict and the index of current cell as parameter. |
|
36 | receive the current cell, the resource dict and the index of current cell as parameter. | |
36 |
|
37 | |||
37 | Returns modified cell and resource dict. |
|
38 | Returns modified cell and resource dict. | |
38 | """ |
|
39 | """ | |
39 |
|
40 | |||
40 | if hasattr(cell, "source") and cell.cell_type == "markdown": |
|
41 | if hasattr(cell, "source") and cell.cell_type == "markdown": | |
41 | cell.source = rm_math_space(cell.source) |
|
42 | cell.source = latex.rm_math_space(cell.source) | |
42 | return cell, other |
|
43 | return cell, other |
@@ -1,17 +1,17 b'' | |||||
1 |
|
1 | from .base import ConfigurableTransformer | ||
2 |
|
2 | |||
3 |
class RevealHelpTransformer(ConfigurableTransformer |
|
3 | class RevealHelpTransformer(ConfigurableTransformer): | |
4 |
|
4 | |||
5 | def __call__(self, nb, other): |
|
5 | def __call__(self, nb, other): | |
6 | for worksheet in nb.worksheets : |
|
6 | for worksheet in nb.worksheets : | |
7 | for i, cell in enumerate(worksheet.cells): |
|
7 | for i, cell in enumerate(worksheet.cells): | |
8 | if not cell.get('metadata', None): |
|
8 | if not cell.get('metadata', None): | |
9 | break |
|
9 | break | |
10 | cell.metadata.slide_type = cell.metadata.get('slideshow', {}).get('slide_type', None) |
|
10 | cell.metadata.slide_type = cell.metadata.get('slideshow', {}).get('slide_type', None) | |
11 | if cell.metadata.slide_type is None: |
|
11 | if cell.metadata.slide_type is None: | |
12 | cell.metadata.slide_type = '-' |
|
12 | cell.metadata.slide_type = '-' | |
13 | if cell.metadata.slide_type in ['slide']: |
|
13 | if cell.metadata.slide_type in ['slide']: | |
14 | worksheet.cells[i - 1].metadata.slide_helper = 'slide_end' |
|
14 | worksheet.cells[i - 1].metadata.slide_helper = 'slide_end' | |
15 | if cell.metadata.slide_type in ['subslide']: |
|
15 | if cell.metadata.slide_type in ['subslide']: | |
16 | worksheet.cells[i - 1].metadata.slide_helper = 'subslide_end' |
|
16 | worksheet.cells[i - 1].metadata.slide_helper = 'subslide_end' | |
17 | return nb, other No newline at end of file |
|
17 | return nb, other |
@@ -1,287 +1,287 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. |
|
2 | on the 'other' object passed into Jinja. | |
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 | from __future__ import print_function, absolute_import |
|
15 | from __future__ import print_function, absolute_import | |
16 |
|
16 | |||
17 | # Stdlib imports |
|
17 | # Stdlib imports | |
18 | # Used to find Sphinx package location |
|
18 | # Used to find Sphinx package location | |
19 | import sphinx |
|
19 | import sphinx | |
20 | import os.path |
|
20 | import os.path | |
21 |
|
21 | |||
22 | # Used to determine python version |
|
22 | # Used to determine python version | |
23 | import sys |
|
23 | import sys | |
24 |
|
24 | |||
25 | # Used to set the default date to today's date |
|
25 | # Used to set the default date to today's date | |
26 | from datetime import date |
|
26 | from datetime import date | |
27 |
|
27 | |||
28 | # Third-party imports |
|
28 | # Third-party imports | |
29 | # Needed for Pygments latex definitions. |
|
29 | # Needed for Pygments latex definitions. | |
30 | from pygments.formatters import LatexFormatter |
|
30 | from pygments.formatters import LatexFormatter | |
31 |
|
31 | |||
32 | # Our own imports |
|
32 | # Our own imports | |
33 | # Configurable traitlets |
|
33 | # Configurable traitlets | |
34 | from IPython.utils.traitlets import Unicode, Bool |
|
34 | from IPython.utils.traitlets import Unicode, Bool | |
35 |
|
35 | |||
36 | # Needed to override transformer |
|
36 | # Needed to override transformer | |
37 |
from . |
|
37 | from .activatable import (ActivatableTransformer) #TODO | |
38 |
|
38 | |||
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 | # Classes and functions |
|
40 | # Classes and functions | |
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 | class SphinxTransformer(ActivatableTransformer): |
|
42 | class SphinxTransformer(ActivatableTransformer): | |
43 | """ |
|
43 | """ | |
44 | Sphinx utility transformer. |
|
44 | Sphinx utility transformer. | |
45 |
|
45 | |||
46 | This transformer is used to set variables needed by the latex to build |
|
46 | This transformer is used to set variables needed by the latex to build | |
47 | Sphinx stylized templates. |
|
47 | Sphinx stylized templates. | |
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | interactive = Bool(True, config=True, help=""" |
|
50 | interactive = Bool(True, config=True, help=""" | |
51 | Allows you to define whether or not the Sphinx exporter will prompt |
|
51 | Allows you to define whether or not the Sphinx exporter will prompt | |
52 | you for input during the conversion process. If this is set to false, |
|
52 | you for input during the conversion process. If this is set to false, | |
53 | the author, version, release, date, and chapter_style traits should |
|
53 | the author, version, release, date, and chapter_style traits should | |
54 | be set. |
|
54 | be set. | |
55 | """) |
|
55 | """) | |
56 |
|
56 | |||
57 | author = Unicode("Unknown Author", config=True, help="Author name") |
|
57 | author = Unicode("Unknown Author", config=True, help="Author name") | |
58 |
|
58 | |||
59 | version = Unicode("", config=True, help="""Version number |
|
59 | version = Unicode("", config=True, help="""Version number | |
60 | You can leave this blank if you do not want to render a version number. |
|
60 | You can leave this blank if you do not want to render a version number. | |
61 | Example: "1.0.0" |
|
61 | Example: "1.0.0" | |
62 | """) |
|
62 | """) | |
63 |
|
63 | |||
64 | release = Unicode("", config=True, help="""Release name |
|
64 | release = Unicode("", config=True, help="""Release name | |
65 | You can leave this blank if you do not want to render a release name. |
|
65 | You can leave this blank if you do not want to render a release name. | |
66 | Example: "Rough Draft" |
|
66 | Example: "Rough Draft" | |
67 | """) |
|
67 | """) | |
68 |
|
68 | |||
69 | publish_date = Unicode("", config=True, help="""Publish date |
|
69 | publish_date = Unicode("", config=True, help="""Publish date | |
70 | This is the date to render on the document as the publish date. |
|
70 | This is the date to render on the document as the publish date. | |
71 | Leave this blank to default to todays date. |
|
71 | Leave this blank to default to todays date. | |
72 | Example: "June 12, 1990" |
|
72 | Example: "June 12, 1990" | |
73 | """) |
|
73 | """) | |
74 |
|
74 | |||
75 | chapter_style = Unicode("Bjarne", config=True, help="""Sphinx chapter style |
|
75 | chapter_style = Unicode("Bjarne", config=True, help="""Sphinx chapter style | |
76 | This is the style to use for the chapter headers in the document. |
|
76 | This is the style to use for the chapter headers in the document. | |
77 | You may choose one of the following: |
|
77 | You may choose one of the following: | |
78 | "Bjarne" (default) |
|
78 | "Bjarne" (default) | |
79 | "Lenny" |
|
79 | "Lenny" | |
80 | "Glenn" |
|
80 | "Glenn" | |
81 | "Conny" |
|
81 | "Conny" | |
82 | "Rejne" |
|
82 | "Rejne" | |
83 | "Sonny" (used for international documents) |
|
83 | "Sonny" (used for international documents) | |
84 | """) |
|
84 | """) | |
85 |
|
85 | |||
86 | output_style = Unicode("notebook", config=True, help="""Nbconvert Ipython |
|
86 | output_style = Unicode("notebook", config=True, help="""Nbconvert Ipython | |
87 | notebook input/output formatting style. |
|
87 | notebook input/output formatting style. | |
88 | You may choose one of the following: |
|
88 | You may choose one of the following: | |
89 | "simple (recommended for long code segments)" |
|
89 | "simple (recommended for long code segments)" | |
90 | "notebook" (default) |
|
90 | "notebook" (default) | |
91 | """) |
|
91 | """) | |
92 |
|
92 | |||
93 | center_output = Bool(False, config=True, help=""" |
|
93 | center_output = Bool(False, config=True, help=""" | |
94 | Optional attempt to center all output. If this is false, no additional |
|
94 | Optional attempt to center all output. If this is false, no additional | |
95 | formatting is applied. |
|
95 | formatting is applied. | |
96 | """) |
|
96 | """) | |
97 |
|
97 | |||
98 | use_headers = Bool(True, config=True, help=""" |
|
98 | use_headers = Bool(True, config=True, help=""" | |
99 | Whether not a header should be added to the document. |
|
99 | Whether not a header should be added to the document. | |
100 | """) |
|
100 | """) | |
101 |
|
101 | |||
102 | overridetitle = Unicode("", config=True, help="") |
|
102 | overridetitle = Unicode("", config=True, help="") | |
103 |
|
103 | |||
104 | def __call__(self, nb, other): |
|
104 | def __call__(self, nb, other): | |
105 | """ |
|
105 | """ | |
106 | Entry |
|
106 | Entry | |
107 | Since we are not interested in any additional manipulation on a cell |
|
107 | Since we are not interested in any additional manipulation on a cell | |
108 | by cell basis, we do not call the base implementation. |
|
108 | by cell basis, we do not call the base implementation. | |
109 | """ |
|
109 | """ | |
110 | if self.enabled: |
|
110 | if self.enabled: | |
111 | return self.transform(nb, other) |
|
111 | return self.transform(nb, other) | |
112 | else: |
|
112 | else: | |
113 | return nb,other |
|
113 | return nb,other | |
114 |
|
114 | |||
115 | def transform(self, nb, other): |
|
115 | def transform(self, nb, other): | |
116 | """ |
|
116 | """ | |
117 | Sphinx transformation to apply on each notebook. |
|
117 | Sphinx transformation to apply on each notebook. | |
118 | """ |
|
118 | """ | |
119 |
|
119 | |||
120 | # TODO: Add versatile method of additional notebook metadata. Include |
|
120 | # TODO: Add versatile method of additional notebook metadata. Include | |
121 | # handling of multiple files. For now use a temporay namespace, |
|
121 | # handling of multiple files. For now use a temporay namespace, | |
122 | # '_draft' to signify that this needs to change. |
|
122 | # '_draft' to signify that this needs to change. | |
123 | if not "_draft" in nb.metadata: |
|
123 | if not "_draft" in nb.metadata: | |
124 | nb.metadata._draft = {} |
|
124 | nb.metadata._draft = {} | |
125 |
|
125 | |||
126 | if not "sphinx" in other: |
|
126 | if not "sphinx" in other: | |
127 | other["sphinx"] = {} |
|
127 | other["sphinx"] = {} | |
128 |
|
128 | |||
129 | if self.interactive: |
|
129 | if self.interactive: | |
130 |
|
130 | |||
131 | # Prompt the user for additional meta data that doesn't exist currently |
|
131 | # Prompt the user for additional meta data that doesn't exist currently | |
132 | # but would be usefull for Sphinx. |
|
132 | # but would be usefull for Sphinx. | |
133 | nb.metadata._draft["author"] = self._prompt_author() |
|
133 | nb.metadata._draft["author"] = self._prompt_author() | |
134 | nb.metadata._draft["version"] = self._prompt_version() |
|
134 | nb.metadata._draft["version"] = self._prompt_version() | |
135 | nb.metadata._draft["release"] = self._prompt_release() |
|
135 | nb.metadata._draft["release"] = self._prompt_release() | |
136 | nb.metadata._draft["date"] = self._prompt_date() |
|
136 | nb.metadata._draft["date"] = self._prompt_date() | |
137 |
|
137 | |||
138 | # Prompt the user for the document style. |
|
138 | # Prompt the user for the document style. | |
139 | other["sphinx"]["chapterstyle"] = self._prompt_chapter_title_style() |
|
139 | other["sphinx"]["chapterstyle"] = self._prompt_chapter_title_style() | |
140 | other["sphinx"]["outputstyle"] = self._prompt_output_style() |
|
140 | other["sphinx"]["outputstyle"] = self._prompt_output_style() | |
141 |
|
141 | |||
142 | # Small options |
|
142 | # Small options | |
143 | other["sphinx"]["centeroutput"] = self._prompt_boolean("Do you want to center the output? (false)", False) |
|
143 | other["sphinx"]["centeroutput"] = self._prompt_boolean("Do you want to center the output? (false)", False) | |
144 | other["sphinx"]["header"] = self._prompt_boolean("Should a Sphinx document header be used? (true)", True) |
|
144 | other["sphinx"]["header"] = self._prompt_boolean("Should a Sphinx document header be used? (true)", True) | |
145 | else: |
|
145 | else: | |
146 |
|
146 | |||
147 | # Try to use the traitlets. |
|
147 | # Try to use the traitlets. | |
148 | nb.metadata._draft["author"] = self.author |
|
148 | nb.metadata._draft["author"] = self.author | |
149 | nb.metadata._draft["version"] = self.version |
|
149 | nb.metadata._draft["version"] = self.version | |
150 | nb.metadata._draft["release"] = self.release |
|
150 | nb.metadata._draft["release"] = self.release | |
151 |
|
151 | |||
152 | # Use todays date if none is provided. |
|
152 | # Use todays date if none is provided. | |
153 | if len(self.publish_date.strip()) == 0: |
|
153 | if len(self.publish_date.strip()) == 0: | |
154 | nb.metadata._draft["date"] = date.today().strftime("%B %-d, %Y") |
|
154 | nb.metadata._draft["date"] = date.today().strftime("%B %-d, %Y") | |
155 | else: |
|
155 | else: | |
156 | nb.metadata._draft["date"] = self.publish_date |
|
156 | nb.metadata._draft["date"] = self.publish_date | |
157 |
|
157 | |||
158 | # Sphinx traitlets. |
|
158 | # Sphinx traitlets. | |
159 | other["sphinx"]["chapterstyle"] = self.chapter_style |
|
159 | other["sphinx"]["chapterstyle"] = self.chapter_style | |
160 | other["sphinx"]["outputstyle"] = self.output_style |
|
160 | other["sphinx"]["outputstyle"] = self.output_style | |
161 | other["sphinx"]["centeroutput"] = self.center_output |
|
161 | other["sphinx"]["centeroutput"] = self.center_output | |
162 | other["sphinx"]["header"] = self.use_headers |
|
162 | other["sphinx"]["header"] = self.use_headers | |
163 |
|
163 | |||
164 | # Find and pass in the path to the Sphinx dependencies. |
|
164 | # Find and pass in the path to the Sphinx dependencies. | |
165 | other["sphinx"]["texinputs"] = os.path.abspath(sphinx.__file__ + "/../texinputs") |
|
165 | other["sphinx"]["texinputs"] = os.path.abspath(sphinx.__file__ + "/../texinputs") | |
166 |
|
166 | |||
167 | # Generate Pygments definitions for Latex |
|
167 | # Generate Pygments definitions for Latex | |
168 | other["sphinx"]["pygment_definitions"] = self._generate_pygments_latex_def() |
|
168 | other["sphinx"]["pygment_definitions"] = self._generate_pygments_latex_def() | |
169 |
|
169 | |||
170 | if not (self.overridetitle == None or len(self.overridetitle.strip()) == 0): |
|
170 | if not (self.overridetitle == None or len(self.overridetitle.strip()) == 0): | |
171 | nb.metadata.name = self.overridetitle |
|
171 | nb.metadata.name = self.overridetitle | |
172 |
|
172 | |||
173 | # End |
|
173 | # End | |
174 | return nb, other |
|
174 | return nb, other | |
175 |
|
175 | |||
176 | def _generate_pygments_latex_def(self): |
|
176 | def _generate_pygments_latex_def(self): | |
177 | return LatexFormatter().get_style_defs() |
|
177 | return LatexFormatter().get_style_defs() | |
178 |
|
178 | |||
179 | def _prompt_author(self): |
|
179 | def _prompt_author(self): | |
180 | return self._input("Author name: ") |
|
180 | return self._input("Author name: ") | |
181 |
|
181 | |||
182 | def _prompt_version(self): |
|
182 | def _prompt_version(self): | |
183 | return self._input("Version (ie ""1.0.0""): ") |
|
183 | return self._input("Version (ie ""1.0.0""): ") | |
184 |
|
184 | |||
185 | def _prompt_release(self): |
|
185 | def _prompt_release(self): | |
186 | return self._input("Release Name (ie ""Rough draft""): ") |
|
186 | return self._input("Release Name (ie ""Rough draft""): ") | |
187 |
|
187 | |||
188 | def _prompt_date(self): |
|
188 | def _prompt_date(self): | |
189 | default_date = date.today().strftime("%B %-d, %Y") |
|
189 | default_date = date.today().strftime("%B %-d, %Y") | |
190 | user_date = self._input("Date (deafults to \"" + default_date + "\"): ") |
|
190 | user_date = self._input("Date (deafults to \"" + default_date + "\"): ") | |
191 | if len(user_date.strip()) == 0: |
|
191 | if len(user_date.strip()) == 0: | |
192 | user_date = default_date |
|
192 | user_date = default_date | |
193 | return user_date |
|
193 | return user_date | |
194 |
|
194 | |||
195 | def _prompt_boolean(self, prompt, default=False): |
|
195 | def _prompt_boolean(self, prompt, default=False): | |
196 | response = self._input(prompt) |
|
196 | response = self._input(prompt) | |
197 | response = response.strip().lower() |
|
197 | response = response.strip().lower() | |
198 |
|
198 | |||
199 | #Catch 1, true, yes as True |
|
199 | #Catch 1, true, yes as True | |
200 | if len(response) > 0 and (response == "1" or response[0] == "t" or response[0] == "y"): |
|
200 | if len(response) > 0 and (response == "1" or response[0] == "t" or response[0] == "y"): | |
201 | return True |
|
201 | return True | |
202 |
|
202 | |||
203 | #Catch 0, false, no as False |
|
203 | #Catch 0, false, no as False | |
204 | elif len(response) > 0 and (response == "0" or response[0] == "f" or response[0] == "n"): |
|
204 | elif len(response) > 0 and (response == "0" or response[0] == "f" or response[0] == "n"): | |
205 | return False |
|
205 | return False | |
206 |
|
206 | |||
207 | else: |
|
207 | else: | |
208 | return default |
|
208 | return default | |
209 |
|
209 | |||
210 | def _prompt_output_style(self): |
|
210 | def _prompt_output_style(self): | |
211 |
|
211 | |||
212 | # Dictionary of available output styles |
|
212 | # Dictionary of available output styles | |
213 | styles = {1: "simple", |
|
213 | styles = {1: "simple", | |
214 | 2: "notebook"} |
|
214 | 2: "notebook"} | |
215 |
|
215 | |||
216 | #Append comments to the menu when displaying it to the user. |
|
216 | #Append comments to the menu when displaying it to the user. | |
217 | comments = {1: "(recommended for long code segments)", |
|
217 | comments = {1: "(recommended for long code segments)", | |
218 | 2: "(default)"} |
|
218 | 2: "(default)"} | |
219 |
|
219 | |||
220 | return self._prompt_dictionary(styles, default_style=2, menu_comments=comments) |
|
220 | return self._prompt_dictionary(styles, default_style=2, menu_comments=comments) | |
221 |
|
221 | |||
222 | def _prompt_chapter_title_style(self): |
|
222 | def _prompt_chapter_title_style(self): | |
223 |
|
223 | |||
224 | # Dictionary of available Sphinx styles |
|
224 | # Dictionary of available Sphinx styles | |
225 | styles = {1: "Bjarne", |
|
225 | styles = {1: "Bjarne", | |
226 | 2: "Lenny", |
|
226 | 2: "Lenny", | |
227 | 3: "Glenn", |
|
227 | 3: "Glenn", | |
228 | 4: "Conny", |
|
228 | 4: "Conny", | |
229 | 5: "Rejne", |
|
229 | 5: "Rejne", | |
230 | 6: "Sonny"} |
|
230 | 6: "Sonny"} | |
231 |
|
231 | |||
232 | #Append comments to the menu when displaying it to the user. |
|
232 | #Append comments to the menu when displaying it to the user. | |
233 | comments = {1: "(default)", |
|
233 | comments = {1: "(default)", | |
234 | 6: "(for international documents)"} |
|
234 | 6: "(for international documents)"} | |
235 |
|
235 | |||
236 | return self._prompt_dictionary(styles, menu_comments=comments) |
|
236 | return self._prompt_dictionary(styles, menu_comments=comments) | |
237 |
|
237 | |||
238 | def _prompt_dictionary(self, choices, default_style=1, menu_comments={}): |
|
238 | def _prompt_dictionary(self, choices, default_style=1, menu_comments={}): | |
239 |
|
239 | |||
240 | # Build the menu that will be displayed to the user with |
|
240 | # Build the menu that will be displayed to the user with | |
241 | # all of the options available. |
|
241 | # all of the options available. | |
242 | prompt = "" |
|
242 | prompt = "" | |
243 | for key, value in choices.iteritems(): |
|
243 | for key, value in choices.iteritems(): | |
244 | prompt += "%d %s " % (key, value) |
|
244 | prompt += "%d %s " % (key, value) | |
245 | if key in menu_comments: |
|
245 | if key in menu_comments: | |
246 | prompt += menu_comments[key] |
|
246 | prompt += menu_comments[key] | |
247 | prompt += "\n" |
|
247 | prompt += "\n" | |
248 |
|
248 | |||
249 | # Continue to ask the user for a style until an appropriate |
|
249 | # Continue to ask the user for a style until an appropriate | |
250 | # one is specified. |
|
250 | # one is specified. | |
251 | response = -1 |
|
251 | response = -1 | |
252 | while (not response in choices): |
|
252 | while (not response in choices): | |
253 | try: |
|
253 | try: | |
254 | text_response = self._input(prompt) |
|
254 | text_response = self._input(prompt) | |
255 |
|
255 | |||
256 | # Use default option if no input. |
|
256 | # Use default option if no input. | |
257 | if len(text_response.strip()) == 0: |
|
257 | if len(text_response.strip()) == 0: | |
258 | response = default_style |
|
258 | response = default_style | |
259 | else: |
|
259 | else: | |
260 | response = int(text_response) |
|
260 | response = int(text_response) | |
261 | except: |
|
261 | except: | |
262 | print("Error: Value is not an available option. 0 selects the default.\n") |
|
262 | print("Error: Value is not an available option. 0 selects the default.\n") | |
263 | return choices[response] |
|
263 | return choices[response] | |
264 |
|
264 | |||
265 | def _input(self, prompt_text): |
|
265 | def _input(self, prompt_text): | |
266 | """ |
|
266 | """ | |
267 | Prompt the user for input. |
|
267 | Prompt the user for input. | |
268 |
|
268 | |||
269 | The input command will change depending on the version of python |
|
269 | The input command will change depending on the version of python | |
270 | installed. To maintain support for 2 and earlier, we must use |
|
270 | installed. To maintain support for 2 and earlier, we must use | |
271 | raw_input in that case. Else use input. |
|
271 | raw_input in that case. Else use input. | |
272 | """ |
|
272 | """ | |
273 |
|
273 | |||
274 | # Try to get the python version. This command is only available in |
|
274 | # Try to get the python version. This command is only available in | |
275 | # python 2 and later, so it's important that we catch the exception |
|
275 | # python 2 and later, so it's important that we catch the exception | |
276 | # if the command isn't found. |
|
276 | # if the command isn't found. | |
277 | try: |
|
277 | try: | |
278 | majorversion = sys.version_info[0] |
|
278 | majorversion = sys.version_info[0] | |
279 | except: |
|
279 | except: | |
280 | majorversion = 1 |
|
280 | majorversion = 1 | |
281 |
|
281 | |||
282 | # Use the correct function to prompt the user for input depending on |
|
282 | # Use the correct function to prompt the user for input depending on | |
283 | # what python version the code is running in. |
|
283 | # what python version the code is running in. | |
284 | if majorversion >= 3: |
|
284 | if majorversion >= 3: | |
285 | return input(prompt_text) |
|
285 | return input(prompt_text) | |
286 | else: |
|
286 | else: | |
287 | return raw_input(prompt_text) |
|
287 | return raw_input(prompt_text) |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed | ||
This diff has been collapsed as it changes many lines, (683 lines changed) Show them Hide them |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed | ||
This diff has been collapsed as it changes many lines, (542 lines changed) Show them Hide them |
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