Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2"""
3@file
4@brief Functions to call from the notebook
5"""
6from IPython.display import Javascript, HTML
7from IPython.core.display import display as jdisp
10def set_notebook_name_theNotebook(name="theNotebook", display=True):
11 """
12 This function must be called from the notebook
13 you want to know the name. It relies on
14 a javascript piece of code. It populates
15 the variable ``theNotebook`` with the notebook name.
17 @param name name of the variable to create
18 @param display calls `display <http://ipython.readthedocs.io/en/stable/api/generated/
19 IPython.display.html#IPython.display.display>`_
20 or returns a javascript object
21 @return None or `Javascript <http://ipython.readthedocs.io/en/stable/api/generated/
22 IPython.display.html#IPython.display.Javascript>`_
24 This solution was found at
25 `How to I get the current IPython Notebook name
26 <http://stackoverflow.com/questions/12544056/how-to-i-get-the-current-ipython-notebook-name>`_.
28 The function can be called in a cell.
29 The variable ``theNotebook`` will be available in the next cells.
31 Try function @see fn store_notebook_path if this one does not work.
32 """
33 code = """var kernel = IPython.notebook.kernel;
34 var body = document.body, attribs = body.attributes;
35 var command = "__NAME__ = " + "'"+attribs['data-notebook-name'].value+"'";
36 kernel.execute(command);""".replace(" ", "").replace("__NAME__", name)
38 def get_name():
39 "return name"
40 j = Javascript(code)
41 if display:
42 jdisp(j)
43 return j
44 return get_name()
47def _add_notebook_menu_js():
48 return """
49 function repeat_indent_string(n){
50 var a = "" ;
51 for ( ; n > 0 ; --n)
52 a += " ";
53 return a;
54 }
55 // look up into all sections and builds an automated menu //
56 var update_menu_string = function(begin, lfirst, llast, sformat, send, keep_item, begin_format, end_format) {
57 var anchors = document.getElementsByClassName("section");
58 if (anchors.length == 0) {
59 anchors = document.getElementsByClassName("text_cell_render rendered_html");
60 }
61 var i,t;
62 var text_menu = begin;
63 var text_memo = "<pre>\\nlength:" + anchors.length + "\\n";
64 var ind = "";
65 var memo_level = 1;
66 var href;
67 var tags = [];
68 var main_item = 0;
69 var format_open = 0;
70 for (i = 0; i <= llast; i++)
71 tags.push("h" + i);
73 for (i = 0; i < anchors.length; i++) {
74 text_memo += "**" + anchors[i].id + "--\\n";
76 var child = null;
77 for(t = 0; t < tags.length; t++) {
78 var r = anchors[i].getElementsByTagName(tags[t]);
79 if (r.length > 0) {
80 child = r[0];
81 break;
82 }
83 }
84 if (child == null) {
85 text_memo += "null\\n";
86 continue;
87 }
88 if (anchors[i].hasAttribute("id")) {
89 // when converted in RST
90 href = anchors[i].id;
91 text_memo += "#1-" + href;
92 // passer à child suivant (le chercher)
93 }
94 else if (child.hasAttribute("id")) {
95 // in a notebook
96 href = child.id;
97 text_memo += "#2-" + href;
98 }
99 else {
100 text_memo += "#3-" + "*" + "\\n";
101 continue;
102 }
103 var title = child.textContent;
104 var level = parseInt(child.tagName.substring(1,2));
106 text_memo += "--" + level + "?" + lfirst + "--" + title + "\\n";
108 if ((level < lfirst) || (level > llast)) {
109 continue ;
110 }
111 if (title.endsWith('¶')) {
112 title = title.substring(0,title.length-1).replace("<", "<")
113 .replace(">", ">").replace("&", "&");
114 }
115 if (title.length == 0) {
116 continue;
117 }
119 while (level < memo_level) {
120 text_menu += end_format + "</ul>\\n";
121 format_open -= 1;
122 memo_level -= 1;
123 }
124 if (level == lfirst) {
125 main_item += 1;
126 }
127 if (keep_item != -1 && main_item != keep_item + 1) {
128 // alert(main_item + " - " + level + " - " + keep_item);
129 continue;
130 }
131 while (level > memo_level) {
132 text_menu += "<ul>\\n";
133 memo_level += 1;
134 }
135 text_menu += repeat_indent_string(level-2);
136 text_menu += begin_format + sformat.replace("__HREF__", href).replace("__TITLE__", title);
137 format_open += 1;
138 }
139 while (1 < memo_level) {
140 text_menu += end_format + "</ul>\\n";
141 memo_level -= 1;
142 format_open -= 1;
143 }
144 text_menu += send;
145 //text_menu += "\\n" + text_memo;
147 while (format_open > 0) {
148 text_menu += end_format;
149 format_open -= 1;
150 }
151 return text_menu;
152 };
153 var update_menu = function() {
154 var sbegin = "__BEGIN__";
155 var sformat = __FORMAT__;
156 var send = "__END__";
157 var begin_format = __BEGIN_FORMAT__;
158 var end_format = __END_FORMAT__;
159 var keep_item = __KEEP_ITEM__;
160 var text_menu = update_menu_string(sbegin, __FIRST__, __LAST__, sformat, send, keep_item,
161 begin_format, end_format);
162 var menu = document.getElementById("__MENUID__");
163 menu.innerHTML=text_menu;
164 };
165 window.setTimeout(update_menu,2000);
166 """
169def add_notebook_menu(menu_id="my_id_menu_nb", raw=False, format="html", header=None,
170 first_level=2, last_level=4, keep_item=None):
171 """
172 Adds :epkg:`javascript` and :epkg:`HTML` to the notebook
173 which gathers all in the notebook and builds a menu.
175 @param menu_id menu_id
176 @param raw raw HTML and Javascript
177 @param format *html* or *rst*
178 @param header title of the menu (None for None)
179 @param first_level first level to consider
180 @param last_level last level to consider
181 @param keep_item None or integer (starts at 0), reduce the number of displayed items to 1
182 and its descendant
183 @return HTML object
185 In a notebook, it is easier to do by using a magic command
186 ``%%html`` for the HTML and another one
187 ``%%javascript`` for the Javascript.
188 This function returns a full text with :epkg:`HTML` and
189 :epkg:`javascript`.
191 If the format is :epkg:`RST`, the menu can be copied/pasted in a text cell.
193 On the notebook, the instruction would work::
195 var anchors = document.getElementsByClassName("anchor-link");
197 But it fails during the conversion from a notebook to format RST.
198 """
199 if keep_item is not None:
200 menu_id += str(keep_item)
201 html = '<div id="{0}">run previous cell, wait for 2 seconds</div>'.format(
202 menu_id)
204 add_notebook_menu_js = _add_notebook_menu_js()
205 js = add_notebook_menu_js.replace(" ", "") \
206 .replace("__MENUID__", menu_id) \
207 .replace("__FIRST__", str(first_level)) \
208 .replace("__LAST__", str(last_level))
210 full = "{0}\n<script>{1}</script>".format(html, js)
211 if keep_item is None:
212 keep_item = -1
214 if format == "html":
215 if header is not None and len(header) > 0:
216 header = "<b>{0}</b>\n".format(header)
217 else:
218 header = ""
219 full = header + \
220 full.replace("__FORMAT__", """'<a href="#__HREF__">__TITLE__</a>'""") \
221 .replace("__BEGIN__", "") \
222 .replace("__END__", "") \
223 .replace("__KEEP_ITEM__", str(keep_item)) \
224 .replace("__BEGIN_FORMAT__", "'<li>'") \
225 .replace("__END_FORMAT__", "'</li>'")
226 elif format == "rst":
227 if header is not None and len(header) > 0:
228 header = "{0}\n\n".format(header)
229 else:
230 header = ""
231 full = header + \
232 full.replace("__FORMAT__", """'* [' + title + '](#' + href + ')\\n'""") \
233 .replace("<ul>", "") \
234 .replace("</ul>", "") \
235 .replace("__BEGIN__", "<pre>\\n") \
236 .replace("__END__", "</pre>\\n") \
237 .replace("__KEEP_ITEM__", str(keep_item)) \
238 .replace("__BEGIN_FORMAT__", "") \
239 .replace("__END_FORMAT__", "")
240 else:
241 raise ValueError("format must be html or rst")
243 if raw:
244 return full
245 else:
246 return HTML(full)
249def load_extension(name):
250 """
251 install an extension, checks first it exists,
252 if not displays an exception with the list of them
254 @param name extension name
255 """
256 return Javascript("IPython.utils.load_extensions('%s')" % name)