##// END OF EJS Templates
Replacement of text with vaiable containing text.
damianavila -
Show More
@@ -1,254 +1,254 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 = notes',
107 u'slide_type = notes',
108 u'slide_type = skip'] # keep this one the last
108 u'slide_type = skip'] # keep this one the last
109 text_cell_render = \
109 text_cell_render = \
110 u'<div class="text_cell_render border-box-sizing rendered_html">'
110 u'<div class="text_cell_render border-box-sizing rendered_html">'
111 for i, j in enumerate(text):
111 for i, j in enumerate(text):
112 if j in self.delim and text[i - 1] == text_cell_render:
112 if j in self.delim and text[i - 1] == text_cell_render:
113 if j == self.delim[0]:
113 if j == self.delim[0]:
114 text[i - 1] = self.delim[0]
114 text[i - 1] = self.delim[0]
115 elif j == self.delim[1]:
115 elif j == self.delim[1]:
116 text[i - 1] = self.delim[1]
116 text[i - 1] = self.delim[1]
117 elif j == self.delim[2]:
117 elif j == self.delim[2]:
118 text[i - 1] = self.delim[2]
118 text[i - 1] = self.delim[2]
119 elif j == self.delim[3]:
119 elif j == self.delim[3]:
120 text[i - 1] = self.delim[3]
120 text[i - 1] = self.delim[3]
121 elif j == self.delim[4]:
121 elif j == self.delim[4]:
122 text[i - 1] = self.delim[4]
122 text[i - 1] = self.delim[4]
123 elif j == self.delim[5]:
123 elif j == self.delim[5]:
124 text[i - 1] = self.delim[5]
124 text[i - 1] = self.delim[5]
125 else:
125 else:
126 text[i - 1] = self.delim[6]
126 text[i - 1] = self.delim[6]
127 text[i] = text_cell_render
127 text[i] = text_cell_render
128 text[0] = u'slide_type = header_slide' # defensive code
128 text[0] = u'slide_type = header_slide' # defensive code
129 text.append(u'slide_type = untouched') # to end search of skipped
129 text.append(u'slide_type = untouched') # to end search of skipped
130 return text
130 return text
131
131
132 def build_slides(self):
132 def build_slides(self):
133 "build the slides structure from text list and delimiters"
133 "build the slides structure from text list and delimiters"
134 text = self.clean_text()
134 text = self.clean_text()
135 left = '<section>'
135 left = '<section>'
136 right = '</section>'
136 right = '</section>'
137 notes_start = '<aside class="notes">'
137 notes_start = '<aside class="notes">'
138 notes_end = '</aside>'
138 notes_end = '</aside>'
139 set_delim_skip = self.delim[:6] # to skip adjacent skkiped cells
139 set_delim_skip = self.delim[:6] # to skip adjacent skkiped cells
140 set_delim_notes = self.delim[:5] # to show adjacent speaker notes
140 set_delim_notes = self.delim[:5] # to show adjacent speaker notes
141 #elimination of skipped cells
141 #elimination of skipped cells
142 for i, j in enumerate(text):
142 for i, j in enumerate(text):
143 if j == u'slide_type = skip':
143 if j == u'slide_type = skip':
144 text.pop(i)
144 text.pop(i)
145 while not text[i] in set_delim_skip:
145 while not text[i] in set_delim_skip:
146 text.pop(i)
146 text.pop(i)
147 #encapsulation of notes cells
147 #encapsulation of notes cells
148 for i, j in enumerate(text):
148 for i, j in enumerate(text):
149 if j == u'slide_type = notes':
149 if j == u'slide_type = notes':
150 text.pop(i)
150 text.pop(i)
151 temp_list = []
151 temp_list = []
152 while not text[i] in set_delim_notes:
152 while not text[i] in set_delim_notes:
153 temp_list.append(text.pop(i))
153 temp_list.append(text.pop(i))
154 else:
154 else:
155 temp_list.insert(0, notes_start)
155 temp_list.insert(0, notes_start)
156 temp_list.append(notes_end)
156 temp_list.append(notes_end)
157 text[i:i] = temp_list
157 text[i:i] = temp_list
158 # elimination of none names
158 # elimination of none names
159 for i, j in enumerate(text):
159 for i, j in enumerate(text):
160 if j in [u'slide_type = untouched', u'slide_type = -']:
160 if j in [u'slide_type = untouched', u'slide_type = -']:
161 text.pop(i)
161 text.pop(i)
162 #generation of slides as a list of list
162 #generation of slides as a list of list
163 slides = [list(x[1]) for x in itertools.groupby(text,
163 slides = [list(x[1]) for x in itertools.groupby(text,
164 lambda x: x == u'slide_type = header_slide') if not x[0]]
164 lambda x: x == u'slide_type = header_slide') if not x[0]]
165 for slide in slides:
165 for slide in slides:
166 slide.insert(0, left)
166 slide.insert(0, left)
167 slide.append(right)
167 slide.append(right)
168 # encapsulation of each fragment
168 # encapsulation of each fragment
169 for i, j in enumerate(slide):
169 for i, j in enumerate(slide):
170 if j == u'slide_type = fragment':
170 if j == u'slide_type = fragment':
171 slide.pop(i)
171 slide.pop(i)
172 slide[i] = slide[i][:4] + \
172 slide[i] = slide[i][:4] + \
173 ' class="fragment"' + slide[i][4:]
173 ' class="fragment"' + slide[i][4:]
174 # encapsulation of each nested slide
174 # encapsulation of each nested slide
175 if u'slide_type = slide' in slide:
175 if u'slide_type = slide' in slide:
176 slide.insert(0, '<section>')
176 slide.insert(0, left)
177 slide.append('</section>')
177 slide.append(right)
178 for i, j in enumerate(slide):
178 for i, j in enumerate(slide):
179 if j == u'slide_type = slide':
179 if j == u'slide_type = slide':
180 slide[i] = right + left
180 slide[i] = right + left
181 return list(itertools.chain(*slides))
181 return list(itertools.chain(*slides))
182
182
183 def render(self):
183 def render(self):
184 "read, convert, and save self.infile"
184 "read, convert, and save self.infile"
185 if not hasattr(self, 'nb'):
185 if not hasattr(self, 'nb'):
186 self.read()
186 self.read()
187 self.output = self.convert()
187 self.output = self.convert()
188 assert(type(self.output) == unicode)
188 assert(type(self.output) == unicode)
189 return self.save()
189 return self.save()
190
190
191 def save(self, outfile=None, encoding=None):
191 def save(self, outfile=None, encoding=None):
192 "read and parse notebook into self.nb"
192 "read and parse notebook into self.nb"
193 if outfile is None:
193 if outfile is None:
194 outfile = self.outbase + '_slides.' + 'html'
194 outfile = self.outbase + '_slides.' + 'html'
195 if encoding is None:
195 if encoding is None:
196 encoding = self.default_encoding
196 encoding = self.default_encoding
197 with io.open(outfile, 'w', encoding=encoding) as f:
197 with io.open(outfile, 'w', encoding=encoding) as f:
198 f.write(self.output)
198 f.write(self.output)
199 return os.path.abspath(outfile)
199 return os.path.abspath(outfile)
200
200
201 def header_body(self):
201 def header_body(self):
202 "return the body of the header as a list of strings"
202 "return the body of the header as a list of strings"
203 from pygments.formatters import HtmlFormatter
203 from pygments.formatters import HtmlFormatter
204 header = []
204 header = []
205 static = os.path.join(path.get_ipython_package_dir(),
205 static = os.path.join(path.get_ipython_package_dir(),
206 'frontend', 'html', 'notebook', 'static',)
206 'frontend', 'html', 'notebook', 'static',)
207 here = os.path.split(os.path.realpath(__file__))[0]
207 here = os.path.split(os.path.realpath(__file__))[0]
208 css = os.path.join(static, 'css')
208 css = os.path.join(static, 'css')
209 for sheet in [
209 for sheet in [
210 # do we need jquery and prettify?
210 # do we need jquery and prettify?
211 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
211 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
212 # 'jquery-ui.min.css'),
212 # 'jquery-ui.min.css'),
213 # os.path.join(static, 'prettify', 'prettify.css'),
213 # os.path.join(static, 'prettify', 'prettify.css'),
214 os.path.join(css, 'boilerplate.css'),
214 os.path.join(css, 'boilerplate.css'),
215 os.path.join(css, 'fbm.css'),
215 os.path.join(css, 'fbm.css'),
216 os.path.join(css, 'notebook.css'),
216 os.path.join(css, 'notebook.css'),
217 os.path.join(css, 'renderedhtml.css'),
217 os.path.join(css, 'renderedhtml.css'),
218 # our overrides:
218 # our overrides:
219 os.path.join(here, '..', 'css', 'reveal_html.css'),
219 os.path.join(here, '..', 'css', 'reveal_html.css'),
220 ]:
220 ]:
221 header.extend(self._stylesheet(sheet))
221 header.extend(self._stylesheet(sheet))
222 # pygments css
222 # pygments css
223 pygments_css = HtmlFormatter().get_style_defs('.highlight')
223 pygments_css = HtmlFormatter().get_style_defs('.highlight')
224 header.extend(['<meta charset="UTF-8">'])
224 header.extend(['<meta charset="UTF-8">'])
225 header.extend(self.in_tag('style', pygments_css,
225 header.extend(self.in_tag('style', pygments_css,
226 dict(type='"text/css"')))
226 dict(type='"text/css"')))
227 return header
227 return header
228
228
229 def template_read(self, templ):
229 def template_read(self, templ):
230 "read the reveal_template.html"
230 "read the reveal_template.html"
231 here = os.path.split(os.path.realpath(__file__))[0]
231 here = os.path.split(os.path.realpath(__file__))[0]
232 reveal_template = os.path.join(here, '..', 'templates',
232 reveal_template = os.path.join(here, '..', 'templates',
233 templ)
233 templ)
234 with io.open(reveal_template, 'r', encoding='utf-8') as f:
234 with io.open(reveal_template, 'r', encoding='utf-8') as f:
235 template = f.readlines()
235 template = f.readlines()
236 template = [s.strip() for s in template]
236 template = [s.strip() for s in template]
237 return template
237 return template
238
238
239 def template_split(self):
239 def template_split(self):
240 "split the reveal_template.html in header and footer lists"
240 "split the reveal_template.html in header and footer lists"
241 temp = self.template_read('reveal_base.html')
241 temp = self.template_read('reveal_base.html')
242 splitted_temp = [list(x[1]) for x in itertools.groupby(temp,
242 splitted_temp = [list(x[1]) for x in itertools.groupby(temp,
243 lambda x: x == u'%slides%') if not x[0]]
243 lambda x: x == u'%slides%') if not x[0]]
244 return splitted_temp
244 return splitted_temp
245
245
246 def optional_header(self):
246 def optional_header(self):
247 optional_header_body = self.template_split()
247 optional_header_body = self.template_split()
248 return ['<!DOCTYPE html>', '<html>', '<head>'] + \
248 return ['<!DOCTYPE html>', '<html>', '<head>'] + \
249 optional_header_body[0] + self.header_body() + \
249 optional_header_body[0] + self.header_body() + \
250 ['</head>', '<body>']
250 ['</head>', '<body>']
251
251
252 def optional_footer(self):
252 def optional_footer(self):
253 optional_footer_body = self.template_split()
253 optional_footer_body = self.template_split()
254 return optional_footer_body[1] + ['</body>', '</html>'] No newline at end of file
254 return optional_footer_body[1] + ['</body>', '</html>']
General Comments 0
You need to be logged in to leave comments. Login now