##// END OF EJS Templates
Fixed bad variable names in nbconvert.py and html.py.
Ivan Djokic -
Show More
@@ -1,185 +1,186 b''
1 from __future__ import absolute_import
1 from __future__ import absolute_import
2
2
3 from converters.base import Converter
3 from converters.base import Converter
4 from converters.utils import text_cell, output_container
4 from converters.utils import text_cell, output_container
5 from converters.utils import highlight, coalesce_streams, ansi2html
5 from converters.utils import highlight, coalesce_streams, ansi2html
6
6
7 from IPython.utils import path
7 from IPython.utils import path
8 from markdown import markdown
8 from markdown import markdown
9 import os
9 import os
10 import io
10 import io
11
11
12
12
13 class ConverterHTML(Converter):
13 class ConverterHTML(Converter):
14 extension = 'html'
14 extension = 'html'
15 blank_symbol = ' '
15 blank_symbol = ' '
16
16
17 def in_tag(self, tag, src, attrs=None):
17 def in_tag(self, tag, src, attrs=None):
18 """Return a list of elements bracketed by the given tag"""
18 """Return a list of elements bracketed by the given tag"""
19 attr_s = '' if attrs is None else \
19 attr_s = '' if attrs is None else \
20 ' '.join("%s=%s" % (attr, value)
20 ' '.join("%s=%s" % (attr, value)
21 for attr, value in attrs.iteritems())
21 for attr, value in attrs.iteritems())
22 return ['<%s %s>' % (tag, attr_s), src, '</%s>' % tag]
22 return ['<%s %s>' % (tag, attr_s), src, '</%s>' % tag]
23
23
24 def _ansi_colored(self, text):
24 def _ansi_colored(self, text):
25 return ['<pre>%s</pre>' % ansi2html(text)]
25 return ['<pre>%s</pre>' % ansi2html(text)]
26
26
27 def _stylesheet(self, fname):
27 def _stylesheet(self, fname):
28 with io.open(fname, encoding='utf-8') as f:
28 with io.open(fname, encoding='utf-8') as f:
29 s = f.read()
29 s = f.read()
30 return self.in_tag('style', s, dict(type='"text/css"'))
30 return self.in_tag('style', s, dict(type='"text/css"'))
31
31
32 def _out_prompt(self, output):
32 def _out_prompt(self, output):
33 if output.output_type == 'pyout':
33 if output.output_type == 'pyout':
34 content = 'Out[%s]:' % self._get_prompt_number(output)
34 content = 'Out[%s]:' % self._get_prompt_number(output)
35 else:
35 else:
36 content = ''
36 content = ''
37 return ['<div class="prompt output_prompt">%s</div>' % content]
37 return ['<div class="prompt output_prompt">%s</div>' % content]
38
38
39 def header_body(self):
39 def header_body(self):
40 """Return the body of the header as a list of strings."""
40 """Return the body of the header as a list of strings."""
41
41
42 from pygments.formatters import HtmlFormatter
42 from pygments.formatters import HtmlFormatter
43
43
44 header = []
44 header = []
45 static = os.path.join(path.get_ipython_package_dir(),
45 static = os.path.join(path.get_ipython_package_dir(),
46 'frontend', 'html', 'notebook', 'static',
46 'frontend', 'html', 'notebook', 'static',
47 )
47 )
48 here = os.path.split(os.path.realpath(__file__))[0]
48 here = os.path.split(os.path.realpath(__file__))[0]
49 css = os.path.join(static, 'css')
49 css = os.path.join(static, 'css')
50 for sheet in [
50 for sheet in [
51 # do we need jquery and prettify?
51 # do we need jquery and prettify?
52 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
52 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
53 # 'jquery-ui.min.css'),
53 # 'jquery-ui.min.css'),
54 # os.path.join(static, 'prettify', 'prettify.css'),
54 # os.path.join(static, 'prettify', 'prettify.css'),
55 os.path.join(css, 'boilerplate.css'),
55 os.path.join(css, 'boilerplate.css'),
56 os.path.join(css, 'fbm.css'),
56 os.path.join(css, 'fbm.css'),
57 os.path.join(css, 'notebook.css'),
57 os.path.join(css, 'notebook.css'),
58 os.path.join(css, 'renderedhtml.css'),
58 os.path.join(css, 'renderedhtml.css'),
59 # our overrides:
59 # our overrides:
60 os.path.join(here, '..', 'css', 'static_html.css'),
60 os.path.join(here, '..', 'css', 'static_html.css'),
61 ]:
61 ]:
62 header.extend(self._stylesheet(sheet))
62 header.extend(self._stylesheet(sheet))
63
63
64 # pygments css
64 # pygments css
65 pygments_css = HtmlFormatter().get_style_defs('.highlight')
65 pygments_css = HtmlFormatter().get_style_defs('.highlight')
66 header.extend(['<meta charset="UTF-8">'])
66 header.extend(['<meta charset="UTF-8">'])
67 header.extend(self.in_tag('style', pygments_css,
67 header.extend(self.in_tag('style', pygments_css,
68 dict(type='"text/css"')))
68 dict(type='"text/css"')))
69
69
70 # TODO: this should be allowed to use local mathjax:
70 # TODO: this should be allowed to use local mathjax:
71 header.extend(self.in_tag('script', '', {'type': '"text/javascript"',
71 header.extend(self.in_tag('script', '', {'type': '"text/javascript"',
72 'src': '"https://c328740.ssl.cf1.rackcdn.com/mathjax/'
72 'src': '"https://c328740.ssl.cf1.rackcdn.com/mathjax/'
73 'latest/MathJax.js?config=TeX-AMS_HTML"',
73 'latest/MathJax.js?config=TeX-AMS_HTML"',
74 }))
74 }))
75 with io.open(os.path.join(here, '..', 'js', 'initmathjax.js'),
75 with io.open(os.path.join(here, '..', 'js', 'initmathjax.js'),
76 encoding='utf-8') as f:
76 encoding='utf-8') as f:
77 header.extend(self.in_tag('script', f.read(),
77 header.extend(self.in_tag('script', f.read(),
78 {'type': '"text/javascript"'}))
78 {'type': '"text/javascript"'}))
79 return header
79 return header
80
80
81 def optional_header(self):
81 def optional_header(self):
82 return ['<html>', '<head>'] + self.header_body() + \
82 return ['<html>', '<head>'] + self.header_body() + \
83 ['</head>', '<body>']
83 ['</head>', '<body>']
84
84
85 def optional_footer(self):
85 def optional_footer(self):
86 return ['</body>', '</html>']
86 return ['</body>', '</html>']
87
87
88 @text_cell
88 @text_cell
89 def render_heading(self, cell):
89 def render_heading(self, cell):
90 marker = cell.level
90 marker = cell.level
91 return [u'<h{1}>\n {0}\n</h{1}>'.format(cell.source, marker)]
91 return [u'<h{1}>\n {0}\n</h{1}>'.format(cell.source, marker)]
92
92
93 def render_code(self, cell):
93 def render_code(self, cell):
94 if not cell.input:
94 if not cell.input:
95 return []
95 return []
96
96
97 lines = ['<div class="cell border-box-sizing code_cell vbox">']
97 lines = ['<div class="cell border-box-sizing code_cell vbox">']
98
98
99 lines.append('<div class="input hbox">')
99 lines.append('<div class="input hbox">')
100 n = self._get_prompt_number(cell)
100 n = self._get_prompt_number(cell)
101 lines.append(
101 lines.append(
102 '<div class="prompt input_prompt">In&nbsp;[%s]:</div>' % n
102 '<div class="prompt input_prompt">In&nbsp;[%s]:</div>' % n
103 )
103 )
104 lines.append('<div class="input_area box-flex1">')
104 lines.append('<div class="input_area box-flex1">')
105 lines.append(highlight(cell.input) if self.highlight else cell.input)
105 lines.append(highlight(cell.input) if self.highlight_code
106 else cell.input)
106 lines.append('</div>') # input_area
107 lines.append('</div>') # input_area
107 lines.append('</div>') # input
108 lines.append('</div>') # input
108
109
109 if cell.outputs:
110 if cell.outputs:
110 lines.append('<div class="vbox output_wrapper">')
111 lines.append('<div class="vbox output_wrapper">')
111 lines.append('<div class="output vbox">')
112 lines.append('<div class="output vbox">')
112
113
113 for output in coalesce_streams(cell.outputs):
114 for output in coalesce_streams(cell.outputs):
114 conv_fn = self.dispatch(output.output_type)
115 conv_fn = self.dispatch(output.output_type)
115 lines.extend(conv_fn(output))
116 lines.extend(conv_fn(output))
116
117
117 lines.append('</div>') # output
118 lines.append('</div>') # output
118 lines.append('</div>') # output_wrapper
119 lines.append('</div>') # output_wrapper
119
120
120 lines.append('</div>') # cell
121 lines.append('</div>') # cell
121
122
122 return lines
123 return lines
123
124
124 @text_cell
125 @text_cell
125 def render_markdown(self, cell):
126 def render_markdown(self, cell):
126 return [markdown(cell.source)]
127 return [markdown(cell.source)]
127
128
128 def render_raw(self, cell):
129 def render_raw(self, cell):
129 if self.raw_as_verbatim:
130 if self.raw_as_verbatim:
130 return self.in_tag('pre', cell.source)
131 return self.in_tag('pre', cell.source)
131 else:
132 else:
132 return [cell.source]
133 return [cell.source]
133
134
134 @output_container
135 @output_container
135 def render_pyout(self, output):
136 def render_pyout(self, output):
136 for fmt in ['html', 'latex', 'png', 'jpeg', 'svg', 'text']:
137 for fmt in ['html', 'latex', 'png', 'jpeg', 'svg', 'text']:
137 if fmt in output:
138 if fmt in output:
138 conv_fn = self.dispatch_display_format(fmt)
139 conv_fn = self.dispatch_display_format(fmt)
139 return conv_fn(output)
140 return conv_fn(output)
140 return []
141 return []
141
142
142 render_display_data = render_pyout
143 render_display_data = render_pyout
143
144
144 @output_container
145 @output_container
145 def render_stream(self, output):
146 def render_stream(self, output):
146 return self._ansi_colored(output.text)
147 return self._ansi_colored(output.text)
147
148
148 @output_container
149 @output_container
149 def render_pyerr(self, output):
150 def render_pyerr(self, output):
150 # Note: a traceback is a *list* of frames.
151 # Note: a traceback is a *list* of frames.
151 # lines = []
152 # lines = []
152
153
153 # stb =
154 # stb =
154 return self._ansi_colored('\n'.join(output.traceback))
155 return self._ansi_colored('\n'.join(output.traceback))
155
156
156 def _img_lines(self, img_file):
157 def _img_lines(self, img_file):
157 return ['<img src="%s">' % img_file, '</img>']
158 return ['<img src="%s">' % img_file, '</img>']
158
159
159 def _unknown_lines(self, data):
160 def _unknown_lines(self, data):
160 return ['<h2>Warning:: Unknown cell</h2>'] + self.in_tag('pre', data)
161 return ['<h2>Warning:: Unknown cell</h2>'] + self.in_tag('pre', data)
161
162
162 def render_display_format_png(self, output):
163 def render_display_format_png(self, output):
163 return ['<img src="data:image/png;base64,%s"></img>' % output.png]
164 return ['<img src="data:image/png;base64,%s"></img>' % output.png]
164
165
165 def render_display_format_svg(self, output):
166 def render_display_format_svg(self, output):
166 return [output.svg]
167 return [output.svg]
167
168
168 def render_display_format_jpeg(self, output):
169 def render_display_format_jpeg(self, output):
169 return ['<img src="data:image/jpeg;base64,%s"></img>' % output.jpeg]
170 return ['<img src="data:image/jpeg;base64,%s"></img>' % output.jpeg]
170
171
171 def render_display_format_text(self, output):
172 def render_display_format_text(self, output):
172 return self._ansi_colored(output.text)
173 return self._ansi_colored(output.text)
173
174
174 def render_display_format_html(self, output):
175 def render_display_format_html(self, output):
175 return [output.html]
176 return [output.html]
176
177
177 def render_display_format_latex(self, output):
178 def render_display_format_latex(self, output):
178 return [output.latex]
179 return [output.latex]
179
180
180 def render_display_format_json(self, output):
181 def render_display_format_json(self, output):
181 # html ignores json
182 # html ignores json
182 return []
183 return []
183
184
184 def render_display_format_javascript(self, output):
185 def render_display_format_javascript(self, output):
185 return [output.javascript]
186 return [output.javascript]
@@ -1,87 +1,87 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Convert IPython notebooks to other formats, such as ReST, and HTML.
2 """Convert IPython notebooks to other formats, such as ReST, and HTML.
3
3
4 Example:
4 Example:
5 ./nbconvert.py --format rst file.ipynb
5 ./nbconvert.py --format rst file.ipynb
6
6
7 Produces 'file.rst', along with auto-generated figure files
7 Produces 'file.rst', along with auto-generated figure files
8 called nb_figure_NN.png.
8 called nb_figure_NN.png.
9 """
9 """
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
13 from __future__ import print_function
14
14
15 # From IPython
15 # From IPython
16 from IPython.external import argparse
16 from IPython.external import argparse
17
17
18 # local
18 # local
19 from converters.html import ConverterHTML
19 from converters.html import ConverterHTML
20 from converters.markdown import ConverterMarkdown
20 from converters.markdown import ConverterMarkdown
21 from converters.bloggerhtml import ConverterBloggerHTML
21 from converters.bloggerhtml import ConverterBloggerHTML
22 from converters.rst import ConverterRST
22 from converters.rst import ConverterRST
23 from converters.latex import ConverterLaTeX
23 from converters.latex import ConverterLaTeX
24 from converters.python import ConverterPy
24 from converters.python import ConverterPy
25
25
26
26
27 # When adding a new format, make sure to add it to the `converters`
27 # When adding a new format, make sure to add it to the `converters`
28 # dictionary below. This is used to create the list of known formats,
28 # dictionary below. This is used to create the list of known formats,
29 # which gets printed in case an unknown format is encounteres, as well
29 # which gets printed in case an unknown format is encounteres, as well
30 # as in the help
30 # as in the help
31
31
32 converters = {
32 converters = {
33 'rst': ConverterRST,
33 'rst': ConverterRST,
34 'markdown': ConverterMarkdown,
34 'markdown': ConverterMarkdown,
35 'html': ConverterHTML,
35 'html': ConverterHTML,
36 'blogger-html': ConverterBloggerHTML,
36 'blogger-html': ConverterBloggerHTML,
37 'latex': ConverterLaTeX,
37 'latex': ConverterLaTeX,
38 'py': ConverterPy,
38 'py': ConverterPy,
39 }
39 }
40
40
41 default_format = 'rst'
41 default_format = 'rst'
42
42
43 # Extract the list of known formats and mark the first format as the default.
43 # Extract the list of known formats and mark the first format as the default.
44 known_formats = ', '.join([key + " (default)" if key == default_format else key
44 known_formats = ', '.join([key + " (default)" if key == default_format else key
45 for key in converters])
45 for key in converters])
46
46
47
47
48 def main(infile, format='rst', preamble=None, exclude=None,
48 def main(infile, format='rst', preamble=None, exclude=None,
49 highlight_code=True):
49 highlight_code=True):
50 """Convert a notebook to html in one step"""
50 """Convert a notebook to html in one step"""
51 try:
51 try:
52 ConverterClass = converters[format]
52 ConverterClass = converters[format]
53 except KeyError:
53 except KeyError:
54 raise SystemExit("Unknown format '%s', " % format +
54 raise SystemExit("Unknown format '%s', " % format +
55 "known formats are: " + known_formats)
55 "known formats are: " + known_formats)
56
56
57 converter = ConverterClass(infile, highlight_code)
57 converter = ConverterClass(infile, highlight_code)
58 converter.render()
58 converter.render()
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 # Script main
61 # Script main
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64 if __name__ == '__main__':
64 if __name__ == '__main__':
65 parser = argparse.ArgumentParser(description=__doc__,
65 parser = argparse.ArgumentParser(description=__doc__,
66 formatter_class=argparse.RawTextHelpFormatter)
66 formatter_class=argparse.RawTextHelpFormatter)
67 # TODO: consider passing file like object around, rather than filenames
67 # TODO: consider passing file like object around, rather than filenames
68 # would allow us to process stdin, or even http streams
68 # would allow us to process stdin, or even http streams
69 #parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
69 #parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
70 # default=sys.stdin)
70 # default=sys.stdin)
71
71
72 #Require a filename as a positional argument
72 #Require a filename as a positional argument
73 parser.add_argument('infile', nargs=1)
73 parser.add_argument('infile', nargs=1)
74 parser.add_argument('-f', '--format', default='rst',
74 parser.add_argument('-f', '--format', default='rst',
75 help='Output format. Supported formats: \n' +
75 help='Output format. Supported formats: \n' +
76 known_formats)
76 known_formats)
77 parser.add_argument('-p', '--preamble',
77 parser.add_argument('-p', '--preamble',
78 help='Path to a user-specified preamble file')
78 help='Path to a user-specified preamble file')
79 parser.add_argument('-e', '--exclude', default='',
79 parser.add_argument('-e', '--exclude', default='',
80 help='Comma-separated list of cells to exclude')
80 help='Comma-separated list of cells to exclude')
81 parser.add_argument('-H', '--no-highlighting', action='store_false',
81 parser.add_argument('-H', '--no-highlighting', action='store_false',
82 help='Disable syntax highlighting for code blocks.')
82 help='Disable syntax highlighting for code blocks.')
83 args = parser.parse_args()
83 args = parser.parse_args()
84 exclude_cells = [s.strip() for s in args.exclude.split(',')]
84 exclude_cells = [s.strip() for s in args.exclude.split(',')]
85
85
86 main(infile=args.infile[0], format=args.format, preamble=args.preamble,
86 main(infile=args.infile[0], format=args.format, preamble=args.preamble,
87 exclude=exclude_cells, highlight_code=args.plain_output)
87 exclude=exclude_cells, highlight_code=args.no_highlighting)
General Comments 0
You need to be logged in to leave comments. Login now