##// END OF EJS Templates
modularize inlining
Matthias BUSSONNIER -
Show More
@@ -1,145 +1,146 b''
1 1 """Base classes for the notebook conversion pipeline.
2 2
3 3 This module defines Converter, from which all objects designed to implement
4 4 a conversion of IPython notebooks to some other format should inherit.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (c) 2012, the IPython Development Team.
8 8 #
9 9 # Distributed under the terms of the Modified BSD License.
10 10 #
11 11 # The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 from __future__ import print_function, absolute_import
19 19
20 20 # Stdlib imports
21 21 import jinja2
22 22 import codecs
23 23 import io
24 24 import logging
25 25 import os
26 26 from IPython.utils import path
27 27 import pprint
28 28 import re
29 29 from types import FunctionType
30 30
31 31 from jinja2 import Environment, PackageLoader, FileSystemLoader
32 32 env = Environment(loader=FileSystemLoader('./templates/'))
33 33
34 34 # IPython imports
35 35 from IPython.nbformat import current as nbformat
36 36 from IPython.config.configurable import Configurable, SingletonConfigurable
37 37 from IPython.utils.traitlets import (List, Unicode, Type, Bool, Dict, CaselessStrEnum,
38 38 Any)
39 39
40 40 # Our own imports
41 41 from IPython.utils.text import indent
42 42 from .utils import remove_ansi
43 43 from markdown import markdown
44 44 from .utils import highlight,ansi2html
45 45 #-----------------------------------------------------------------------------
46 46 # Class declarations
47 47 #-----------------------------------------------------------------------------
48 48 def rm_fake(strng):
49 49 return strng.replace('/files/', '')
50 50
51 51 class ConversionException(Exception):
52 52 pass
53 53
54 54
55 55 def python_comment(string):
56 56 return '# '+'\n# '.join(string.split('\n'))
57 57
58 58
59 59
60 60 def header_body():
61 61 """Return the body of the header as a list of strings."""
62 62
63 63 from pygments.formatters import HtmlFormatter
64 64
65 65 header = []
66 66 static = os.path.join(path.get_ipython_package_dir(),
67 67 'frontend', 'html', 'notebook', 'static',
68 68 )
69 69 here = os.path.split(os.path.realpath(__file__))[0]
70 70 css = os.path.join(static, 'css')
71 71 for sheet in [
72 72 # do we need jquery and prettify?
73 73 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
74 74 # 'jquery-ui.min.css'),
75 75 # os.path.join(static, 'prettify', 'prettify.css'),
76 76 os.path.join(css, 'boilerplate.css'),
77 77 os.path.join(css, 'fbm.css'),
78 78 os.path.join(css, 'notebook.css'),
79 79 os.path.join(css, 'renderedhtml.css'),
80 80 # our overrides:
81 81 os.path.join(here, '..', 'css', 'static_html.css'),
82 82 ]:
83 83
84 84 with io.open(sheet, encoding='utf-8') as f:
85 85 s = f.read()
86 header.extend(s.split('\n'))
86 header.append(s)
87 87
88 88 pygments_css = HtmlFormatter().get_style_defs('.highlight')
89 header.extend(pygments_css.split('\n'))
89 header.append(pygments_css)
90 90 return header
91 91
92 ecss = header_body()
92 inlining= {}
93 inlining['css'] = header_body()
93 94
94 95 env.filters['pycomment'] = python_comment
95 96 env.filters['indent'] = indent
96 97 env.filters['rm_fake'] = rm_fake
97 98 env.filters['rm_ansi'] = remove_ansi
98 99 env.filters['markdown'] = markdown
99 100 env.filters['highlight'] = highlight
100 101 env.filters['ansi2html'] = ansi2html
101 102
102 103 class ConverterTemplate(Configurable):
103 104
104 105 display_data_priority = ['pdf', 'svg', 'png', 'jpg', 'text']
105 106 #-------------------------------------------------------------------------
106 107 # Instance-level attributes that are set in the constructor for this
107 108 # class.
108 109 #-------------------------------------------------------------------------
109 110 infile = Any()
110 111
111 112
112 113 infile_dir = Unicode()
113 114
114 115 def __init__(self, tplfile='fullhtml', config=None, **kw):
115 116 self.template = env.get_template(tplfile+'.tpl')
116 117 super(ConverterTemplate,self).__init__(config=config)
117 118
118 119 def _get_prompt_number(self, cell):
119 120 return cell.prompt_number if hasattr(cell, 'prompt_number') \
120 121 else self.blank_symbol
121 122
122 123
123 124 def process(self):
124 125 converted_cells = []
125 126 for worksheet in self.nb.worksheets:
126 127 for cell in worksheet.cells:
127 128 cell.type = cell.cell_type
128 129 cell.haspyout = False
129 130 for out in cell.get('outputs',[]):
130 131 if out.output_type == 'pyout':
131 132 cell.haspyout = True
132 133 break
133 134 converted_cells.append(worksheet)
134 135
135 136 return converted_cells
136 137
137 138 def convert(self, cell_separator='\n'):
138 return self.template.render(worksheets=self.process(), ecss=ecss)
139 return self.template.render(worksheets=self.process(), inlining=inlining)
139 140
140 141
141 142 def read(self, filename):
142 143 "read and parse notebook into NotebookNode called self.nb"
143 144 with io.open(filename) as f:
144 145 self.nb = nbformat.read(f, 'json')
145 146
@@ -1,43 +1,45 b''
1 1 {%- extends 'basichtml.tpl' -%}
2 2
3 3 {%- block header -%}
4 4 <html>
5 5 <head>
6 <meta charset="UTF-8">
7 {% for css in inlining.css -%}
6 8 <style type="text/css">
7 {% for css in ecss %}{{css}}
8 {% endfor %}
9 {{css}}
9 10 </style>
11 {% endfor %}
10 12 <script src="https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript">
11 13
12 14 </script>
13 15 <script type="text/javascript">
14 16 init_mathjax = function() {
15 17 if (window.MathJax) {
16 18 // MathJax loaded
17 19 MathJax.Hub.Config({
18 20 tex2jax: {
19 21 inlineMath: [ ['$','$'], ["\\(","\\)"] ],
20 22 displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
21 23 },
22 24 displayAlign: 'left', // Change this to 'center' to center equations.
23 25 "HTML-CSS": {
24 26 styles: {'.MathJax_Display': {"margin": 0}}
25 27 }
26 28 });
27 29 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
28 30 }
29 31 }
30 32 init_mathjax();
31 33 </script>
32 34 </head>
33 35 {%- endblock header -%}
34 36
35 37
36 38 {% block body %}
37 39 <body>{{ super() }}
38 40 </body>
39 41 {%- endblock body %}
40 42
41 43
42 44 {% block footer %}
43 45 </html>{% endblock footer %}
General Comments 0
You need to be logged in to leave comments. Login now