##// END OF EJS Templates
Added important comment
damianavila -
Show More
@@ -1,228 +1,228 b''
1 from __future__ import absolute_import
1 from __future__ import absolute_import
2
2
3 from converters.html import ConverterHTML
3 from converters.html import ConverterHTML
4 from converters.utils import text_cell
4 from converters.utils import text_cell
5 from converters.utils import highlight, coalesce_streams
5 from converters.utils import highlight, coalesce_streams
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
9
10 import os
10 import os
11 import io
11 import io
12 import itertools
12 import itertools
13
13
14
14
15 class ConverterReveal(ConverterHTML):
15 class ConverterReveal(ConverterHTML):
16 #"""
16 #"""
17 #Convert a ipython notebook to a html slideshow
17 #Convert a ipython notebook to a html slideshow
18 #based in reveal.js library.
18 #based in reveal.js library.
19 #"""
19 #"""
20
20
21 @text_cell
21 @text_cell
22 def render_heading(self, cell):
22 def render_heading(self, cell):
23 marker = cell.level
23 marker = cell.level
24 return [self.meta2str(cell.metadata),
24 return [self.meta2str(cell.metadata),
25 u'<h{1}>\n {0}\n</h{1}>'.format(cell.source, marker)]
25 u'<h{1}>\n {0}\n</h{1}>'.format(cell.source, marker)]
26
26
27 def render_code(self, cell):
27 def render_code(self, cell):
28 if not cell.input:
28 if not cell.input:
29 return []
29 return []
30 lines = []
30 lines = []
31 meta_code = self.meta2str(cell.metadata)
31 meta_code = self.meta2str(cell.metadata)
32 lines.extend([meta_code])
32 lines.extend([meta_code])
33 lines.extend(['<div class="cell border-box-sizing code_cell vbox">'])
33 lines.extend(['<div class="cell border-box-sizing code_cell vbox">'])
34 lines.append('<div class="input hbox">')
34 lines.append('<div class="input hbox">')
35 n = self._get_prompt_number(cell)
35 n = self._get_prompt_number(cell)
36 lines.append(
36 lines.append(
37 '<div class="prompt input_prompt">In&nbsp;[%s]:</div>' % n
37 '<div class="prompt input_prompt">In&nbsp;[%s]:</div>' % n
38 )
38 )
39 lines.append('<div class="input_area box-flex1">')
39 lines.append('<div class="input_area box-flex1">')
40 lines.append(highlight(cell.input))
40 lines.append(highlight(cell.input))
41 lines.append('</div>') # input_area
41 lines.append('</div>') # input_area
42 lines.append('</div>') # input
42 lines.append('</div>') # input
43 if cell.outputs:
43 if cell.outputs:
44 lines.append('<div class="vbox output_wrapper">')
44 lines.append('<div class="vbox output_wrapper">')
45 lines.append('<div class="output vbox">')
45 lines.append('<div class="output vbox">')
46 for output in coalesce_streams(cell.outputs):
46 for output in coalesce_streams(cell.outputs):
47 conv_fn = self.dispatch(output.output_type)
47 conv_fn = self.dispatch(output.output_type)
48 lines.extend(conv_fn(output))
48 lines.extend(conv_fn(output))
49 lines.append('</div>') # output
49 lines.append('</div>') # output
50 lines.append('</div>') # output_wrapper
50 lines.append('</div>') # output_wrapper
51 lines.append('</div>') # cell
51 lines.append('</div>') # cell
52 return lines
52 return lines
53
53
54 @text_cell
54 @text_cell
55 def render_markdown(self, cell):
55 def render_markdown(self, cell):
56 return [self.meta2str(cell.metadata), markdown(cell.source)]
56 return [self.meta2str(cell.metadata), markdown(cell.source)]
57
57
58 def render_raw(self, cell):
58 def render_raw(self, cell):
59 if self.raw_as_verbatim:
59 if self.raw_as_verbatim:
60 return [self.in_tag('pre', self.meta2str(cell.metadata)),
60 return [self.in_tag('pre', self.meta2str(cell.metadata)),
61 self.in_tag('pre', cell.source)]
61 self.in_tag('pre', cell.source)]
62 else:
62 else:
63 return [self.meta2str(cell.metadata), cell.source]
63 return [self.meta2str(cell.metadata), cell.source]
64
64
65 def meta2str(self, meta):
65 def meta2str(self, meta):
66 "transform metadata dict (containing slides delimiters) to string "
66 "transform metadata dict (containing slides delimiters) to string "
67 try:
67 try:
68 meta_tuple = meta[u'slideshow'].items()
68 meta_tuple = meta[u'slideshow'].items()
69 except KeyError as e: # if there is not slideshow metadata
69 except KeyError as e: # if there is not slideshow metadata
70 meta_tuple = [(u'slide_type', u'untouched')]
70 meta_tuple = [(u'slide_type', u'untouched')]
71 meta_list = [[x + ' = ' + unicode(y)] for x, y in meta_tuple]
71 meta_list = [[x + ' = ' + unicode(y)] for x, y in meta_tuple]
72 return u'\n'.join(list(itertools.chain(*meta_list)))
72 return u'\n'.join(list(itertools.chain(*meta_list)))
73
73
74 def convert(self, cell_separator='\n'):
74 def convert(self, cell_separator='\n'):
75 """
75 """
76 Specific method to converts notebook to a string representation.
76 Specific method to converts notebook to a string representation.
77
77
78 Parameters
78 Parameters
79 ----------
79 ----------
80 cell_separator : string
80 cell_separator : string
81 Character or string to join cells with. Default is "\n"
81 Character or string to join cells with. Default is "\n"
82
82
83 Returns
83 Returns
84 -------
84 -------
85 out : string
85 out : string
86 """
86 """
87
87
88 lines = []
88 lines = []
89 lines.extend(self.optional_header())
89 lines.extend(self.optional_header())
90 begin = ['<div class="reveal"><div class="slides">']
90 begin = ['<div class="reveal"><div class="slides">']
91 lines.extend(begin)
91 lines.extend(begin)
92 slides_list = self.build_slides()
92 slides_list = self.build_slides()
93 lines.extend(slides_list)
93 lines.extend(slides_list)
94 end = ['</div></div>']
94 end = ['</div></div>']
95 lines.extend(end)
95 lines.extend(end)
96 lines.extend(self.optional_footer())
96 lines.extend(self.optional_footer())
97 return u'\n'.join(lines)
97 return u'\n'.join(lines)
98
98
99 def clean_text(self, cell_separator='\n'):
99 def clean_text(self, cell_separator='\n'):
100 "clean and reorganize the text list to be slided"
100 "clean and reorganize the text list to be slided"
101 text = self.main_body(cell_separator)
101 text = self.main_body(cell_separator)
102 self.delim = [u'slide_type = untouched',
102 self.delim = [u'slide_type = untouched',
103 u'slide_type = -',
103 u'slide_type = -',
104 u'slide_type = header_slide',
104 u'slide_type = header_slide',
105 u'slide_type = slide',
105 u'slide_type = slide',
106 u'slide_type = fragment',
106 u'slide_type = fragment',
107 u'slide_type = skip']
107 u'slide_type = skip'] # keep this one the last
108 text_cell_render = \
108 text_cell_render = \
109 u'<div class="text_cell_render border-box-sizing rendered_html">'
109 u'<div class="text_cell_render border-box-sizing rendered_html">'
110 for i, j in enumerate(text):
110 for i, j in enumerate(text):
111 if j in self.delim and text[i - 1] == text_cell_render:
111 if j in self.delim and text[i - 1] == text_cell_render:
112 if j == self.delim[0]:
112 if j == self.delim[0]:
113 text[i - 1] = self.delim[0]
113 text[i - 1] = self.delim[0]
114 elif j == self.delim[1]:
114 elif j == self.delim[1]:
115 text[i - 1] = self.delim[1]
115 text[i - 1] = self.delim[1]
116 elif j == self.delim[2]:
116 elif j == self.delim[2]:
117 text[i - 1] = self.delim[2]
117 text[i - 1] = self.delim[2]
118 elif j == self.delim[3]:
118 elif j == self.delim[3]:
119 text[i - 1] = self.delim[3]
119 text[i - 1] = self.delim[3]
120 elif j == self.delim[4]:
120 elif j == self.delim[4]:
121 text[i - 1] = self.delim[4]
121 text[i - 1] = self.delim[4]
122 else:
122 else:
123 text[i - 1] = self.delim[5]
123 text[i - 1] = self.delim[5]
124 text[i] = text_cell_render
124 text[i] = text_cell_render
125 text[0] = u'slide_type = header_slide' # defensive code
125 text[0] = u'slide_type = header_slide' # defensive code
126 text.append(u'slide_type = untouched') # to end search of skipped
126 text.append(u'slide_type = untouched') # to end search of skipped
127 return text
127 return text
128
128
129 def build_slides(self):
129 def build_slides(self):
130 "build the slides structure from text list and delimiters"
130 "build the slides structure from text list and delimiters"
131 text = self.clean_text()
131 text = self.clean_text()
132 left = '<section>'
132 left = '<section>'
133 right = '</section>'
133 right = '</section>'
134 set_delim = self.delim[:5]
134 set_delim = self.delim[:5]
135 #elimination of skipped cells
135 #elimination of skipped cells
136 for i, j in enumerate(text):
136 for i, j in enumerate(text):
137 if j == u'slide_type = skip':
137 if j == u'slide_type = skip':
138 text.pop(i)
138 text.pop(i)
139 while not text[i] in set_delim:
139 while not text[i] in set_delim:
140 text.pop(i)
140 text.pop(i)
141 # elimination of none names
141 # elimination of none names
142 for i, j in enumerate(text):
142 for i, j in enumerate(text):
143 if j in [u'slide_type = untouched', u'slide_type = -']:
143 if j in [u'slide_type = untouched', u'slide_type = -']:
144 text.pop(i)
144 text.pop(i)
145 #generation of slides as a list of list
145 #generation of slides as a list of list
146 slides = [list(x[1]) for x in itertools.groupby(text,
146 slides = [list(x[1]) for x in itertools.groupby(text,
147 lambda x: x == u'slide_type = header_slide') if not x[0]]
147 lambda x: x == u'slide_type = header_slide') if not x[0]]
148 for slide in slides:
148 for slide in slides:
149 slide.insert(0, left)
149 slide.insert(0, left)
150 slide.append(right)
150 slide.append(right)
151 # encapsulation of each fragment
151 # encapsulation of each fragment
152 for i, j in enumerate(slide):
152 for i, j in enumerate(slide):
153 if j == u'slide_type = fragment':
153 if j == u'slide_type = fragment':
154 slide.pop(i)
154 slide.pop(i)
155 slide[i] = slide[i][:4] + ' class="fragment"' + slide[i][4:]
155 slide[i] = slide[i][:4] + ' class="fragment"' + slide[i][4:]
156 # encapsulation of each nested slide
156 # encapsulation of each nested slide
157 if u'slide_type = slide' in slide:
157 if u'slide_type = slide' in slide:
158 slide.insert(0, '<section>')
158 slide.insert(0, '<section>')
159 slide.append('</section>')
159 slide.append('</section>')
160 for i, j in enumerate(slide):
160 for i, j in enumerate(slide):
161 if j == u'slide_type = slide':
161 if j == u'slide_type = slide':
162 slide[i] = right + left
162 slide[i] = right + left
163 return list(itertools.chain(*slides))
163 return list(itertools.chain(*slides))
164
164
165 def save(self, outfile=None, encoding=None):
165 def save(self, outfile=None, encoding=None):
166 "read and parse notebook into self.nb"
166 "read and parse notebook into self.nb"
167 if outfile is None:
167 if outfile is None:
168 outfile = self.outbase + '_slides.' + 'html'
168 outfile = self.outbase + '_slides.' + 'html'
169 if encoding is None:
169 if encoding is None:
170 encoding = self.default_encoding
170 encoding = self.default_encoding
171 with io.open(outfile, 'w', encoding=encoding) as f:
171 with io.open(outfile, 'w', encoding=encoding) as f:
172 f.write(self.output)
172 f.write(self.output)
173 return os.path.abspath(outfile)
173 return os.path.abspath(outfile)
174
174
175 def header_body(self):
175 def header_body(self):
176 "return the body of the header as a list of strings"
176 "return the body of the header as a list of strings"
177 from pygments.formatters import HtmlFormatter
177 from pygments.formatters import HtmlFormatter
178 header = []
178 header = []
179 static = os.path.join(path.get_ipython_package_dir(),
179 static = os.path.join(path.get_ipython_package_dir(),
180 'frontend', 'html', 'notebook', 'static',)
180 'frontend', 'html', 'notebook', 'static',)
181 here = os.path.split(os.path.realpath(__file__))[0]
181 here = os.path.split(os.path.realpath(__file__))[0]
182 css = os.path.join(static, 'css')
182 css = os.path.join(static, 'css')
183 for sheet in [
183 for sheet in [
184 # do we need jquery and prettify?
184 # do we need jquery and prettify?
185 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
185 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
186 # 'jquery-ui.min.css'),
186 # 'jquery-ui.min.css'),
187 # os.path.join(static, 'prettify', 'prettify.css'),
187 # os.path.join(static, 'prettify', 'prettify.css'),
188 os.path.join(css, 'boilerplate.css'),
188 os.path.join(css, 'boilerplate.css'),
189 os.path.join(css, 'fbm.css'),
189 os.path.join(css, 'fbm.css'),
190 os.path.join(css, 'notebook.css'),
190 os.path.join(css, 'notebook.css'),
191 os.path.join(css, 'renderedhtml.css'),
191 os.path.join(css, 'renderedhtml.css'),
192 # our overrides:
192 # our overrides:
193 os.path.join(here, '..', 'css', 'reveal_html.css'),
193 os.path.join(here, '..', 'css', 'reveal_html.css'),
194 ]:
194 ]:
195 header.extend(self._stylesheet(sheet))
195 header.extend(self._stylesheet(sheet))
196 # pygments css
196 # pygments css
197 pygments_css = HtmlFormatter().get_style_defs('.highlight')
197 pygments_css = HtmlFormatter().get_style_defs('.highlight')
198 header.extend(['<meta charset="UTF-8">'])
198 header.extend(['<meta charset="UTF-8">'])
199 header.extend(self.in_tag('style', pygments_css,
199 header.extend(self.in_tag('style', pygments_css,
200 dict(type='"text/css"')))
200 dict(type='"text/css"')))
201 return header
201 return header
202
202
203 def template_read(self):
203 def template_read(self):
204 "read the reveal_template.html"
204 "read the reveal_template.html"
205 here = os.path.split(os.path.realpath(__file__))[0]
205 here = os.path.split(os.path.realpath(__file__))[0]
206 reveal_template = os.path.join(here, '..', 'templates',
206 reveal_template = os.path.join(here, '..', 'templates',
207 'reveal_base.html')
207 'reveal_base.html')
208 with io.open(reveal_template, 'r', encoding='utf-8') as f:
208 with io.open(reveal_template, 'r', encoding='utf-8') as f:
209 template = f.readlines()
209 template = f.readlines()
210 template = [s.strip() for s in template]
210 template = [s.strip() for s in template]
211 return template
211 return template
212
212
213 def template_split(self):
213 def template_split(self):
214 "split the reveal_template.html in header and footer lists"
214 "split the reveal_template.html in header and footer lists"
215 temp = self.template_read()
215 temp = self.template_read()
216 splitted_temp = [list(x[1]) for x in itertools.groupby(temp,
216 splitted_temp = [list(x[1]) for x in itertools.groupby(temp,
217 lambda x: x == u'%slides%') if not x[0]]
217 lambda x: x == u'%slides%') if not x[0]]
218 return splitted_temp
218 return splitted_temp
219
219
220 def optional_header(self):
220 def optional_header(self):
221 optional_header_body = self.template_split()
221 optional_header_body = self.template_split()
222 return ['<!DOCTYPE html>', '<html>', '<head>'] + \
222 return ['<!DOCTYPE html>', '<html>', '<head>'] + \
223 optional_header_body[0] + self.header_body() + \
223 optional_header_body[0] + self.header_body() + \
224 ['</head>', '<body>']
224 ['</head>', '<body>']
225
225
226 def optional_footer(self):
226 def optional_footer(self):
227 optional_footer_body = self.template_split()
227 optional_footer_body = self.template_split()
228 return optional_footer_body[1] + ['</body>', '</html>'] No newline at end of file
228 return optional_footer_body[1] + ['</body>', '</html>']
General Comments 0
You need to be logged in to leave comments. Login now