##// END OF EJS Templates
Merge pull request #6045 from minrk/nbformat4...
Thomas Kluyver -
r18617:482c7bd6 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,3302 +1,3302 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 from __future__ import absolute_import, print_function
14 14
15 15 import __future__
16 16 import abc
17 17 import ast
18 18 import atexit
19 19 import functools
20 20 import os
21 21 import re
22 22 import runpy
23 23 import sys
24 24 import tempfile
25 25 import types
26 26 import subprocess
27 27 from io import open as io_open
28 28
29 29 from IPython.config.configurable import SingletonConfigurable
30 30 from IPython.core import debugger, oinspect
31 31 from IPython.core import magic
32 32 from IPython.core import page
33 33 from IPython.core import prefilter
34 34 from IPython.core import shadowns
35 35 from IPython.core import ultratb
36 36 from IPython.core.alias import AliasManager, AliasError
37 37 from IPython.core.autocall import ExitAutocall
38 38 from IPython.core.builtin_trap import BuiltinTrap
39 39 from IPython.core.events import EventManager, available_events
40 40 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
41 41 from IPython.core.display_trap import DisplayTrap
42 42 from IPython.core.displayhook import DisplayHook
43 43 from IPython.core.displaypub import DisplayPublisher
44 44 from IPython.core.error import InputRejected, UsageError
45 45 from IPython.core.extensions import ExtensionManager
46 46 from IPython.core.formatters import DisplayFormatter
47 47 from IPython.core.history import HistoryManager
48 48 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
49 49 from IPython.core.logger import Logger
50 50 from IPython.core.macro import Macro
51 51 from IPython.core.payload import PayloadManager
52 52 from IPython.core.prefilter import PrefilterManager
53 53 from IPython.core.profiledir import ProfileDir
54 54 from IPython.core.prompts import PromptManager
55 55 from IPython.core.usage import default_banner
56 56 from IPython.lib.latextools import LaTeXTool
57 57 from IPython.testing.skipdoctest import skip_doctest
58 58 from IPython.utils import PyColorize
59 59 from IPython.utils import io
60 60 from IPython.utils import py3compat
61 61 from IPython.utils import openpy
62 62 from IPython.utils.decorators import undoc
63 63 from IPython.utils.io import ask_yes_no
64 64 from IPython.utils.ipstruct import Struct
65 65 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
66 66 from IPython.utils.pickleshare import PickleShareDB
67 67 from IPython.utils.process import system, getoutput
68 68 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
69 69 with_metaclass, iteritems)
70 70 from IPython.utils.strdispatch import StrDispatch
71 71 from IPython.utils.syspathcontext import prepended_to_syspath
72 72 from IPython.utils.text import (format_screen, LSString, SList,
73 73 DollarFormatter)
74 74 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
75 75 List, Unicode, Instance, Type)
76 76 from IPython.utils.warn import warn, error
77 77 import IPython.core.hooks
78 78
79 79 #-----------------------------------------------------------------------------
80 80 # Globals
81 81 #-----------------------------------------------------------------------------
82 82
83 83 # compiled regexps for autoindent management
84 84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 85
86 86 #-----------------------------------------------------------------------------
87 87 # Utilities
88 88 #-----------------------------------------------------------------------------
89 89
90 90 @undoc
91 91 def softspace(file, newvalue):
92 92 """Copied from code.py, to remove the dependency"""
93 93
94 94 oldvalue = 0
95 95 try:
96 96 oldvalue = file.softspace
97 97 except AttributeError:
98 98 pass
99 99 try:
100 100 file.softspace = newvalue
101 101 except (AttributeError, TypeError):
102 102 # "attribute-less object" or "read-only attributes"
103 103 pass
104 104 return oldvalue
105 105
106 106 @undoc
107 107 def no_op(*a, **kw): pass
108 108
109 109 @undoc
110 110 class NoOpContext(object):
111 111 def __enter__(self): pass
112 112 def __exit__(self, type, value, traceback): pass
113 113 no_op_context = NoOpContext()
114 114
115 115 class SpaceInInput(Exception): pass
116 116
117 117 @undoc
118 118 class Bunch: pass
119 119
120 120
121 121 def get_default_colors():
122 122 if sys.platform=='darwin':
123 123 return "LightBG"
124 124 elif os.name=='nt':
125 125 return 'Linux'
126 126 else:
127 127 return 'Linux'
128 128
129 129
130 130 class SeparateUnicode(Unicode):
131 131 r"""A Unicode subclass to validate separate_in, separate_out, etc.
132 132
133 133 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
134 134 """
135 135
136 136 def validate(self, obj, value):
137 137 if value == '0': value = ''
138 138 value = value.replace('\\n','\n')
139 139 return super(SeparateUnicode, self).validate(obj, value)
140 140
141 141
142 142 class ReadlineNoRecord(object):
143 143 """Context manager to execute some code, then reload readline history
144 144 so that interactive input to the code doesn't appear when pressing up."""
145 145 def __init__(self, shell):
146 146 self.shell = shell
147 147 self._nested_level = 0
148 148
149 149 def __enter__(self):
150 150 if self._nested_level == 0:
151 151 try:
152 152 self.orig_length = self.current_length()
153 153 self.readline_tail = self.get_readline_tail()
154 154 except (AttributeError, IndexError): # Can fail with pyreadline
155 155 self.orig_length, self.readline_tail = 999999, []
156 156 self._nested_level += 1
157 157
158 158 def __exit__(self, type, value, traceback):
159 159 self._nested_level -= 1
160 160 if self._nested_level == 0:
161 161 # Try clipping the end if it's got longer
162 162 try:
163 163 e = self.current_length() - self.orig_length
164 164 if e > 0:
165 165 for _ in range(e):
166 166 self.shell.readline.remove_history_item(self.orig_length)
167 167
168 168 # If it still doesn't match, just reload readline history.
169 169 if self.current_length() != self.orig_length \
170 170 or self.get_readline_tail() != self.readline_tail:
171 171 self.shell.refill_readline_hist()
172 172 except (AttributeError, IndexError):
173 173 pass
174 174 # Returning False will cause exceptions to propagate
175 175 return False
176 176
177 177 def current_length(self):
178 178 return self.shell.readline.get_current_history_length()
179 179
180 180 def get_readline_tail(self, n=10):
181 181 """Get the last n items in readline history."""
182 182 end = self.shell.readline.get_current_history_length() + 1
183 183 start = max(end-n, 1)
184 184 ghi = self.shell.readline.get_history_item
185 185 return [ghi(x) for x in range(start, end)]
186 186
187 187
188 188 @undoc
189 189 class DummyMod(object):
190 190 """A dummy module used for IPython's interactive module when
191 191 a namespace must be assigned to the module's __dict__."""
192 192 pass
193 193
194 194 #-----------------------------------------------------------------------------
195 195 # Main IPython class
196 196 #-----------------------------------------------------------------------------
197 197
198 198 class InteractiveShell(SingletonConfigurable):
199 199 """An enhanced, interactive shell for Python."""
200 200
201 201 _instance = None
202 202
203 203 ast_transformers = List([], config=True, help=
204 204 """
205 205 A list of ast.NodeTransformer subclass instances, which will be applied
206 206 to user input before code is run.
207 207 """
208 208 )
209 209
210 210 autocall = Enum((0,1,2), default_value=0, config=True, help=
211 211 """
212 212 Make IPython automatically call any callable object even if you didn't
213 213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 214 automatically. The value can be '0' to disable the feature, '1' for
215 215 'smart' autocall, where it is not applied if there are no more
216 216 arguments on the line, and '2' for 'full' autocall, where all callable
217 217 objects are automatically called (even if no arguments are present).
218 218 """
219 219 )
220 220 # TODO: remove all autoindent logic and put into frontends.
221 221 # We can't do this yet because even runlines uses the autoindent.
222 222 autoindent = CBool(True, config=True, help=
223 223 """
224 224 Autoindent IPython code entered interactively.
225 225 """
226 226 )
227 227 automagic = CBool(True, config=True, help=
228 228 """
229 229 Enable magic commands to be called without the leading %.
230 230 """
231 231 )
232 232
233 233 banner = Unicode('')
234 234
235 235 banner1 = Unicode(default_banner, config=True,
236 236 help="""The part of the banner to be printed before the profile"""
237 237 )
238 238 banner2 = Unicode('', config=True,
239 239 help="""The part of the banner to be printed after the profile"""
240 240 )
241 241
242 242 cache_size = Integer(1000, config=True, help=
243 243 """
244 244 Set the size of the output cache. The default is 1000, you can
245 245 change it permanently in your config file. Setting it to 0 completely
246 246 disables the caching system, and the minimum value accepted is 20 (if
247 247 you provide a value less than 20, it is reset to 0 and a warning is
248 248 issued). This limit is defined because otherwise you'll spend more
249 249 time re-flushing a too small cache than working
250 250 """
251 251 )
252 252 color_info = CBool(True, config=True, help=
253 253 """
254 254 Use colors for displaying information about objects. Because this
255 255 information is passed through a pager (like 'less'), and some pagers
256 256 get confused with color codes, this capability can be turned off.
257 257 """
258 258 )
259 259 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
260 260 default_value=get_default_colors(), config=True,
261 261 help="Set the color scheme (NoColor, Linux, or LightBG)."
262 262 )
263 263 colors_force = CBool(False, help=
264 264 """
265 265 Force use of ANSI color codes, regardless of OS and readline
266 266 availability.
267 267 """
268 268 # FIXME: This is essentially a hack to allow ZMQShell to show colors
269 269 # without readline on Win32. When the ZMQ formatting system is
270 270 # refactored, this should be removed.
271 271 )
272 272 debug = CBool(False, config=True)
273 273 deep_reload = CBool(False, config=True, help=
274 274 """
275 275 Enable deep (recursive) reloading by default. IPython can use the
276 276 deep_reload module which reloads changes in modules recursively (it
277 277 replaces the reload() function, so you don't need to change anything to
278 278 use it). deep_reload() forces a full reload of modules whose code may
279 279 have changed, which the default reload() function does not. When
280 280 deep_reload is off, IPython will use the normal reload(), but
281 281 deep_reload will still be available as dreload().
282 282 """
283 283 )
284 284 disable_failing_post_execute = CBool(False, config=True,
285 285 help="Don't call post-execute functions that have failed in the past."
286 286 )
287 287 display_formatter = Instance(DisplayFormatter)
288 288 displayhook_class = Type(DisplayHook)
289 289 display_pub_class = Type(DisplayPublisher)
290 290 data_pub_class = None
291 291
292 292 exit_now = CBool(False)
293 293 exiter = Instance(ExitAutocall)
294 294 def _exiter_default(self):
295 295 return ExitAutocall(self)
296 296 # Monotonically increasing execution counter
297 297 execution_count = Integer(1)
298 298 filename = Unicode("<ipython console>")
299 299 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
300 300
301 301 # Input splitter, to transform input line by line and detect when a block
302 302 # is ready to be executed.
303 303 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
304 304 (), {'line_input_checker': True})
305 305
306 306 # This InputSplitter instance is used to transform completed cells before
307 307 # running them. It allows cell magics to contain blank lines.
308 308 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
309 309 (), {'line_input_checker': False})
310 310
311 311 logstart = CBool(False, config=True, help=
312 312 """
313 313 Start logging to the default log file.
314 314 """
315 315 )
316 316 logfile = Unicode('', config=True, help=
317 317 """
318 318 The name of the logfile to use.
319 319 """
320 320 )
321 321 logappend = Unicode('', config=True, help=
322 322 """
323 323 Start logging to the given file in append mode.
324 324 """
325 325 )
326 326 object_info_string_level = Enum((0,1,2), default_value=0,
327 327 config=True)
328 328 pdb = CBool(False, config=True, help=
329 329 """
330 330 Automatically call the pdb debugger after every exception.
331 331 """
332 332 )
333 333 multiline_history = CBool(sys.platform != 'win32', config=True,
334 334 help="Save multi-line entries as one entry in readline history"
335 335 )
336 336
337 337 # deprecated prompt traits:
338 338
339 339 prompt_in1 = Unicode('In [\\#]: ', config=True,
340 340 help="Deprecated, use PromptManager.in_template")
341 341 prompt_in2 = Unicode(' .\\D.: ', config=True,
342 342 help="Deprecated, use PromptManager.in2_template")
343 343 prompt_out = Unicode('Out[\\#]: ', config=True,
344 344 help="Deprecated, use PromptManager.out_template")
345 345 prompts_pad_left = CBool(True, config=True,
346 346 help="Deprecated, use PromptManager.justify")
347 347
348 348 def _prompt_trait_changed(self, name, old, new):
349 349 table = {
350 350 'prompt_in1' : 'in_template',
351 351 'prompt_in2' : 'in2_template',
352 352 'prompt_out' : 'out_template',
353 353 'prompts_pad_left' : 'justify',
354 354 }
355 355 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
356 356 name=name, newname=table[name])
357 357 )
358 358 # protect against weird cases where self.config may not exist:
359 359 if self.config is not None:
360 360 # propagate to corresponding PromptManager trait
361 361 setattr(self.config.PromptManager, table[name], new)
362 362
363 363 _prompt_in1_changed = _prompt_trait_changed
364 364 _prompt_in2_changed = _prompt_trait_changed
365 365 _prompt_out_changed = _prompt_trait_changed
366 366 _prompt_pad_left_changed = _prompt_trait_changed
367 367
368 368 show_rewritten_input = CBool(True, config=True,
369 369 help="Show rewritten input, e.g. for autocall."
370 370 )
371 371
372 372 quiet = CBool(False, config=True)
373 373
374 374 history_length = Integer(10000, config=True)
375 375
376 376 # The readline stuff will eventually be moved to the terminal subclass
377 377 # but for now, we can't do that as readline is welded in everywhere.
378 378 readline_use = CBool(True, config=True)
379 379 readline_remove_delims = Unicode('-/~', config=True)
380 380 readline_delims = Unicode() # set by init_readline()
381 381 # don't use \M- bindings by default, because they
382 382 # conflict with 8-bit encodings. See gh-58,gh-88
383 383 readline_parse_and_bind = List([
384 384 'tab: complete',
385 385 '"\C-l": clear-screen',
386 386 'set show-all-if-ambiguous on',
387 387 '"\C-o": tab-insert',
388 388 '"\C-r": reverse-search-history',
389 389 '"\C-s": forward-search-history',
390 390 '"\C-p": history-search-backward',
391 391 '"\C-n": history-search-forward',
392 392 '"\e[A": history-search-backward',
393 393 '"\e[B": history-search-forward',
394 394 '"\C-k": kill-line',
395 395 '"\C-u": unix-line-discard',
396 396 ], config=True)
397 397
398 398 _custom_readline_config = False
399 399
400 400 def _readline_parse_and_bind_changed(self, name, old, new):
401 401 # notice that readline config is customized
402 402 # indicates that it should have higher priority than inputrc
403 403 self._custom_readline_config = True
404 404
405 405 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
406 406 default_value='last_expr', config=True,
407 407 help="""
408 408 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
409 409 run interactively (displaying output from expressions).""")
410 410
411 411 # TODO: this part of prompt management should be moved to the frontends.
412 412 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
413 413 separate_in = SeparateUnicode('\n', config=True)
414 414 separate_out = SeparateUnicode('', config=True)
415 415 separate_out2 = SeparateUnicode('', config=True)
416 416 wildcards_case_sensitive = CBool(True, config=True)
417 417 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
418 418 default_value='Context', config=True)
419 419
420 420 # Subcomponents of InteractiveShell
421 421 alias_manager = Instance('IPython.core.alias.AliasManager')
422 422 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
423 423 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
424 424 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
425 425 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
426 426 payload_manager = Instance('IPython.core.payload.PayloadManager')
427 427 history_manager = Instance('IPython.core.history.HistoryManager')
428 428 magics_manager = Instance('IPython.core.magic.MagicsManager')
429 429
430 430 profile_dir = Instance('IPython.core.application.ProfileDir')
431 431 @property
432 432 def profile(self):
433 433 if self.profile_dir is not None:
434 434 name = os.path.basename(self.profile_dir.location)
435 435 return name.replace('profile_','')
436 436
437 437
438 438 # Private interface
439 439 _post_execute = Instance(dict)
440 440
441 441 # Tracks any GUI loop loaded for pylab
442 442 pylab_gui_select = None
443 443
444 444 def __init__(self, ipython_dir=None, profile_dir=None,
445 445 user_module=None, user_ns=None,
446 446 custom_exceptions=((), None), **kwargs):
447 447
448 448 # This is where traits with a config_key argument are updated
449 449 # from the values on config.
450 450 super(InteractiveShell, self).__init__(**kwargs)
451 451 self.configurables = [self]
452 452
453 453 # These are relatively independent and stateless
454 454 self.init_ipython_dir(ipython_dir)
455 455 self.init_profile_dir(profile_dir)
456 456 self.init_instance_attrs()
457 457 self.init_environment()
458 458
459 459 # Check if we're in a virtualenv, and set up sys.path.
460 460 self.init_virtualenv()
461 461
462 462 # Create namespaces (user_ns, user_global_ns, etc.)
463 463 self.init_create_namespaces(user_module, user_ns)
464 464 # This has to be done after init_create_namespaces because it uses
465 465 # something in self.user_ns, but before init_sys_modules, which
466 466 # is the first thing to modify sys.
467 467 # TODO: When we override sys.stdout and sys.stderr before this class
468 468 # is created, we are saving the overridden ones here. Not sure if this
469 469 # is what we want to do.
470 470 self.save_sys_module_state()
471 471 self.init_sys_modules()
472 472
473 473 # While we're trying to have each part of the code directly access what
474 474 # it needs without keeping redundant references to objects, we have too
475 475 # much legacy code that expects ip.db to exist.
476 476 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
477 477
478 478 self.init_history()
479 479 self.init_encoding()
480 480 self.init_prefilter()
481 481
482 482 self.init_syntax_highlighting()
483 483 self.init_hooks()
484 484 self.init_events()
485 485 self.init_pushd_popd_magic()
486 486 # self.init_traceback_handlers use to be here, but we moved it below
487 487 # because it and init_io have to come after init_readline.
488 488 self.init_user_ns()
489 489 self.init_logger()
490 490 self.init_builtins()
491 491
492 492 # The following was in post_config_initialization
493 493 self.init_inspector()
494 494 # init_readline() must come before init_io(), because init_io uses
495 495 # readline related things.
496 496 self.init_readline()
497 497 # We save this here in case user code replaces raw_input, but it needs
498 498 # to be after init_readline(), because PyPy's readline works by replacing
499 499 # raw_input.
500 500 if py3compat.PY3:
501 501 self.raw_input_original = input
502 502 else:
503 503 self.raw_input_original = raw_input
504 504 # init_completer must come after init_readline, because it needs to
505 505 # know whether readline is present or not system-wide to configure the
506 506 # completers, since the completion machinery can now operate
507 507 # independently of readline (e.g. over the network)
508 508 self.init_completer()
509 509 # TODO: init_io() needs to happen before init_traceback handlers
510 510 # because the traceback handlers hardcode the stdout/stderr streams.
511 511 # This logic in in debugger.Pdb and should eventually be changed.
512 512 self.init_io()
513 513 self.init_traceback_handlers(custom_exceptions)
514 514 self.init_prompts()
515 515 self.init_display_formatter()
516 516 self.init_display_pub()
517 517 self.init_data_pub()
518 518 self.init_displayhook()
519 519 self.init_latextool()
520 520 self.init_magics()
521 521 self.init_alias()
522 522 self.init_logstart()
523 523 self.init_pdb()
524 524 self.init_extension_manager()
525 525 self.init_payload()
526 526 self.hooks.late_startup_hook()
527 527 self.events.trigger('shell_initialized', self)
528 528 atexit.register(self.atexit_operations)
529 529
530 530 def get_ipython(self):
531 531 """Return the currently running IPython instance."""
532 532 return self
533 533
534 534 #-------------------------------------------------------------------------
535 535 # Trait changed handlers
536 536 #-------------------------------------------------------------------------
537 537
538 538 def _ipython_dir_changed(self, name, new):
539 539 ensure_dir_exists(new)
540 540
541 541 def set_autoindent(self,value=None):
542 542 """Set the autoindent flag, checking for readline support.
543 543
544 544 If called with no arguments, it acts as a toggle."""
545 545
546 546 if value != 0 and not self.has_readline:
547 547 if os.name == 'posix':
548 548 warn("The auto-indent feature requires the readline library")
549 549 self.autoindent = 0
550 550 return
551 551 if value is None:
552 552 self.autoindent = not self.autoindent
553 553 else:
554 554 self.autoindent = value
555 555
556 556 #-------------------------------------------------------------------------
557 557 # init_* methods called by __init__
558 558 #-------------------------------------------------------------------------
559 559
560 560 def init_ipython_dir(self, ipython_dir):
561 561 if ipython_dir is not None:
562 562 self.ipython_dir = ipython_dir
563 563 return
564 564
565 565 self.ipython_dir = get_ipython_dir()
566 566
567 567 def init_profile_dir(self, profile_dir):
568 568 if profile_dir is not None:
569 569 self.profile_dir = profile_dir
570 570 return
571 571 self.profile_dir =\
572 572 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
573 573
574 574 def init_instance_attrs(self):
575 575 self.more = False
576 576
577 577 # command compiler
578 578 self.compile = CachingCompiler()
579 579
580 580 # Make an empty namespace, which extension writers can rely on both
581 581 # existing and NEVER being used by ipython itself. This gives them a
582 582 # convenient location for storing additional information and state
583 583 # their extensions may require, without fear of collisions with other
584 584 # ipython names that may develop later.
585 585 self.meta = Struct()
586 586
587 587 # Temporary files used for various purposes. Deleted at exit.
588 588 self.tempfiles = []
589 589 self.tempdirs = []
590 590
591 591 # Keep track of readline usage (later set by init_readline)
592 592 self.has_readline = False
593 593
594 594 # keep track of where we started running (mainly for crash post-mortem)
595 595 # This is not being used anywhere currently.
596 596 self.starting_dir = py3compat.getcwd()
597 597
598 598 # Indentation management
599 599 self.indent_current_nsp = 0
600 600
601 601 # Dict to track post-execution functions that have been registered
602 602 self._post_execute = {}
603 603
604 604 def init_environment(self):
605 605 """Any changes we need to make to the user's environment."""
606 606 pass
607 607
608 608 def init_encoding(self):
609 609 # Get system encoding at startup time. Certain terminals (like Emacs
610 610 # under Win32 have it set to None, and we need to have a known valid
611 611 # encoding to use in the raw_input() method
612 612 try:
613 613 self.stdin_encoding = sys.stdin.encoding or 'ascii'
614 614 except AttributeError:
615 615 self.stdin_encoding = 'ascii'
616 616
617 617 def init_syntax_highlighting(self):
618 618 # Python source parser/formatter for syntax highlighting
619 619 pyformat = PyColorize.Parser().format
620 620 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
621 621
622 622 def init_pushd_popd_magic(self):
623 623 # for pushd/popd management
624 624 self.home_dir = get_home_dir()
625 625
626 626 self.dir_stack = []
627 627
628 628 def init_logger(self):
629 629 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
630 630 logmode='rotate')
631 631
632 632 def init_logstart(self):
633 633 """Initialize logging in case it was requested at the command line.
634 634 """
635 635 if self.logappend:
636 636 self.magic('logstart %s append' % self.logappend)
637 637 elif self.logfile:
638 638 self.magic('logstart %s' % self.logfile)
639 639 elif self.logstart:
640 640 self.magic('logstart')
641 641
642 642 def init_builtins(self):
643 643 # A single, static flag that we set to True. Its presence indicates
644 644 # that an IPython shell has been created, and we make no attempts at
645 645 # removing on exit or representing the existence of more than one
646 646 # IPython at a time.
647 647 builtin_mod.__dict__['__IPYTHON__'] = True
648 648
649 649 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
650 650 # manage on enter/exit, but with all our shells it's virtually
651 651 # impossible to get all the cases right. We're leaving the name in for
652 652 # those who adapted their codes to check for this flag, but will
653 653 # eventually remove it after a few more releases.
654 654 builtin_mod.__dict__['__IPYTHON__active'] = \
655 655 'Deprecated, check for __IPYTHON__'
656 656
657 657 self.builtin_trap = BuiltinTrap(shell=self)
658 658
659 659 def init_inspector(self):
660 660 # Object inspector
661 661 self.inspector = oinspect.Inspector(oinspect.InspectColors,
662 662 PyColorize.ANSICodeColors,
663 663 'NoColor',
664 664 self.object_info_string_level)
665 665
666 666 def init_io(self):
667 667 # This will just use sys.stdout and sys.stderr. If you want to
668 668 # override sys.stdout and sys.stderr themselves, you need to do that
669 669 # *before* instantiating this class, because io holds onto
670 670 # references to the underlying streams.
671 671 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
672 672 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
673 673 else:
674 674 io.stdout = io.IOStream(sys.stdout)
675 675 io.stderr = io.IOStream(sys.stderr)
676 676
677 677 def init_prompts(self):
678 678 self.prompt_manager = PromptManager(shell=self, parent=self)
679 679 self.configurables.append(self.prompt_manager)
680 680 # Set system prompts, so that scripts can decide if they are running
681 681 # interactively.
682 682 sys.ps1 = 'In : '
683 683 sys.ps2 = '...: '
684 684 sys.ps3 = 'Out: '
685 685
686 686 def init_display_formatter(self):
687 687 self.display_formatter = DisplayFormatter(parent=self)
688 688 self.configurables.append(self.display_formatter)
689 689
690 690 def init_display_pub(self):
691 691 self.display_pub = self.display_pub_class(parent=self)
692 692 self.configurables.append(self.display_pub)
693 693
694 694 def init_data_pub(self):
695 695 if not self.data_pub_class:
696 696 self.data_pub = None
697 697 return
698 698 self.data_pub = self.data_pub_class(parent=self)
699 699 self.configurables.append(self.data_pub)
700 700
701 701 def init_displayhook(self):
702 702 # Initialize displayhook, set in/out prompts and printing system
703 703 self.displayhook = self.displayhook_class(
704 704 parent=self,
705 705 shell=self,
706 706 cache_size=self.cache_size,
707 707 )
708 708 self.configurables.append(self.displayhook)
709 709 # This is a context manager that installs/revmoes the displayhook at
710 710 # the appropriate time.
711 711 self.display_trap = DisplayTrap(hook=self.displayhook)
712 712
713 713 def init_latextool(self):
714 714 """Configure LaTeXTool."""
715 715 cfg = LaTeXTool.instance(parent=self)
716 716 if cfg not in self.configurables:
717 717 self.configurables.append(cfg)
718 718
719 719 def init_virtualenv(self):
720 720 """Add a virtualenv to sys.path so the user can import modules from it.
721 721 This isn't perfect: it doesn't use the Python interpreter with which the
722 722 virtualenv was built, and it ignores the --no-site-packages option. A
723 723 warning will appear suggesting the user installs IPython in the
724 724 virtualenv, but for many cases, it probably works well enough.
725 725
726 726 Adapted from code snippets online.
727 727
728 728 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
729 729 """
730 730 if 'VIRTUAL_ENV' not in os.environ:
731 731 # Not in a virtualenv
732 732 return
733 733
734 734 # venv detection:
735 735 # stdlib venv may symlink sys.executable, so we can't use realpath.
736 736 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
737 737 # So we just check every item in the symlink tree (generally <= 3)
738 738 p = os.path.normcase(sys.executable)
739 739 paths = [p]
740 740 while os.path.islink(p):
741 741 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
742 742 paths.append(p)
743 743 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
744 744 if any(p.startswith(p_venv) for p in paths):
745 745 # Running properly in the virtualenv, don't need to do anything
746 746 return
747 747
748 748 warn("Attempting to work in a virtualenv. If you encounter problems, please "
749 749 "install IPython inside the virtualenv.")
750 750 if sys.platform == "win32":
751 751 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
752 752 else:
753 753 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
754 754 'python%d.%d' % sys.version_info[:2], 'site-packages')
755 755
756 756 import site
757 757 sys.path.insert(0, virtual_env)
758 758 site.addsitedir(virtual_env)
759 759
760 760 #-------------------------------------------------------------------------
761 761 # Things related to injections into the sys module
762 762 #-------------------------------------------------------------------------
763 763
764 764 def save_sys_module_state(self):
765 765 """Save the state of hooks in the sys module.
766 766
767 767 This has to be called after self.user_module is created.
768 768 """
769 769 self._orig_sys_module_state = {}
770 770 self._orig_sys_module_state['stdin'] = sys.stdin
771 771 self._orig_sys_module_state['stdout'] = sys.stdout
772 772 self._orig_sys_module_state['stderr'] = sys.stderr
773 773 self._orig_sys_module_state['excepthook'] = sys.excepthook
774 774 self._orig_sys_modules_main_name = self.user_module.__name__
775 775 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
776 776
777 777 def restore_sys_module_state(self):
778 778 """Restore the state of the sys module."""
779 779 try:
780 780 for k, v in iteritems(self._orig_sys_module_state):
781 781 setattr(sys, k, v)
782 782 except AttributeError:
783 783 pass
784 784 # Reset what what done in self.init_sys_modules
785 785 if self._orig_sys_modules_main_mod is not None:
786 786 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
787 787
788 788 #-------------------------------------------------------------------------
789 789 # Things related to the banner
790 790 #-------------------------------------------------------------------------
791 791
792 792 @property
793 793 def banner(self):
794 794 banner = self.banner1
795 795 if self.profile and self.profile != 'default':
796 796 banner += '\nIPython profile: %s\n' % self.profile
797 797 if self.banner2:
798 798 banner += '\n' + self.banner2
799 799 return banner
800 800
801 801 def show_banner(self, banner=None):
802 802 if banner is None:
803 803 banner = self.banner
804 804 self.write(banner)
805 805
806 806 #-------------------------------------------------------------------------
807 807 # Things related to hooks
808 808 #-------------------------------------------------------------------------
809 809
810 810 def init_hooks(self):
811 811 # hooks holds pointers used for user-side customizations
812 812 self.hooks = Struct()
813 813
814 814 self.strdispatchers = {}
815 815
816 816 # Set all default hooks, defined in the IPython.hooks module.
817 817 hooks = IPython.core.hooks
818 818 for hook_name in hooks.__all__:
819 819 # default hooks have priority 100, i.e. low; user hooks should have
820 820 # 0-100 priority
821 821 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
822 822
823 823 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
824 824 _warn_deprecated=True):
825 825 """set_hook(name,hook) -> sets an internal IPython hook.
826 826
827 827 IPython exposes some of its internal API as user-modifiable hooks. By
828 828 adding your function to one of these hooks, you can modify IPython's
829 829 behavior to call at runtime your own routines."""
830 830
831 831 # At some point in the future, this should validate the hook before it
832 832 # accepts it. Probably at least check that the hook takes the number
833 833 # of args it's supposed to.
834 834
835 835 f = types.MethodType(hook,self)
836 836
837 837 # check if the hook is for strdispatcher first
838 838 if str_key is not None:
839 839 sdp = self.strdispatchers.get(name, StrDispatch())
840 840 sdp.add_s(str_key, f, priority )
841 841 self.strdispatchers[name] = sdp
842 842 return
843 843 if re_key is not None:
844 844 sdp = self.strdispatchers.get(name, StrDispatch())
845 845 sdp.add_re(re.compile(re_key), f, priority )
846 846 self.strdispatchers[name] = sdp
847 847 return
848 848
849 849 dp = getattr(self.hooks, name, None)
850 850 if name not in IPython.core.hooks.__all__:
851 851 print("Warning! Hook '%s' is not one of %s" % \
852 852 (name, IPython.core.hooks.__all__ ))
853 853
854 854 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
855 855 alternative = IPython.core.hooks.deprecated[name]
856 856 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
857 857
858 858 if not dp:
859 859 dp = IPython.core.hooks.CommandChainDispatcher()
860 860
861 861 try:
862 862 dp.add(f,priority)
863 863 except AttributeError:
864 864 # it was not commandchain, plain old func - replace
865 865 dp = f
866 866
867 867 setattr(self.hooks,name, dp)
868 868
869 869 #-------------------------------------------------------------------------
870 870 # Things related to events
871 871 #-------------------------------------------------------------------------
872 872
873 873 def init_events(self):
874 874 self.events = EventManager(self, available_events)
875 875
876 876 self.events.register("pre_execute", self._clear_warning_registry)
877 877
878 878 def register_post_execute(self, func):
879 879 """DEPRECATED: Use ip.events.register('post_run_cell', func)
880 880
881 881 Register a function for calling after code execution.
882 882 """
883 883 warn("ip.register_post_execute is deprecated, use "
884 884 "ip.events.register('post_run_cell', func) instead.")
885 885 self.events.register('post_run_cell', func)
886 886
887 887 def _clear_warning_registry(self):
888 888 # clear the warning registry, so that different code blocks with
889 889 # overlapping line number ranges don't cause spurious suppression of
890 890 # warnings (see gh-6611 for details)
891 891 if "__warningregistry__" in self.user_global_ns:
892 892 del self.user_global_ns["__warningregistry__"]
893 893
894 894 #-------------------------------------------------------------------------
895 895 # Things related to the "main" module
896 896 #-------------------------------------------------------------------------
897 897
898 898 def new_main_mod(self, filename, modname):
899 899 """Return a new 'main' module object for user code execution.
900 900
901 901 ``filename`` should be the path of the script which will be run in the
902 902 module. Requests with the same filename will get the same module, with
903 903 its namespace cleared.
904 904
905 905 ``modname`` should be the module name - normally either '__main__' or
906 906 the basename of the file without the extension.
907 907
908 908 When scripts are executed via %run, we must keep a reference to their
909 909 __main__ module around so that Python doesn't
910 910 clear it, rendering references to module globals useless.
911 911
912 912 This method keeps said reference in a private dict, keyed by the
913 913 absolute path of the script. This way, for multiple executions of the
914 914 same script we only keep one copy of the namespace (the last one),
915 915 thus preventing memory leaks from old references while allowing the
916 916 objects from the last execution to be accessible.
917 917 """
918 918 filename = os.path.abspath(filename)
919 919 try:
920 920 main_mod = self._main_mod_cache[filename]
921 921 except KeyError:
922 922 main_mod = self._main_mod_cache[filename] = types.ModuleType(
923 923 py3compat.cast_bytes_py2(modname),
924 924 doc="Module created for script run in IPython")
925 925 else:
926 926 main_mod.__dict__.clear()
927 927 main_mod.__name__ = modname
928 928
929 929 main_mod.__file__ = filename
930 930 # It seems pydoc (and perhaps others) needs any module instance to
931 931 # implement a __nonzero__ method
932 932 main_mod.__nonzero__ = lambda : True
933 933
934 934 return main_mod
935 935
936 936 def clear_main_mod_cache(self):
937 937 """Clear the cache of main modules.
938 938
939 939 Mainly for use by utilities like %reset.
940 940
941 941 Examples
942 942 --------
943 943
944 944 In [15]: import IPython
945 945
946 946 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
947 947
948 948 In [17]: len(_ip._main_mod_cache) > 0
949 949 Out[17]: True
950 950
951 951 In [18]: _ip.clear_main_mod_cache()
952 952
953 953 In [19]: len(_ip._main_mod_cache) == 0
954 954 Out[19]: True
955 955 """
956 956 self._main_mod_cache.clear()
957 957
958 958 #-------------------------------------------------------------------------
959 959 # Things related to debugging
960 960 #-------------------------------------------------------------------------
961 961
962 962 def init_pdb(self):
963 963 # Set calling of pdb on exceptions
964 964 # self.call_pdb is a property
965 965 self.call_pdb = self.pdb
966 966
967 967 def _get_call_pdb(self):
968 968 return self._call_pdb
969 969
970 970 def _set_call_pdb(self,val):
971 971
972 972 if val not in (0,1,False,True):
973 973 raise ValueError('new call_pdb value must be boolean')
974 974
975 975 # store value in instance
976 976 self._call_pdb = val
977 977
978 978 # notify the actual exception handlers
979 979 self.InteractiveTB.call_pdb = val
980 980
981 981 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
982 982 'Control auto-activation of pdb at exceptions')
983 983
984 984 def debugger(self,force=False):
985 985 """Call the pydb/pdb debugger.
986 986
987 987 Keywords:
988 988
989 989 - force(False): by default, this routine checks the instance call_pdb
990 990 flag and does not actually invoke the debugger if the flag is false.
991 991 The 'force' option forces the debugger to activate even if the flag
992 992 is false.
993 993 """
994 994
995 995 if not (force or self.call_pdb):
996 996 return
997 997
998 998 if not hasattr(sys,'last_traceback'):
999 999 error('No traceback has been produced, nothing to debug.')
1000 1000 return
1001 1001
1002 1002 # use pydb if available
1003 1003 if debugger.has_pydb:
1004 1004 from pydb import pm
1005 1005 else:
1006 1006 # fallback to our internal debugger
1007 1007 pm = lambda : self.InteractiveTB.debugger(force=True)
1008 1008
1009 1009 with self.readline_no_record:
1010 1010 pm()
1011 1011
1012 1012 #-------------------------------------------------------------------------
1013 1013 # Things related to IPython's various namespaces
1014 1014 #-------------------------------------------------------------------------
1015 1015 default_user_namespaces = True
1016 1016
1017 1017 def init_create_namespaces(self, user_module=None, user_ns=None):
1018 1018 # Create the namespace where the user will operate. user_ns is
1019 1019 # normally the only one used, and it is passed to the exec calls as
1020 1020 # the locals argument. But we do carry a user_global_ns namespace
1021 1021 # given as the exec 'globals' argument, This is useful in embedding
1022 1022 # situations where the ipython shell opens in a context where the
1023 1023 # distinction between locals and globals is meaningful. For
1024 1024 # non-embedded contexts, it is just the same object as the user_ns dict.
1025 1025
1026 1026 # FIXME. For some strange reason, __builtins__ is showing up at user
1027 1027 # level as a dict instead of a module. This is a manual fix, but I
1028 1028 # should really track down where the problem is coming from. Alex
1029 1029 # Schmolck reported this problem first.
1030 1030
1031 1031 # A useful post by Alex Martelli on this topic:
1032 1032 # Re: inconsistent value from __builtins__
1033 1033 # Von: Alex Martelli <aleaxit@yahoo.com>
1034 1034 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1035 1035 # Gruppen: comp.lang.python
1036 1036
1037 1037 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1038 1038 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1039 1039 # > <type 'dict'>
1040 1040 # > >>> print type(__builtins__)
1041 1041 # > <type 'module'>
1042 1042 # > Is this difference in return value intentional?
1043 1043
1044 1044 # Well, it's documented that '__builtins__' can be either a dictionary
1045 1045 # or a module, and it's been that way for a long time. Whether it's
1046 1046 # intentional (or sensible), I don't know. In any case, the idea is
1047 1047 # that if you need to access the built-in namespace directly, you
1048 1048 # should start with "import __builtin__" (note, no 's') which will
1049 1049 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1050 1050
1051 1051 # These routines return a properly built module and dict as needed by
1052 1052 # the rest of the code, and can also be used by extension writers to
1053 1053 # generate properly initialized namespaces.
1054 1054 if (user_ns is not None) or (user_module is not None):
1055 1055 self.default_user_namespaces = False
1056 1056 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1057 1057
1058 1058 # A record of hidden variables we have added to the user namespace, so
1059 1059 # we can list later only variables defined in actual interactive use.
1060 1060 self.user_ns_hidden = {}
1061 1061
1062 1062 # Now that FakeModule produces a real module, we've run into a nasty
1063 1063 # problem: after script execution (via %run), the module where the user
1064 1064 # code ran is deleted. Now that this object is a true module (needed
1065 1065 # so docetst and other tools work correctly), the Python module
1066 1066 # teardown mechanism runs over it, and sets to None every variable
1067 1067 # present in that module. Top-level references to objects from the
1068 1068 # script survive, because the user_ns is updated with them. However,
1069 1069 # calling functions defined in the script that use other things from
1070 1070 # the script will fail, because the function's closure had references
1071 1071 # to the original objects, which are now all None. So we must protect
1072 1072 # these modules from deletion by keeping a cache.
1073 1073 #
1074 1074 # To avoid keeping stale modules around (we only need the one from the
1075 1075 # last run), we use a dict keyed with the full path to the script, so
1076 1076 # only the last version of the module is held in the cache. Note,
1077 1077 # however, that we must cache the module *namespace contents* (their
1078 1078 # __dict__). Because if we try to cache the actual modules, old ones
1079 1079 # (uncached) could be destroyed while still holding references (such as
1080 1080 # those held by GUI objects that tend to be long-lived)>
1081 1081 #
1082 1082 # The %reset command will flush this cache. See the cache_main_mod()
1083 1083 # and clear_main_mod_cache() methods for details on use.
1084 1084
1085 1085 # This is the cache used for 'main' namespaces
1086 1086 self._main_mod_cache = {}
1087 1087
1088 1088 # A table holding all the namespaces IPython deals with, so that
1089 1089 # introspection facilities can search easily.
1090 1090 self.ns_table = {'user_global':self.user_module.__dict__,
1091 1091 'user_local':self.user_ns,
1092 1092 'builtin':builtin_mod.__dict__
1093 1093 }
1094 1094
1095 1095 @property
1096 1096 def user_global_ns(self):
1097 1097 return self.user_module.__dict__
1098 1098
1099 1099 def prepare_user_module(self, user_module=None, user_ns=None):
1100 1100 """Prepare the module and namespace in which user code will be run.
1101 1101
1102 1102 When IPython is started normally, both parameters are None: a new module
1103 1103 is created automatically, and its __dict__ used as the namespace.
1104 1104
1105 1105 If only user_module is provided, its __dict__ is used as the namespace.
1106 1106 If only user_ns is provided, a dummy module is created, and user_ns
1107 1107 becomes the global namespace. If both are provided (as they may be
1108 1108 when embedding), user_ns is the local namespace, and user_module
1109 1109 provides the global namespace.
1110 1110
1111 1111 Parameters
1112 1112 ----------
1113 1113 user_module : module, optional
1114 1114 The current user module in which IPython is being run. If None,
1115 1115 a clean module will be created.
1116 1116 user_ns : dict, optional
1117 1117 A namespace in which to run interactive commands.
1118 1118
1119 1119 Returns
1120 1120 -------
1121 1121 A tuple of user_module and user_ns, each properly initialised.
1122 1122 """
1123 1123 if user_module is None and user_ns is not None:
1124 1124 user_ns.setdefault("__name__", "__main__")
1125 1125 user_module = DummyMod()
1126 1126 user_module.__dict__ = user_ns
1127 1127
1128 1128 if user_module is None:
1129 1129 user_module = types.ModuleType("__main__",
1130 1130 doc="Automatically created module for IPython interactive environment")
1131 1131
1132 1132 # We must ensure that __builtin__ (without the final 's') is always
1133 1133 # available and pointing to the __builtin__ *module*. For more details:
1134 1134 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1135 1135 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1136 1136 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1137 1137
1138 1138 if user_ns is None:
1139 1139 user_ns = user_module.__dict__
1140 1140
1141 1141 return user_module, user_ns
1142 1142
1143 1143 def init_sys_modules(self):
1144 1144 # We need to insert into sys.modules something that looks like a
1145 1145 # module but which accesses the IPython namespace, for shelve and
1146 1146 # pickle to work interactively. Normally they rely on getting
1147 1147 # everything out of __main__, but for embedding purposes each IPython
1148 1148 # instance has its own private namespace, so we can't go shoving
1149 1149 # everything into __main__.
1150 1150
1151 1151 # note, however, that we should only do this for non-embedded
1152 1152 # ipythons, which really mimic the __main__.__dict__ with their own
1153 1153 # namespace. Embedded instances, on the other hand, should not do
1154 1154 # this because they need to manage the user local/global namespaces
1155 1155 # only, but they live within a 'normal' __main__ (meaning, they
1156 1156 # shouldn't overtake the execution environment of the script they're
1157 1157 # embedded in).
1158 1158
1159 1159 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1160 1160 main_name = self.user_module.__name__
1161 1161 sys.modules[main_name] = self.user_module
1162 1162
1163 1163 def init_user_ns(self):
1164 1164 """Initialize all user-visible namespaces to their minimum defaults.
1165 1165
1166 1166 Certain history lists are also initialized here, as they effectively
1167 1167 act as user namespaces.
1168 1168
1169 1169 Notes
1170 1170 -----
1171 1171 All data structures here are only filled in, they are NOT reset by this
1172 1172 method. If they were not empty before, data will simply be added to
1173 1173 therm.
1174 1174 """
1175 1175 # This function works in two parts: first we put a few things in
1176 1176 # user_ns, and we sync that contents into user_ns_hidden so that these
1177 1177 # initial variables aren't shown by %who. After the sync, we add the
1178 1178 # rest of what we *do* want the user to see with %who even on a new
1179 1179 # session (probably nothing, so theye really only see their own stuff)
1180 1180
1181 1181 # The user dict must *always* have a __builtin__ reference to the
1182 1182 # Python standard __builtin__ namespace, which must be imported.
1183 1183 # This is so that certain operations in prompt evaluation can be
1184 1184 # reliably executed with builtins. Note that we can NOT use
1185 1185 # __builtins__ (note the 's'), because that can either be a dict or a
1186 1186 # module, and can even mutate at runtime, depending on the context
1187 1187 # (Python makes no guarantees on it). In contrast, __builtin__ is
1188 1188 # always a module object, though it must be explicitly imported.
1189 1189
1190 1190 # For more details:
1191 1191 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1192 1192 ns = dict()
1193 1193
1194 1194 # make global variables for user access to the histories
1195 1195 ns['_ih'] = self.history_manager.input_hist_parsed
1196 1196 ns['_oh'] = self.history_manager.output_hist
1197 1197 ns['_dh'] = self.history_manager.dir_hist
1198 1198
1199 1199 ns['_sh'] = shadowns
1200 1200
1201 1201 # user aliases to input and output histories. These shouldn't show up
1202 1202 # in %who, as they can have very large reprs.
1203 1203 ns['In'] = self.history_manager.input_hist_parsed
1204 1204 ns['Out'] = self.history_manager.output_hist
1205 1205
1206 1206 # Store myself as the public api!!!
1207 1207 ns['get_ipython'] = self.get_ipython
1208 1208
1209 1209 ns['exit'] = self.exiter
1210 1210 ns['quit'] = self.exiter
1211 1211
1212 1212 # Sync what we've added so far to user_ns_hidden so these aren't seen
1213 1213 # by %who
1214 1214 self.user_ns_hidden.update(ns)
1215 1215
1216 1216 # Anything put into ns now would show up in %who. Think twice before
1217 1217 # putting anything here, as we really want %who to show the user their
1218 1218 # stuff, not our variables.
1219 1219
1220 1220 # Finally, update the real user's namespace
1221 1221 self.user_ns.update(ns)
1222 1222
1223 1223 @property
1224 1224 def all_ns_refs(self):
1225 1225 """Get a list of references to all the namespace dictionaries in which
1226 1226 IPython might store a user-created object.
1227 1227
1228 1228 Note that this does not include the displayhook, which also caches
1229 1229 objects from the output."""
1230 1230 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1231 1231 [m.__dict__ for m in self._main_mod_cache.values()]
1232 1232
1233 1233 def reset(self, new_session=True):
1234 1234 """Clear all internal namespaces, and attempt to release references to
1235 1235 user objects.
1236 1236
1237 1237 If new_session is True, a new history session will be opened.
1238 1238 """
1239 1239 # Clear histories
1240 1240 self.history_manager.reset(new_session)
1241 1241 # Reset counter used to index all histories
1242 1242 if new_session:
1243 1243 self.execution_count = 1
1244 1244
1245 1245 # Flush cached output items
1246 1246 if self.displayhook.do_full_cache:
1247 1247 self.displayhook.flush()
1248 1248
1249 1249 # The main execution namespaces must be cleared very carefully,
1250 1250 # skipping the deletion of the builtin-related keys, because doing so
1251 1251 # would cause errors in many object's __del__ methods.
1252 1252 if self.user_ns is not self.user_global_ns:
1253 1253 self.user_ns.clear()
1254 1254 ns = self.user_global_ns
1255 1255 drop_keys = set(ns.keys())
1256 1256 drop_keys.discard('__builtin__')
1257 1257 drop_keys.discard('__builtins__')
1258 1258 drop_keys.discard('__name__')
1259 1259 for k in drop_keys:
1260 1260 del ns[k]
1261 1261
1262 1262 self.user_ns_hidden.clear()
1263 1263
1264 1264 # Restore the user namespaces to minimal usability
1265 1265 self.init_user_ns()
1266 1266
1267 1267 # Restore the default and user aliases
1268 1268 self.alias_manager.clear_aliases()
1269 1269 self.alias_manager.init_aliases()
1270 1270
1271 1271 # Flush the private list of module references kept for script
1272 1272 # execution protection
1273 1273 self.clear_main_mod_cache()
1274 1274
1275 1275 def del_var(self, varname, by_name=False):
1276 1276 """Delete a variable from the various namespaces, so that, as
1277 1277 far as possible, we're not keeping any hidden references to it.
1278 1278
1279 1279 Parameters
1280 1280 ----------
1281 1281 varname : str
1282 1282 The name of the variable to delete.
1283 1283 by_name : bool
1284 1284 If True, delete variables with the given name in each
1285 1285 namespace. If False (default), find the variable in the user
1286 1286 namespace, and delete references to it.
1287 1287 """
1288 1288 if varname in ('__builtin__', '__builtins__'):
1289 1289 raise ValueError("Refusing to delete %s" % varname)
1290 1290
1291 1291 ns_refs = self.all_ns_refs
1292 1292
1293 1293 if by_name: # Delete by name
1294 1294 for ns in ns_refs:
1295 1295 try:
1296 1296 del ns[varname]
1297 1297 except KeyError:
1298 1298 pass
1299 1299 else: # Delete by object
1300 1300 try:
1301 1301 obj = self.user_ns[varname]
1302 1302 except KeyError:
1303 1303 raise NameError("name '%s' is not defined" % varname)
1304 1304 # Also check in output history
1305 1305 ns_refs.append(self.history_manager.output_hist)
1306 1306 for ns in ns_refs:
1307 1307 to_delete = [n for n, o in iteritems(ns) if o is obj]
1308 1308 for name in to_delete:
1309 1309 del ns[name]
1310 1310
1311 1311 # displayhook keeps extra references, but not in a dictionary
1312 1312 for name in ('_', '__', '___'):
1313 1313 if getattr(self.displayhook, name) is obj:
1314 1314 setattr(self.displayhook, name, None)
1315 1315
1316 1316 def reset_selective(self, regex=None):
1317 1317 """Clear selective variables from internal namespaces based on a
1318 1318 specified regular expression.
1319 1319
1320 1320 Parameters
1321 1321 ----------
1322 1322 regex : string or compiled pattern, optional
1323 1323 A regular expression pattern that will be used in searching
1324 1324 variable names in the users namespaces.
1325 1325 """
1326 1326 if regex is not None:
1327 1327 try:
1328 1328 m = re.compile(regex)
1329 1329 except TypeError:
1330 1330 raise TypeError('regex must be a string or compiled pattern')
1331 1331 # Search for keys in each namespace that match the given regex
1332 1332 # If a match is found, delete the key/value pair.
1333 1333 for ns in self.all_ns_refs:
1334 1334 for var in ns:
1335 1335 if m.search(var):
1336 1336 del ns[var]
1337 1337
1338 1338 def push(self, variables, interactive=True):
1339 1339 """Inject a group of variables into the IPython user namespace.
1340 1340
1341 1341 Parameters
1342 1342 ----------
1343 1343 variables : dict, str or list/tuple of str
1344 1344 The variables to inject into the user's namespace. If a dict, a
1345 1345 simple update is done. If a str, the string is assumed to have
1346 1346 variable names separated by spaces. A list/tuple of str can also
1347 1347 be used to give the variable names. If just the variable names are
1348 1348 give (list/tuple/str) then the variable values looked up in the
1349 1349 callers frame.
1350 1350 interactive : bool
1351 1351 If True (default), the variables will be listed with the ``who``
1352 1352 magic.
1353 1353 """
1354 1354 vdict = None
1355 1355
1356 1356 # We need a dict of name/value pairs to do namespace updates.
1357 1357 if isinstance(variables, dict):
1358 1358 vdict = variables
1359 1359 elif isinstance(variables, string_types+(list, tuple)):
1360 1360 if isinstance(variables, string_types):
1361 1361 vlist = variables.split()
1362 1362 else:
1363 1363 vlist = variables
1364 1364 vdict = {}
1365 1365 cf = sys._getframe(1)
1366 1366 for name in vlist:
1367 1367 try:
1368 1368 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1369 1369 except:
1370 1370 print('Could not get variable %s from %s' %
1371 1371 (name,cf.f_code.co_name))
1372 1372 else:
1373 1373 raise ValueError('variables must be a dict/str/list/tuple')
1374 1374
1375 1375 # Propagate variables to user namespace
1376 1376 self.user_ns.update(vdict)
1377 1377
1378 1378 # And configure interactive visibility
1379 1379 user_ns_hidden = self.user_ns_hidden
1380 1380 if interactive:
1381 1381 for name in vdict:
1382 1382 user_ns_hidden.pop(name, None)
1383 1383 else:
1384 1384 user_ns_hidden.update(vdict)
1385 1385
1386 1386 def drop_by_id(self, variables):
1387 1387 """Remove a dict of variables from the user namespace, if they are the
1388 1388 same as the values in the dictionary.
1389 1389
1390 1390 This is intended for use by extensions: variables that they've added can
1391 1391 be taken back out if they are unloaded, without removing any that the
1392 1392 user has overwritten.
1393 1393
1394 1394 Parameters
1395 1395 ----------
1396 1396 variables : dict
1397 1397 A dictionary mapping object names (as strings) to the objects.
1398 1398 """
1399 1399 for name, obj in iteritems(variables):
1400 1400 if name in self.user_ns and self.user_ns[name] is obj:
1401 1401 del self.user_ns[name]
1402 1402 self.user_ns_hidden.pop(name, None)
1403 1403
1404 1404 #-------------------------------------------------------------------------
1405 1405 # Things related to object introspection
1406 1406 #-------------------------------------------------------------------------
1407 1407
1408 1408 def _ofind(self, oname, namespaces=None):
1409 1409 """Find an object in the available namespaces.
1410 1410
1411 1411 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1412 1412
1413 1413 Has special code to detect magic functions.
1414 1414 """
1415 1415 oname = oname.strip()
1416 1416 #print '1- oname: <%r>' % oname # dbg
1417 1417 if not oname.startswith(ESC_MAGIC) and \
1418 1418 not oname.startswith(ESC_MAGIC2) and \
1419 1419 not py3compat.isidentifier(oname, dotted=True):
1420 1420 return dict(found=False)
1421 1421
1422 1422 alias_ns = None
1423 1423 if namespaces is None:
1424 1424 # Namespaces to search in:
1425 1425 # Put them in a list. The order is important so that we
1426 1426 # find things in the same order that Python finds them.
1427 1427 namespaces = [ ('Interactive', self.user_ns),
1428 1428 ('Interactive (global)', self.user_global_ns),
1429 1429 ('Python builtin', builtin_mod.__dict__),
1430 1430 ]
1431 1431
1432 1432 # initialize results to 'null'
1433 1433 found = False; obj = None; ospace = None; ds = None;
1434 1434 ismagic = False; isalias = False; parent = None
1435 1435
1436 1436 # We need to special-case 'print', which as of python2.6 registers as a
1437 1437 # function but should only be treated as one if print_function was
1438 1438 # loaded with a future import. In this case, just bail.
1439 1439 if (oname == 'print' and not py3compat.PY3 and not \
1440 1440 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1441 1441 return {'found':found, 'obj':obj, 'namespace':ospace,
1442 1442 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1443 1443
1444 1444 # Look for the given name by splitting it in parts. If the head is
1445 1445 # found, then we look for all the remaining parts as members, and only
1446 1446 # declare success if we can find them all.
1447 1447 oname_parts = oname.split('.')
1448 1448 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1449 1449 for nsname,ns in namespaces:
1450 1450 try:
1451 1451 obj = ns[oname_head]
1452 1452 except KeyError:
1453 1453 continue
1454 1454 else:
1455 1455 #print 'oname_rest:', oname_rest # dbg
1456 1456 for idx, part in enumerate(oname_rest):
1457 1457 try:
1458 1458 parent = obj
1459 1459 # The last part is looked up in a special way to avoid
1460 1460 # descriptor invocation as it may raise or have side
1461 1461 # effects.
1462 1462 if idx == len(oname_rest) - 1:
1463 1463 obj = self._getattr_property(obj, part)
1464 1464 else:
1465 1465 obj = getattr(obj, part)
1466 1466 except:
1467 1467 # Blanket except b/c some badly implemented objects
1468 1468 # allow __getattr__ to raise exceptions other than
1469 1469 # AttributeError, which then crashes IPython.
1470 1470 break
1471 1471 else:
1472 1472 # If we finish the for loop (no break), we got all members
1473 1473 found = True
1474 1474 ospace = nsname
1475 1475 break # namespace loop
1476 1476
1477 1477 # Try to see if it's magic
1478 1478 if not found:
1479 1479 obj = None
1480 1480 if oname.startswith(ESC_MAGIC2):
1481 1481 oname = oname.lstrip(ESC_MAGIC2)
1482 1482 obj = self.find_cell_magic(oname)
1483 1483 elif oname.startswith(ESC_MAGIC):
1484 1484 oname = oname.lstrip(ESC_MAGIC)
1485 1485 obj = self.find_line_magic(oname)
1486 1486 else:
1487 1487 # search without prefix, so run? will find %run?
1488 1488 obj = self.find_line_magic(oname)
1489 1489 if obj is None:
1490 1490 obj = self.find_cell_magic(oname)
1491 1491 if obj is not None:
1492 1492 found = True
1493 1493 ospace = 'IPython internal'
1494 1494 ismagic = True
1495 1495
1496 1496 # Last try: special-case some literals like '', [], {}, etc:
1497 1497 if not found and oname_head in ["''",'""','[]','{}','()']:
1498 1498 obj = eval(oname_head)
1499 1499 found = True
1500 1500 ospace = 'Interactive'
1501 1501
1502 1502 return {'found':found, 'obj':obj, 'namespace':ospace,
1503 1503 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1504 1504
1505 1505 @staticmethod
1506 1506 def _getattr_property(obj, attrname):
1507 1507 """Property-aware getattr to use in object finding.
1508 1508
1509 1509 If attrname represents a property, return it unevaluated (in case it has
1510 1510 side effects or raises an error.
1511 1511
1512 1512 """
1513 1513 if not isinstance(obj, type):
1514 1514 try:
1515 1515 # `getattr(type(obj), attrname)` is not guaranteed to return
1516 1516 # `obj`, but does so for property:
1517 1517 #
1518 1518 # property.__get__(self, None, cls) -> self
1519 1519 #
1520 1520 # The universal alternative is to traverse the mro manually
1521 1521 # searching for attrname in class dicts.
1522 1522 attr = getattr(type(obj), attrname)
1523 1523 except AttributeError:
1524 1524 pass
1525 1525 else:
1526 1526 # This relies on the fact that data descriptors (with both
1527 1527 # __get__ & __set__ magic methods) take precedence over
1528 1528 # instance-level attributes:
1529 1529 #
1530 1530 # class A(object):
1531 1531 # @property
1532 1532 # def foobar(self): return 123
1533 1533 # a = A()
1534 1534 # a.__dict__['foobar'] = 345
1535 1535 # a.foobar # == 123
1536 1536 #
1537 1537 # So, a property may be returned right away.
1538 1538 if isinstance(attr, property):
1539 1539 return attr
1540 1540
1541 1541 # Nothing helped, fall back.
1542 1542 return getattr(obj, attrname)
1543 1543
1544 1544 def _object_find(self, oname, namespaces=None):
1545 1545 """Find an object and return a struct with info about it."""
1546 1546 return Struct(self._ofind(oname, namespaces))
1547 1547
1548 1548 def _inspect(self, meth, oname, namespaces=None, **kw):
1549 1549 """Generic interface to the inspector system.
1550 1550
1551 1551 This function is meant to be called by pdef, pdoc & friends."""
1552 1552 info = self._object_find(oname, namespaces)
1553 1553 if info.found:
1554 1554 pmethod = getattr(self.inspector, meth)
1555 1555 formatter = format_screen if info.ismagic else None
1556 1556 if meth == 'pdoc':
1557 1557 pmethod(info.obj, oname, formatter)
1558 1558 elif meth == 'pinfo':
1559 1559 pmethod(info.obj, oname, formatter, info, **kw)
1560 1560 else:
1561 1561 pmethod(info.obj, oname)
1562 1562 else:
1563 1563 print('Object `%s` not found.' % oname)
1564 1564 return 'not found' # so callers can take other action
1565 1565
1566 1566 def object_inspect(self, oname, detail_level=0):
1567 1567 """Get object info about oname"""
1568 1568 with self.builtin_trap:
1569 1569 info = self._object_find(oname)
1570 1570 if info.found:
1571 1571 return self.inspector.info(info.obj, oname, info=info,
1572 1572 detail_level=detail_level
1573 1573 )
1574 1574 else:
1575 1575 return oinspect.object_info(name=oname, found=False)
1576 1576
1577 1577 def object_inspect_text(self, oname, detail_level=0):
1578 1578 """Get object info as formatted text"""
1579 1579 with self.builtin_trap:
1580 1580 info = self._object_find(oname)
1581 1581 if info.found:
1582 1582 return self.inspector._format_info(info.obj, oname, info=info,
1583 1583 detail_level=detail_level
1584 1584 )
1585 1585 else:
1586 1586 raise KeyError(oname)
1587 1587
1588 1588 #-------------------------------------------------------------------------
1589 1589 # Things related to history management
1590 1590 #-------------------------------------------------------------------------
1591 1591
1592 1592 def init_history(self):
1593 1593 """Sets up the command history, and starts regular autosaves."""
1594 1594 self.history_manager = HistoryManager(shell=self, parent=self)
1595 1595 self.configurables.append(self.history_manager)
1596 1596
1597 1597 #-------------------------------------------------------------------------
1598 1598 # Things related to exception handling and tracebacks (not debugging)
1599 1599 #-------------------------------------------------------------------------
1600 1600
1601 1601 def init_traceback_handlers(self, custom_exceptions):
1602 1602 # Syntax error handler.
1603 1603 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1604 1604
1605 1605 # The interactive one is initialized with an offset, meaning we always
1606 1606 # want to remove the topmost item in the traceback, which is our own
1607 1607 # internal code. Valid modes: ['Plain','Context','Verbose']
1608 1608 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1609 1609 color_scheme='NoColor',
1610 1610 tb_offset = 1,
1611 1611 check_cache=check_linecache_ipython)
1612 1612
1613 1613 # The instance will store a pointer to the system-wide exception hook,
1614 1614 # so that runtime code (such as magics) can access it. This is because
1615 1615 # during the read-eval loop, it may get temporarily overwritten.
1616 1616 self.sys_excepthook = sys.excepthook
1617 1617
1618 1618 # and add any custom exception handlers the user may have specified
1619 1619 self.set_custom_exc(*custom_exceptions)
1620 1620
1621 1621 # Set the exception mode
1622 1622 self.InteractiveTB.set_mode(mode=self.xmode)
1623 1623
1624 1624 def set_custom_exc(self, exc_tuple, handler):
1625 1625 """set_custom_exc(exc_tuple,handler)
1626 1626
1627 1627 Set a custom exception handler, which will be called if any of the
1628 1628 exceptions in exc_tuple occur in the mainloop (specifically, in the
1629 1629 run_code() method).
1630 1630
1631 1631 Parameters
1632 1632 ----------
1633 1633
1634 1634 exc_tuple : tuple of exception classes
1635 1635 A *tuple* of exception classes, for which to call the defined
1636 1636 handler. It is very important that you use a tuple, and NOT A
1637 1637 LIST here, because of the way Python's except statement works. If
1638 1638 you only want to trap a single exception, use a singleton tuple::
1639 1639
1640 1640 exc_tuple == (MyCustomException,)
1641 1641
1642 1642 handler : callable
1643 1643 handler must have the following signature::
1644 1644
1645 1645 def my_handler(self, etype, value, tb, tb_offset=None):
1646 1646 ...
1647 1647 return structured_traceback
1648 1648
1649 1649 Your handler must return a structured traceback (a list of strings),
1650 1650 or None.
1651 1651
1652 1652 This will be made into an instance method (via types.MethodType)
1653 1653 of IPython itself, and it will be called if any of the exceptions
1654 1654 listed in the exc_tuple are caught. If the handler is None, an
1655 1655 internal basic one is used, which just prints basic info.
1656 1656
1657 1657 To protect IPython from crashes, if your handler ever raises an
1658 1658 exception or returns an invalid result, it will be immediately
1659 1659 disabled.
1660 1660
1661 1661 WARNING: by putting in your own exception handler into IPython's main
1662 1662 execution loop, you run a very good chance of nasty crashes. This
1663 1663 facility should only be used if you really know what you are doing."""
1664 1664
1665 1665 assert type(exc_tuple)==type(()) , \
1666 1666 "The custom exceptions must be given AS A TUPLE."
1667 1667
1668 1668 def dummy_handler(self,etype,value,tb,tb_offset=None):
1669 1669 print('*** Simple custom exception handler ***')
1670 1670 print('Exception type :',etype)
1671 1671 print('Exception value:',value)
1672 1672 print('Traceback :',tb)
1673 1673 #print 'Source code :','\n'.join(self.buffer)
1674 1674
1675 1675 def validate_stb(stb):
1676 1676 """validate structured traceback return type
1677 1677
1678 1678 return type of CustomTB *should* be a list of strings, but allow
1679 1679 single strings or None, which are harmless.
1680 1680
1681 1681 This function will *always* return a list of strings,
1682 1682 and will raise a TypeError if stb is inappropriate.
1683 1683 """
1684 1684 msg = "CustomTB must return list of strings, not %r" % stb
1685 1685 if stb is None:
1686 1686 return []
1687 1687 elif isinstance(stb, string_types):
1688 1688 return [stb]
1689 1689 elif not isinstance(stb, list):
1690 1690 raise TypeError(msg)
1691 1691 # it's a list
1692 1692 for line in stb:
1693 1693 # check every element
1694 1694 if not isinstance(line, string_types):
1695 1695 raise TypeError(msg)
1696 1696 return stb
1697 1697
1698 1698 if handler is None:
1699 1699 wrapped = dummy_handler
1700 1700 else:
1701 1701 def wrapped(self,etype,value,tb,tb_offset=None):
1702 1702 """wrap CustomTB handler, to protect IPython from user code
1703 1703
1704 1704 This makes it harder (but not impossible) for custom exception
1705 1705 handlers to crash IPython.
1706 1706 """
1707 1707 try:
1708 1708 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1709 1709 return validate_stb(stb)
1710 1710 except:
1711 1711 # clear custom handler immediately
1712 1712 self.set_custom_exc((), None)
1713 1713 print("Custom TB Handler failed, unregistering", file=io.stderr)
1714 1714 # show the exception in handler first
1715 1715 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1716 1716 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1717 1717 print("The original exception:", file=io.stdout)
1718 1718 stb = self.InteractiveTB.structured_traceback(
1719 1719 (etype,value,tb), tb_offset=tb_offset
1720 1720 )
1721 1721 return stb
1722 1722
1723 1723 self.CustomTB = types.MethodType(wrapped,self)
1724 1724 self.custom_exceptions = exc_tuple
1725 1725
1726 1726 def excepthook(self, etype, value, tb):
1727 1727 """One more defense for GUI apps that call sys.excepthook.
1728 1728
1729 1729 GUI frameworks like wxPython trap exceptions and call
1730 1730 sys.excepthook themselves. I guess this is a feature that
1731 1731 enables them to keep running after exceptions that would
1732 1732 otherwise kill their mainloop. This is a bother for IPython
1733 1733 which excepts to catch all of the program exceptions with a try:
1734 1734 except: statement.
1735 1735
1736 1736 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1737 1737 any app directly invokes sys.excepthook, it will look to the user like
1738 1738 IPython crashed. In order to work around this, we can disable the
1739 1739 CrashHandler and replace it with this excepthook instead, which prints a
1740 1740 regular traceback using our InteractiveTB. In this fashion, apps which
1741 1741 call sys.excepthook will generate a regular-looking exception from
1742 1742 IPython, and the CrashHandler will only be triggered by real IPython
1743 1743 crashes.
1744 1744
1745 1745 This hook should be used sparingly, only in places which are not likely
1746 1746 to be true IPython errors.
1747 1747 """
1748 1748 self.showtraceback((etype, value, tb), tb_offset=0)
1749 1749
1750 1750 def _get_exc_info(self, exc_tuple=None):
1751 1751 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1752 1752
1753 1753 Ensures sys.last_type,value,traceback hold the exc_info we found,
1754 1754 from whichever source.
1755 1755
1756 1756 raises ValueError if none of these contain any information
1757 1757 """
1758 1758 if exc_tuple is None:
1759 1759 etype, value, tb = sys.exc_info()
1760 1760 else:
1761 1761 etype, value, tb = exc_tuple
1762 1762
1763 1763 if etype is None:
1764 1764 if hasattr(sys, 'last_type'):
1765 1765 etype, value, tb = sys.last_type, sys.last_value, \
1766 1766 sys.last_traceback
1767 1767
1768 1768 if etype is None:
1769 1769 raise ValueError("No exception to find")
1770 1770
1771 1771 # Now store the exception info in sys.last_type etc.
1772 1772 # WARNING: these variables are somewhat deprecated and not
1773 1773 # necessarily safe to use in a threaded environment, but tools
1774 1774 # like pdb depend on their existence, so let's set them. If we
1775 1775 # find problems in the field, we'll need to revisit their use.
1776 1776 sys.last_type = etype
1777 1777 sys.last_value = value
1778 1778 sys.last_traceback = tb
1779 1779
1780 1780 return etype, value, tb
1781 1781
1782 1782 def show_usage_error(self, exc):
1783 1783 """Show a short message for UsageErrors
1784 1784
1785 1785 These are special exceptions that shouldn't show a traceback.
1786 1786 """
1787 1787 self.write_err("UsageError: %s" % exc)
1788 1788
1789 1789 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1790 1790 exception_only=False):
1791 1791 """Display the exception that just occurred.
1792 1792
1793 1793 If nothing is known about the exception, this is the method which
1794 1794 should be used throughout the code for presenting user tracebacks,
1795 1795 rather than directly invoking the InteractiveTB object.
1796 1796
1797 1797 A specific showsyntaxerror() also exists, but this method can take
1798 1798 care of calling it if needed, so unless you are explicitly catching a
1799 1799 SyntaxError exception, don't try to analyze the stack manually and
1800 1800 simply call this method."""
1801 1801
1802 1802 try:
1803 1803 try:
1804 1804 etype, value, tb = self._get_exc_info(exc_tuple)
1805 1805 except ValueError:
1806 1806 self.write_err('No traceback available to show.\n')
1807 1807 return
1808 1808
1809 1809 if issubclass(etype, SyntaxError):
1810 1810 # Though this won't be called by syntax errors in the input
1811 1811 # line, there may be SyntaxError cases with imported code.
1812 1812 self.showsyntaxerror(filename)
1813 1813 elif etype is UsageError:
1814 1814 self.show_usage_error(value)
1815 1815 else:
1816 1816 if exception_only:
1817 1817 stb = ['An exception has occurred, use %tb to see '
1818 1818 'the full traceback.\n']
1819 1819 stb.extend(self.InteractiveTB.get_exception_only(etype,
1820 1820 value))
1821 1821 else:
1822 1822 try:
1823 1823 # Exception classes can customise their traceback - we
1824 1824 # use this in IPython.parallel for exceptions occurring
1825 1825 # in the engines. This should return a list of strings.
1826 1826 stb = value._render_traceback_()
1827 1827 except Exception:
1828 1828 stb = self.InteractiveTB.structured_traceback(etype,
1829 1829 value, tb, tb_offset=tb_offset)
1830 1830
1831 1831 self._showtraceback(etype, value, stb)
1832 1832 if self.call_pdb:
1833 1833 # drop into debugger
1834 1834 self.debugger(force=True)
1835 1835 return
1836 1836
1837 1837 # Actually show the traceback
1838 1838 self._showtraceback(etype, value, stb)
1839 1839
1840 1840 except KeyboardInterrupt:
1841 1841 self.write_err("\nKeyboardInterrupt\n")
1842 1842
1843 1843 def _showtraceback(self, etype, evalue, stb):
1844 1844 """Actually show a traceback.
1845 1845
1846 1846 Subclasses may override this method to put the traceback on a different
1847 1847 place, like a side channel.
1848 1848 """
1849 1849 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1850 1850
1851 1851 def showsyntaxerror(self, filename=None):
1852 1852 """Display the syntax error that just occurred.
1853 1853
1854 1854 This doesn't display a stack trace because there isn't one.
1855 1855
1856 1856 If a filename is given, it is stuffed in the exception instead
1857 1857 of what was there before (because Python's parser always uses
1858 1858 "<string>" when reading from a string).
1859 1859 """
1860 1860 etype, value, last_traceback = self._get_exc_info()
1861 1861
1862 1862 if filename and issubclass(etype, SyntaxError):
1863 1863 try:
1864 1864 value.filename = filename
1865 1865 except:
1866 1866 # Not the format we expect; leave it alone
1867 1867 pass
1868 1868
1869 1869 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1870 1870 self._showtraceback(etype, value, stb)
1871 1871
1872 1872 # This is overridden in TerminalInteractiveShell to show a message about
1873 1873 # the %paste magic.
1874 1874 def showindentationerror(self):
1875 1875 """Called by run_cell when there's an IndentationError in code entered
1876 1876 at the prompt.
1877 1877
1878 1878 This is overridden in TerminalInteractiveShell to show a message about
1879 1879 the %paste magic."""
1880 1880 self.showsyntaxerror()
1881 1881
1882 1882 #-------------------------------------------------------------------------
1883 1883 # Things related to readline
1884 1884 #-------------------------------------------------------------------------
1885 1885
1886 1886 def init_readline(self):
1887 1887 """Command history completion/saving/reloading."""
1888 1888
1889 1889 if self.readline_use:
1890 1890 import IPython.utils.rlineimpl as readline
1891 1891
1892 1892 self.rl_next_input = None
1893 1893 self.rl_do_indent = False
1894 1894
1895 1895 if not self.readline_use or not readline.have_readline:
1896 1896 self.has_readline = False
1897 1897 self.readline = None
1898 1898 # Set a number of methods that depend on readline to be no-op
1899 1899 self.readline_no_record = no_op_context
1900 1900 self.set_readline_completer = no_op
1901 1901 self.set_custom_completer = no_op
1902 1902 if self.readline_use:
1903 1903 warn('Readline services not available or not loaded.')
1904 1904 else:
1905 1905 self.has_readline = True
1906 1906 self.readline = readline
1907 1907 sys.modules['readline'] = readline
1908 1908
1909 1909 # Platform-specific configuration
1910 1910 if os.name == 'nt':
1911 1911 # FIXME - check with Frederick to see if we can harmonize
1912 1912 # naming conventions with pyreadline to avoid this
1913 1913 # platform-dependent check
1914 1914 self.readline_startup_hook = readline.set_pre_input_hook
1915 1915 else:
1916 1916 self.readline_startup_hook = readline.set_startup_hook
1917 1917
1918 1918 # Readline config order:
1919 1919 # - IPython config (default value)
1920 1920 # - custom inputrc
1921 1921 # - IPython config (user customized)
1922 1922
1923 1923 # load IPython config before inputrc if default
1924 1924 # skip if libedit because parse_and_bind syntax is different
1925 1925 if not self._custom_readline_config and not readline.uses_libedit:
1926 1926 for rlcommand in self.readline_parse_and_bind:
1927 1927 readline.parse_and_bind(rlcommand)
1928 1928
1929 1929 # Load user's initrc file (readline config)
1930 1930 # Or if libedit is used, load editrc.
1931 1931 inputrc_name = os.environ.get('INPUTRC')
1932 1932 if inputrc_name is None:
1933 1933 inputrc_name = '.inputrc'
1934 1934 if readline.uses_libedit:
1935 1935 inputrc_name = '.editrc'
1936 1936 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1937 1937 if os.path.isfile(inputrc_name):
1938 1938 try:
1939 1939 readline.read_init_file(inputrc_name)
1940 1940 except:
1941 1941 warn('Problems reading readline initialization file <%s>'
1942 1942 % inputrc_name)
1943 1943
1944 1944 # load IPython config after inputrc if user has customized
1945 1945 if self._custom_readline_config:
1946 1946 for rlcommand in self.readline_parse_and_bind:
1947 1947 readline.parse_and_bind(rlcommand)
1948 1948
1949 1949 # Remove some chars from the delimiters list. If we encounter
1950 1950 # unicode chars, discard them.
1951 1951 delims = readline.get_completer_delims()
1952 1952 if not py3compat.PY3:
1953 1953 delims = delims.encode("ascii", "ignore")
1954 1954 for d in self.readline_remove_delims:
1955 1955 delims = delims.replace(d, "")
1956 1956 delims = delims.replace(ESC_MAGIC, '')
1957 1957 readline.set_completer_delims(delims)
1958 1958 # Store these so we can restore them if something like rpy2 modifies
1959 1959 # them.
1960 1960 self.readline_delims = delims
1961 1961 # otherwise we end up with a monster history after a while:
1962 1962 readline.set_history_length(self.history_length)
1963 1963
1964 1964 self.refill_readline_hist()
1965 1965 self.readline_no_record = ReadlineNoRecord(self)
1966 1966
1967 1967 # Configure auto-indent for all platforms
1968 1968 self.set_autoindent(self.autoindent)
1969 1969
1970 1970 def refill_readline_hist(self):
1971 1971 # Load the last 1000 lines from history
1972 1972 self.readline.clear_history()
1973 1973 stdin_encoding = sys.stdin.encoding or "utf-8"
1974 1974 last_cell = u""
1975 1975 for _, _, cell in self.history_manager.get_tail(1000,
1976 1976 include_latest=True):
1977 1977 # Ignore blank lines and consecutive duplicates
1978 1978 cell = cell.rstrip()
1979 1979 if cell and (cell != last_cell):
1980 1980 try:
1981 1981 if self.multiline_history:
1982 1982 self.readline.add_history(py3compat.unicode_to_str(cell,
1983 1983 stdin_encoding))
1984 1984 else:
1985 1985 for line in cell.splitlines():
1986 1986 self.readline.add_history(py3compat.unicode_to_str(line,
1987 1987 stdin_encoding))
1988 1988 last_cell = cell
1989 1989
1990 1990 except TypeError:
1991 1991 # The history DB can get corrupted so it returns strings
1992 1992 # containing null bytes, which readline objects to.
1993 1993 continue
1994 1994
1995 1995 @skip_doctest
1996 1996 def set_next_input(self, s):
1997 1997 """ Sets the 'default' input string for the next command line.
1998 1998
1999 1999 Requires readline.
2000 2000
2001 2001 Example::
2002 2002
2003 2003 In [1]: _ip.set_next_input("Hello Word")
2004 2004 In [2]: Hello Word_ # cursor is here
2005 2005 """
2006 2006 self.rl_next_input = py3compat.cast_bytes_py2(s)
2007 2007
2008 2008 # Maybe move this to the terminal subclass?
2009 2009 def pre_readline(self):
2010 2010 """readline hook to be used at the start of each line.
2011 2011
2012 2012 Currently it handles auto-indent only."""
2013 2013
2014 2014 if self.rl_do_indent:
2015 2015 self.readline.insert_text(self._indent_current_str())
2016 2016 if self.rl_next_input is not None:
2017 2017 self.readline.insert_text(self.rl_next_input)
2018 2018 self.rl_next_input = None
2019 2019
2020 2020 def _indent_current_str(self):
2021 2021 """return the current level of indentation as a string"""
2022 2022 return self.input_splitter.indent_spaces * ' '
2023 2023
2024 2024 #-------------------------------------------------------------------------
2025 2025 # Things related to text completion
2026 2026 #-------------------------------------------------------------------------
2027 2027
2028 2028 def init_completer(self):
2029 2029 """Initialize the completion machinery.
2030 2030
2031 2031 This creates completion machinery that can be used by client code,
2032 2032 either interactively in-process (typically triggered by the readline
2033 2033 library), programatically (such as in test suites) or out-of-prcess
2034 2034 (typically over the network by remote frontends).
2035 2035 """
2036 2036 from IPython.core.completer import IPCompleter
2037 2037 from IPython.core.completerlib import (module_completer,
2038 2038 magic_run_completer, cd_completer, reset_completer)
2039 2039
2040 2040 self.Completer = IPCompleter(shell=self,
2041 2041 namespace=self.user_ns,
2042 2042 global_namespace=self.user_global_ns,
2043 2043 use_readline=self.has_readline,
2044 2044 parent=self,
2045 2045 )
2046 2046 self.configurables.append(self.Completer)
2047 2047
2048 2048 # Add custom completers to the basic ones built into IPCompleter
2049 2049 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2050 2050 self.strdispatchers['complete_command'] = sdisp
2051 2051 self.Completer.custom_completers = sdisp
2052 2052
2053 2053 self.set_hook('complete_command', module_completer, str_key = 'import')
2054 2054 self.set_hook('complete_command', module_completer, str_key = 'from')
2055 2055 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2056 2056 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2057 2057 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2058 2058
2059 2059 # Only configure readline if we truly are using readline. IPython can
2060 2060 # do tab-completion over the network, in GUIs, etc, where readline
2061 2061 # itself may be absent
2062 2062 if self.has_readline:
2063 2063 self.set_readline_completer()
2064 2064
2065 2065 def complete(self, text, line=None, cursor_pos=None):
2066 2066 """Return the completed text and a list of completions.
2067 2067
2068 2068 Parameters
2069 2069 ----------
2070 2070
2071 2071 text : string
2072 2072 A string of text to be completed on. It can be given as empty and
2073 2073 instead a line/position pair are given. In this case, the
2074 2074 completer itself will split the line like readline does.
2075 2075
2076 2076 line : string, optional
2077 2077 The complete line that text is part of.
2078 2078
2079 2079 cursor_pos : int, optional
2080 2080 The position of the cursor on the input line.
2081 2081
2082 2082 Returns
2083 2083 -------
2084 2084 text : string
2085 2085 The actual text that was completed.
2086 2086
2087 2087 matches : list
2088 2088 A sorted list with all possible completions.
2089 2089
2090 2090 The optional arguments allow the completion to take more context into
2091 2091 account, and are part of the low-level completion API.
2092 2092
2093 2093 This is a wrapper around the completion mechanism, similar to what
2094 2094 readline does at the command line when the TAB key is hit. By
2095 2095 exposing it as a method, it can be used by other non-readline
2096 2096 environments (such as GUIs) for text completion.
2097 2097
2098 2098 Simple usage example:
2099 2099
2100 2100 In [1]: x = 'hello'
2101 2101
2102 2102 In [2]: _ip.complete('x.l')
2103 2103 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2104 2104 """
2105 2105
2106 2106 # Inject names into __builtin__ so we can complete on the added names.
2107 2107 with self.builtin_trap:
2108 2108 return self.Completer.complete(text, line, cursor_pos)
2109 2109
2110 2110 def set_custom_completer(self, completer, pos=0):
2111 2111 """Adds a new custom completer function.
2112 2112
2113 2113 The position argument (defaults to 0) is the index in the completers
2114 2114 list where you want the completer to be inserted."""
2115 2115
2116 2116 newcomp = types.MethodType(completer,self.Completer)
2117 2117 self.Completer.matchers.insert(pos,newcomp)
2118 2118
2119 2119 def set_readline_completer(self):
2120 2120 """Reset readline's completer to be our own."""
2121 2121 self.readline.set_completer(self.Completer.rlcomplete)
2122 2122
2123 2123 def set_completer_frame(self, frame=None):
2124 2124 """Set the frame of the completer."""
2125 2125 if frame:
2126 2126 self.Completer.namespace = frame.f_locals
2127 2127 self.Completer.global_namespace = frame.f_globals
2128 2128 else:
2129 2129 self.Completer.namespace = self.user_ns
2130 2130 self.Completer.global_namespace = self.user_global_ns
2131 2131
2132 2132 #-------------------------------------------------------------------------
2133 2133 # Things related to magics
2134 2134 #-------------------------------------------------------------------------
2135 2135
2136 2136 def init_magics(self):
2137 2137 from IPython.core import magics as m
2138 2138 self.magics_manager = magic.MagicsManager(shell=self,
2139 2139 parent=self,
2140 2140 user_magics=m.UserMagics(self))
2141 2141 self.configurables.append(self.magics_manager)
2142 2142
2143 2143 # Expose as public API from the magics manager
2144 2144 self.register_magics = self.magics_manager.register
2145 2145 self.define_magic = self.magics_manager.define_magic
2146 2146
2147 2147 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2148 2148 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2149 2149 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2150 2150 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2151 2151 )
2152 2152
2153 2153 # Register Magic Aliases
2154 2154 mman = self.magics_manager
2155 2155 # FIXME: magic aliases should be defined by the Magics classes
2156 2156 # or in MagicsManager, not here
2157 2157 mman.register_alias('ed', 'edit')
2158 2158 mman.register_alias('hist', 'history')
2159 2159 mman.register_alias('rep', 'recall')
2160 2160 mman.register_alias('SVG', 'svg', 'cell')
2161 2161 mman.register_alias('HTML', 'html', 'cell')
2162 2162 mman.register_alias('file', 'writefile', 'cell')
2163 2163
2164 2164 # FIXME: Move the color initialization to the DisplayHook, which
2165 2165 # should be split into a prompt manager and displayhook. We probably
2166 2166 # even need a centralize colors management object.
2167 2167 self.magic('colors %s' % self.colors)
2168 2168
2169 2169 # Defined here so that it's included in the documentation
2170 2170 @functools.wraps(magic.MagicsManager.register_function)
2171 2171 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2172 2172 self.magics_manager.register_function(func,
2173 2173 magic_kind=magic_kind, magic_name=magic_name)
2174 2174
2175 2175 def run_line_magic(self, magic_name, line):
2176 2176 """Execute the given line magic.
2177 2177
2178 2178 Parameters
2179 2179 ----------
2180 2180 magic_name : str
2181 2181 Name of the desired magic function, without '%' prefix.
2182 2182
2183 2183 line : str
2184 2184 The rest of the input line as a single string.
2185 2185 """
2186 2186 fn = self.find_line_magic(magic_name)
2187 2187 if fn is None:
2188 2188 cm = self.find_cell_magic(magic_name)
2189 2189 etpl = "Line magic function `%%%s` not found%s."
2190 2190 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2191 2191 'did you mean that instead?)' % magic_name )
2192 2192 error(etpl % (magic_name, extra))
2193 2193 else:
2194 2194 # Note: this is the distance in the stack to the user's frame.
2195 2195 # This will need to be updated if the internal calling logic gets
2196 2196 # refactored, or else we'll be expanding the wrong variables.
2197 2197 stack_depth = 2
2198 2198 magic_arg_s = self.var_expand(line, stack_depth)
2199 2199 # Put magic args in a list so we can call with f(*a) syntax
2200 2200 args = [magic_arg_s]
2201 2201 kwargs = {}
2202 2202 # Grab local namespace if we need it:
2203 2203 if getattr(fn, "needs_local_scope", False):
2204 2204 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2205 2205 with self.builtin_trap:
2206 2206 result = fn(*args,**kwargs)
2207 2207 return result
2208 2208
2209 2209 def run_cell_magic(self, magic_name, line, cell):
2210 2210 """Execute the given cell magic.
2211 2211
2212 2212 Parameters
2213 2213 ----------
2214 2214 magic_name : str
2215 2215 Name of the desired magic function, without '%' prefix.
2216 2216
2217 2217 line : str
2218 2218 The rest of the first input line as a single string.
2219 2219
2220 2220 cell : str
2221 2221 The body of the cell as a (possibly multiline) string.
2222 2222 """
2223 2223 fn = self.find_cell_magic(magic_name)
2224 2224 if fn is None:
2225 2225 lm = self.find_line_magic(magic_name)
2226 2226 etpl = "Cell magic `%%{0}` not found{1}."
2227 2227 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2228 2228 'did you mean that instead?)'.format(magic_name))
2229 2229 error(etpl.format(magic_name, extra))
2230 2230 elif cell == '':
2231 2231 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2232 2232 if self.find_line_magic(magic_name) is not None:
2233 2233 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2234 2234 raise UsageError(message)
2235 2235 else:
2236 2236 # Note: this is the distance in the stack to the user's frame.
2237 2237 # This will need to be updated if the internal calling logic gets
2238 2238 # refactored, or else we'll be expanding the wrong variables.
2239 2239 stack_depth = 2
2240 2240 magic_arg_s = self.var_expand(line, stack_depth)
2241 2241 with self.builtin_trap:
2242 2242 result = fn(magic_arg_s, cell)
2243 2243 return result
2244 2244
2245 2245 def find_line_magic(self, magic_name):
2246 2246 """Find and return a line magic by name.
2247 2247
2248 2248 Returns None if the magic isn't found."""
2249 2249 return self.magics_manager.magics['line'].get(magic_name)
2250 2250
2251 2251 def find_cell_magic(self, magic_name):
2252 2252 """Find and return a cell magic by name.
2253 2253
2254 2254 Returns None if the magic isn't found."""
2255 2255 return self.magics_manager.magics['cell'].get(magic_name)
2256 2256
2257 2257 def find_magic(self, magic_name, magic_kind='line'):
2258 2258 """Find and return a magic of the given type by name.
2259 2259
2260 2260 Returns None if the magic isn't found."""
2261 2261 return self.magics_manager.magics[magic_kind].get(magic_name)
2262 2262
2263 2263 def magic(self, arg_s):
2264 2264 """DEPRECATED. Use run_line_magic() instead.
2265 2265
2266 2266 Call a magic function by name.
2267 2267
2268 2268 Input: a string containing the name of the magic function to call and
2269 2269 any additional arguments to be passed to the magic.
2270 2270
2271 2271 magic('name -opt foo bar') is equivalent to typing at the ipython
2272 2272 prompt:
2273 2273
2274 2274 In[1]: %name -opt foo bar
2275 2275
2276 2276 To call a magic without arguments, simply use magic('name').
2277 2277
2278 2278 This provides a proper Python function to call IPython's magics in any
2279 2279 valid Python code you can type at the interpreter, including loops and
2280 2280 compound statements.
2281 2281 """
2282 2282 # TODO: should we issue a loud deprecation warning here?
2283 2283 magic_name, _, magic_arg_s = arg_s.partition(' ')
2284 2284 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2285 2285 return self.run_line_magic(magic_name, magic_arg_s)
2286 2286
2287 2287 #-------------------------------------------------------------------------
2288 2288 # Things related to macros
2289 2289 #-------------------------------------------------------------------------
2290 2290
2291 2291 def define_macro(self, name, themacro):
2292 2292 """Define a new macro
2293 2293
2294 2294 Parameters
2295 2295 ----------
2296 2296 name : str
2297 2297 The name of the macro.
2298 2298 themacro : str or Macro
2299 2299 The action to do upon invoking the macro. If a string, a new
2300 2300 Macro object is created by passing the string to it.
2301 2301 """
2302 2302
2303 2303 from IPython.core import macro
2304 2304
2305 2305 if isinstance(themacro, string_types):
2306 2306 themacro = macro.Macro(themacro)
2307 2307 if not isinstance(themacro, macro.Macro):
2308 2308 raise ValueError('A macro must be a string or a Macro instance.')
2309 2309 self.user_ns[name] = themacro
2310 2310
2311 2311 #-------------------------------------------------------------------------
2312 2312 # Things related to the running of system commands
2313 2313 #-------------------------------------------------------------------------
2314 2314
2315 2315 def system_piped(self, cmd):
2316 2316 """Call the given cmd in a subprocess, piping stdout/err
2317 2317
2318 2318 Parameters
2319 2319 ----------
2320 2320 cmd : str
2321 2321 Command to execute (can not end in '&', as background processes are
2322 2322 not supported. Should not be a command that expects input
2323 2323 other than simple text.
2324 2324 """
2325 2325 if cmd.rstrip().endswith('&'):
2326 2326 # this is *far* from a rigorous test
2327 2327 # We do not support backgrounding processes because we either use
2328 2328 # pexpect or pipes to read from. Users can always just call
2329 2329 # os.system() or use ip.system=ip.system_raw
2330 2330 # if they really want a background process.
2331 2331 raise OSError("Background processes not supported.")
2332 2332
2333 2333 # we explicitly do NOT return the subprocess status code, because
2334 2334 # a non-None value would trigger :func:`sys.displayhook` calls.
2335 2335 # Instead, we store the exit_code in user_ns.
2336 2336 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2337 2337
2338 2338 def system_raw(self, cmd):
2339 2339 """Call the given cmd in a subprocess using os.system on Windows or
2340 2340 subprocess.call using the system shell on other platforms.
2341 2341
2342 2342 Parameters
2343 2343 ----------
2344 2344 cmd : str
2345 2345 Command to execute.
2346 2346 """
2347 2347 cmd = self.var_expand(cmd, depth=1)
2348 2348 # protect os.system from UNC paths on Windows, which it can't handle:
2349 2349 if sys.platform == 'win32':
2350 2350 from IPython.utils._process_win32 import AvoidUNCPath
2351 2351 with AvoidUNCPath() as path:
2352 2352 if path is not None:
2353 2353 cmd = '"pushd %s &&"%s' % (path, cmd)
2354 2354 cmd = py3compat.unicode_to_str(cmd)
2355 2355 ec = os.system(cmd)
2356 2356 else:
2357 2357 cmd = py3compat.unicode_to_str(cmd)
2358 2358 # Call the cmd using the OS shell, instead of the default /bin/sh, if set.
2359 2359 ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None))
2360 2360 # exit code is positive for program failure, or negative for
2361 2361 # terminating signal number.
2362 2362
2363 2363 # Interpret ec > 128 as signal
2364 2364 # Some shells (csh, fish) don't follow sh/bash conventions for exit codes
2365 2365 if ec > 128:
2366 2366 ec = -(ec - 128)
2367 2367
2368 2368 # We explicitly do NOT return the subprocess status code, because
2369 2369 # a non-None value would trigger :func:`sys.displayhook` calls.
2370 2370 # Instead, we store the exit_code in user_ns.
2371 2371 self.user_ns['_exit_code'] = ec
2372 2372
2373 2373 # use piped system by default, because it is better behaved
2374 2374 system = system_piped
2375 2375
2376 2376 def getoutput(self, cmd, split=True, depth=0):
2377 2377 """Get output (possibly including stderr) from a subprocess.
2378 2378
2379 2379 Parameters
2380 2380 ----------
2381 2381 cmd : str
2382 2382 Command to execute (can not end in '&', as background processes are
2383 2383 not supported.
2384 2384 split : bool, optional
2385 2385 If True, split the output into an IPython SList. Otherwise, an
2386 2386 IPython LSString is returned. These are objects similar to normal
2387 2387 lists and strings, with a few convenience attributes for easier
2388 2388 manipulation of line-based output. You can use '?' on them for
2389 2389 details.
2390 2390 depth : int, optional
2391 2391 How many frames above the caller are the local variables which should
2392 2392 be expanded in the command string? The default (0) assumes that the
2393 2393 expansion variables are in the stack frame calling this function.
2394 2394 """
2395 2395 if cmd.rstrip().endswith('&'):
2396 2396 # this is *far* from a rigorous test
2397 2397 raise OSError("Background processes not supported.")
2398 2398 out = getoutput(self.var_expand(cmd, depth=depth+1))
2399 2399 if split:
2400 2400 out = SList(out.splitlines())
2401 2401 else:
2402 2402 out = LSString(out)
2403 2403 return out
2404 2404
2405 2405 #-------------------------------------------------------------------------
2406 2406 # Things related to aliases
2407 2407 #-------------------------------------------------------------------------
2408 2408
2409 2409 def init_alias(self):
2410 2410 self.alias_manager = AliasManager(shell=self, parent=self)
2411 2411 self.configurables.append(self.alias_manager)
2412 2412
2413 2413 #-------------------------------------------------------------------------
2414 2414 # Things related to extensions
2415 2415 #-------------------------------------------------------------------------
2416 2416
2417 2417 def init_extension_manager(self):
2418 2418 self.extension_manager = ExtensionManager(shell=self, parent=self)
2419 2419 self.configurables.append(self.extension_manager)
2420 2420
2421 2421 #-------------------------------------------------------------------------
2422 2422 # Things related to payloads
2423 2423 #-------------------------------------------------------------------------
2424 2424
2425 2425 def init_payload(self):
2426 2426 self.payload_manager = PayloadManager(parent=self)
2427 2427 self.configurables.append(self.payload_manager)
2428 2428
2429 2429 #-------------------------------------------------------------------------
2430 2430 # Things related to the prefilter
2431 2431 #-------------------------------------------------------------------------
2432 2432
2433 2433 def init_prefilter(self):
2434 2434 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2435 2435 self.configurables.append(self.prefilter_manager)
2436 2436 # Ultimately this will be refactored in the new interpreter code, but
2437 2437 # for now, we should expose the main prefilter method (there's legacy
2438 2438 # code out there that may rely on this).
2439 2439 self.prefilter = self.prefilter_manager.prefilter_lines
2440 2440
2441 2441 def auto_rewrite_input(self, cmd):
2442 2442 """Print to the screen the rewritten form of the user's command.
2443 2443
2444 2444 This shows visual feedback by rewriting input lines that cause
2445 2445 automatic calling to kick in, like::
2446 2446
2447 2447 /f x
2448 2448
2449 2449 into::
2450 2450
2451 2451 ------> f(x)
2452 2452
2453 2453 after the user's input prompt. This helps the user understand that the
2454 2454 input line was transformed automatically by IPython.
2455 2455 """
2456 2456 if not self.show_rewritten_input:
2457 2457 return
2458 2458
2459 2459 rw = self.prompt_manager.render('rewrite') + cmd
2460 2460
2461 2461 try:
2462 2462 # plain ascii works better w/ pyreadline, on some machines, so
2463 2463 # we use it and only print uncolored rewrite if we have unicode
2464 2464 rw = str(rw)
2465 2465 print(rw, file=io.stdout)
2466 2466 except UnicodeEncodeError:
2467 2467 print("------> " + cmd)
2468 2468
2469 2469 #-------------------------------------------------------------------------
2470 2470 # Things related to extracting values/expressions from kernel and user_ns
2471 2471 #-------------------------------------------------------------------------
2472 2472
2473 2473 def _user_obj_error(self):
2474 2474 """return simple exception dict
2475 2475
2476 2476 for use in user_expressions
2477 2477 """
2478 2478
2479 2479 etype, evalue, tb = self._get_exc_info()
2480 2480 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2481 2481
2482 2482 exc_info = {
2483 2483 u'status' : 'error',
2484 2484 u'traceback' : stb,
2485 2485 u'ename' : unicode_type(etype.__name__),
2486 2486 u'evalue' : py3compat.safe_unicode(evalue),
2487 2487 }
2488 2488
2489 2489 return exc_info
2490 2490
2491 2491 def _format_user_obj(self, obj):
2492 2492 """format a user object to display dict
2493 2493
2494 2494 for use in user_expressions
2495 2495 """
2496 2496
2497 2497 data, md = self.display_formatter.format(obj)
2498 2498 value = {
2499 2499 'status' : 'ok',
2500 2500 'data' : data,
2501 2501 'metadata' : md,
2502 2502 }
2503 2503 return value
2504 2504
2505 2505 def user_expressions(self, expressions):
2506 2506 """Evaluate a dict of expressions in the user's namespace.
2507 2507
2508 2508 Parameters
2509 2509 ----------
2510 2510 expressions : dict
2511 2511 A dict with string keys and string values. The expression values
2512 2512 should be valid Python expressions, each of which will be evaluated
2513 2513 in the user namespace.
2514 2514
2515 2515 Returns
2516 2516 -------
2517 2517 A dict, keyed like the input expressions dict, with the rich mime-typed
2518 2518 display_data of each value.
2519 2519 """
2520 2520 out = {}
2521 2521 user_ns = self.user_ns
2522 2522 global_ns = self.user_global_ns
2523 2523
2524 2524 for key, expr in iteritems(expressions):
2525 2525 try:
2526 2526 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2527 2527 except:
2528 2528 value = self._user_obj_error()
2529 2529 out[key] = value
2530 2530 return out
2531 2531
2532 2532 #-------------------------------------------------------------------------
2533 2533 # Things related to the running of code
2534 2534 #-------------------------------------------------------------------------
2535 2535
2536 2536 def ex(self, cmd):
2537 2537 """Execute a normal python statement in user namespace."""
2538 2538 with self.builtin_trap:
2539 2539 exec(cmd, self.user_global_ns, self.user_ns)
2540 2540
2541 2541 def ev(self, expr):
2542 2542 """Evaluate python expression expr in user namespace.
2543 2543
2544 2544 Returns the result of evaluation
2545 2545 """
2546 2546 with self.builtin_trap:
2547 2547 return eval(expr, self.user_global_ns, self.user_ns)
2548 2548
2549 2549 def safe_execfile(self, fname, *where, **kw):
2550 2550 """A safe version of the builtin execfile().
2551 2551
2552 2552 This version will never throw an exception, but instead print
2553 2553 helpful error messages to the screen. This only works on pure
2554 2554 Python files with the .py extension.
2555 2555
2556 2556 Parameters
2557 2557 ----------
2558 2558 fname : string
2559 2559 The name of the file to be executed.
2560 2560 where : tuple
2561 2561 One or two namespaces, passed to execfile() as (globals,locals).
2562 2562 If only one is given, it is passed as both.
2563 2563 exit_ignore : bool (False)
2564 2564 If True, then silence SystemExit for non-zero status (it is always
2565 2565 silenced for zero status, as it is so common).
2566 2566 raise_exceptions : bool (False)
2567 2567 If True raise exceptions everywhere. Meant for testing.
2568 2568 shell_futures : bool (False)
2569 2569 If True, the code will share future statements with the interactive
2570 2570 shell. It will both be affected by previous __future__ imports, and
2571 2571 any __future__ imports in the code will affect the shell. If False,
2572 2572 __future__ imports are not shared in either direction.
2573 2573
2574 2574 """
2575 2575 kw.setdefault('exit_ignore', False)
2576 2576 kw.setdefault('raise_exceptions', False)
2577 2577 kw.setdefault('shell_futures', False)
2578 2578
2579 2579 fname = os.path.abspath(os.path.expanduser(fname))
2580 2580
2581 2581 # Make sure we can open the file
2582 2582 try:
2583 2583 with open(fname) as thefile:
2584 2584 pass
2585 2585 except:
2586 2586 warn('Could not open file <%s> for safe execution.' % fname)
2587 2587 return
2588 2588
2589 2589 # Find things also in current directory. This is needed to mimic the
2590 2590 # behavior of running a script from the system command line, where
2591 2591 # Python inserts the script's directory into sys.path
2592 2592 dname = os.path.dirname(fname)
2593 2593
2594 2594 with prepended_to_syspath(dname):
2595 2595 try:
2596 2596 glob, loc = (where + (None, ))[:2]
2597 2597 py3compat.execfile(
2598 2598 fname, glob, loc,
2599 2599 self.compile if kw['shell_futures'] else None)
2600 2600 except SystemExit as status:
2601 2601 # If the call was made with 0 or None exit status (sys.exit(0)
2602 2602 # or sys.exit() ), don't bother showing a traceback, as both of
2603 2603 # these are considered normal by the OS:
2604 2604 # > python -c'import sys;sys.exit(0)'; echo $?
2605 2605 # 0
2606 2606 # > python -c'import sys;sys.exit()'; echo $?
2607 2607 # 0
2608 2608 # For other exit status, we show the exception unless
2609 2609 # explicitly silenced, but only in short form.
2610 2610 if kw['raise_exceptions']:
2611 2611 raise
2612 2612 if status.code and not kw['exit_ignore']:
2613 2613 self.showtraceback(exception_only=True)
2614 2614 except:
2615 2615 if kw['raise_exceptions']:
2616 2616 raise
2617 2617 # tb offset is 2 because we wrap execfile
2618 2618 self.showtraceback(tb_offset=2)
2619 2619
2620 2620 def safe_execfile_ipy(self, fname, shell_futures=False):
2621 2621 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2622 2622
2623 2623 Parameters
2624 2624 ----------
2625 2625 fname : str
2626 2626 The name of the file to execute. The filename must have a
2627 2627 .ipy or .ipynb extension.
2628 2628 shell_futures : bool (False)
2629 2629 If True, the code will share future statements with the interactive
2630 2630 shell. It will both be affected by previous __future__ imports, and
2631 2631 any __future__ imports in the code will affect the shell. If False,
2632 2632 __future__ imports are not shared in either direction.
2633 2633 """
2634 2634 fname = os.path.abspath(os.path.expanduser(fname))
2635 2635
2636 2636 # Make sure we can open the file
2637 2637 try:
2638 2638 with open(fname) as thefile:
2639 2639 pass
2640 2640 except:
2641 2641 warn('Could not open file <%s> for safe execution.' % fname)
2642 2642 return
2643 2643
2644 2644 # Find things also in current directory. This is needed to mimic the
2645 2645 # behavior of running a script from the system command line, where
2646 2646 # Python inserts the script's directory into sys.path
2647 2647 dname = os.path.dirname(fname)
2648 2648
2649 2649 def get_cells():
2650 2650 """generator for sequence of code blocks to run"""
2651 2651 if fname.endswith('.ipynb'):
2652 from IPython.nbformat import current
2653 with open(fname) as f:
2654 nb = current.read(f, 'json')
2655 if not nb.worksheets:
2652 from IPython.nbformat import read
2653 with io_open(fname) as f:
2654 nb = read(f, as_version=4)
2655 if not nb.cells:
2656 2656 return
2657 for cell in nb.worksheets[0].cells:
2657 for cell in nb.cells:
2658 2658 if cell.cell_type == 'code':
2659 yield cell.input
2659 yield cell.source
2660 2660 else:
2661 2661 with open(fname) as f:
2662 2662 yield f.read()
2663 2663
2664 2664 with prepended_to_syspath(dname):
2665 2665 try:
2666 2666 for cell in get_cells():
2667 2667 # self.run_cell currently captures all exceptions
2668 2668 # raised in user code. It would be nice if there were
2669 2669 # versions of run_cell that did raise, so
2670 2670 # we could catch the errors.
2671 2671 self.run_cell(cell, silent=True, shell_futures=shell_futures)
2672 2672 except:
2673 2673 self.showtraceback()
2674 2674 warn('Unknown failure executing file: <%s>' % fname)
2675 2675
2676 2676 def safe_run_module(self, mod_name, where):
2677 2677 """A safe version of runpy.run_module().
2678 2678
2679 2679 This version will never throw an exception, but instead print
2680 2680 helpful error messages to the screen.
2681 2681
2682 2682 `SystemExit` exceptions with status code 0 or None are ignored.
2683 2683
2684 2684 Parameters
2685 2685 ----------
2686 2686 mod_name : string
2687 2687 The name of the module to be executed.
2688 2688 where : dict
2689 2689 The globals namespace.
2690 2690 """
2691 2691 try:
2692 2692 try:
2693 2693 where.update(
2694 2694 runpy.run_module(str(mod_name), run_name="__main__",
2695 2695 alter_sys=True)
2696 2696 )
2697 2697 except SystemExit as status:
2698 2698 if status.code:
2699 2699 raise
2700 2700 except:
2701 2701 self.showtraceback()
2702 2702 warn('Unknown failure executing module: <%s>' % mod_name)
2703 2703
2704 2704 def _run_cached_cell_magic(self, magic_name, line):
2705 2705 """Special method to call a cell magic with the data stored in self.
2706 2706 """
2707 2707 cell = self._current_cell_magic_body
2708 2708 self._current_cell_magic_body = None
2709 2709 return self.run_cell_magic(magic_name, line, cell)
2710 2710
2711 2711 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2712 2712 """Run a complete IPython cell.
2713 2713
2714 2714 Parameters
2715 2715 ----------
2716 2716 raw_cell : str
2717 2717 The code (including IPython code such as %magic functions) to run.
2718 2718 store_history : bool
2719 2719 If True, the raw and translated cell will be stored in IPython's
2720 2720 history. For user code calling back into IPython's machinery, this
2721 2721 should be set to False.
2722 2722 silent : bool
2723 2723 If True, avoid side-effects, such as implicit displayhooks and
2724 2724 and logging. silent=True forces store_history=False.
2725 2725 shell_futures : bool
2726 2726 If True, the code will share future statements with the interactive
2727 2727 shell. It will both be affected by previous __future__ imports, and
2728 2728 any __future__ imports in the code will affect the shell. If False,
2729 2729 __future__ imports are not shared in either direction.
2730 2730 """
2731 2731 if (not raw_cell) or raw_cell.isspace():
2732 2732 return
2733 2733
2734 2734 if silent:
2735 2735 store_history = False
2736 2736
2737 2737 self.events.trigger('pre_execute')
2738 2738 if not silent:
2739 2739 self.events.trigger('pre_run_cell')
2740 2740
2741 2741 # If any of our input transformation (input_transformer_manager or
2742 2742 # prefilter_manager) raises an exception, we store it in this variable
2743 2743 # so that we can display the error after logging the input and storing
2744 2744 # it in the history.
2745 2745 preprocessing_exc_tuple = None
2746 2746 try:
2747 2747 # Static input transformations
2748 2748 cell = self.input_transformer_manager.transform_cell(raw_cell)
2749 2749 except SyntaxError:
2750 2750 preprocessing_exc_tuple = sys.exc_info()
2751 2751 cell = raw_cell # cell has to exist so it can be stored/logged
2752 2752 else:
2753 2753 if len(cell.splitlines()) == 1:
2754 2754 # Dynamic transformations - only applied for single line commands
2755 2755 with self.builtin_trap:
2756 2756 try:
2757 2757 # use prefilter_lines to handle trailing newlines
2758 2758 # restore trailing newline for ast.parse
2759 2759 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2760 2760 except Exception:
2761 2761 # don't allow prefilter errors to crash IPython
2762 2762 preprocessing_exc_tuple = sys.exc_info()
2763 2763
2764 2764 # Store raw and processed history
2765 2765 if store_history:
2766 2766 self.history_manager.store_inputs(self.execution_count,
2767 2767 cell, raw_cell)
2768 2768 if not silent:
2769 2769 self.logger.log(cell, raw_cell)
2770 2770
2771 2771 # Display the exception if input processing failed.
2772 2772 if preprocessing_exc_tuple is not None:
2773 2773 self.showtraceback(preprocessing_exc_tuple)
2774 2774 if store_history:
2775 2775 self.execution_count += 1
2776 2776 return
2777 2777
2778 2778 # Our own compiler remembers the __future__ environment. If we want to
2779 2779 # run code with a separate __future__ environment, use the default
2780 2780 # compiler
2781 2781 compiler = self.compile if shell_futures else CachingCompiler()
2782 2782
2783 2783 with self.builtin_trap:
2784 2784 cell_name = self.compile.cache(cell, self.execution_count)
2785 2785
2786 2786 with self.display_trap:
2787 2787 # Compile to bytecode
2788 2788 try:
2789 2789 code_ast = compiler.ast_parse(cell, filename=cell_name)
2790 2790 except IndentationError:
2791 2791 self.showindentationerror()
2792 2792 if store_history:
2793 2793 self.execution_count += 1
2794 2794 return None
2795 2795 except (OverflowError, SyntaxError, ValueError, TypeError,
2796 2796 MemoryError):
2797 2797 self.showsyntaxerror()
2798 2798 if store_history:
2799 2799 self.execution_count += 1
2800 2800 return None
2801 2801
2802 2802 # Apply AST transformations
2803 2803 try:
2804 2804 code_ast = self.transform_ast(code_ast)
2805 2805 except InputRejected:
2806 2806 self.showtraceback()
2807 2807 if store_history:
2808 2808 self.execution_count += 1
2809 2809 return None
2810 2810
2811 2811 # Execute the user code
2812 2812 interactivity = "none" if silent else self.ast_node_interactivity
2813 2813 self.run_ast_nodes(code_ast.body, cell_name,
2814 2814 interactivity=interactivity, compiler=compiler)
2815 2815
2816 2816 self.events.trigger('post_execute')
2817 2817 if not silent:
2818 2818 self.events.trigger('post_run_cell')
2819 2819
2820 2820 if store_history:
2821 2821 # Write output to the database. Does nothing unless
2822 2822 # history output logging is enabled.
2823 2823 self.history_manager.store_output(self.execution_count)
2824 2824 # Each cell is a *single* input, regardless of how many lines it has
2825 2825 self.execution_count += 1
2826 2826
2827 2827 def transform_ast(self, node):
2828 2828 """Apply the AST transformations from self.ast_transformers
2829 2829
2830 2830 Parameters
2831 2831 ----------
2832 2832 node : ast.Node
2833 2833 The root node to be transformed. Typically called with the ast.Module
2834 2834 produced by parsing user input.
2835 2835
2836 2836 Returns
2837 2837 -------
2838 2838 An ast.Node corresponding to the node it was called with. Note that it
2839 2839 may also modify the passed object, so don't rely on references to the
2840 2840 original AST.
2841 2841 """
2842 2842 for transformer in self.ast_transformers:
2843 2843 try:
2844 2844 node = transformer.visit(node)
2845 2845 except InputRejected:
2846 2846 # User-supplied AST transformers can reject an input by raising
2847 2847 # an InputRejected. Short-circuit in this case so that we
2848 2848 # don't unregister the transform.
2849 2849 raise
2850 2850 except Exception:
2851 2851 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2852 2852 self.ast_transformers.remove(transformer)
2853 2853
2854 2854 if self.ast_transformers:
2855 2855 ast.fix_missing_locations(node)
2856 2856 return node
2857 2857
2858 2858
2859 2859 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2860 2860 compiler=compile):
2861 2861 """Run a sequence of AST nodes. The execution mode depends on the
2862 2862 interactivity parameter.
2863 2863
2864 2864 Parameters
2865 2865 ----------
2866 2866 nodelist : list
2867 2867 A sequence of AST nodes to run.
2868 2868 cell_name : str
2869 2869 Will be passed to the compiler as the filename of the cell. Typically
2870 2870 the value returned by ip.compile.cache(cell).
2871 2871 interactivity : str
2872 2872 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2873 2873 run interactively (displaying output from expressions). 'last_expr'
2874 2874 will run the last node interactively only if it is an expression (i.e.
2875 2875 expressions in loops or other blocks are not displayed. Other values
2876 2876 for this parameter will raise a ValueError.
2877 2877 compiler : callable
2878 2878 A function with the same interface as the built-in compile(), to turn
2879 2879 the AST nodes into code objects. Default is the built-in compile().
2880 2880 """
2881 2881 if not nodelist:
2882 2882 return
2883 2883
2884 2884 if interactivity == 'last_expr':
2885 2885 if isinstance(nodelist[-1], ast.Expr):
2886 2886 interactivity = "last"
2887 2887 else:
2888 2888 interactivity = "none"
2889 2889
2890 2890 if interactivity == 'none':
2891 2891 to_run_exec, to_run_interactive = nodelist, []
2892 2892 elif interactivity == 'last':
2893 2893 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2894 2894 elif interactivity == 'all':
2895 2895 to_run_exec, to_run_interactive = [], nodelist
2896 2896 else:
2897 2897 raise ValueError("Interactivity was %r" % interactivity)
2898 2898
2899 2899 exec_count = self.execution_count
2900 2900
2901 2901 try:
2902 2902 for i, node in enumerate(to_run_exec):
2903 2903 mod = ast.Module([node])
2904 2904 code = compiler(mod, cell_name, "exec")
2905 2905 if self.run_code(code):
2906 2906 return True
2907 2907
2908 2908 for i, node in enumerate(to_run_interactive):
2909 2909 mod = ast.Interactive([node])
2910 2910 code = compiler(mod, cell_name, "single")
2911 2911 if self.run_code(code):
2912 2912 return True
2913 2913
2914 2914 # Flush softspace
2915 2915 if softspace(sys.stdout, 0):
2916 2916 print()
2917 2917
2918 2918 except:
2919 2919 # It's possible to have exceptions raised here, typically by
2920 2920 # compilation of odd code (such as a naked 'return' outside a
2921 2921 # function) that did parse but isn't valid. Typically the exception
2922 2922 # is a SyntaxError, but it's safest just to catch anything and show
2923 2923 # the user a traceback.
2924 2924
2925 2925 # We do only one try/except outside the loop to minimize the impact
2926 2926 # on runtime, and also because if any node in the node list is
2927 2927 # broken, we should stop execution completely.
2928 2928 self.showtraceback()
2929 2929
2930 2930 return False
2931 2931
2932 2932 def run_code(self, code_obj):
2933 2933 """Execute a code object.
2934 2934
2935 2935 When an exception occurs, self.showtraceback() is called to display a
2936 2936 traceback.
2937 2937
2938 2938 Parameters
2939 2939 ----------
2940 2940 code_obj : code object
2941 2941 A compiled code object, to be executed
2942 2942
2943 2943 Returns
2944 2944 -------
2945 2945 False : successful execution.
2946 2946 True : an error occurred.
2947 2947 """
2948 2948 # Set our own excepthook in case the user code tries to call it
2949 2949 # directly, so that the IPython crash handler doesn't get triggered
2950 2950 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2951 2951
2952 2952 # we save the original sys.excepthook in the instance, in case config
2953 2953 # code (such as magics) needs access to it.
2954 2954 self.sys_excepthook = old_excepthook
2955 2955 outflag = 1 # happens in more places, so it's easier as default
2956 2956 try:
2957 2957 try:
2958 2958 self.hooks.pre_run_code_hook()
2959 2959 #rprint('Running code', repr(code_obj)) # dbg
2960 2960 exec(code_obj, self.user_global_ns, self.user_ns)
2961 2961 finally:
2962 2962 # Reset our crash handler in place
2963 2963 sys.excepthook = old_excepthook
2964 2964 except SystemExit:
2965 2965 self.showtraceback(exception_only=True)
2966 2966 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2967 2967 except self.custom_exceptions:
2968 2968 etype, value, tb = sys.exc_info()
2969 2969 self.CustomTB(etype, value, tb)
2970 2970 except:
2971 2971 self.showtraceback()
2972 2972 else:
2973 2973 outflag = 0
2974 2974 return outflag
2975 2975
2976 2976 # For backwards compatibility
2977 2977 runcode = run_code
2978 2978
2979 2979 #-------------------------------------------------------------------------
2980 2980 # Things related to GUI support and pylab
2981 2981 #-------------------------------------------------------------------------
2982 2982
2983 2983 def enable_gui(self, gui=None):
2984 2984 raise NotImplementedError('Implement enable_gui in a subclass')
2985 2985
2986 2986 def enable_matplotlib(self, gui=None):
2987 2987 """Enable interactive matplotlib and inline figure support.
2988 2988
2989 2989 This takes the following steps:
2990 2990
2991 2991 1. select the appropriate eventloop and matplotlib backend
2992 2992 2. set up matplotlib for interactive use with that backend
2993 2993 3. configure formatters for inline figure display
2994 2994 4. enable the selected gui eventloop
2995 2995
2996 2996 Parameters
2997 2997 ----------
2998 2998 gui : optional, string
2999 2999 If given, dictates the choice of matplotlib GUI backend to use
3000 3000 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3001 3001 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3002 3002 matplotlib (as dictated by the matplotlib build-time options plus the
3003 3003 user's matplotlibrc configuration file). Note that not all backends
3004 3004 make sense in all contexts, for example a terminal ipython can't
3005 3005 display figures inline.
3006 3006 """
3007 3007 from IPython.core import pylabtools as pt
3008 3008 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3009 3009
3010 3010 if gui != 'inline':
3011 3011 # If we have our first gui selection, store it
3012 3012 if self.pylab_gui_select is None:
3013 3013 self.pylab_gui_select = gui
3014 3014 # Otherwise if they are different
3015 3015 elif gui != self.pylab_gui_select:
3016 3016 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3017 3017 ' Using %s instead.' % (gui, self.pylab_gui_select))
3018 3018 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3019 3019
3020 3020 pt.activate_matplotlib(backend)
3021 3021 pt.configure_inline_support(self, backend)
3022 3022
3023 3023 # Now we must activate the gui pylab wants to use, and fix %run to take
3024 3024 # plot updates into account
3025 3025 self.enable_gui(gui)
3026 3026 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3027 3027 pt.mpl_runner(self.safe_execfile)
3028 3028
3029 3029 return gui, backend
3030 3030
3031 3031 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3032 3032 """Activate pylab support at runtime.
3033 3033
3034 3034 This turns on support for matplotlib, preloads into the interactive
3035 3035 namespace all of numpy and pylab, and configures IPython to correctly
3036 3036 interact with the GUI event loop. The GUI backend to be used can be
3037 3037 optionally selected with the optional ``gui`` argument.
3038 3038
3039 3039 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3040 3040
3041 3041 Parameters
3042 3042 ----------
3043 3043 gui : optional, string
3044 3044 If given, dictates the choice of matplotlib GUI backend to use
3045 3045 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3046 3046 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3047 3047 matplotlib (as dictated by the matplotlib build-time options plus the
3048 3048 user's matplotlibrc configuration file). Note that not all backends
3049 3049 make sense in all contexts, for example a terminal ipython can't
3050 3050 display figures inline.
3051 3051 import_all : optional, bool, default: True
3052 3052 Whether to do `from numpy import *` and `from pylab import *`
3053 3053 in addition to module imports.
3054 3054 welcome_message : deprecated
3055 3055 This argument is ignored, no welcome message will be displayed.
3056 3056 """
3057 3057 from IPython.core.pylabtools import import_pylab
3058 3058
3059 3059 gui, backend = self.enable_matplotlib(gui)
3060 3060
3061 3061 # We want to prevent the loading of pylab to pollute the user's
3062 3062 # namespace as shown by the %who* magics, so we execute the activation
3063 3063 # code in an empty namespace, and we update *both* user_ns and
3064 3064 # user_ns_hidden with this information.
3065 3065 ns = {}
3066 3066 import_pylab(ns, import_all)
3067 3067 # warn about clobbered names
3068 3068 ignored = set(["__builtins__"])
3069 3069 both = set(ns).intersection(self.user_ns).difference(ignored)
3070 3070 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3071 3071 self.user_ns.update(ns)
3072 3072 self.user_ns_hidden.update(ns)
3073 3073 return gui, backend, clobbered
3074 3074
3075 3075 #-------------------------------------------------------------------------
3076 3076 # Utilities
3077 3077 #-------------------------------------------------------------------------
3078 3078
3079 3079 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3080 3080 """Expand python variables in a string.
3081 3081
3082 3082 The depth argument indicates how many frames above the caller should
3083 3083 be walked to look for the local namespace where to expand variables.
3084 3084
3085 3085 The global namespace for expansion is always the user's interactive
3086 3086 namespace.
3087 3087 """
3088 3088 ns = self.user_ns.copy()
3089 3089 ns.update(sys._getframe(depth+1).f_locals)
3090 3090 try:
3091 3091 # We have to use .vformat() here, because 'self' is a valid and common
3092 3092 # name, and expanding **ns for .format() would make it collide with
3093 3093 # the 'self' argument of the method.
3094 3094 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3095 3095 except Exception:
3096 3096 # if formatter couldn't format, just let it go untransformed
3097 3097 pass
3098 3098 return cmd
3099 3099
3100 3100 def mktempfile(self, data=None, prefix='ipython_edit_'):
3101 3101 """Make a new tempfile and return its filename.
3102 3102
3103 3103 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3104 3104 but it registers the created filename internally so ipython cleans it up
3105 3105 at exit time.
3106 3106
3107 3107 Optional inputs:
3108 3108
3109 3109 - data(None): if data is given, it gets written out to the temp file
3110 3110 immediately, and the file is closed again."""
3111 3111
3112 3112 dirname = tempfile.mkdtemp(prefix=prefix)
3113 3113 self.tempdirs.append(dirname)
3114 3114
3115 3115 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3116 3116 os.close(handle) # On Windows, there can only be one open handle on a file
3117 3117 self.tempfiles.append(filename)
3118 3118
3119 3119 if data:
3120 3120 tmp_file = open(filename,'w')
3121 3121 tmp_file.write(data)
3122 3122 tmp_file.close()
3123 3123 return filename
3124 3124
3125 3125 # TODO: This should be removed when Term is refactored.
3126 3126 def write(self,data):
3127 3127 """Write a string to the default output"""
3128 3128 io.stdout.write(data)
3129 3129
3130 3130 # TODO: This should be removed when Term is refactored.
3131 3131 def write_err(self,data):
3132 3132 """Write a string to the default error output"""
3133 3133 io.stderr.write(data)
3134 3134
3135 3135 def ask_yes_no(self, prompt, default=None):
3136 3136 if self.quiet:
3137 3137 return True
3138 3138 return ask_yes_no(prompt,default)
3139 3139
3140 3140 def show_usage(self):
3141 3141 """Show a usage message"""
3142 3142 page.page(IPython.core.usage.interactive_usage)
3143 3143
3144 3144 def extract_input_lines(self, range_str, raw=False):
3145 3145 """Return as a string a set of input history slices.
3146 3146
3147 3147 Parameters
3148 3148 ----------
3149 3149 range_str : string
3150 3150 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3151 3151 since this function is for use by magic functions which get their
3152 3152 arguments as strings. The number before the / is the session
3153 3153 number: ~n goes n back from the current session.
3154 3154
3155 3155 raw : bool, optional
3156 3156 By default, the processed input is used. If this is true, the raw
3157 3157 input history is used instead.
3158 3158
3159 3159 Notes
3160 3160 -----
3161 3161
3162 3162 Slices can be described with two notations:
3163 3163
3164 3164 * ``N:M`` -> standard python form, means including items N...(M-1).
3165 3165 * ``N-M`` -> include items N..M (closed endpoint).
3166 3166 """
3167 3167 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3168 3168 return "\n".join(x for _, _, x in lines)
3169 3169
3170 3170 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3171 3171 """Get a code string from history, file, url, or a string or macro.
3172 3172
3173 3173 This is mainly used by magic functions.
3174 3174
3175 3175 Parameters
3176 3176 ----------
3177 3177
3178 3178 target : str
3179 3179
3180 3180 A string specifying code to retrieve. This will be tried respectively
3181 3181 as: ranges of input history (see %history for syntax), url,
3182 3182 correspnding .py file, filename, or an expression evaluating to a
3183 3183 string or Macro in the user namespace.
3184 3184
3185 3185 raw : bool
3186 3186 If true (default), retrieve raw history. Has no effect on the other
3187 3187 retrieval mechanisms.
3188 3188
3189 3189 py_only : bool (default False)
3190 3190 Only try to fetch python code, do not try alternative methods to decode file
3191 3191 if unicode fails.
3192 3192
3193 3193 Returns
3194 3194 -------
3195 3195 A string of code.
3196 3196
3197 3197 ValueError is raised if nothing is found, and TypeError if it evaluates
3198 3198 to an object of another type. In each case, .args[0] is a printable
3199 3199 message.
3200 3200 """
3201 3201 code = self.extract_input_lines(target, raw=raw) # Grab history
3202 3202 if code:
3203 3203 return code
3204 3204 utarget = unquote_filename(target)
3205 3205 try:
3206 3206 if utarget.startswith(('http://', 'https://')):
3207 3207 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3208 3208 except UnicodeDecodeError:
3209 3209 if not py_only :
3210 3210 # Deferred import
3211 3211 try:
3212 3212 from urllib.request import urlopen # Py3
3213 3213 except ImportError:
3214 3214 from urllib import urlopen
3215 3215 response = urlopen(target)
3216 3216 return response.read().decode('latin1')
3217 3217 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3218 3218
3219 3219 potential_target = [target]
3220 3220 try :
3221 3221 potential_target.insert(0,get_py_filename(target))
3222 3222 except IOError:
3223 3223 pass
3224 3224
3225 3225 for tgt in potential_target :
3226 3226 if os.path.isfile(tgt): # Read file
3227 3227 try :
3228 3228 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3229 3229 except UnicodeDecodeError :
3230 3230 if not py_only :
3231 3231 with io_open(tgt,'r', encoding='latin1') as f :
3232 3232 return f.read()
3233 3233 raise ValueError(("'%s' seem to be unreadable.") % target)
3234 3234 elif os.path.isdir(os.path.expanduser(tgt)):
3235 3235 raise ValueError("'%s' is a directory, not a regular file." % target)
3236 3236
3237 3237 if search_ns:
3238 3238 # Inspect namespace to load object source
3239 3239 object_info = self.object_inspect(target, detail_level=1)
3240 3240 if object_info['found'] and object_info['source']:
3241 3241 return object_info['source']
3242 3242
3243 3243 try: # User namespace
3244 3244 codeobj = eval(target, self.user_ns)
3245 3245 except Exception:
3246 3246 raise ValueError(("'%s' was not found in history, as a file, url, "
3247 3247 "nor in the user namespace.") % target)
3248 3248
3249 3249 if isinstance(codeobj, string_types):
3250 3250 return codeobj
3251 3251 elif isinstance(codeobj, Macro):
3252 3252 return codeobj.value
3253 3253
3254 3254 raise TypeError("%s is neither a string nor a macro." % target,
3255 3255 codeobj)
3256 3256
3257 3257 #-------------------------------------------------------------------------
3258 3258 # Things related to IPython exiting
3259 3259 #-------------------------------------------------------------------------
3260 3260 def atexit_operations(self):
3261 3261 """This will be executed at the time of exit.
3262 3262
3263 3263 Cleanup operations and saving of persistent data that is done
3264 3264 unconditionally by IPython should be performed here.
3265 3265
3266 3266 For things that may depend on startup flags or platform specifics (such
3267 3267 as having readline or not), register a separate atexit function in the
3268 3268 code that has the appropriate information, rather than trying to
3269 3269 clutter
3270 3270 """
3271 3271 # Close the history session (this stores the end time and line count)
3272 3272 # this must be *before* the tempfile cleanup, in case of temporary
3273 3273 # history db
3274 3274 self.history_manager.end_session()
3275 3275
3276 3276 # Cleanup all tempfiles and folders left around
3277 3277 for tfile in self.tempfiles:
3278 3278 try:
3279 3279 os.unlink(tfile)
3280 3280 except OSError:
3281 3281 pass
3282 3282
3283 3283 for tdir in self.tempdirs:
3284 3284 try:
3285 3285 os.rmdir(tdir)
3286 3286 except OSError:
3287 3287 pass
3288 3288
3289 3289 # Clear all user namespaces to release all references cleanly.
3290 3290 self.reset(new_session=False)
3291 3291
3292 3292 # Run user hooks
3293 3293 self.hooks.shutdown_hook()
3294 3294
3295 3295 def cleanup(self):
3296 3296 self.restore_sys_module_state()
3297 3297
3298 3298
3299 3299 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3300 3300 """An abstract base class for InteractiveShell."""
3301 3301
3302 3302 InteractiveShellABC.register(InteractiveShell)
@@ -1,653 +1,611 b''
1 """Implementation of basic magic functions.
2 """
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10
11 #-----------------------------------------------------------------------------
12 # Imports
13 #-----------------------------------------------------------------------------
1 """Implementation of basic magic functions."""
2
14 3 from __future__ import print_function
15 4
16 # Stdlib
17 5 import io
18 6 import json
19 7 import sys
20 8 from pprint import pformat
21 9
22 # Our own packages
23 10 from IPython.core import magic_arguments, page
24 11 from IPython.core.error import UsageError
25 12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
26 13 from IPython.utils.text import format_screen, dedent, indent
27 14 from IPython.testing.skipdoctest import skip_doctest
28 15 from IPython.utils.ipstruct import Struct
29 16 from IPython.utils.path import unquote_filename
30 17 from IPython.utils.py3compat import unicode_type
31 18 from IPython.utils.warn import warn, error
32 19
33 #-----------------------------------------------------------------------------
34 # Magics class implementation
35 #-----------------------------------------------------------------------------
36 20
37 21 class MagicsDisplay(object):
38 22 def __init__(self, magics_manager):
39 23 self.magics_manager = magics_manager
40 24
41 25 def _lsmagic(self):
42 26 """The main implementation of the %lsmagic"""
43 27 mesc = magic_escapes['line']
44 28 cesc = magic_escapes['cell']
45 29 mman = self.magics_manager
46 30 magics = mman.lsmagic()
47 31 out = ['Available line magics:',
48 32 mesc + (' '+mesc).join(sorted(magics['line'])),
49 33 '',
50 34 'Available cell magics:',
51 35 cesc + (' '+cesc).join(sorted(magics['cell'])),
52 36 '',
53 37 mman.auto_status()]
54 38 return '\n'.join(out)
55 39
56 40 def _repr_pretty_(self, p, cycle):
57 41 p.text(self._lsmagic())
58 42
59 43 def __str__(self):
60 44 return self._lsmagic()
61 45
62 46 def _jsonable(self):
63 47 """turn magics dict into jsonable dict of the same structure
64 48
65 49 replaces object instances with their class names as strings
66 50 """
67 51 magic_dict = {}
68 52 mman = self.magics_manager
69 53 magics = mman.lsmagic()
70 54 for key, subdict in magics.items():
71 55 d = {}
72 56 magic_dict[key] = d
73 57 for name, obj in subdict.items():
74 58 try:
75 59 classname = obj.__self__.__class__.__name__
76 60 except AttributeError:
77 61 classname = 'Other'
78 62
79 63 d[name] = classname
80 64 return magic_dict
81 65
82 66 def _repr_json_(self):
83 67 return json.dumps(self._jsonable())
84 68
85 69
86 70 @magics_class
87 71 class BasicMagics(Magics):
88 72 """Magics that provide central IPython functionality.
89 73
90 74 These are various magics that don't fit into specific categories but that
91 75 are all part of the base 'IPython experience'."""
92 76
93 77 @magic_arguments.magic_arguments()
94 78 @magic_arguments.argument(
95 79 '-l', '--line', action='store_true',
96 80 help="""Create a line magic alias."""
97 81 )
98 82 @magic_arguments.argument(
99 83 '-c', '--cell', action='store_true',
100 84 help="""Create a cell magic alias."""
101 85 )
102 86 @magic_arguments.argument(
103 87 'name',
104 88 help="""Name of the magic to be created."""
105 89 )
106 90 @magic_arguments.argument(
107 91 'target',
108 92 help="""Name of the existing line or cell magic."""
109 93 )
110 94 @line_magic
111 95 def alias_magic(self, line=''):
112 96 """Create an alias for an existing line or cell magic.
113 97
114 98 Examples
115 99 --------
116 100 ::
117 101
118 102 In [1]: %alias_magic t timeit
119 103 Created `%t` as an alias for `%timeit`.
120 104 Created `%%t` as an alias for `%%timeit`.
121 105
122 106 In [2]: %t -n1 pass
123 107 1 loops, best of 3: 954 ns per loop
124 108
125 109 In [3]: %%t -n1
126 110 ...: pass
127 111 ...:
128 112 1 loops, best of 3: 954 ns per loop
129 113
130 114 In [4]: %alias_magic --cell whereami pwd
131 115 UsageError: Cell magic function `%%pwd` not found.
132 116 In [5]: %alias_magic --line whereami pwd
133 117 Created `%whereami` as an alias for `%pwd`.
134 118
135 119 In [6]: %whereami
136 120 Out[6]: u'/home/testuser'
137 121 """
138 122 args = magic_arguments.parse_argstring(self.alias_magic, line)
139 123 shell = self.shell
140 124 mman = self.shell.magics_manager
141 125 escs = ''.join(magic_escapes.values())
142 126
143 127 target = args.target.lstrip(escs)
144 128 name = args.name.lstrip(escs)
145 129
146 130 # Find the requested magics.
147 131 m_line = shell.find_magic(target, 'line')
148 132 m_cell = shell.find_magic(target, 'cell')
149 133 if args.line and m_line is None:
150 134 raise UsageError('Line magic function `%s%s` not found.' %
151 135 (magic_escapes['line'], target))
152 136 if args.cell and m_cell is None:
153 137 raise UsageError('Cell magic function `%s%s` not found.' %
154 138 (magic_escapes['cell'], target))
155 139
156 140 # If --line and --cell are not specified, default to the ones
157 141 # that are available.
158 142 if not args.line and not args.cell:
159 143 if not m_line and not m_cell:
160 144 raise UsageError(
161 145 'No line or cell magic with name `%s` found.' % target
162 146 )
163 147 args.line = bool(m_line)
164 148 args.cell = bool(m_cell)
165 149
166 150 if args.line:
167 151 mman.register_alias(name, target, 'line')
168 152 print('Created `%s%s` as an alias for `%s%s`.' % (
169 153 magic_escapes['line'], name,
170 154 magic_escapes['line'], target))
171 155
172 156 if args.cell:
173 157 mman.register_alias(name, target, 'cell')
174 158 print('Created `%s%s` as an alias for `%s%s`.' % (
175 159 magic_escapes['cell'], name,
176 160 magic_escapes['cell'], target))
177 161
178 162 @line_magic
179 163 def lsmagic(self, parameter_s=''):
180 164 """List currently available magic functions."""
181 165 return MagicsDisplay(self.shell.magics_manager)
182 166
183 167 def _magic_docs(self, brief=False, rest=False):
184 168 """Return docstrings from magic functions."""
185 169 mman = self.shell.magics_manager
186 170 docs = mman.lsmagic_docs(brief, missing='No documentation')
187 171
188 172 if rest:
189 173 format_string = '**%s%s**::\n\n%s\n\n'
190 174 else:
191 175 format_string = '%s%s:\n%s\n'
192 176
193 177 return ''.join(
194 178 [format_string % (magic_escapes['line'], fname,
195 179 indent(dedent(fndoc)))
196 180 for fname, fndoc in sorted(docs['line'].items())]
197 181 +
198 182 [format_string % (magic_escapes['cell'], fname,
199 183 indent(dedent(fndoc)))
200 184 for fname, fndoc in sorted(docs['cell'].items())]
201 185 )
202 186
203 187 @line_magic
204 188 def magic(self, parameter_s=''):
205 189 """Print information about the magic function system.
206 190
207 191 Supported formats: -latex, -brief, -rest
208 192 """
209 193
210 194 mode = ''
211 195 try:
212 196 mode = parameter_s.split()[0][1:]
213 197 if mode == 'rest':
214 198 rest_docs = []
215 199 except IndexError:
216 200 pass
217 201
218 202 brief = (mode == 'brief')
219 203 rest = (mode == 'rest')
220 204 magic_docs = self._magic_docs(brief, rest)
221 205
222 206 if mode == 'latex':
223 207 print(self.format_latex(magic_docs))
224 208 return
225 209 else:
226 210 magic_docs = format_screen(magic_docs)
227 211
228 212 out = ["""
229 213 IPython's 'magic' functions
230 214 ===========================
231 215
232 216 The magic function system provides a series of functions which allow you to
233 217 control the behavior of IPython itself, plus a lot of system-type
234 218 features. There are two kinds of magics, line-oriented and cell-oriented.
235 219
236 220 Line magics are prefixed with the % character and work much like OS
237 221 command-line calls: they get as an argument the rest of the line, where
238 222 arguments are passed without parentheses or quotes. For example, this will
239 223 time the given statement::
240 224
241 225 %timeit range(1000)
242 226
243 227 Cell magics are prefixed with a double %%, and they are functions that get as
244 228 an argument not only the rest of the line, but also the lines below it in a
245 229 separate argument. These magics are called with two arguments: the rest of the
246 230 call line and the body of the cell, consisting of the lines below the first.
247 231 For example::
248 232
249 233 %%timeit x = numpy.random.randn((100, 100))
250 234 numpy.linalg.svd(x)
251 235
252 236 will time the execution of the numpy svd routine, running the assignment of x
253 237 as part of the setup phase, which is not timed.
254 238
255 239 In a line-oriented client (the terminal or Qt console IPython), starting a new
256 240 input with %% will automatically enter cell mode, and IPython will continue
257 241 reading input until a blank line is given. In the notebook, simply type the
258 242 whole cell as one entity, but keep in mind that the %% escape can only be at
259 243 the very start of the cell.
260 244
261 245 NOTE: If you have 'automagic' enabled (via the command line option or with the
262 246 %automagic function), you don't need to type in the % explicitly for line
263 247 magics; cell magics always require an explicit '%%' escape. By default,
264 248 IPython ships with automagic on, so you should only rarely need the % escape.
265 249
266 250 Example: typing '%cd mydir' (without the quotes) changes you working directory
267 251 to 'mydir', if it exists.
268 252
269 253 For a list of the available magic functions, use %lsmagic. For a description
270 254 of any of them, type %magic_name?, e.g. '%cd?'.
271 255
272 256 Currently the magic system has the following functions:""",
273 257 magic_docs,
274 258 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
275 259 str(self.lsmagic()),
276 260 ]
277 261 page.page('\n'.join(out))
278 262
279 263
280 264 @line_magic
281 265 def page(self, parameter_s=''):
282 266 """Pretty print the object and display it through a pager.
283 267
284 268 %page [options] OBJECT
285 269
286 270 If no object is given, use _ (last output).
287 271
288 272 Options:
289 273
290 274 -r: page str(object), don't pretty-print it."""
291 275
292 276 # After a function contributed by Olivier Aubert, slightly modified.
293 277
294 278 # Process options/args
295 279 opts, args = self.parse_options(parameter_s, 'r')
296 280 raw = 'r' in opts
297 281
298 282 oname = args and args or '_'
299 283 info = self.shell._ofind(oname)
300 284 if info['found']:
301 285 txt = (raw and str or pformat)( info['obj'] )
302 286 page.page(txt)
303 287 else:
304 288 print('Object `%s` not found' % oname)
305 289
306 290 @line_magic
307 291 def profile(self, parameter_s=''):
308 292 """Print your currently active IPython profile.
309 293
310 294 See Also
311 295 --------
312 296 prun : run code using the Python profiler
313 297 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
314 298 """
315 299 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
316 300 from IPython.core.application import BaseIPythonApplication
317 301 if BaseIPythonApplication.initialized():
318 302 print(BaseIPythonApplication.instance().profile)
319 303 else:
320 304 error("profile is an application-level value, but you don't appear to be in an IPython application")
321 305
322 306 @line_magic
323 307 def pprint(self, parameter_s=''):
324 308 """Toggle pretty printing on/off."""
325 309 ptformatter = self.shell.display_formatter.formatters['text/plain']
326 310 ptformatter.pprint = bool(1 - ptformatter.pprint)
327 311 print('Pretty printing has been turned',
328 312 ['OFF','ON'][ptformatter.pprint])
329 313
330 314 @line_magic
331 315 def colors(self, parameter_s=''):
332 316 """Switch color scheme for prompts, info system and exception handlers.
333 317
334 318 Currently implemented schemes: NoColor, Linux, LightBG.
335 319
336 320 Color scheme names are not case-sensitive.
337 321
338 322 Examples
339 323 --------
340 324 To get a plain black and white terminal::
341 325
342 326 %colors nocolor
343 327 """
344 328 def color_switch_err(name):
345 329 warn('Error changing %s color schemes.\n%s' %
346 330 (name, sys.exc_info()[1]))
347 331
348 332
349 333 new_scheme = parameter_s.strip()
350 334 if not new_scheme:
351 335 raise UsageError(
352 336 "%colors: you must specify a color scheme. See '%colors?'")
353 337 # local shortcut
354 338 shell = self.shell
355 339
356 340 import IPython.utils.rlineimpl as readline
357 341
358 342 if not shell.colors_force and \
359 343 not readline.have_readline and \
360 344 (sys.platform == "win32" or sys.platform == "cli"):
361 345 msg = """\
362 346 Proper color support under MS Windows requires the pyreadline library.
363 347 You can find it at:
364 348 http://ipython.org/pyreadline.html
365 349
366 350 Defaulting color scheme to 'NoColor'"""
367 351 new_scheme = 'NoColor'
368 352 warn(msg)
369 353
370 354 # readline option is 0
371 355 if not shell.colors_force and not shell.has_readline:
372 356 new_scheme = 'NoColor'
373 357
374 358 # Set prompt colors
375 359 try:
376 360 shell.prompt_manager.color_scheme = new_scheme
377 361 except:
378 362 color_switch_err('prompt')
379 363 else:
380 364 shell.colors = \
381 365 shell.prompt_manager.color_scheme_table.active_scheme_name
382 366 # Set exception colors
383 367 try:
384 368 shell.InteractiveTB.set_colors(scheme = new_scheme)
385 369 shell.SyntaxTB.set_colors(scheme = new_scheme)
386 370 except:
387 371 color_switch_err('exception')
388 372
389 373 # Set info (for 'object?') colors
390 374 if shell.color_info:
391 375 try:
392 376 shell.inspector.set_active_scheme(new_scheme)
393 377 except:
394 378 color_switch_err('object inspector')
395 379 else:
396 380 shell.inspector.set_active_scheme('NoColor')
397 381
398 382 @line_magic
399 383 def xmode(self, parameter_s=''):
400 384 """Switch modes for the exception handlers.
401 385
402 386 Valid modes: Plain, Context and Verbose.
403 387
404 388 If called without arguments, acts as a toggle."""
405 389
406 390 def xmode_switch_err(name):
407 391 warn('Error changing %s exception modes.\n%s' %
408 392 (name,sys.exc_info()[1]))
409 393
410 394 shell = self.shell
411 395 new_mode = parameter_s.strip().capitalize()
412 396 try:
413 397 shell.InteractiveTB.set_mode(mode=new_mode)
414 398 print('Exception reporting mode:',shell.InteractiveTB.mode)
415 399 except:
416 400 xmode_switch_err('user')
417 401
418 402 @line_magic
419 403 def quickref(self,arg):
420 404 """ Show a quick reference sheet """
421 405 from IPython.core.usage import quick_reference
422 406 qr = quick_reference + self._magic_docs(brief=True)
423 407 page.page(qr)
424 408
425 409 @line_magic
426 410 def doctest_mode(self, parameter_s=''):
427 411 """Toggle doctest mode on and off.
428 412
429 413 This mode is intended to make IPython behave as much as possible like a
430 414 plain Python shell, from the perspective of how its prompts, exceptions
431 415 and output look. This makes it easy to copy and paste parts of a
432 416 session into doctests. It does so by:
433 417
434 418 - Changing the prompts to the classic ``>>>`` ones.
435 419 - Changing the exception reporting mode to 'Plain'.
436 420 - Disabling pretty-printing of output.
437 421
438 422 Note that IPython also supports the pasting of code snippets that have
439 423 leading '>>>' and '...' prompts in them. This means that you can paste
440 424 doctests from files or docstrings (even if they have leading
441 425 whitespace), and the code will execute correctly. You can then use
442 426 '%history -t' to see the translated history; this will give you the
443 427 input after removal of all the leading prompts and whitespace, which
444 428 can be pasted back into an editor.
445 429
446 430 With these features, you can switch into this mode easily whenever you
447 431 need to do testing and changes to doctests, without having to leave
448 432 your existing IPython session.
449 433 """
450 434
451 435 # Shorthands
452 436 shell = self.shell
453 437 pm = shell.prompt_manager
454 438 meta = shell.meta
455 439 disp_formatter = self.shell.display_formatter
456 440 ptformatter = disp_formatter.formatters['text/plain']
457 441 # dstore is a data store kept in the instance metadata bag to track any
458 442 # changes we make, so we can undo them later.
459 443 dstore = meta.setdefault('doctest_mode',Struct())
460 444 save_dstore = dstore.setdefault
461 445
462 446 # save a few values we'll need to recover later
463 447 mode = save_dstore('mode',False)
464 448 save_dstore('rc_pprint',ptformatter.pprint)
465 449 save_dstore('xmode',shell.InteractiveTB.mode)
466 450 save_dstore('rc_separate_out',shell.separate_out)
467 451 save_dstore('rc_separate_out2',shell.separate_out2)
468 452 save_dstore('rc_prompts_pad_left',pm.justify)
469 453 save_dstore('rc_separate_in',shell.separate_in)
470 454 save_dstore('rc_active_types',disp_formatter.active_types)
471 455 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
472 456
473 457 if mode == False:
474 458 # turn on
475 459 pm.in_template = '>>> '
476 460 pm.in2_template = '... '
477 461 pm.out_template = ''
478 462
479 463 # Prompt separators like plain python
480 464 shell.separate_in = ''
481 465 shell.separate_out = ''
482 466 shell.separate_out2 = ''
483 467
484 468 pm.justify = False
485 469
486 470 ptformatter.pprint = False
487 471 disp_formatter.active_types = ['text/plain']
488 472
489 473 shell.magic('xmode Plain')
490 474 else:
491 475 # turn off
492 476 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
493 477
494 478 shell.separate_in = dstore.rc_separate_in
495 479
496 480 shell.separate_out = dstore.rc_separate_out
497 481 shell.separate_out2 = dstore.rc_separate_out2
498 482
499 483 pm.justify = dstore.rc_prompts_pad_left
500 484
501 485 ptformatter.pprint = dstore.rc_pprint
502 486 disp_formatter.active_types = dstore.rc_active_types
503 487
504 488 shell.magic('xmode ' + dstore.xmode)
505 489
506 490 # Store new mode and inform
507 491 dstore.mode = bool(1-int(mode))
508 492 mode_label = ['OFF','ON'][dstore.mode]
509 493 print('Doctest mode is:', mode_label)
510 494
511 495 @line_magic
512 496 def gui(self, parameter_s=''):
513 497 """Enable or disable IPython GUI event loop integration.
514 498
515 499 %gui [GUINAME]
516 500
517 501 This magic replaces IPython's threaded shells that were activated
518 502 using the (pylab/wthread/etc.) command line flags. GUI toolkits
519 503 can now be enabled at runtime and keyboard
520 504 interrupts should work without any problems. The following toolkits
521 505 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
522 506
523 507 %gui wx # enable wxPython event loop integration
524 508 %gui qt4|qt # enable PyQt4 event loop integration
525 509 %gui qt5 # enable PyQt5 event loop integration
526 510 %gui gtk # enable PyGTK event loop integration
527 511 %gui gtk3 # enable Gtk3 event loop integration
528 512 %gui tk # enable Tk event loop integration
529 513 %gui osx # enable Cocoa event loop integration
530 514 # (requires %matplotlib 1.1)
531 515 %gui # disable all event loop integration
532 516
533 517 WARNING: after any of these has been called you can simply create
534 518 an application object, but DO NOT start the event loop yourself, as
535 519 we have already handled that.
536 520 """
537 521 opts, arg = self.parse_options(parameter_s, '')
538 522 if arg=='': arg = None
539 523 try:
540 524 return self.shell.enable_gui(arg)
541 525 except Exception as e:
542 526 # print simple error message, rather than traceback if we can't
543 527 # hook up the GUI
544 528 error(str(e))
545 529
546 530 @skip_doctest
547 531 @line_magic
548 532 def precision(self, s=''):
549 533 """Set floating point precision for pretty printing.
550 534
551 535 Can set either integer precision or a format string.
552 536
553 537 If numpy has been imported and precision is an int,
554 538 numpy display precision will also be set, via ``numpy.set_printoptions``.
555 539
556 540 If no argument is given, defaults will be restored.
557 541
558 542 Examples
559 543 --------
560 544 ::
561 545
562 546 In [1]: from math import pi
563 547
564 548 In [2]: %precision 3
565 549 Out[2]: u'%.3f'
566 550
567 551 In [3]: pi
568 552 Out[3]: 3.142
569 553
570 554 In [4]: %precision %i
571 555 Out[4]: u'%i'
572 556
573 557 In [5]: pi
574 558 Out[5]: 3
575 559
576 560 In [6]: %precision %e
577 561 Out[6]: u'%e'
578 562
579 563 In [7]: pi**10
580 564 Out[7]: 9.364805e+04
581 565
582 566 In [8]: %precision
583 567 Out[8]: u'%r'
584 568
585 569 In [9]: pi**10
586 570 Out[9]: 93648.047476082982
587 571 """
588 572 ptformatter = self.shell.display_formatter.formatters['text/plain']
589 573 ptformatter.float_precision = s
590 574 return ptformatter.float_format
591 575
592 576 @magic_arguments.magic_arguments()
593 577 @magic_arguments.argument(
594 578 '-e', '--export', action='store_true', default=False,
595 579 help='Export IPython history as a notebook. The filename argument '
596 580 'is used to specify the notebook name and format. For example '
597 581 'a filename of notebook.ipynb will result in a notebook name '
598 582 'of "notebook" and a format of "json". Likewise using a ".py" '
599 583 'file extension will write the notebook as a Python script'
600 584 )
601 585 @magic_arguments.argument(
602 '-f', '--format',
603 help='Convert an existing IPython notebook to a new format. This option '
604 'specifies the new format and can have the values: json, py. '
605 'The target filename is chosen automatically based on the new '
606 'format. The filename argument gives the name of the source file.'
607 )
608 @magic_arguments.argument(
609 586 'filename', type=unicode_type,
610 587 help='Notebook name or filename'
611 588 )
612 589 @line_magic
613 590 def notebook(self, s):
614 591 """Export and convert IPython notebooks.
615 592
616 This function can export the current IPython history to a notebook file
617 or can convert an existing notebook file into a different format. For
618 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
619 To export the history to "foo.py" do "%notebook -e foo.py". To convert
620 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
621 formats include (json/ipynb, py).
593 This function can export the current IPython history to a notebook file.
594 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
595 To export the history to "foo.py" do "%notebook -e foo.py".
622 596 """
623 597 args = magic_arguments.parse_argstring(self.notebook, s)
624 598
625 from IPython.nbformat import current
599 from IPython.nbformat import write, v4
626 600 args.filename = unquote_filename(args.filename)
627 601 if args.export:
628 fname, name, format = current.parse_filename(args.filename)
629 602 cells = []
630 603 hist = list(self.shell.history_manager.get_range())
631 for session, prompt_number, input in hist[:-1]:
632 cells.append(current.new_code_cell(prompt_number=prompt_number,
633 input=input))
634 worksheet = current.new_worksheet(cells=cells)
635 nb = current.new_notebook(name=name,worksheets=[worksheet])
636 with io.open(fname, 'w', encoding='utf-8') as f:
637 current.write(nb, f, format);
638 elif args.format is not None:
639 old_fname, old_name, old_format = current.parse_filename(args.filename)
640 new_format = args.format
641 if new_format == u'xml':
642 raise ValueError('Notebooks cannot be written as xml.')
643 elif new_format == u'ipynb' or new_format == u'json':
644 new_fname = old_name + u'.ipynb'
645 new_format = u'json'
646 elif new_format == u'py':
647 new_fname = old_name + u'.py'
648 else:
649 raise ValueError('Invalid notebook format: %s' % new_format)
650 with io.open(old_fname, 'r', encoding='utf-8') as f:
651 nb = current.read(f, old_format)
652 with io.open(new_fname, 'w', encoding='utf-8') as f:
653 current.write(nb, f, new_format)
604 for session, execution_count, input in hist[:-1]:
605 cells.append(v4.new_code_cell(
606 execution_count=execution_count,
607 source=source
608 ))
609 nb = v4.new_notebook(cells=cells)
610 with io.open(args.filename, 'w', encoding='utf-8') as f:
611 write(nb, f, version=4)
@@ -1,991 +1,955 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for various magic functions.
3 3
4 4 Needs to be run by nose (to make ipython session available).
5 5 """
6 6 from __future__ import absolute_import
7 7
8 #-----------------------------------------------------------------------------
9 # Imports
10 #-----------------------------------------------------------------------------
11
12 8 import io
13 9 import os
14 10 import sys
15 11 from unittest import TestCase, skipIf
16 12
17 13 try:
18 14 from importlib import invalidate_caches # Required from Python 3.3
19 15 except ImportError:
20 16 def invalidate_caches():
21 17 pass
22 18
23 19 import nose.tools as nt
24 20
25 21 from IPython.core import magic
26 22 from IPython.core.magic import (Magics, magics_class, line_magic,
27 23 cell_magic, line_cell_magic,
28 24 register_line_magic, register_cell_magic,
29 25 register_line_cell_magic)
30 26 from IPython.core.magics import execution, script, code
31 27 from IPython.testing import decorators as dec
32 28 from IPython.testing import tools as tt
33 29 from IPython.utils import py3compat
34 30 from IPython.utils.io import capture_output
35 31 from IPython.utils.tempdir import TemporaryDirectory
36 32 from IPython.utils.process import find_cmd
37 33
38 34 if py3compat.PY3:
39 35 from io import StringIO
40 36 else:
41 37 from StringIO import StringIO
42 38
43 #-----------------------------------------------------------------------------
44 # Test functions begin
45 #-----------------------------------------------------------------------------
46 39
47 40 @magic.magics_class
48 41 class DummyMagics(magic.Magics): pass
49 42
50 43 def test_extract_code_ranges():
51 44 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
52 45 expected = [(0, 1),
53 46 (2, 3),
54 47 (4, 6),
55 48 (6, 9),
56 49 (9, 14),
57 50 (16, None),
58 51 (None, 9),
59 52 (9, None),
60 53 (None, 13),
61 54 (None, None)]
62 55 actual = list(code.extract_code_ranges(instr))
63 56 nt.assert_equal(actual, expected)
64 57
65 58 def test_extract_symbols():
66 59 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
67 60 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
68 61 expected = [([], ['a']),
69 62 (["def b():\n return 42\n"], []),
70 63 (["class A: pass\n"], []),
71 64 (["class A: pass\n", "def b():\n return 42\n"], []),
72 65 (["class A: pass\n"], ['a']),
73 66 ([], ['z'])]
74 67 for symbols, exp in zip(symbols_args, expected):
75 68 nt.assert_equal(code.extract_symbols(source, symbols), exp)
76 69
77 70
78 71 def test_extract_symbols_raises_exception_with_non_python_code():
79 72 source = ("=begin A Ruby program :)=end\n"
80 73 "def hello\n"
81 74 "puts 'Hello world'\n"
82 75 "end")
83 76 with nt.assert_raises(SyntaxError):
84 77 code.extract_symbols(source, "hello")
85 78
86 79 def test_config():
87 80 """ test that config magic does not raise
88 81 can happen if Configurable init is moved too early into
89 82 Magics.__init__ as then a Config object will be registerd as a
90 83 magic.
91 84 """
92 85 ## should not raise.
93 86 _ip.magic('config')
94 87
95 88 def test_rehashx():
96 89 # clear up everything
97 90 _ip = get_ipython()
98 91 _ip.alias_manager.clear_aliases()
99 92 del _ip.db['syscmdlist']
100 93
101 94 _ip.magic('rehashx')
102 95 # Practically ALL ipython development systems will have more than 10 aliases
103 96
104 97 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
105 98 for name, cmd in _ip.alias_manager.aliases:
106 99 # we must strip dots from alias names
107 100 nt.assert_not_in('.', name)
108 101
109 102 # rehashx must fill up syscmdlist
110 103 scoms = _ip.db['syscmdlist']
111 104 nt.assert_true(len(scoms) > 10)
112 105
113 106
114 107 def test_magic_parse_options():
115 108 """Test that we don't mangle paths when parsing magic options."""
116 109 ip = get_ipython()
117 110 path = 'c:\\x'
118 111 m = DummyMagics(ip)
119 112 opts = m.parse_options('-f %s' % path,'f:')[0]
120 113 # argv splitting is os-dependent
121 114 if os.name == 'posix':
122 115 expected = 'c:x'
123 116 else:
124 117 expected = path
125 118 nt.assert_equal(opts['f'], expected)
126 119
127 120 def test_magic_parse_long_options():
128 121 """Magic.parse_options can handle --foo=bar long options"""
129 122 ip = get_ipython()
130 123 m = DummyMagics(ip)
131 124 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
132 125 nt.assert_in('foo', opts)
133 126 nt.assert_in('bar', opts)
134 127 nt.assert_equal(opts['bar'], "bubble")
135 128
136 129
137 130 @dec.skip_without('sqlite3')
138 131 def doctest_hist_f():
139 132 """Test %hist -f with temporary filename.
140 133
141 134 In [9]: import tempfile
142 135
143 136 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
144 137
145 138 In [11]: %hist -nl -f $tfile 3
146 139
147 140 In [13]: import os; os.unlink(tfile)
148 141 """
149 142
150 143
151 144 @dec.skip_without('sqlite3')
152 145 def doctest_hist_r():
153 146 """Test %hist -r
154 147
155 148 XXX - This test is not recording the output correctly. For some reason, in
156 149 testing mode the raw history isn't getting populated. No idea why.
157 150 Disabling the output checking for now, though at least we do run it.
158 151
159 152 In [1]: 'hist' in _ip.lsmagic()
160 153 Out[1]: True
161 154
162 155 In [2]: x=1
163 156
164 157 In [3]: %hist -rl 2
165 158 x=1 # random
166 159 %hist -r 2
167 160 """
168 161
169 162
170 163 @dec.skip_without('sqlite3')
171 164 def doctest_hist_op():
172 165 """Test %hist -op
173 166
174 167 In [1]: class b(float):
175 168 ...: pass
176 169 ...:
177 170
178 171 In [2]: class s(object):
179 172 ...: def __str__(self):
180 173 ...: return 's'
181 174 ...:
182 175
183 176 In [3]:
184 177
185 178 In [4]: class r(b):
186 179 ...: def __repr__(self):
187 180 ...: return 'r'
188 181 ...:
189 182
190 183 In [5]: class sr(s,r): pass
191 184 ...:
192 185
193 186 In [6]:
194 187
195 188 In [7]: bb=b()
196 189
197 190 In [8]: ss=s()
198 191
199 192 In [9]: rr=r()
200 193
201 194 In [10]: ssrr=sr()
202 195
203 196 In [11]: 4.5
204 197 Out[11]: 4.5
205 198
206 199 In [12]: str(ss)
207 200 Out[12]: 's'
208 201
209 202 In [13]:
210 203
211 204 In [14]: %hist -op
212 205 >>> class b:
213 206 ... pass
214 207 ...
215 208 >>> class s(b):
216 209 ... def __str__(self):
217 210 ... return 's'
218 211 ...
219 212 >>>
220 213 >>> class r(b):
221 214 ... def __repr__(self):
222 215 ... return 'r'
223 216 ...
224 217 >>> class sr(s,r): pass
225 218 >>>
226 219 >>> bb=b()
227 220 >>> ss=s()
228 221 >>> rr=r()
229 222 >>> ssrr=sr()
230 223 >>> 4.5
231 224 4.5
232 225 >>> str(ss)
233 226 's'
234 227 >>>
235 228 """
236 229
237 230 def test_hist_pof():
238 231 ip = get_ipython()
239 232 ip.run_cell(u"1+2", store_history=True)
240 233 #raise Exception(ip.history_manager.session_number)
241 234 #raise Exception(list(ip.history_manager._get_range_session()))
242 235 with TemporaryDirectory() as td:
243 236 tf = os.path.join(td, 'hist.py')
244 237 ip.run_line_magic('history', '-pof %s' % tf)
245 238 assert os.path.isfile(tf)
246 239
247 240
248 241 @dec.skip_without('sqlite3')
249 242 def test_macro():
250 243 ip = get_ipython()
251 244 ip.history_manager.reset() # Clear any existing history.
252 245 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
253 246 for i, cmd in enumerate(cmds, start=1):
254 247 ip.history_manager.store_inputs(i, cmd)
255 248 ip.magic("macro test 1-3")
256 249 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
257 250
258 251 # List macros
259 252 nt.assert_in("test", ip.magic("macro"))
260 253
261 254
262 255 @dec.skip_without('sqlite3')
263 256 def test_macro_run():
264 257 """Test that we can run a multi-line macro successfully."""
265 258 ip = get_ipython()
266 259 ip.history_manager.reset()
267 260 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
268 261 "%macro test 2-3"]
269 262 for cmd in cmds:
270 263 ip.run_cell(cmd, store_history=True)
271 264 nt.assert_equal(ip.user_ns["test"].value,
272 265 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
273 266 with tt.AssertPrints("12"):
274 267 ip.run_cell("test")
275 268 with tt.AssertPrints("13"):
276 269 ip.run_cell("test")
277 270
278 271
279 272 def test_magic_magic():
280 273 """Test %magic"""
281 274 ip = get_ipython()
282 275 with capture_output() as captured:
283 276 ip.magic("magic")
284 277
285 278 stdout = captured.stdout
286 279 nt.assert_in('%magic', stdout)
287 280 nt.assert_in('IPython', stdout)
288 281 nt.assert_in('Available', stdout)
289 282
290 283
291 284 @dec.skipif_not_numpy
292 285 def test_numpy_reset_array_undec():
293 286 "Test '%reset array' functionality"
294 287 _ip.ex('import numpy as np')
295 288 _ip.ex('a = np.empty(2)')
296 289 nt.assert_in('a', _ip.user_ns)
297 290 _ip.magic('reset -f array')
298 291 nt.assert_not_in('a', _ip.user_ns)
299 292
300 293 def test_reset_out():
301 294 "Test '%reset out' magic"
302 295 _ip.run_cell("parrot = 'dead'", store_history=True)
303 296 # test '%reset -f out', make an Out prompt
304 297 _ip.run_cell("parrot", store_history=True)
305 298 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
306 299 _ip.magic('reset -f out')
307 300 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
308 301 nt.assert_equal(len(_ip.user_ns['Out']), 0)
309 302
310 303 def test_reset_in():
311 304 "Test '%reset in' magic"
312 305 # test '%reset -f in'
313 306 _ip.run_cell("parrot", store_history=True)
314 307 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
315 308 _ip.magic('%reset -f in')
316 309 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
317 310 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
318 311
319 312 def test_reset_dhist():
320 313 "Test '%reset dhist' magic"
321 314 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
322 315 _ip.magic('cd ' + os.path.dirname(nt.__file__))
323 316 _ip.magic('cd -')
324 317 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
325 318 _ip.magic('reset -f dhist')
326 319 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
327 320 _ip.run_cell("_dh = [d for d in tmp]") #restore
328 321
329 322 def test_reset_in_length():
330 323 "Test that '%reset in' preserves In[] length"
331 324 _ip.run_cell("print 'foo'")
332 325 _ip.run_cell("reset -f in")
333 326 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
334 327
335 328 def test_tb_syntaxerror():
336 329 """test %tb after a SyntaxError"""
337 330 ip = get_ipython()
338 331 ip.run_cell("for")
339 332
340 333 # trap and validate stdout
341 334 save_stdout = sys.stdout
342 335 try:
343 336 sys.stdout = StringIO()
344 337 ip.run_cell("%tb")
345 338 out = sys.stdout.getvalue()
346 339 finally:
347 340 sys.stdout = save_stdout
348 341 # trim output, and only check the last line
349 342 last_line = out.rstrip().splitlines()[-1].strip()
350 343 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
351 344
352 345
353 346 def test_time():
354 347 ip = get_ipython()
355 348
356 349 with tt.AssertPrints("Wall time: "):
357 350 ip.run_cell("%time None")
358 351
359 352 ip.run_cell("def f(kmjy):\n"
360 353 " %time print (2*kmjy)")
361 354
362 355 with tt.AssertPrints("Wall time: "):
363 356 with tt.AssertPrints("hihi", suppress=False):
364 357 ip.run_cell("f('hi')")
365 358
366 359
367 360 @dec.skip_win32
368 361 def test_time2():
369 362 ip = get_ipython()
370 363
371 364 with tt.AssertPrints("CPU times: user "):
372 365 ip.run_cell("%time None")
373 366
374 367 def test_time3():
375 368 """Erroneous magic function calls, issue gh-3334"""
376 369 ip = get_ipython()
377 370 ip.user_ns.pop('run', None)
378 371
379 372 with tt.AssertNotPrints("not found", channel='stderr'):
380 373 ip.run_cell("%%time\n"
381 374 "run = 0\n"
382 375 "run += 1")
383 376
384 377 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
385 378 def test_time_futures():
386 379 "Test %time with __future__ environments"
387 380 ip = get_ipython()
388 381 ip.autocall = 0
389 382 ip.run_cell("from __future__ import division")
390 383 with tt.AssertPrints('0.25'):
391 384 ip.run_line_magic('time', 'print(1/4)')
392 385 ip.compile.reset_compiler_flags()
393 386 with tt.AssertNotPrints('0.25'):
394 387 ip.run_line_magic('time', 'print(1/4)')
395 388
396 389 def test_doctest_mode():
397 390 "Toggle doctest_mode twice, it should be a no-op and run without error"
398 391 _ip.magic('doctest_mode')
399 392 _ip.magic('doctest_mode')
400 393
401 394
402 395 def test_parse_options():
403 396 """Tests for basic options parsing in magics."""
404 397 # These are only the most minimal of tests, more should be added later. At
405 398 # the very least we check that basic text/unicode calls work OK.
406 399 m = DummyMagics(_ip)
407 400 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
408 401 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
409 402
410 403
411 404 def test_dirops():
412 405 """Test various directory handling operations."""
413 406 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
414 407 curpath = py3compat.getcwd
415 408 startdir = py3compat.getcwd()
416 409 ipdir = os.path.realpath(_ip.ipython_dir)
417 410 try:
418 411 _ip.magic('cd "%s"' % ipdir)
419 412 nt.assert_equal(curpath(), ipdir)
420 413 _ip.magic('cd -')
421 414 nt.assert_equal(curpath(), startdir)
422 415 _ip.magic('pushd "%s"' % ipdir)
423 416 nt.assert_equal(curpath(), ipdir)
424 417 _ip.magic('popd')
425 418 nt.assert_equal(curpath(), startdir)
426 419 finally:
427 420 os.chdir(startdir)
428 421
429 422
430 423 def test_xmode():
431 424 # Calling xmode three times should be a no-op
432 425 xmode = _ip.InteractiveTB.mode
433 426 for i in range(3):
434 427 _ip.magic("xmode")
435 428 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
436 429
437 430 def test_reset_hard():
438 431 monitor = []
439 432 class A(object):
440 433 def __del__(self):
441 434 monitor.append(1)
442 435 def __repr__(self):
443 436 return "<A instance>"
444 437
445 438 _ip.user_ns["a"] = A()
446 439 _ip.run_cell("a")
447 440
448 441 nt.assert_equal(monitor, [])
449 442 _ip.magic("reset -f")
450 443 nt.assert_equal(monitor, [1])
451 444
452 445 class TestXdel(tt.TempFileMixin):
453 446 def test_xdel(self):
454 447 """Test that references from %run are cleared by xdel."""
455 448 src = ("class A(object):\n"
456 449 " monitor = []\n"
457 450 " def __del__(self):\n"
458 451 " self.monitor.append(1)\n"
459 452 "a = A()\n")
460 453 self.mktmp(src)
461 454 # %run creates some hidden references...
462 455 _ip.magic("run %s" % self.fname)
463 456 # ... as does the displayhook.
464 457 _ip.run_cell("a")
465 458
466 459 monitor = _ip.user_ns["A"].monitor
467 460 nt.assert_equal(monitor, [])
468 461
469 462 _ip.magic("xdel a")
470 463
471 464 # Check that a's __del__ method has been called.
472 465 nt.assert_equal(monitor, [1])
473 466
474 467 def doctest_who():
475 468 """doctest for %who
476 469
477 470 In [1]: %reset -f
478 471
479 472 In [2]: alpha = 123
480 473
481 474 In [3]: beta = 'beta'
482 475
483 476 In [4]: %who int
484 477 alpha
485 478
486 479 In [5]: %who str
487 480 beta
488 481
489 482 In [6]: %whos
490 483 Variable Type Data/Info
491 484 ----------------------------
492 485 alpha int 123
493 486 beta str beta
494 487
495 488 In [7]: %who_ls
496 489 Out[7]: ['alpha', 'beta']
497 490 """
498 491
499 492 def test_whos():
500 493 """Check that whos is protected against objects where repr() fails."""
501 494 class A(object):
502 495 def __repr__(self):
503 496 raise Exception()
504 497 _ip.user_ns['a'] = A()
505 498 _ip.magic("whos")
506 499
507 500 @py3compat.u_format
508 501 def doctest_precision():
509 502 """doctest for %precision
510 503
511 504 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
512 505
513 506 In [2]: %precision 5
514 507 Out[2]: {u}'%.5f'
515 508
516 509 In [3]: f.float_format
517 510 Out[3]: {u}'%.5f'
518 511
519 512 In [4]: %precision %e
520 513 Out[4]: {u}'%e'
521 514
522 515 In [5]: f(3.1415927)
523 516 Out[5]: {u}'3.141593e+00'
524 517 """
525 518
526 519 def test_psearch():
527 520 with tt.AssertPrints("dict.fromkeys"):
528 521 _ip.run_cell("dict.fr*?")
529 522
530 523 def test_timeit_shlex():
531 524 """test shlex issues with timeit (#1109)"""
532 525 _ip.ex("def f(*a,**kw): pass")
533 526 _ip.magic('timeit -n1 "this is a bug".count(" ")')
534 527 _ip.magic('timeit -r1 -n1 f(" ", 1)')
535 528 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
536 529 _ip.magic('timeit -r1 -n1 ("a " + "b")')
537 530 _ip.magic('timeit -r1 -n1 f("a " + "b")')
538 531 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
539 532
540 533
541 534 def test_timeit_arguments():
542 535 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
543 536 _ip.magic("timeit ('#')")
544 537
545 538
546 539 def test_timeit_special_syntax():
547 540 "Test %%timeit with IPython special syntax"
548 541 @register_line_magic
549 542 def lmagic(line):
550 543 ip = get_ipython()
551 544 ip.user_ns['lmagic_out'] = line
552 545
553 546 # line mode test
554 547 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
555 548 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
556 549 # cell mode test
557 550 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
558 551 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
559 552
560 553 def test_timeit_return():
561 554 """
562 555 test wether timeit -o return object
563 556 """
564 557
565 558 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
566 559 assert(res is not None)
567 560
568 561 def test_timeit_quiet():
569 562 """
570 563 test quiet option of timeit magic
571 564 """
572 565 with tt.AssertNotPrints("loops"):
573 566 _ip.run_cell("%timeit -n1 -r1 -q 1")
574 567
575 568 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
576 569 def test_timeit_futures():
577 570 "Test %timeit with __future__ environments"
578 571 ip = get_ipython()
579 572 ip.run_cell("from __future__ import division")
580 573 with tt.AssertPrints('0.25'):
581 574 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
582 575 ip.compile.reset_compiler_flags()
583 576 with tt.AssertNotPrints('0.25'):
584 577 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
585 578
586 579 @dec.skipif(execution.profile is None)
587 580 def test_prun_special_syntax():
588 581 "Test %%prun with IPython special syntax"
589 582 @register_line_magic
590 583 def lmagic(line):
591 584 ip = get_ipython()
592 585 ip.user_ns['lmagic_out'] = line
593 586
594 587 # line mode test
595 588 _ip.run_line_magic('prun', '-q %lmagic my line')
596 589 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
597 590 # cell mode test
598 591 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
599 592 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
600 593
601 594 @dec.skipif(execution.profile is None)
602 595 def test_prun_quotes():
603 596 "Test that prun does not clobber string escapes (GH #1302)"
604 597 _ip.magic(r"prun -q x = '\t'")
605 598 nt.assert_equal(_ip.user_ns['x'], '\t')
606 599
607 600 def test_extension():
608 601 tmpdir = TemporaryDirectory()
609 602 orig_ipython_dir = _ip.ipython_dir
610 603 try:
611 604 _ip.ipython_dir = tmpdir.name
612 605 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
613 606 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
614 607 _ip.magic("install_ext %s" % url)
615 608 _ip.user_ns.pop('arq', None)
616 609 invalidate_caches() # Clear import caches
617 610 _ip.magic("load_ext daft_extension")
618 611 nt.assert_equal(_ip.user_ns['arq'], 185)
619 612 _ip.magic("unload_ext daft_extension")
620 613 assert 'arq' not in _ip.user_ns
621 614 finally:
622 615 _ip.ipython_dir = orig_ipython_dir
623 616 tmpdir.cleanup()
624 617
625 618
626 619 # The nose skip decorator doesn't work on classes, so this uses unittest's skipIf
627 @skipIf(dec.module_not_available('IPython.nbformat.current'), 'nbformat not importable')
620 @skipIf(dec.module_not_available('IPython.nbformat'), 'nbformat not importable')
628 621 class NotebookExportMagicTests(TestCase):
629 622 def test_notebook_export_json(self):
630 623 with TemporaryDirectory() as td:
631 624 outfile = os.path.join(td, "nb.ipynb")
632 625 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
633 626 _ip.magic("notebook -e %s" % outfile)
634 627
635 def test_notebook_export_py(self):
636 with TemporaryDirectory() as td:
637 outfile = os.path.join(td, "nb.py")
638 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
639 _ip.magic("notebook -e %s" % outfile)
640
641 def test_notebook_reformat_py(self):
642 from IPython.nbformat.v3.tests.nbexamples import nb0
643 from IPython.nbformat import current
644 with TemporaryDirectory() as td:
645 infile = os.path.join(td, "nb.ipynb")
646 with io.open(infile, 'w', encoding='utf-8') as f:
647 current.write(nb0, f, 'json')
648
649 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
650 _ip.magic("notebook -f py %s" % infile)
651
652 def test_notebook_reformat_json(self):
653 from IPython.nbformat.v3.tests.nbexamples import nb0
654 from IPython.nbformat import current
655 with TemporaryDirectory() as td:
656 infile = os.path.join(td, "nb.py")
657 with io.open(infile, 'w', encoding='utf-8') as f:
658 current.write(nb0, f, 'py')
659
660 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
661 _ip.magic("notebook -f ipynb %s" % infile)
662 _ip.magic("notebook -f json %s" % infile)
663
664 628
665 629 def test_env():
666 630 env = _ip.magic("env")
667 631 assert isinstance(env, dict), type(env)
668 632
669 633
670 634 class CellMagicTestCase(TestCase):
671 635
672 636 def check_ident(self, magic):
673 637 # Manually called, we get the result
674 638 out = _ip.run_cell_magic(magic, 'a', 'b')
675 639 nt.assert_equal(out, ('a','b'))
676 640 # Via run_cell, it goes into the user's namespace via displayhook
677 641 _ip.run_cell('%%' + magic +' c\nd')
678 642 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
679 643
680 644 def test_cell_magic_func_deco(self):
681 645 "Cell magic using simple decorator"
682 646 @register_cell_magic
683 647 def cellm(line, cell):
684 648 return line, cell
685 649
686 650 self.check_ident('cellm')
687 651
688 652 def test_cell_magic_reg(self):
689 653 "Cell magic manually registered"
690 654 def cellm(line, cell):
691 655 return line, cell
692 656
693 657 _ip.register_magic_function(cellm, 'cell', 'cellm2')
694 658 self.check_ident('cellm2')
695 659
696 660 def test_cell_magic_class(self):
697 661 "Cell magics declared via a class"
698 662 @magics_class
699 663 class MyMagics(Magics):
700 664
701 665 @cell_magic
702 666 def cellm3(self, line, cell):
703 667 return line, cell
704 668
705 669 _ip.register_magics(MyMagics)
706 670 self.check_ident('cellm3')
707 671
708 672 def test_cell_magic_class2(self):
709 673 "Cell magics declared via a class, #2"
710 674 @magics_class
711 675 class MyMagics2(Magics):
712 676
713 677 @cell_magic('cellm4')
714 678 def cellm33(self, line, cell):
715 679 return line, cell
716 680
717 681 _ip.register_magics(MyMagics2)
718 682 self.check_ident('cellm4')
719 683 # Check that nothing is registered as 'cellm33'
720 684 c33 = _ip.find_cell_magic('cellm33')
721 685 nt.assert_equal(c33, None)
722 686
723 687 def test_file():
724 688 """Basic %%file"""
725 689 ip = get_ipython()
726 690 with TemporaryDirectory() as td:
727 691 fname = os.path.join(td, 'file1')
728 692 ip.run_cell_magic("file", fname, u'\n'.join([
729 693 'line1',
730 694 'line2',
731 695 ]))
732 696 with open(fname) as f:
733 697 s = f.read()
734 698 nt.assert_in('line1\n', s)
735 699 nt.assert_in('line2', s)
736 700
737 701 def test_file_var_expand():
738 702 """%%file $filename"""
739 703 ip = get_ipython()
740 704 with TemporaryDirectory() as td:
741 705 fname = os.path.join(td, 'file1')
742 706 ip.user_ns['filename'] = fname
743 707 ip.run_cell_magic("file", '$filename', u'\n'.join([
744 708 'line1',
745 709 'line2',
746 710 ]))
747 711 with open(fname) as f:
748 712 s = f.read()
749 713 nt.assert_in('line1\n', s)
750 714 nt.assert_in('line2', s)
751 715
752 716 def test_file_unicode():
753 717 """%%file with unicode cell"""
754 718 ip = get_ipython()
755 719 with TemporaryDirectory() as td:
756 720 fname = os.path.join(td, 'file1')
757 721 ip.run_cell_magic("file", fname, u'\n'.join([
758 722 u'liné1',
759 723 u'liné2',
760 724 ]))
761 725 with io.open(fname, encoding='utf-8') as f:
762 726 s = f.read()
763 727 nt.assert_in(u'liné1\n', s)
764 728 nt.assert_in(u'liné2', s)
765 729
766 730 def test_file_amend():
767 731 """%%file -a amends files"""
768 732 ip = get_ipython()
769 733 with TemporaryDirectory() as td:
770 734 fname = os.path.join(td, 'file2')
771 735 ip.run_cell_magic("file", fname, u'\n'.join([
772 736 'line1',
773 737 'line2',
774 738 ]))
775 739 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
776 740 'line3',
777 741 'line4',
778 742 ]))
779 743 with open(fname) as f:
780 744 s = f.read()
781 745 nt.assert_in('line1\n', s)
782 746 nt.assert_in('line3\n', s)
783 747
784 748
785 749 def test_script_config():
786 750 ip = get_ipython()
787 751 ip.config.ScriptMagics.script_magics = ['whoda']
788 752 sm = script.ScriptMagics(shell=ip)
789 753 nt.assert_in('whoda', sm.magics['cell'])
790 754
791 755 @dec.skip_win32
792 756 def test_script_out():
793 757 ip = get_ipython()
794 758 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
795 759 nt.assert_equal(ip.user_ns['output'], 'hi\n')
796 760
797 761 @dec.skip_win32
798 762 def test_script_err():
799 763 ip = get_ipython()
800 764 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
801 765 nt.assert_equal(ip.user_ns['error'], 'hello\n')
802 766
803 767 @dec.skip_win32
804 768 def test_script_out_err():
805 769 ip = get_ipython()
806 770 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
807 771 nt.assert_equal(ip.user_ns['output'], 'hi\n')
808 772 nt.assert_equal(ip.user_ns['error'], 'hello\n')
809 773
810 774 @dec.skip_win32
811 775 def test_script_bg_out():
812 776 ip = get_ipython()
813 777 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
814 778 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
815 779
816 780 @dec.skip_win32
817 781 def test_script_bg_err():
818 782 ip = get_ipython()
819 783 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
820 784 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
821 785
822 786 @dec.skip_win32
823 787 def test_script_bg_out_err():
824 788 ip = get_ipython()
825 789 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
826 790 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
827 791 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
828 792
829 793 def test_script_defaults():
830 794 ip = get_ipython()
831 795 for cmd in ['sh', 'bash', 'perl', 'ruby']:
832 796 try:
833 797 find_cmd(cmd)
834 798 except Exception:
835 799 pass
836 800 else:
837 801 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
838 802
839 803
840 804 @magics_class
841 805 class FooFoo(Magics):
842 806 """class with both %foo and %%foo magics"""
843 807 @line_magic('foo')
844 808 def line_foo(self, line):
845 809 "I am line foo"
846 810 pass
847 811
848 812 @cell_magic("foo")
849 813 def cell_foo(self, line, cell):
850 814 "I am cell foo, not line foo"
851 815 pass
852 816
853 817 def test_line_cell_info():
854 818 """%%foo and %foo magics are distinguishable to inspect"""
855 819 ip = get_ipython()
856 820 ip.magics_manager.register(FooFoo)
857 821 oinfo = ip.object_inspect('foo')
858 822 nt.assert_true(oinfo['found'])
859 823 nt.assert_true(oinfo['ismagic'])
860 824
861 825 oinfo = ip.object_inspect('%%foo')
862 826 nt.assert_true(oinfo['found'])
863 827 nt.assert_true(oinfo['ismagic'])
864 828 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
865 829
866 830 oinfo = ip.object_inspect('%foo')
867 831 nt.assert_true(oinfo['found'])
868 832 nt.assert_true(oinfo['ismagic'])
869 833 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
870 834
871 835 def test_multiple_magics():
872 836 ip = get_ipython()
873 837 foo1 = FooFoo(ip)
874 838 foo2 = FooFoo(ip)
875 839 mm = ip.magics_manager
876 840 mm.register(foo1)
877 841 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
878 842 mm.register(foo2)
879 843 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
880 844
881 845 def test_alias_magic():
882 846 """Test %alias_magic."""
883 847 ip = get_ipython()
884 848 mm = ip.magics_manager
885 849
886 850 # Basic operation: both cell and line magics are created, if possible.
887 851 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
888 852 nt.assert_in('timeit_alias', mm.magics['line'])
889 853 nt.assert_in('timeit_alias', mm.magics['cell'])
890 854
891 855 # --cell is specified, line magic not created.
892 856 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
893 857 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
894 858 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
895 859
896 860 # Test that line alias is created successfully.
897 861 ip.run_line_magic('alias_magic', '--line env_alias env')
898 862 nt.assert_equal(ip.run_line_magic('env', ''),
899 863 ip.run_line_magic('env_alias', ''))
900 864
901 865 def test_save():
902 866 """Test %save."""
903 867 ip = get_ipython()
904 868 ip.history_manager.reset() # Clear any existing history.
905 869 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
906 870 for i, cmd in enumerate(cmds, start=1):
907 871 ip.history_manager.store_inputs(i, cmd)
908 872 with TemporaryDirectory() as tmpdir:
909 873 file = os.path.join(tmpdir, "testsave.py")
910 874 ip.run_line_magic("save", "%s 1-10" % file)
911 875 with open(file) as f:
912 876 content = f.read()
913 877 nt.assert_equal(content.count(cmds[0]), 1)
914 878 nt.assert_in('coding: utf-8', content)
915 879 ip.run_line_magic("save", "-a %s 1-10" % file)
916 880 with open(file) as f:
917 881 content = f.read()
918 882 nt.assert_equal(content.count(cmds[0]), 2)
919 883 nt.assert_in('coding: utf-8', content)
920 884
921 885
922 886 def test_store():
923 887 """Test %store."""
924 888 ip = get_ipython()
925 889 ip.run_line_magic('load_ext', 'storemagic')
926 890
927 891 # make sure the storage is empty
928 892 ip.run_line_magic('store', '-z')
929 893 ip.user_ns['var'] = 42
930 894 ip.run_line_magic('store', 'var')
931 895 ip.user_ns['var'] = 39
932 896 ip.run_line_magic('store', '-r')
933 897 nt.assert_equal(ip.user_ns['var'], 42)
934 898
935 899 ip.run_line_magic('store', '-d var')
936 900 ip.user_ns['var'] = 39
937 901 ip.run_line_magic('store' , '-r')
938 902 nt.assert_equal(ip.user_ns['var'], 39)
939 903
940 904
941 905 def _run_edit_test(arg_s, exp_filename=None,
942 906 exp_lineno=-1,
943 907 exp_contents=None,
944 908 exp_is_temp=None):
945 909 ip = get_ipython()
946 910 M = code.CodeMagics(ip)
947 911 last_call = ['','']
948 912 opts,args = M.parse_options(arg_s,'prxn:')
949 913 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
950 914
951 915 if exp_filename is not None:
952 916 nt.assert_equal(exp_filename, filename)
953 917 if exp_contents is not None:
954 918 with io.open(filename, 'r', encoding='utf-8') as f:
955 919 contents = f.read()
956 920 nt.assert_equal(exp_contents, contents)
957 921 if exp_lineno != -1:
958 922 nt.assert_equal(exp_lineno, lineno)
959 923 if exp_is_temp is not None:
960 924 nt.assert_equal(exp_is_temp, is_temp)
961 925
962 926
963 927 def test_edit_interactive():
964 928 """%edit on interactively defined objects"""
965 929 ip = get_ipython()
966 930 n = ip.execution_count
967 931 ip.run_cell(u"def foo(): return 1", store_history=True)
968 932
969 933 try:
970 934 _run_edit_test("foo")
971 935 except code.InteractivelyDefined as e:
972 936 nt.assert_equal(e.index, n)
973 937 else:
974 938 raise AssertionError("Should have raised InteractivelyDefined")
975 939
976 940
977 941 def test_edit_cell():
978 942 """%edit [cell id]"""
979 943 ip = get_ipython()
980 944
981 945 ip.run_cell(u"def foo(): return 1", store_history=True)
982 946
983 947 # test
984 948 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
985 949
986 950 def test_bookmark():
987 951 ip = get_ipython()
988 952 ip.run_line_magic('bookmark', 'bmname')
989 953 with tt.AssertPrints('bmname'):
990 954 ip.run_line_magic('bookmark', '-l')
991 955 ip.run_line_magic('bookmark', '-d bmname')
@@ -1,516 +1,512 b''
1 1 # encoding: utf-8
2 2 """Tests for code execution (%run and related), which is particularly tricky.
3 3
4 4 Because of how %run manages namespaces, and the fact that we are trying here to
5 5 verify subtle object deletion and reference counting issues, the %run tests
6 6 will be kept in this separate file. This makes it easier to aggregate in one
7 7 place the tricks needed to handle it; most other magics are much easier to test
8 8 and we do so in a common test_magic file.
9 9 """
10
11 # Copyright (c) IPython Development Team.
12 # Distributed under the terms of the Modified BSD License.
13
10 14 from __future__ import absolute_import
11 15
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15 16
16 17 import functools
17 18 import os
18 19 from os.path import join as pjoin
19 20 import random
20 21 import sys
21 22 import tempfile
22 23 import textwrap
23 24 import unittest
24 25
25 26 import nose.tools as nt
26 27 from nose import SkipTest
27 28
28 29 from IPython.testing import decorators as dec
29 30 from IPython.testing import tools as tt
30 31 from IPython.utils import py3compat
31 32 from IPython.utils.io import capture_output
32 33 from IPython.utils.tempdir import TemporaryDirectory
33 34 from IPython.core import debugger
34 35
35 #-----------------------------------------------------------------------------
36 # Test functions begin
37 #-----------------------------------------------------------------------------
38 36
39 37 def doctest_refbug():
40 38 """Very nasty problem with references held by multiple runs of a script.
41 39 See: https://github.com/ipython/ipython/issues/141
42 40
43 41 In [1]: _ip.clear_main_mod_cache()
44 42 # random
45 43
46 44 In [2]: %run refbug
47 45
48 46 In [3]: call_f()
49 47 lowercased: hello
50 48
51 49 In [4]: %run refbug
52 50
53 51 In [5]: call_f()
54 52 lowercased: hello
55 53 lowercased: hello
56 54 """
57 55
58 56
59 57 def doctest_run_builtins():
60 58 r"""Check that %run doesn't damage __builtins__.
61 59
62 60 In [1]: import tempfile
63 61
64 62 In [2]: bid1 = id(__builtins__)
65 63
66 64 In [3]: fname = tempfile.mkstemp('.py')[1]
67 65
68 66 In [3]: f = open(fname,'w')
69 67
70 68 In [4]: dummy= f.write('pass\n')
71 69
72 70 In [5]: f.flush()
73 71
74 72 In [6]: t1 = type(__builtins__)
75 73
76 74 In [7]: %run $fname
77 75
78 76 In [7]: f.close()
79 77
80 78 In [8]: bid2 = id(__builtins__)
81 79
82 80 In [9]: t2 = type(__builtins__)
83 81
84 82 In [10]: t1 == t2
85 83 Out[10]: True
86 84
87 85 In [10]: bid1 == bid2
88 86 Out[10]: True
89 87
90 88 In [12]: try:
91 89 ....: os.unlink(fname)
92 90 ....: except:
93 91 ....: pass
94 92 ....:
95 93 """
96 94
97 95
98 96 def doctest_run_option_parser():
99 97 r"""Test option parser in %run.
100 98
101 99 In [1]: %run print_argv.py
102 100 []
103 101
104 102 In [2]: %run print_argv.py print*.py
105 103 ['print_argv.py']
106 104
107 105 In [3]: %run -G print_argv.py print*.py
108 106 ['print*.py']
109 107
110 108 """
111 109
112 110
113 111 @dec.skip_win32
114 112 def doctest_run_option_parser_for_posix():
115 113 r"""Test option parser in %run (Linux/OSX specific).
116 114
117 115 You need double quote to escape glob in POSIX systems:
118 116
119 117 In [1]: %run print_argv.py print\\*.py
120 118 ['print*.py']
121 119
122 120 You can't use quote to escape glob in POSIX systems:
123 121
124 122 In [2]: %run print_argv.py 'print*.py'
125 123 ['print_argv.py']
126 124
127 125 """
128 126
129 127
130 128 @dec.skip_if_not_win32
131 129 def doctest_run_option_parser_for_windows():
132 130 r"""Test option parser in %run (Windows specific).
133 131
134 132 In Windows, you can't escape ``*` `by backslash:
135 133
136 134 In [1]: %run print_argv.py print\\*.py
137 135 ['print\\*.py']
138 136
139 137 You can use quote to escape glob:
140 138
141 139 In [2]: %run print_argv.py 'print*.py'
142 140 ['print*.py']
143 141
144 142 """
145 143
146 144
147 145 @py3compat.doctest_refactor_print
148 146 def doctest_reset_del():
149 147 """Test that resetting doesn't cause errors in __del__ methods.
150 148
151 149 In [2]: class A(object):
152 150 ...: def __del__(self):
153 151 ...: print str("Hi")
154 152 ...:
155 153
156 154 In [3]: a = A()
157 155
158 156 In [4]: get_ipython().reset()
159 157 Hi
160 158
161 159 In [5]: 1+1
162 160 Out[5]: 2
163 161 """
164 162
165 163 # For some tests, it will be handy to organize them in a class with a common
166 164 # setup that makes a temp file
167 165
168 166 class TestMagicRunPass(tt.TempFileMixin):
169 167
170 168 def setup(self):
171 169 """Make a valid python temp file."""
172 170 self.mktmp('pass\n')
173 171
174 172 def run_tmpfile(self):
175 173 _ip = get_ipython()
176 174 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
177 175 # See below and ticket https://bugs.launchpad.net/bugs/366353
178 176 _ip.magic('run %s' % self.fname)
179 177
180 178 def run_tmpfile_p(self):
181 179 _ip = get_ipython()
182 180 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
183 181 # See below and ticket https://bugs.launchpad.net/bugs/366353
184 182 _ip.magic('run -p %s' % self.fname)
185 183
186 184 def test_builtins_id(self):
187 185 """Check that %run doesn't damage __builtins__ """
188 186 _ip = get_ipython()
189 187 # Test that the id of __builtins__ is not modified by %run
190 188 bid1 = id(_ip.user_ns['__builtins__'])
191 189 self.run_tmpfile()
192 190 bid2 = id(_ip.user_ns['__builtins__'])
193 191 nt.assert_equal(bid1, bid2)
194 192
195 193 def test_builtins_type(self):
196 194 """Check that the type of __builtins__ doesn't change with %run.
197 195
198 196 However, the above could pass if __builtins__ was already modified to
199 197 be a dict (it should be a module) by a previous use of %run. So we
200 198 also check explicitly that it really is a module:
201 199 """
202 200 _ip = get_ipython()
203 201 self.run_tmpfile()
204 202 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
205 203
206 204 def test_prompts(self):
207 205 """Test that prompts correctly generate after %run"""
208 206 self.run_tmpfile()
209 207 _ip = get_ipython()
210 208 p2 = _ip.prompt_manager.render('in2').strip()
211 209 nt.assert_equal(p2[:3], '...')
212 210
213 211 def test_run_profile( self ):
214 212 """Test that the option -p, which invokes the profiler, do not
215 213 crash by invoking execfile"""
216 214 _ip = get_ipython()
217 215 self.run_tmpfile_p()
218 216
219 217
220 218 class TestMagicRunSimple(tt.TempFileMixin):
221 219
222 220 def test_simpledef(self):
223 221 """Test that simple class definitions work."""
224 222 src = ("class foo: pass\n"
225 223 "def f(): return foo()")
226 224 self.mktmp(src)
227 225 _ip.magic('run %s' % self.fname)
228 226 _ip.run_cell('t = isinstance(f(), foo)')
229 227 nt.assert_true(_ip.user_ns['t'])
230 228
231 229 def test_obj_del(self):
232 230 """Test that object's __del__ methods are called on exit."""
233 231 if sys.platform == 'win32':
234 232 try:
235 233 import win32api
236 234 except ImportError:
237 235 raise SkipTest("Test requires pywin32")
238 236 src = ("class A(object):\n"
239 237 " def __del__(self):\n"
240 238 " print 'object A deleted'\n"
241 239 "a = A()\n")
242 240 self.mktmp(py3compat.doctest_refactor_print(src))
243 241 if dec.module_not_available('sqlite3'):
244 242 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
245 243 else:
246 244 err = None
247 245 tt.ipexec_validate(self.fname, 'object A deleted', err)
248 246
249 247 def test_aggressive_namespace_cleanup(self):
250 248 """Test that namespace cleanup is not too aggressive GH-238
251 249
252 250 Returning from another run magic deletes the namespace"""
253 251 # see ticket https://github.com/ipython/ipython/issues/238
254 252 class secondtmp(tt.TempFileMixin): pass
255 253 empty = secondtmp()
256 254 empty.mktmp('')
257 255 # On Windows, the filename will have \users in it, so we need to use the
258 256 # repr so that the \u becomes \\u.
259 257 src = ("ip = get_ipython()\n"
260 258 "for i in range(5):\n"
261 259 " try:\n"
262 260 " ip.magic(%r)\n"
263 261 " except NameError as e:\n"
264 262 " print(i)\n"
265 263 " break\n" % ('run ' + empty.fname))
266 264 self.mktmp(src)
267 265 _ip.magic('run %s' % self.fname)
268 266 _ip.run_cell('ip == get_ipython()')
269 267 nt.assert_equal(_ip.user_ns['i'], 4)
270 268
271 269 def test_run_second(self):
272 270 """Test that running a second file doesn't clobber the first, gh-3547
273 271 """
274 272 self.mktmp("avar = 1\n"
275 273 "def afunc():\n"
276 274 " return avar\n")
277 275
278 276 empty = tt.TempFileMixin()
279 277 empty.mktmp("")
280 278
281 279 _ip.magic('run %s' % self.fname)
282 280 _ip.magic('run %s' % empty.fname)
283 281 nt.assert_equal(_ip.user_ns['afunc'](), 1)
284 282
285 283 @dec.skip_win32
286 284 def test_tclass(self):
287 285 mydir = os.path.dirname(__file__)
288 286 tc = os.path.join(mydir, 'tclass')
289 287 src = ("%%run '%s' C-first\n"
290 288 "%%run '%s' C-second\n"
291 289 "%%run '%s' C-third\n") % (tc, tc, tc)
292 290 self.mktmp(src, '.ipy')
293 291 out = """\
294 292 ARGV 1-: ['C-first']
295 293 ARGV 1-: ['C-second']
296 294 tclass.py: deleting object: C-first
297 295 ARGV 1-: ['C-third']
298 296 tclass.py: deleting object: C-second
299 297 tclass.py: deleting object: C-third
300 298 """
301 299 if dec.module_not_available('sqlite3'):
302 300 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
303 301 else:
304 302 err = None
305 303 tt.ipexec_validate(self.fname, out, err)
306 304
307 305 def test_run_i_after_reset(self):
308 306 """Check that %run -i still works after %reset (gh-693)"""
309 307 src = "yy = zz\n"
310 308 self.mktmp(src)
311 309 _ip.run_cell("zz = 23")
312 310 _ip.magic('run -i %s' % self.fname)
313 311 nt.assert_equal(_ip.user_ns['yy'], 23)
314 312 _ip.magic('reset -f')
315 313 _ip.run_cell("zz = 23")
316 314 _ip.magic('run -i %s' % self.fname)
317 315 nt.assert_equal(_ip.user_ns['yy'], 23)
318 316
319 317 def test_unicode(self):
320 318 """Check that files in odd encodings are accepted."""
321 319 mydir = os.path.dirname(__file__)
322 320 na = os.path.join(mydir, 'nonascii.py')
323 321 _ip.magic('run "%s"' % na)
324 322 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
325 323
326 324 def test_run_py_file_attribute(self):
327 325 """Test handling of `__file__` attribute in `%run <file>.py`."""
328 326 src = "t = __file__\n"
329 327 self.mktmp(src)
330 328 _missing = object()
331 329 file1 = _ip.user_ns.get('__file__', _missing)
332 330 _ip.magic('run %s' % self.fname)
333 331 file2 = _ip.user_ns.get('__file__', _missing)
334 332
335 333 # Check that __file__ was equal to the filename in the script's
336 334 # namespace.
337 335 nt.assert_equal(_ip.user_ns['t'], self.fname)
338 336
339 337 # Check that __file__ was not leaked back into user_ns.
340 338 nt.assert_equal(file1, file2)
341 339
342 340 def test_run_ipy_file_attribute(self):
343 341 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
344 342 src = "t = __file__\n"
345 343 self.mktmp(src, ext='.ipy')
346 344 _missing = object()
347 345 file1 = _ip.user_ns.get('__file__', _missing)
348 346 _ip.magic('run %s' % self.fname)
349 347 file2 = _ip.user_ns.get('__file__', _missing)
350 348
351 349 # Check that __file__ was equal to the filename in the script's
352 350 # namespace.
353 351 nt.assert_equal(_ip.user_ns['t'], self.fname)
354 352
355 353 # Check that __file__ was not leaked back into user_ns.
356 354 nt.assert_equal(file1, file2)
357 355
358 356 def test_run_formatting(self):
359 357 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
360 358 src = "pass"
361 359 self.mktmp(src)
362 360 _ip.magic('run -t -N 1 %s' % self.fname)
363 361 _ip.magic('run -t -N 10 %s' % self.fname)
364 362
365 363 def test_ignore_sys_exit(self):
366 364 """Test the -e option to ignore sys.exit()"""
367 365 src = "import sys; sys.exit(1)"
368 366 self.mktmp(src)
369 367 with tt.AssertPrints('SystemExit'):
370 368 _ip.magic('run %s' % self.fname)
371 369
372 370 with tt.AssertNotPrints('SystemExit'):
373 371 _ip.magic('run -e %s' % self.fname)
374 372
375 @dec.skip_without('IPython.nbformat.current') # Requires jsonschema
373 @dec.skip_without('IPython.nbformat') # Requires jsonschema
376 374 def test_run_nb(self):
377 375 """Test %run notebook.ipynb"""
378 from IPython.nbformat import current
379 nb = current.new_notebook(
380 worksheets=[
381 current.new_worksheet(cells=[
382 current.new_text_cell("The Ultimate Question of Everything"),
383 current.new_code_cell("answer=42")
384 ])
376 from IPython.nbformat import v4, writes
377 nb = v4.new_notebook(
378 cells=[
379 v4.new_markdown_cell("The Ultimate Question of Everything"),
380 v4.new_code_cell("answer=42")
385 381 ]
386 382 )
387 src = current.writes(nb, 'json')
383 src = writes(nb, version=4)
388 384 self.mktmp(src, ext='.ipynb')
389 385
390 386 _ip.magic("run %s" % self.fname)
391 387
392 388 nt.assert_equal(_ip.user_ns['answer'], 42)
393 389
394 390
395 391
396 392 class TestMagicRunWithPackage(unittest.TestCase):
397 393
398 394 def writefile(self, name, content):
399 395 path = os.path.join(self.tempdir.name, name)
400 396 d = os.path.dirname(path)
401 397 if not os.path.isdir(d):
402 398 os.makedirs(d)
403 399 with open(path, 'w') as f:
404 400 f.write(textwrap.dedent(content))
405 401
406 402 def setUp(self):
407 403 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
408 404 """Temporary valid python package name."""
409 405
410 406 self.value = int(random.random() * 10000)
411 407
412 408 self.tempdir = TemporaryDirectory()
413 409 self.__orig_cwd = py3compat.getcwd()
414 410 sys.path.insert(0, self.tempdir.name)
415 411
416 412 self.writefile(os.path.join(package, '__init__.py'), '')
417 413 self.writefile(os.path.join(package, 'sub.py'), """
418 414 x = {0!r}
419 415 """.format(self.value))
420 416 self.writefile(os.path.join(package, 'relative.py'), """
421 417 from .sub import x
422 418 """)
423 419 self.writefile(os.path.join(package, 'absolute.py'), """
424 420 from {0}.sub import x
425 421 """.format(package))
426 422
427 423 def tearDown(self):
428 424 os.chdir(self.__orig_cwd)
429 425 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
430 426 self.tempdir.cleanup()
431 427
432 428 def check_run_submodule(self, submodule, opts=''):
433 429 _ip.user_ns.pop('x', None)
434 430 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
435 431 self.assertEqual(_ip.user_ns['x'], self.value,
436 432 'Variable `x` is not loaded from module `{0}`.'
437 433 .format(submodule))
438 434
439 435 def test_run_submodule_with_absolute_import(self):
440 436 self.check_run_submodule('absolute')
441 437
442 438 def test_run_submodule_with_relative_import(self):
443 439 """Run submodule that has a relative import statement (#2727)."""
444 440 self.check_run_submodule('relative')
445 441
446 442 def test_prun_submodule_with_absolute_import(self):
447 443 self.check_run_submodule('absolute', '-p')
448 444
449 445 def test_prun_submodule_with_relative_import(self):
450 446 self.check_run_submodule('relative', '-p')
451 447
452 448 def with_fake_debugger(func):
453 449 @functools.wraps(func)
454 450 def wrapper(*args, **kwds):
455 451 with tt.monkeypatch(debugger.Pdb, 'run', staticmethod(eval)):
456 452 return func(*args, **kwds)
457 453 return wrapper
458 454
459 455 @with_fake_debugger
460 456 def test_debug_run_submodule_with_absolute_import(self):
461 457 self.check_run_submodule('absolute', '-d')
462 458
463 459 @with_fake_debugger
464 460 def test_debug_run_submodule_with_relative_import(self):
465 461 self.check_run_submodule('relative', '-d')
466 462
467 463 def test_run__name__():
468 464 with TemporaryDirectory() as td:
469 465 path = pjoin(td, 'foo.py')
470 466 with open(path, 'w') as f:
471 467 f.write("q = __name__")
472 468
473 469 _ip.user_ns.pop('q', None)
474 470 _ip.magic('run {}'.format(path))
475 471 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
476 472
477 473 _ip.magic('run -n {}'.format(path))
478 474 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
479 475
480 476 def test_run_tb():
481 477 """Test traceback offset in %run"""
482 478 with TemporaryDirectory() as td:
483 479 path = pjoin(td, 'foo.py')
484 480 with open(path, 'w') as f:
485 481 f.write('\n'.join([
486 482 "def foo():",
487 483 " return bar()",
488 484 "def bar():",
489 485 " raise RuntimeError('hello!')",
490 486 "foo()",
491 487 ]))
492 488 with capture_output() as io:
493 489 _ip.magic('run {}'.format(path))
494 490 out = io.stdout
495 491 nt.assert_not_in("execfile", out)
496 492 nt.assert_in("RuntimeError", out)
497 493 nt.assert_equal(out.count("---->"), 3)
498 494
499 495 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
500 496 def test_script_tb():
501 497 """Test traceback offset in `ipython script.py`"""
502 498 with TemporaryDirectory() as td:
503 499 path = pjoin(td, 'foo.py')
504 500 with open(path, 'w') as f:
505 501 f.write('\n'.join([
506 502 "def foo():",
507 503 " return bar()",
508 504 "def bar():",
509 505 " raise RuntimeError('hello!')",
510 506 "foo()",
511 507 ]))
512 508 out, err = tt.ipexec(path)
513 509 nt.assert_not_in("execfile", out)
514 510 nt.assert_in("RuntimeError", out)
515 511 nt.assert_equal(out.count("---->"), 3)
516 512
@@ -1,147 +1,148 b''
1 1 """Tornado handlers for nbconvert."""
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 6 import io
7 7 import os
8 8 import zipfile
9 9
10 10 from tornado import web
11 11
12 12 from ..base.handlers import (
13 13 IPythonHandler, FilesRedirectHandler,
14 14 notebook_path_regex, path_regex,
15 15 )
16 from IPython.nbformat.current import to_notebook_json
16 from IPython.nbformat import from_dict
17 17
18 18 from IPython.utils.py3compat import cast_bytes
19 19
20 20 def find_resource_files(output_files_dir):
21 21 files = []
22 22 for dirpath, dirnames, filenames in os.walk(output_files_dir):
23 23 files.extend([os.path.join(dirpath, f) for f in filenames])
24 24 return files
25 25
26 26 def respond_zip(handler, name, output, resources):
27 27 """Zip up the output and resource files and respond with the zip file.
28 28
29 29 Returns True if it has served a zip file, False if there are no resource
30 30 files, in which case we serve the plain output file.
31 31 """
32 32 # Check if we have resource files we need to zip
33 33 output_files = resources.get('outputs', None)
34 34 if not output_files:
35 35 return False
36 36
37 37 # Headers
38 38 zip_filename = os.path.splitext(name)[0] + '.zip'
39 39 handler.set_header('Content-Disposition',
40 40 'attachment; filename="%s"' % zip_filename)
41 41 handler.set_header('Content-Type', 'application/zip')
42 42
43 43 # Prepare the zip file
44 44 buffer = io.BytesIO()
45 45 zipf = zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED)
46 46 output_filename = os.path.splitext(name)[0] + '.' + resources['output_extension']
47 47 zipf.writestr(output_filename, cast_bytes(output, 'utf-8'))
48 48 for filename, data in output_files.items():
49 49 zipf.writestr(os.path.basename(filename), data)
50 50 zipf.close()
51 51
52 52 handler.finish(buffer.getvalue())
53 53 return True
54 54
55 55 def get_exporter(format, **kwargs):
56 56 """get an exporter, raising appropriate errors"""
57 57 # if this fails, will raise 500
58 58 try:
59 59 from IPython.nbconvert.exporters.export import exporter_map
60 60 except ImportError as e:
61 61 raise web.HTTPError(500, "Could not import nbconvert: %s" % e)
62 62
63 63 try:
64 64 Exporter = exporter_map[format]
65 65 except KeyError:
66 66 # should this be 400?
67 67 raise web.HTTPError(404, u"No exporter for format: %s" % format)
68 68
69 69 try:
70 70 return Exporter(**kwargs)
71 71 except Exception as e:
72 72 raise web.HTTPError(500, "Could not construct Exporter: %s" % e)
73 73
74 74 class NbconvertFileHandler(IPythonHandler):
75 75
76 76 SUPPORTED_METHODS = ('GET',)
77 77
78 78 @web.authenticated
79 79 def get(self, format, path='', name=None):
80 80
81 81 exporter = get_exporter(format, config=self.config, log=self.log)
82 82
83 83 path = path.strip('/')
84 84 model = self.contents_manager.get_model(name=name, path=path)
85 85
86 86 self.set_header('Last-Modified', model['last_modified'])
87 87
88 88 try:
89 89 output, resources = exporter.from_notebook_node(model['content'])
90 90 except Exception as e:
91 91 raise web.HTTPError(500, "nbconvert failed: %s" % e)
92 92
93 93 if respond_zip(self, name, output, resources):
94 94 return
95 95
96 96 # Force download if requested
97 97 if self.get_argument('download', 'false').lower() == 'true':
98 98 filename = os.path.splitext(name)[0] + '.' + resources['output_extension']
99 99 self.set_header('Content-Disposition',
100 100 'attachment; filename="%s"' % filename)
101 101
102 102 # MIME type
103 103 if exporter.output_mimetype:
104 104 self.set_header('Content-Type',
105 105 '%s; charset=utf-8' % exporter.output_mimetype)
106 106
107 107 self.finish(output)
108 108
109 109 class NbconvertPostHandler(IPythonHandler):
110 110 SUPPORTED_METHODS = ('POST',)
111 111
112 112 @web.authenticated
113 113 def post(self, format):
114 114 exporter = get_exporter(format, config=self.config)
115 115
116 116 model = self.get_json_body()
117 nbnode = to_notebook_json(model['content'])
117 name = model.get('name', 'notebook.ipynb')
118 nbnode = from_dict(model['content'])
118 119
119 120 try:
120 121 output, resources = exporter.from_notebook_node(nbnode)
121 122 except Exception as e:
122 123 raise web.HTTPError(500, "nbconvert failed: %s" % e)
123 124
124 if respond_zip(self, nbnode.metadata.name, output, resources):
125 if respond_zip(self, name, output, resources):
125 126 return
126 127
127 128 # MIME type
128 129 if exporter.output_mimetype:
129 130 self.set_header('Content-Type',
130 131 '%s; charset=utf-8' % exporter.output_mimetype)
131 132
132 133 self.finish(output)
133 134
134 135
135 136 #-----------------------------------------------------------------------------
136 137 # URL to handler mappings
137 138 #-----------------------------------------------------------------------------
138 139
139 140 _format_regex = r"(?P<format>\w+)"
140 141
141 142
142 143 default_handlers = [
143 144 (r"/nbconvert/%s%s" % (_format_regex, notebook_path_regex),
144 145 NbconvertFileHandler),
145 146 (r"/nbconvert/%s" % _format_regex, NbconvertPostHandler),
146 147 (r"/nbconvert/html%s" % path_regex, FilesRedirectHandler),
147 148 ]
@@ -1,129 +1,132 b''
1 1 # coding: utf-8
2 2 import base64
3 3 import io
4 4 import json
5 5 import os
6 6 from os.path import join as pjoin
7 7 import shutil
8 8
9 9 import requests
10 10
11 11 from IPython.html.utils import url_path_join
12 12 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
13 from IPython.nbformat.current import (new_notebook, write, new_worksheet,
14 new_heading_cell, new_code_cell,
15 new_output)
13 from IPython.nbformat import write
14 from IPython.nbformat.v4 import (
15 new_notebook, new_markdown_cell, new_code_cell, new_output,
16 )
16 17
17 18 from IPython.testing.decorators import onlyif_cmds_exist
18 19
19 20
20 21 class NbconvertAPI(object):
21 22 """Wrapper for nbconvert API calls."""
22 23 def __init__(self, base_url):
23 24 self.base_url = base_url
24 25
25 26 def _req(self, verb, path, body=None, params=None):
26 27 response = requests.request(verb,
27 28 url_path_join(self.base_url, 'nbconvert', path),
28 29 data=body, params=params,
29 30 )
30 31 response.raise_for_status()
31 32 return response
32 33
33 34 def from_file(self, format, path, name, download=False):
34 35 return self._req('GET', url_path_join(format, path, name),
35 36 params={'download':download})
36 37
37 38 def from_post(self, format, nbmodel):
38 39 body = json.dumps(nbmodel)
39 40 return self._req('POST', format, body)
40 41
41 42 def list_formats(self):
42 43 return self._req('GET', '')
43 44
44 45 png_green_pixel = base64.encodestring(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00'
45 46 b'\x00\x00\x01\x00\x00x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDAT'
46 b'\x08\xd7c\x90\xfb\xcf\x00\x00\x02\\\x01\x1e.~d\x87\x00\x00\x00\x00IEND\xaeB`\x82')
47 b'\x08\xd7c\x90\xfb\xcf\x00\x00\x02\\\x01\x1e.~d\x87\x00\x00\x00\x00IEND\xaeB`\x82'
48 ).decode('ascii')
47 49
48 50 class APITest(NotebookTestBase):
49 51 def setUp(self):
50 52 nbdir = self.notebook_dir.name
51 53
52 54 if not os.path.isdir(pjoin(nbdir, 'foo')):
53 55 os.mkdir(pjoin(nbdir, 'foo'))
54 56
55 nb = new_notebook(name='testnb')
57 nb = new_notebook()
56 58
57 ws = new_worksheet()
58 nb.worksheets = [ws]
59 ws.cells.append(new_heading_cell(u'Created by test ³'))
60 cc1 = new_code_cell(input=u'print(2*6)')
61 cc1.outputs.append(new_output(output_text=u'12', output_type='stream'))
62 cc1.outputs.append(new_output(output_png=png_green_pixel, output_type='pyout'))
63 ws.cells.append(cc1)
59 nb.cells.append(new_markdown_cell(u'Created by test ³'))
60 cc1 = new_code_cell(source=u'print(2*6)')
61 cc1.outputs.append(new_output(output_type="stream", text=u'12'))
62 cc1.outputs.append(new_output(output_type="execute_result",
63 data={'image/png' : png_green_pixel},
64 execution_count=1,
65 ))
66 nb.cells.append(cc1)
64 67
65 68 with io.open(pjoin(nbdir, 'foo', 'testnb.ipynb'), 'w',
66 69 encoding='utf-8') as f:
67 write(nb, f, format='ipynb')
70 write(nb, f, version=4)
68 71
69 72 self.nbconvert_api = NbconvertAPI(self.base_url())
70 73
71 74 def tearDown(self):
72 75 nbdir = self.notebook_dir.name
73 76
74 77 for dname in ['foo']:
75 78 shutil.rmtree(pjoin(nbdir, dname), ignore_errors=True)
76 79
77 80 @onlyif_cmds_exist('pandoc')
78 81 def test_from_file(self):
79 82 r = self.nbconvert_api.from_file('html', 'foo', 'testnb.ipynb')
80 83 self.assertEqual(r.status_code, 200)
81 84 self.assertIn(u'text/html', r.headers['Content-Type'])
82 85 self.assertIn(u'Created by test', r.text)
83 86 self.assertIn(u'print', r.text)
84 87
85 88 r = self.nbconvert_api.from_file('python', 'foo', 'testnb.ipynb')
86 89 self.assertIn(u'text/x-python', r.headers['Content-Type'])
87 90 self.assertIn(u'print(2*6)', r.text)
88 91
89 92 @onlyif_cmds_exist('pandoc')
90 93 def test_from_file_404(self):
91 94 with assert_http_error(404):
92 95 self.nbconvert_api.from_file('html', 'foo', 'thisdoesntexist.ipynb')
93 96
94 97 @onlyif_cmds_exist('pandoc')
95 98 def test_from_file_download(self):
96 99 r = self.nbconvert_api.from_file('python', 'foo', 'testnb.ipynb', download=True)
97 100 content_disposition = r.headers['Content-Disposition']
98 101 self.assertIn('attachment', content_disposition)
99 102 self.assertIn('testnb.py', content_disposition)
100 103
101 104 @onlyif_cmds_exist('pandoc')
102 105 def test_from_file_zip(self):
103 106 r = self.nbconvert_api.from_file('latex', 'foo', 'testnb.ipynb', download=True)
104 107 self.assertIn(u'application/zip', r.headers['Content-Type'])
105 108 self.assertIn(u'.zip', r.headers['Content-Disposition'])
106 109
107 110 @onlyif_cmds_exist('pandoc')
108 111 def test_from_post(self):
109 112 nbmodel_url = url_path_join(self.base_url(), 'api/contents/foo/testnb.ipynb')
110 113 nbmodel = requests.get(nbmodel_url).json()
111 114
112 115 r = self.nbconvert_api.from_post(format='html', nbmodel=nbmodel)
113 116 self.assertEqual(r.status_code, 200)
114 117 self.assertIn(u'text/html', r.headers['Content-Type'])
115 118 self.assertIn(u'Created by test', r.text)
116 119 self.assertIn(u'print', r.text)
117 120
118 121 r = self.nbconvert_api.from_post(format='python', nbmodel=nbmodel)
119 122 self.assertIn(u'text/x-python', r.headers['Content-Type'])
120 123 self.assertIn(u'print(2*6)', r.text)
121 124
122 125 @onlyif_cmds_exist('pandoc')
123 126 def test_from_post_zip(self):
124 127 nbmodel_url = url_path_join(self.base_url(), 'api/contents/foo/testnb.ipynb')
125 128 nbmodel = requests.get(nbmodel_url).json()
126 129
127 130 r = self.nbconvert_api.from_post(format='latex', nbmodel=nbmodel)
128 131 self.assertIn(u'application/zip', r.headers['Content-Type'])
129 132 self.assertIn(u'.zip', r.headers['Content-Disposition'])
@@ -1,545 +1,545 b''
1 1 """A contents manager that uses the local file system for storage."""
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 6 import base64
7 7 import io
8 8 import os
9 9 import glob
10 10 import shutil
11 11
12 12 from tornado import web
13 13
14 14 from .manager import ContentsManager
15 from IPython.nbformat import current
15 from IPython import nbformat
16 16 from IPython.utils.io import atomic_writing
17 17 from IPython.utils.path import ensure_dir_exists
18 18 from IPython.utils.traitlets import Unicode, Bool, TraitError
19 19 from IPython.utils.py3compat import getcwd
20 20 from IPython.utils import tz
21 21 from IPython.html.utils import is_hidden, to_os_path, url_path_join
22 22
23 23
24 24 class FileContentsManager(ContentsManager):
25 25
26 26 root_dir = Unicode(getcwd(), config=True)
27 27
28 28 save_script = Bool(False, config=True, help='DEPRECATED, IGNORED')
29 29 def _save_script_changed(self):
30 30 self.log.warn("""
31 31 Automatically saving notebooks as scripts has been removed.
32 32 Use `ipython nbconvert --to python [notebook]` instead.
33 33 """)
34 34
35 35 def _root_dir_changed(self, name, old, new):
36 36 """Do a bit of validation of the root_dir."""
37 37 if not os.path.isabs(new):
38 38 # If we receive a non-absolute path, make it absolute.
39 39 self.root_dir = os.path.abspath(new)
40 40 return
41 41 if not os.path.isdir(new):
42 42 raise TraitError("%r is not a directory" % new)
43 43
44 44 checkpoint_dir = Unicode('.ipynb_checkpoints', config=True,
45 45 help="""The directory name in which to keep file checkpoints
46 46
47 47 This is a path relative to the file's own directory.
48 48
49 49 By default, it is .ipynb_checkpoints
50 50 """
51 51 )
52 52
53 53 def _copy(self, src, dest):
54 54 """copy src to dest
55 55
56 56 like shutil.copy2, but log errors in copystat
57 57 """
58 58 shutil.copyfile(src, dest)
59 59 try:
60 60 shutil.copystat(src, dest)
61 61 except OSError as e:
62 62 self.log.debug("copystat on %s failed", dest, exc_info=True)
63 63
64 64 def _get_os_path(self, name=None, path=''):
65 65 """Given a filename and API path, return its file system
66 66 path.
67 67
68 68 Parameters
69 69 ----------
70 70 name : string
71 71 A filename
72 72 path : string
73 73 The relative API path to the named file.
74 74
75 75 Returns
76 76 -------
77 77 path : string
78 78 API path to be evaluated relative to root_dir.
79 79 """
80 80 if name is not None:
81 81 path = url_path_join(path, name)
82 82 return to_os_path(path, self.root_dir)
83 83
84 84 def path_exists(self, path):
85 85 """Does the API-style path refer to an extant directory?
86 86
87 87 API-style wrapper for os.path.isdir
88 88
89 89 Parameters
90 90 ----------
91 91 path : string
92 92 The path to check. This is an API path (`/` separated,
93 93 relative to root_dir).
94 94
95 95 Returns
96 96 -------
97 97 exists : bool
98 98 Whether the path is indeed a directory.
99 99 """
100 100 path = path.strip('/')
101 101 os_path = self._get_os_path(path=path)
102 102 return os.path.isdir(os_path)
103 103
104 104 def is_hidden(self, path):
105 105 """Does the API style path correspond to a hidden directory or file?
106 106
107 107 Parameters
108 108 ----------
109 109 path : string
110 110 The path to check. This is an API path (`/` separated,
111 111 relative to root_dir).
112 112
113 113 Returns
114 114 -------
115 115 exists : bool
116 116 Whether the path is hidden.
117 117
118 118 """
119 119 path = path.strip('/')
120 120 os_path = self._get_os_path(path=path)
121 121 return is_hidden(os_path, self.root_dir)
122 122
123 123 def file_exists(self, name, path=''):
124 124 """Returns True if the file exists, else returns False.
125 125
126 126 API-style wrapper for os.path.isfile
127 127
128 128 Parameters
129 129 ----------
130 130 name : string
131 131 The name of the file you are checking.
132 132 path : string
133 133 The relative path to the file's directory (with '/' as separator)
134 134
135 135 Returns
136 136 -------
137 137 exists : bool
138 138 Whether the file exists.
139 139 """
140 140 path = path.strip('/')
141 141 nbpath = self._get_os_path(name, path=path)
142 142 return os.path.isfile(nbpath)
143 143
144 144 def exists(self, name=None, path=''):
145 145 """Returns True if the path [and name] exists, else returns False.
146 146
147 147 API-style wrapper for os.path.exists
148 148
149 149 Parameters
150 150 ----------
151 151 name : string
152 152 The name of the file you are checking.
153 153 path : string
154 154 The relative path to the file's directory (with '/' as separator)
155 155
156 156 Returns
157 157 -------
158 158 exists : bool
159 159 Whether the target exists.
160 160 """
161 161 path = path.strip('/')
162 162 os_path = self._get_os_path(name, path=path)
163 163 return os.path.exists(os_path)
164 164
165 165 def _base_model(self, name, path=''):
166 166 """Build the common base of a contents model"""
167 167 os_path = self._get_os_path(name, path)
168 168 info = os.stat(os_path)
169 169 last_modified = tz.utcfromtimestamp(info.st_mtime)
170 170 created = tz.utcfromtimestamp(info.st_ctime)
171 171 # Create the base model.
172 172 model = {}
173 173 model['name'] = name
174 174 model['path'] = path
175 175 model['last_modified'] = last_modified
176 176 model['created'] = created
177 177 model['content'] = None
178 178 model['format'] = None
179 179 model['message'] = None
180 180 return model
181 181
182 182 def _dir_model(self, name, path='', content=True):
183 183 """Build a model for a directory
184 184
185 185 if content is requested, will include a listing of the directory
186 186 """
187 187 os_path = self._get_os_path(name, path)
188 188
189 189 four_o_four = u'directory does not exist: %r' % os_path
190 190
191 191 if not os.path.isdir(os_path):
192 192 raise web.HTTPError(404, four_o_four)
193 193 elif is_hidden(os_path, self.root_dir):
194 194 self.log.info("Refusing to serve hidden directory %r, via 404 Error",
195 195 os_path
196 196 )
197 197 raise web.HTTPError(404, four_o_four)
198 198
199 199 if name is None:
200 200 if '/' in path:
201 201 path, name = path.rsplit('/', 1)
202 202 else:
203 203 name = ''
204 204 model = self._base_model(name, path)
205 205 model['type'] = 'directory'
206 206 dir_path = u'{}/{}'.format(path, name)
207 207 if content:
208 208 model['content'] = contents = []
209 209 for os_path in glob.glob(self._get_os_path('*', dir_path)):
210 210 name = os.path.basename(os_path)
211 211 # skip over broken symlinks in listing
212 212 if not os.path.exists(os_path):
213 213 self.log.warn("%s doesn't exist", os_path)
214 214 continue
215 215 if self.should_list(name) and not is_hidden(os_path, self.root_dir):
216 216 contents.append(self.get_model(name=name, path=dir_path, content=False))
217 217
218 218 model['format'] = 'json'
219 219
220 220 return model
221 221
222 222 def _file_model(self, name, path='', content=True):
223 223 """Build a model for a file
224 224
225 225 if content is requested, include the file contents.
226 226 UTF-8 text files will be unicode, binary files will be base64-encoded.
227 227 """
228 228 model = self._base_model(name, path)
229 229 model['type'] = 'file'
230 230 if content:
231 231 os_path = self._get_os_path(name, path)
232 232 with io.open(os_path, 'rb') as f:
233 233 bcontent = f.read()
234 234 try:
235 235 model['content'] = bcontent.decode('utf8')
236 236 except UnicodeError as e:
237 237 model['content'] = base64.encodestring(bcontent).decode('ascii')
238 238 model['format'] = 'base64'
239 239 else:
240 240 model['format'] = 'text'
241 241 return model
242 242
243 243
244 244 def _notebook_model(self, name, path='', content=True):
245 245 """Build a notebook model
246 246
247 247 if content is requested, the notebook content will be populated
248 248 as a JSON structure (not double-serialized)
249 249 """
250 250 model = self._base_model(name, path)
251 251 model['type'] = 'notebook'
252 252 if content:
253 253 os_path = self._get_os_path(name, path)
254 254 with io.open(os_path, 'r', encoding='utf-8') as f:
255 255 try:
256 nb = current.read(f, u'json')
256 nb = nbformat.read(f, as_version=4)
257 257 except Exception as e:
258 raise web.HTTPError(400, u"Unreadable Notebook: %s %s" % (os_path, e))
258 raise web.HTTPError(400, u"Unreadable Notebook: %s %r" % (os_path, e))
259 259 self.mark_trusted_cells(nb, name, path)
260 260 model['content'] = nb
261 261 model['format'] = 'json'
262 262 self.validate_notebook_model(model)
263 263 return model
264 264
265 265 def get_model(self, name, path='', content=True):
266 266 """ Takes a path and name for an entity and returns its model
267 267
268 268 Parameters
269 269 ----------
270 270 name : str
271 271 the name of the target
272 272 path : str
273 273 the API path that describes the relative path for the target
274 274
275 275 Returns
276 276 -------
277 277 model : dict
278 278 the contents model. If content=True, returns the contents
279 279 of the file or directory as well.
280 280 """
281 281 path = path.strip('/')
282 282
283 283 if not self.exists(name=name, path=path):
284 284 raise web.HTTPError(404, u'No such file or directory: %s/%s' % (path, name))
285 285
286 286 os_path = self._get_os_path(name, path)
287 287 if os.path.isdir(os_path):
288 288 model = self._dir_model(name, path, content)
289 289 elif name.endswith('.ipynb'):
290 290 model = self._notebook_model(name, path, content)
291 291 else:
292 292 model = self._file_model(name, path, content)
293 293 return model
294 294
295 295 def _save_notebook(self, os_path, model, name='', path=''):
296 296 """save a notebook file"""
297 297 # Save the notebook file
298 nb = current.to_notebook_json(model['content'])
298 nb = nbformat.from_dict(model['content'])
299 299
300 300 self.check_and_sign(nb, name, path)
301 301
302 302 if 'name' in nb['metadata']:
303 303 nb['metadata']['name'] = u''
304 304
305 305 with atomic_writing(os_path, encoding='utf-8') as f:
306 current.write(nb, f, version=nb.nbformat)
306 nbformat.write(nb, f, version=nbformat.NO_CONVERT)
307 307
308 308 def _save_file(self, os_path, model, name='', path=''):
309 309 """save a non-notebook file"""
310 310 fmt = model.get('format', None)
311 311 if fmt not in {'text', 'base64'}:
312 312 raise web.HTTPError(400, "Must specify format of file contents as 'text' or 'base64'")
313 313 try:
314 314 content = model['content']
315 315 if fmt == 'text':
316 316 bcontent = content.encode('utf8')
317 317 else:
318 318 b64_bytes = content.encode('ascii')
319 319 bcontent = base64.decodestring(b64_bytes)
320 320 except Exception as e:
321 321 raise web.HTTPError(400, u'Encoding error saving %s: %s' % (os_path, e))
322 322 with atomic_writing(os_path, text=False) as f:
323 323 f.write(bcontent)
324 324
325 325 def _save_directory(self, os_path, model, name='', path=''):
326 326 """create a directory"""
327 327 if is_hidden(os_path, self.root_dir):
328 328 raise web.HTTPError(400, u'Cannot create hidden directory %r' % os_path)
329 329 if not os.path.exists(os_path):
330 330 os.mkdir(os_path)
331 331 elif not os.path.isdir(os_path):
332 332 raise web.HTTPError(400, u'Not a directory: %s' % (os_path))
333 333 else:
334 334 self.log.debug("Directory %r already exists", os_path)
335 335
336 336 def save(self, model, name='', path=''):
337 337 """Save the file model and return the model with no content."""
338 338 path = path.strip('/')
339 339
340 340 if 'type' not in model:
341 341 raise web.HTTPError(400, u'No file type provided')
342 342 if 'content' not in model and model['type'] != 'directory':
343 343 raise web.HTTPError(400, u'No file content provided')
344 344
345 345 # One checkpoint should always exist
346 346 if self.file_exists(name, path) and not self.list_checkpoints(name, path):
347 347 self.create_checkpoint(name, path)
348 348
349 349 new_path = model.get('path', path).strip('/')
350 350 new_name = model.get('name', name)
351 351
352 352 if path != new_path or name != new_name:
353 353 self.rename(name, path, new_name, new_path)
354 354
355 355 os_path = self._get_os_path(new_name, new_path)
356 356 self.log.debug("Saving %s", os_path)
357 357 try:
358 358 if model['type'] == 'notebook':
359 359 self._save_notebook(os_path, model, new_name, new_path)
360 360 elif model['type'] == 'file':
361 361 self._save_file(os_path, model, new_name, new_path)
362 362 elif model['type'] == 'directory':
363 363 self._save_directory(os_path, model, new_name, new_path)
364 364 else:
365 365 raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
366 366 except web.HTTPError:
367 367 raise
368 368 except Exception as e:
369 369 raise web.HTTPError(400, u'Unexpected error while saving file: %s %s' % (os_path, e))
370 370
371 371 validation_message = None
372 372 if model['type'] == 'notebook':
373 373 self.validate_notebook_model(model)
374 374 validation_message = model.get('message', None)
375 375
376 376 model = self.get_model(new_name, new_path, content=False)
377 377 if validation_message:
378 378 model['message'] = validation_message
379 379 return model
380 380
381 381 def update(self, model, name, path=''):
382 382 """Update the file's path and/or name
383 383
384 384 For use in PATCH requests, to enable renaming a file without
385 385 re-uploading its contents. Only used for renaming at the moment.
386 386 """
387 387 path = path.strip('/')
388 388 new_name = model.get('name', name)
389 389 new_path = model.get('path', path).strip('/')
390 390 if path != new_path or name != new_name:
391 391 self.rename(name, path, new_name, new_path)
392 392 model = self.get_model(new_name, new_path, content=False)
393 393 return model
394 394
395 395 def delete(self, name, path=''):
396 396 """Delete file by name and path."""
397 397 path = path.strip('/')
398 398 os_path = self._get_os_path(name, path)
399 399 rm = os.unlink
400 400 if os.path.isdir(os_path):
401 401 listing = os.listdir(os_path)
402 402 # don't delete non-empty directories (checkpoints dir doesn't count)
403 403 if listing and listing != [self.checkpoint_dir]:
404 404 raise web.HTTPError(400, u'Directory %s not empty' % os_path)
405 405 elif not os.path.isfile(os_path):
406 406 raise web.HTTPError(404, u'File does not exist: %s' % os_path)
407 407
408 408 # clear checkpoints
409 409 for checkpoint in self.list_checkpoints(name, path):
410 410 checkpoint_id = checkpoint['id']
411 411 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
412 412 if os.path.isfile(cp_path):
413 413 self.log.debug("Unlinking checkpoint %s", cp_path)
414 414 os.unlink(cp_path)
415 415
416 416 if os.path.isdir(os_path):
417 417 self.log.debug("Removing directory %s", os_path)
418 418 shutil.rmtree(os_path)
419 419 else:
420 420 self.log.debug("Unlinking file %s", os_path)
421 421 rm(os_path)
422 422
423 423 def rename(self, old_name, old_path, new_name, new_path):
424 424 """Rename a file."""
425 425 old_path = old_path.strip('/')
426 426 new_path = new_path.strip('/')
427 427 if new_name == old_name and new_path == old_path:
428 428 return
429 429
430 430 new_os_path = self._get_os_path(new_name, new_path)
431 431 old_os_path = self._get_os_path(old_name, old_path)
432 432
433 433 # Should we proceed with the move?
434 434 if os.path.isfile(new_os_path):
435 435 raise web.HTTPError(409, u'File with name already exists: %s' % new_os_path)
436 436
437 437 # Move the file
438 438 try:
439 439 shutil.move(old_os_path, new_os_path)
440 440 except Exception as e:
441 441 raise web.HTTPError(500, u'Unknown error renaming file: %s %s' % (old_os_path, e))
442 442
443 443 # Move the checkpoints
444 444 old_checkpoints = self.list_checkpoints(old_name, old_path)
445 445 for cp in old_checkpoints:
446 446 checkpoint_id = cp['id']
447 447 old_cp_path = self.get_checkpoint_path(checkpoint_id, old_name, old_path)
448 448 new_cp_path = self.get_checkpoint_path(checkpoint_id, new_name, new_path)
449 449 if os.path.isfile(old_cp_path):
450 450 self.log.debug("Renaming checkpoint %s -> %s", old_cp_path, new_cp_path)
451 451 shutil.move(old_cp_path, new_cp_path)
452 452
453 453 # Checkpoint-related utilities
454 454
455 455 def get_checkpoint_path(self, checkpoint_id, name, path=''):
456 456 """find the path to a checkpoint"""
457 457 path = path.strip('/')
458 458 basename, ext = os.path.splitext(name)
459 459 filename = u"{name}-{checkpoint_id}{ext}".format(
460 460 name=basename,
461 461 checkpoint_id=checkpoint_id,
462 462 ext=ext,
463 463 )
464 464 os_path = self._get_os_path(path=path)
465 465 cp_dir = os.path.join(os_path, self.checkpoint_dir)
466 466 ensure_dir_exists(cp_dir)
467 467 cp_path = os.path.join(cp_dir, filename)
468 468 return cp_path
469 469
470 470 def get_checkpoint_model(self, checkpoint_id, name, path=''):
471 471 """construct the info dict for a given checkpoint"""
472 472 path = path.strip('/')
473 473 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
474 474 stats = os.stat(cp_path)
475 475 last_modified = tz.utcfromtimestamp(stats.st_mtime)
476 476 info = dict(
477 477 id = checkpoint_id,
478 478 last_modified = last_modified,
479 479 )
480 480 return info
481 481
482 482 # public checkpoint API
483 483
484 484 def create_checkpoint(self, name, path=''):
485 485 """Create a checkpoint from the current state of a file"""
486 486 path = path.strip('/')
487 487 src_path = self._get_os_path(name, path)
488 488 # only the one checkpoint ID:
489 489 checkpoint_id = u"checkpoint"
490 490 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
491 491 self.log.debug("creating checkpoint for %s", name)
492 492 self._copy(src_path, cp_path)
493 493
494 494 # return the checkpoint info
495 495 return self.get_checkpoint_model(checkpoint_id, name, path)
496 496
497 497 def list_checkpoints(self, name, path=''):
498 498 """list the checkpoints for a given file
499 499
500 500 This contents manager currently only supports one checkpoint per file.
501 501 """
502 502 path = path.strip('/')
503 503 checkpoint_id = "checkpoint"
504 504 os_path = self.get_checkpoint_path(checkpoint_id, name, path)
505 505 if not os.path.exists(os_path):
506 506 return []
507 507 else:
508 508 return [self.get_checkpoint_model(checkpoint_id, name, path)]
509 509
510 510
511 511 def restore_checkpoint(self, checkpoint_id, name, path=''):
512 512 """restore a file to a checkpointed state"""
513 513 path = path.strip('/')
514 514 self.log.info("restoring %s from checkpoint %s", name, checkpoint_id)
515 515 nb_path = self._get_os_path(name, path)
516 516 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
517 517 if not os.path.isfile(cp_path):
518 518 self.log.debug("checkpoint file does not exist: %s", cp_path)
519 519 raise web.HTTPError(404,
520 520 u'checkpoint does not exist: %s-%s' % (name, checkpoint_id)
521 521 )
522 522 # ensure notebook is readable (never restore from an unreadable notebook)
523 523 if cp_path.endswith('.ipynb'):
524 524 with io.open(cp_path, 'r', encoding='utf-8') as f:
525 current.read(f, u'json')
525 nbformat.read(f, as_version=4)
526 526 self._copy(cp_path, nb_path)
527 527 self.log.debug("copying %s -> %s", cp_path, nb_path)
528 528
529 529 def delete_checkpoint(self, checkpoint_id, name, path=''):
530 530 """delete a file's checkpoint"""
531 531 path = path.strip('/')
532 532 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
533 533 if not os.path.isfile(cp_path):
534 534 raise web.HTTPError(404,
535 535 u'Checkpoint does not exist: %s%s-%s' % (path, name, checkpoint_id)
536 536 )
537 537 self.log.debug("unlinking %s", cp_path)
538 538 os.unlink(cp_path)
539 539
540 540 def info_string(self):
541 541 return "Serving notebooks from local directory: %s" % self.root_dir
542 542
543 543 def get_kernel_path(self, name, path='', model=None):
544 544 """Return the initial working dir a kernel associated with a given notebook"""
545 545 return os.path.join(self.root_dir, path)
@@ -1,346 +1,344 b''
1 1 """A base class for contents managers."""
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 6 from fnmatch import fnmatch
7 7 import itertools
8 8 import json
9 9 import os
10 10
11 11 from tornado.web import HTTPError
12 12
13 13 from IPython.config.configurable import LoggingConfigurable
14 from IPython.nbformat import current, sign
14 from IPython.nbformat import sign, validate, ValidationError
15 from IPython.nbformat.v4 import new_notebook
15 16 from IPython.utils.traitlets import Instance, Unicode, List
16 17
17 18
18 19 class ContentsManager(LoggingConfigurable):
19 20 """Base class for serving files and directories.
20 21
21 22 This serves any text or binary file,
22 23 as well as directories,
23 24 with special handling for JSON notebook documents.
24 25
25 26 Most APIs take a path argument,
26 27 which is always an API-style unicode path,
27 28 and always refers to a directory.
28 29
29 30 - unicode, not url-escaped
30 31 - '/'-separated
31 32 - leading and trailing '/' will be stripped
32 33 - if unspecified, path defaults to '',
33 34 indicating the root path.
34 35
35 36 name is also unicode, and refers to a specfic target:
36 37
37 38 - unicode, not url-escaped
38 39 - must not contain '/'
39 40 - It refers to an individual filename
40 41 - It may refer to a directory name,
41 42 in the case of listing or creating directories.
42 43
43 44 """
44 45
45 46 notary = Instance(sign.NotebookNotary)
46 47 def _notary_default(self):
47 48 return sign.NotebookNotary(parent=self)
48 49
49 50 hide_globs = List(Unicode, [
50 51 u'__pycache__', '*.pyc', '*.pyo',
51 52 '.DS_Store', '*.so', '*.dylib', '*~',
52 53 ], config=True, help="""
53 54 Glob patterns to hide in file and directory listings.
54 55 """)
55 56
56 57 untitled_notebook = Unicode("Untitled", config=True,
57 58 help="The base name used when creating untitled notebooks."
58 59 )
59 60
60 61 untitled_file = Unicode("untitled", config=True,
61 62 help="The base name used when creating untitled files."
62 63 )
63 64
64 65 untitled_directory = Unicode("Untitled Folder", config=True,
65 66 help="The base name used when creating untitled directories."
66 67 )
67 68
68 69 # ContentsManager API part 1: methods that must be
69 70 # implemented in subclasses.
70 71
71 72 def path_exists(self, path):
72 73 """Does the API-style path (directory) actually exist?
73 74
74 75 Like os.path.isdir
75 76
76 77 Override this method in subclasses.
77 78
78 79 Parameters
79 80 ----------
80 81 path : string
81 82 The path to check
82 83
83 84 Returns
84 85 -------
85 86 exists : bool
86 87 Whether the path does indeed exist.
87 88 """
88 89 raise NotImplementedError
89 90
90 91 def is_hidden(self, path):
91 92 """Does the API style path correspond to a hidden directory or file?
92 93
93 94 Parameters
94 95 ----------
95 96 path : string
96 97 The path to check. This is an API path (`/` separated,
97 98 relative to root dir).
98 99
99 100 Returns
100 101 -------
101 102 hidden : bool
102 103 Whether the path is hidden.
103 104
104 105 """
105 106 raise NotImplementedError
106 107
107 108 def file_exists(self, name, path=''):
108 109 """Does a file exist at the given name and path?
109 110
110 111 Like os.path.isfile
111 112
112 113 Override this method in subclasses.
113 114
114 115 Parameters
115 116 ----------
116 117 name : string
117 118 The name of the file you are checking.
118 119 path : string
119 120 The relative path to the file's directory (with '/' as separator)
120 121
121 122 Returns
122 123 -------
123 124 exists : bool
124 125 Whether the file exists.
125 126 """
126 127 raise NotImplementedError('must be implemented in a subclass')
127 128
128 129 def exists(self, name, path=''):
129 130 """Does a file or directory exist at the given name and path?
130 131
131 132 Like os.path.exists
132 133
133 134 Parameters
134 135 ----------
135 136 name : string
136 137 The name of the file you are checking.
137 138 path : string
138 139 The relative path to the file's directory (with '/' as separator)
139 140
140 141 Returns
141 142 -------
142 143 exists : bool
143 144 Whether the target exists.
144 145 """
145 146 return self.file_exists(name, path) or self.path_exists("%s/%s" % (path, name))
146 147
147 148 def get_model(self, name, path='', content=True):
148 149 """Get the model of a file or directory with or without content."""
149 150 raise NotImplementedError('must be implemented in a subclass')
150 151
151 152 def save(self, model, name, path=''):
152 153 """Save the file or directory and return the model with no content."""
153 154 raise NotImplementedError('must be implemented in a subclass')
154 155
155 156 def update(self, model, name, path=''):
156 157 """Update the file or directory and return the model with no content.
157 158
158 159 For use in PATCH requests, to enable renaming a file without
159 160 re-uploading its contents. Only used for renaming at the moment.
160 161 """
161 162 raise NotImplementedError('must be implemented in a subclass')
162 163
163 164 def delete(self, name, path=''):
164 165 """Delete file or directory by name and path."""
165 166 raise NotImplementedError('must be implemented in a subclass')
166 167
167 168 def create_checkpoint(self, name, path=''):
168 169 """Create a checkpoint of the current state of a file
169 170
170 171 Returns a checkpoint_id for the new checkpoint.
171 172 """
172 173 raise NotImplementedError("must be implemented in a subclass")
173 174
174 175 def list_checkpoints(self, name, path=''):
175 176 """Return a list of checkpoints for a given file"""
176 177 return []
177 178
178 179 def restore_checkpoint(self, checkpoint_id, name, path=''):
179 180 """Restore a file from one of its checkpoints"""
180 181 raise NotImplementedError("must be implemented in a subclass")
181 182
182 183 def delete_checkpoint(self, checkpoint_id, name, path=''):
183 184 """delete a checkpoint for a file"""
184 185 raise NotImplementedError("must be implemented in a subclass")
185 186
186 187 # ContentsManager API part 2: methods that have useable default
187 188 # implementations, but can be overridden in subclasses.
188 189
189 190 def info_string(self):
190 191 return "Serving contents"
191 192
192 193 def get_kernel_path(self, name, path='', model=None):
193 194 """ Return the path to start kernel in """
194 195 return path
195 196
196 197 def increment_filename(self, filename, path=''):
197 198 """Increment a filename until it is unique.
198 199
199 200 Parameters
200 201 ----------
201 202 filename : unicode
202 203 The name of a file, including extension
203 204 path : unicode
204 205 The API path of the target's directory
205 206
206 207 Returns
207 208 -------
208 209 name : unicode
209 210 A filename that is unique, based on the input filename.
210 211 """
211 212 path = path.strip('/')
212 213 basename, ext = os.path.splitext(filename)
213 214 for i in itertools.count():
214 215 name = u'{basename}{i}{ext}'.format(basename=basename, i=i,
215 216 ext=ext)
216 217 if not self.file_exists(name, path):
217 218 break
218 219 return name
219 220
220 221 def validate_notebook_model(self, model):
221 222 """Add failed-validation message to model"""
222 223 try:
223 current.validate(model['content'])
224 except current.ValidationError as e:
224 validate(model['content'])
225 except ValidationError as e:
225 226 model['message'] = 'Notebook Validation failed: {}:\n{}'.format(
226 227 e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'),
227 228 )
228 229 return model
229 230
230 231 def create_file(self, model=None, path='', ext='.ipynb'):
231 232 """Create a new file or directory and return its model with no content."""
232 233 path = path.strip('/')
233 234 if model is None:
234 235 model = {}
235 236 if 'content' not in model and model.get('type', None) != 'directory':
236 237 if ext == '.ipynb':
237 metadata = current.new_metadata(name=u'')
238 model['content'] = current.new_notebook(metadata=metadata)
238 model['content'] = new_notebook()
239 239 model['type'] = 'notebook'
240 240 model['format'] = 'json'
241 241 else:
242 242 model['content'] = ''
243 243 model['type'] = 'file'
244 244 model['format'] = 'text'
245 245 if 'name' not in model:
246 246 if model['type'] == 'directory':
247 247 untitled = self.untitled_directory
248 248 elif model['type'] == 'notebook':
249 249 untitled = self.untitled_notebook
250 250 elif model['type'] == 'file':
251 251 untitled = self.untitled_file
252 252 else:
253 253 raise HTTPError(400, "Unexpected model type: %r" % model['type'])
254 254 model['name'] = self.increment_filename(untitled + ext, path)
255 255
256 256 model['path'] = path
257 257 model = self.save(model, model['name'], model['path'])
258 258 return model
259 259
260 260 def copy(self, from_name, to_name=None, path=''):
261 261 """Copy an existing file and return its new model.
262 262
263 263 If to_name not specified, increment `from_name-Copy#.ext`.
264 264
265 265 copy_from can be a full path to a file,
266 266 or just a base name. If a base name, `path` is used.
267 267 """
268 268 path = path.strip('/')
269 269 if '/' in from_name:
270 270 from_path, from_name = from_name.rsplit('/', 1)
271 271 else:
272 272 from_path = path
273 273 model = self.get_model(from_name, from_path)
274 274 if model['type'] == 'directory':
275 275 raise HTTPError(400, "Can't copy directories")
276 276 if not to_name:
277 277 base, ext = os.path.splitext(from_name)
278 278 copy_name = u'{0}-Copy{1}'.format(base, ext)
279 279 to_name = self.increment_filename(copy_name, path)
280 280 model['name'] = to_name
281 281 model['path'] = path
282 282 model = self.save(model, to_name, path)
283 283 return model
284 284
285 285 def log_info(self):
286 286 self.log.info(self.info_string())
287 287
288 288 def trust_notebook(self, name, path=''):
289 289 """Explicitly trust a notebook
290 290
291 291 Parameters
292 292 ----------
293 293 name : string
294 294 The filename of the notebook
295 295 path : string
296 296 The notebook's directory
297 297 """
298 298 model = self.get_model(name, path)
299 299 nb = model['content']
300 300 self.log.warn("Trusting notebook %s/%s", path, name)
301 301 self.notary.mark_cells(nb, True)
302 302 self.save(model, name, path)
303 303
304 304 def check_and_sign(self, nb, name='', path=''):
305 305 """Check for trusted cells, and sign the notebook.
306 306
307 307 Called as a part of saving notebooks.
308 308
309 309 Parameters
310 310 ----------
311 311 nb : dict
312 The notebook object (in nbformat.current format)
312 The notebook dict
313 313 name : string
314 314 The filename of the notebook (for logging)
315 315 path : string
316 316 The notebook's directory (for logging)
317 317 """
318 if nb['nbformat'] != current.nbformat:
319 return
320 318 if self.notary.check_cells(nb):
321 319 self.notary.sign(nb)
322 320 else:
323 321 self.log.warn("Saving untrusted notebook %s/%s", path, name)
324 322
325 323 def mark_trusted_cells(self, nb, name='', path=''):
326 324 """Mark cells as trusted if the notebook signature matches.
327 325
328 326 Called as a part of loading notebooks.
329 327
330 328 Parameters
331 329 ----------
332 330 nb : dict
333 The notebook object (in nbformat.current format)
331 The notebook object (in current nbformat)
334 332 name : string
335 333 The filename of the notebook (for logging)
336 334 path : string
337 335 The notebook's directory (for logging)
338 336 """
339 337 trusted = self.notary.check_signature(nb)
340 338 if not trusted:
341 339 self.log.warn("Notebook %s/%s is not trusted", path, name)
342 340 self.notary.mark_cells(nb, trusted)
343 341
344 342 def should_list(self, name):
345 343 """Should this file/directory name be displayed in a listing?"""
346 344 return not any(fnmatch(name, glob) for glob in self.hide_globs)
@@ -1,485 +1,481 b''
1 1 # coding: utf-8
2 2 """Test the contents webservice API."""
3 3
4 4 import base64
5 5 import io
6 6 import json
7 7 import os
8 8 import shutil
9 9 from unicodedata import normalize
10 10
11 11 pjoin = os.path.join
12 12
13 13 import requests
14 14
15 15 from IPython.html.utils import url_path_join, url_escape
16 16 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
17 from IPython.nbformat import current
18 from IPython.nbformat.current import (new_notebook, write, read, new_worksheet,
19 new_heading_cell, to_notebook_json)
17 from IPython.nbformat import read, write, from_dict
18 from IPython.nbformat.v4 import (
19 new_notebook, new_markdown_cell,
20 )
20 21 from IPython.nbformat import v2
21 22 from IPython.utils import py3compat
22 23 from IPython.utils.data import uniq_stable
23 24
24 25
25 26 def notebooks_only(dir_model):
26 27 return [nb for nb in dir_model['content'] if nb['type']=='notebook']
27 28
28 29 def dirs_only(dir_model):
29 30 return [x for x in dir_model['content'] if x['type']=='directory']
30 31
31 32
32 33 class API(object):
33 34 """Wrapper for contents API calls."""
34 35 def __init__(self, base_url):
35 36 self.base_url = base_url
36 37
37 38 def _req(self, verb, path, body=None):
38 39 response = requests.request(verb,
39 40 url_path_join(self.base_url, 'api/contents', path),
40 41 data=body,
41 42 )
42 43 response.raise_for_status()
43 44 return response
44 45
45 46 def list(self, path='/'):
46 47 return self._req('GET', path)
47 48
48 49 def read(self, name, path='/'):
49 50 return self._req('GET', url_path_join(path, name))
50 51
51 52 def create_untitled(self, path='/', ext=None):
52 53 body = None
53 54 if ext:
54 55 body = json.dumps({'ext': ext})
55 56 return self._req('POST', path, body)
56 57
57 58 def upload_untitled(self, body, path='/'):
58 59 return self._req('POST', path, body)
59 60
60 61 def copy_untitled(self, copy_from, path='/'):
61 62 body = json.dumps({'copy_from':copy_from})
62 63 return self._req('POST', path, body)
63 64
64 65 def create(self, name, path='/'):
65 66 return self._req('PUT', url_path_join(path, name))
66 67
67 68 def upload(self, name, body, path='/'):
68 69 return self._req('PUT', url_path_join(path, name), body)
69 70
70 71 def mkdir(self, name, path='/'):
71 72 return self._req('PUT', url_path_join(path, name), json.dumps({'type': 'directory'}))
72 73
73 74 def copy(self, copy_from, copy_to, path='/'):
74 75 body = json.dumps({'copy_from':copy_from})
75 76 return self._req('PUT', url_path_join(path, copy_to), body)
76 77
77 78 def save(self, name, body, path='/'):
78 79 return self._req('PUT', url_path_join(path, name), body)
79 80
80 81 def delete(self, name, path='/'):
81 82 return self._req('DELETE', url_path_join(path, name))
82 83
83 84 def rename(self, name, path, new_name):
84 85 body = json.dumps({'name': new_name})
85 86 return self._req('PATCH', url_path_join(path, name), body)
86 87
87 88 def get_checkpoints(self, name, path):
88 89 return self._req('GET', url_path_join(path, name, 'checkpoints'))
89 90
90 91 def new_checkpoint(self, name, path):
91 92 return self._req('POST', url_path_join(path, name, 'checkpoints'))
92 93
93 94 def restore_checkpoint(self, name, path, checkpoint_id):
94 95 return self._req('POST', url_path_join(path, name, 'checkpoints', checkpoint_id))
95 96
96 97 def delete_checkpoint(self, name, path, checkpoint_id):
97 98 return self._req('DELETE', url_path_join(path, name, 'checkpoints', checkpoint_id))
98 99
99 100 class APITest(NotebookTestBase):
100 101 """Test the kernels web service API"""
101 102 dirs_nbs = [('', 'inroot'),
102 103 ('Directory with spaces in', 'inspace'),
103 104 (u'unicodé', 'innonascii'),
104 105 ('foo', 'a'),
105 106 ('foo', 'b'),
106 107 ('foo', 'name with spaces'),
107 108 ('foo', u'unicodé'),
108 109 ('foo/bar', 'baz'),
109 110 ('ordering', 'A'),
110 111 ('ordering', 'b'),
111 112 ('ordering', 'C'),
112 113 (u'å b', u'ç d'),
113 114 ]
114 115 hidden_dirs = ['.hidden', '__pycache__']
115 116
116 117 dirs = uniq_stable([py3compat.cast_unicode(d) for (d,n) in dirs_nbs])
117 118 del dirs[0] # remove ''
118 119 top_level_dirs = {normalize('NFC', d.split('/')[0]) for d in dirs}
119 120
120 121 @staticmethod
121 122 def _blob_for_name(name):
122 123 return name.encode('utf-8') + b'\xFF'
123 124
124 125 @staticmethod
125 126 def _txt_for_name(name):
126 127 return u'%s text file' % name
127 128
128 129 def setUp(self):
129 130 nbdir = self.notebook_dir.name
130 131 self.blob = os.urandom(100)
131 132 self.b64_blob = base64.encodestring(self.blob).decode('ascii')
132 133
133 134
134 135
135 136 for d in (self.dirs + self.hidden_dirs):
136 137 d.replace('/', os.sep)
137 138 if not os.path.isdir(pjoin(nbdir, d)):
138 139 os.mkdir(pjoin(nbdir, d))
139 140
140 141 for d, name in self.dirs_nbs:
141 142 d = d.replace('/', os.sep)
142 143 # create a notebook
143 144 with io.open(pjoin(nbdir, d, '%s.ipynb' % name), 'w',
144 145 encoding='utf-8') as f:
145 nb = new_notebook(name=name)
146 write(nb, f, format='ipynb')
146 nb = new_notebook()
147 write(nb, f, version=4)
147 148
148 149 # create a text file
149 150 with io.open(pjoin(nbdir, d, '%s.txt' % name), 'w',
150 151 encoding='utf-8') as f:
151 152 f.write(self._txt_for_name(name))
152 153
153 154 # create a binary file
154 155 with io.open(pjoin(nbdir, d, '%s.blob' % name), 'wb') as f:
155 156 f.write(self._blob_for_name(name))
156 157
157 158 self.api = API(self.base_url())
158 159
159 160 def tearDown(self):
160 161 nbdir = self.notebook_dir.name
161 162
162 163 for dname in (list(self.top_level_dirs) + self.hidden_dirs):
163 164 shutil.rmtree(pjoin(nbdir, dname), ignore_errors=True)
164 165
165 166 if os.path.isfile(pjoin(nbdir, 'inroot.ipynb')):
166 167 os.unlink(pjoin(nbdir, 'inroot.ipynb'))
167 168
168 169 def test_list_notebooks(self):
169 170 nbs = notebooks_only(self.api.list().json())
170 171 self.assertEqual(len(nbs), 1)
171 172 self.assertEqual(nbs[0]['name'], 'inroot.ipynb')
172 173
173 174 nbs = notebooks_only(self.api.list('/Directory with spaces in/').json())
174 175 self.assertEqual(len(nbs), 1)
175 176 self.assertEqual(nbs[0]['name'], 'inspace.ipynb')
176 177
177 178 nbs = notebooks_only(self.api.list(u'/unicodé/').json())
178 179 self.assertEqual(len(nbs), 1)
179 180 self.assertEqual(nbs[0]['name'], 'innonascii.ipynb')
180 181 self.assertEqual(nbs[0]['path'], u'unicodé')
181 182
182 183 nbs = notebooks_only(self.api.list('/foo/bar/').json())
183 184 self.assertEqual(len(nbs), 1)
184 185 self.assertEqual(nbs[0]['name'], 'baz.ipynb')
185 186 self.assertEqual(nbs[0]['path'], 'foo/bar')
186 187
187 188 nbs = notebooks_only(self.api.list('foo').json())
188 189 self.assertEqual(len(nbs), 4)
189 190 nbnames = { normalize('NFC', n['name']) for n in nbs }
190 191 expected = [ u'a.ipynb', u'b.ipynb', u'name with spaces.ipynb', u'unicodé.ipynb']
191 192 expected = { normalize('NFC', name) for name in expected }
192 193 self.assertEqual(nbnames, expected)
193 194
194 195 nbs = notebooks_only(self.api.list('ordering').json())
195 196 nbnames = [n['name'] for n in nbs]
196 197 expected = ['A.ipynb', 'b.ipynb', 'C.ipynb']
197 198 self.assertEqual(nbnames, expected)
198 199
199 200 def test_list_dirs(self):
200 201 dirs = dirs_only(self.api.list().json())
201 202 dir_names = {normalize('NFC', d['name']) for d in dirs}
202 203 self.assertEqual(dir_names, self.top_level_dirs) # Excluding hidden dirs
203 204
204 205 def test_list_nonexistant_dir(self):
205 206 with assert_http_error(404):
206 207 self.api.list('nonexistant')
207 208
208 209 def test_get_nb_contents(self):
209 210 for d, name in self.dirs_nbs:
210 211 nb = self.api.read('%s.ipynb' % name, d+'/').json()
211 212 self.assertEqual(nb['name'], u'%s.ipynb' % name)
212 213 self.assertEqual(nb['type'], 'notebook')
213 214 self.assertIn('content', nb)
214 215 self.assertEqual(nb['format'], 'json')
215 216 self.assertIn('content', nb)
216 217 self.assertIn('metadata', nb['content'])
217 218 self.assertIsInstance(nb['content']['metadata'], dict)
218 219
219 220 def test_get_contents_no_such_file(self):
220 221 # Name that doesn't exist - should be a 404
221 222 with assert_http_error(404):
222 223 self.api.read('q.ipynb', 'foo')
223 224
224 225 def test_get_text_file_contents(self):
225 226 for d, name in self.dirs_nbs:
226 227 model = self.api.read(u'%s.txt' % name, d+'/').json()
227 228 self.assertEqual(model['name'], u'%s.txt' % name)
228 229 self.assertIn('content', model)
229 230 self.assertEqual(model['format'], 'text')
230 231 self.assertEqual(model['type'], 'file')
231 232 self.assertEqual(model['content'], self._txt_for_name(name))
232 233
233 234 # Name that doesn't exist - should be a 404
234 235 with assert_http_error(404):
235 236 self.api.read('q.txt', 'foo')
236 237
237 238 def test_get_binary_file_contents(self):
238 239 for d, name in self.dirs_nbs:
239 240 model = self.api.read(u'%s.blob' % name, d+'/').json()
240 241 self.assertEqual(model['name'], u'%s.blob' % name)
241 242 self.assertIn('content', model)
242 243 self.assertEqual(model['format'], 'base64')
243 244 self.assertEqual(model['type'], 'file')
244 245 b64_data = base64.encodestring(self._blob_for_name(name)).decode('ascii')
245 246 self.assertEqual(model['content'], b64_data)
246 247
247 248 # Name that doesn't exist - should be a 404
248 249 with assert_http_error(404):
249 250 self.api.read('q.txt', 'foo')
250 251
251 252 def _check_created(self, resp, name, path, type='notebook'):
252 253 self.assertEqual(resp.status_code, 201)
253 254 location_header = py3compat.str_to_unicode(resp.headers['Location'])
254 255 self.assertEqual(location_header, url_escape(url_path_join(u'/api/contents', path, name)))
255 256 rjson = resp.json()
256 257 self.assertEqual(rjson['name'], name)
257 258 self.assertEqual(rjson['path'], path)
258 259 self.assertEqual(rjson['type'], type)
259 260 isright = os.path.isdir if type == 'directory' else os.path.isfile
260 261 assert isright(pjoin(
261 262 self.notebook_dir.name,
262 263 path.replace('/', os.sep),
263 264 name,
264 265 ))
265 266
266 267 def test_create_untitled(self):
267 268 resp = self.api.create_untitled(path=u'å b')
268 269 self._check_created(resp, 'Untitled0.ipynb', u'å b')
269 270
270 271 # Second time
271 272 resp = self.api.create_untitled(path=u'å b')
272 273 self._check_created(resp, 'Untitled1.ipynb', u'å b')
273 274
274 275 # And two directories down
275 276 resp = self.api.create_untitled(path='foo/bar')
276 277 self._check_created(resp, 'Untitled0.ipynb', 'foo/bar')
277 278
278 279 def test_create_untitled_txt(self):
279 280 resp = self.api.create_untitled(path='foo/bar', ext='.txt')
280 281 self._check_created(resp, 'untitled0.txt', 'foo/bar', type='file')
281 282
282 283 resp = self.api.read(path='foo/bar', name='untitled0.txt')
283 284 model = resp.json()
284 285 self.assertEqual(model['type'], 'file')
285 286 self.assertEqual(model['format'], 'text')
286 287 self.assertEqual(model['content'], '')
287 288
288 289 def test_upload_untitled(self):
289 nb = new_notebook(name='Upload test')
290 nb = new_notebook()
290 291 nbmodel = {'content': nb, 'type': 'notebook'}
291 292 resp = self.api.upload_untitled(path=u'å b',
292 293 body=json.dumps(nbmodel))
293 294 self._check_created(resp, 'Untitled0.ipynb', u'å b')
294 295
295 296 def test_upload(self):
296 nb = new_notebook(name=u'ignored')
297 nb = new_notebook()
297 298 nbmodel = {'content': nb, 'type': 'notebook'}
298 299 resp = self.api.upload(u'Upload tést.ipynb', path=u'å b',
299 300 body=json.dumps(nbmodel))
300 301 self._check_created(resp, u'Upload tést.ipynb', u'å b')
301 302
302 303 def test_mkdir(self):
303 304 resp = self.api.mkdir(u'New ∂ir', path=u'å b')
304 305 self._check_created(resp, u'New ∂ir', u'å b', type='directory')
305 306
306 307 def test_mkdir_hidden_400(self):
307 308 with assert_http_error(400):
308 309 resp = self.api.mkdir(u'.hidden', path=u'å b')
309 310
310 311 def test_upload_txt(self):
311 312 body = u'ünicode téxt'
312 313 model = {
313 314 'content' : body,
314 315 'format' : 'text',
315 316 'type' : 'file',
316 317 }
317 318 resp = self.api.upload(u'Upload tést.txt', path=u'å b',
318 319 body=json.dumps(model))
319 320
320 321 # check roundtrip
321 322 resp = self.api.read(path=u'å b', name=u'Upload tést.txt')
322 323 model = resp.json()
323 324 self.assertEqual(model['type'], 'file')
324 325 self.assertEqual(model['format'], 'text')
325 326 self.assertEqual(model['content'], body)
326 327
327 328 def test_upload_b64(self):
328 329 body = b'\xFFblob'
329 330 b64body = base64.encodestring(body).decode('ascii')
330 331 model = {
331 332 'content' : b64body,
332 333 'format' : 'base64',
333 334 'type' : 'file',
334 335 }
335 336 resp = self.api.upload(u'Upload tést.blob', path=u'å b',
336 337 body=json.dumps(model))
337 338
338 339 # check roundtrip
339 340 resp = self.api.read(path=u'å b', name=u'Upload tést.blob')
340 341 model = resp.json()
341 342 self.assertEqual(model['type'], 'file')
342 343 self.assertEqual(model['format'], 'base64')
343 344 decoded = base64.decodestring(model['content'].encode('ascii'))
344 345 self.assertEqual(decoded, body)
345 346
346 347 def test_upload_v2(self):
347 348 nb = v2.new_notebook()
348 349 ws = v2.new_worksheet()
349 350 nb.worksheets.append(ws)
350 351 ws.cells.append(v2.new_code_cell(input='print("hi")'))
351 352 nbmodel = {'content': nb, 'type': 'notebook'}
352 353 resp = self.api.upload(u'Upload tést.ipynb', path=u'å b',
353 354 body=json.dumps(nbmodel))
354 355 self._check_created(resp, u'Upload tést.ipynb', u'å b')
355 356 resp = self.api.read(u'Upload tést.ipynb', u'å b')
356 357 data = resp.json()
357 self.assertEqual(data['content']['nbformat'], current.nbformat)
358 self.assertEqual(data['content']['orig_nbformat'], 2)
358 self.assertEqual(data['content']['nbformat'], 4)
359 359
360 360 def test_copy_untitled(self):
361 361 resp = self.api.copy_untitled(u'ç d.ipynb', path=u'å b')
362 362 self._check_created(resp, u'ç d-Copy0.ipynb', u'å b')
363 363
364 364 def test_copy(self):
365 365 resp = self.api.copy(u'ç d.ipynb', u'cøpy.ipynb', path=u'å b')
366 366 self._check_created(resp, u'cøpy.ipynb', u'å b')
367 367
368 368 def test_copy_path(self):
369 369 resp = self.api.copy(u'foo/a.ipynb', u'cøpyfoo.ipynb', path=u'å b')
370 370 self._check_created(resp, u'cøpyfoo.ipynb', u'å b')
371 371
372 372 def test_copy_dir_400(self):
373 373 # can't copy directories
374 374 with assert_http_error(400):
375 375 resp = self.api.copy(u'å b', u'å c')
376 376
377 377 def test_delete(self):
378 378 for d, name in self.dirs_nbs:
379 379 resp = self.api.delete('%s.ipynb' % name, d)
380 380 self.assertEqual(resp.status_code, 204)
381 381
382 382 for d in self.dirs + ['/']:
383 383 nbs = notebooks_only(self.api.list(d).json())
384 384 self.assertEqual(len(nbs), 0)
385 385
386 386 def test_delete_dirs(self):
387 387 # depth-first delete everything, so we don't try to delete empty directories
388 388 for name in sorted(self.dirs + ['/'], key=len, reverse=True):
389 389 listing = self.api.list(name).json()['content']
390 390 for model in listing:
391 391 self.api.delete(model['name'], model['path'])
392 392 listing = self.api.list('/').json()['content']
393 393 self.assertEqual(listing, [])
394 394
395 395 def test_delete_non_empty_dir(self):
396 396 """delete non-empty dir raises 400"""
397 397 with assert_http_error(400):
398 398 self.api.delete(u'å b')
399 399
400 400 def test_rename(self):
401 401 resp = self.api.rename('a.ipynb', 'foo', 'z.ipynb')
402 402 self.assertEqual(resp.headers['Location'].split('/')[-1], 'z.ipynb')
403 403 self.assertEqual(resp.json()['name'], 'z.ipynb')
404 404 assert os.path.isfile(pjoin(self.notebook_dir.name, 'foo', 'z.ipynb'))
405 405
406 406 nbs = notebooks_only(self.api.list('foo').json())
407 407 nbnames = set(n['name'] for n in nbs)
408 408 self.assertIn('z.ipynb', nbnames)
409 409 self.assertNotIn('a.ipynb', nbnames)
410 410
411 411 def test_rename_existing(self):
412 412 with assert_http_error(409):
413 413 self.api.rename('a.ipynb', 'foo', 'b.ipynb')
414 414
415 415 def test_save(self):
416 416 resp = self.api.read('a.ipynb', 'foo')
417 417 nbcontent = json.loads(resp.text)['content']
418 nb = to_notebook_json(nbcontent)
419 ws = new_worksheet()
420 nb.worksheets = [ws]
421 ws.cells.append(new_heading_cell(u'Created by test ³'))
418 nb = from_dict(nbcontent)
419 nb.cells.append(new_markdown_cell(u'Created by test ³'))
422 420
423 421 nbmodel= {'name': 'a.ipynb', 'path':'foo', 'content': nb, 'type': 'notebook'}
424 422 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
425 423
426 424 nbfile = pjoin(self.notebook_dir.name, 'foo', 'a.ipynb')
427 425 with io.open(nbfile, 'r', encoding='utf-8') as f:
428 newnb = read(f, format='ipynb')
429 self.assertEqual(newnb.worksheets[0].cells[0].source,
426 newnb = read(f, as_version=4)
427 self.assertEqual(newnb.cells[0].source,
430 428 u'Created by test ³')
431 429 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
432 newnb = to_notebook_json(nbcontent)
433 self.assertEqual(newnb.worksheets[0].cells[0].source,
430 newnb = from_dict(nbcontent)
431 self.assertEqual(newnb.cells[0].source,
434 432 u'Created by test ³')
435 433
436 434 # Save and rename
437 435 nbmodel= {'name': 'a2.ipynb', 'path':'foo/bar', 'content': nb, 'type': 'notebook'}
438 436 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
439 437 saved = resp.json()
440 438 self.assertEqual(saved['name'], 'a2.ipynb')
441 439 self.assertEqual(saved['path'], 'foo/bar')
442 440 assert os.path.isfile(pjoin(self.notebook_dir.name,'foo','bar','a2.ipynb'))
443 441 assert not os.path.isfile(pjoin(self.notebook_dir.name, 'foo', 'a.ipynb'))
444 442 with assert_http_error(404):
445 443 self.api.read('a.ipynb', 'foo')
446 444
447 445 def test_checkpoints(self):
448 446 resp = self.api.read('a.ipynb', 'foo')
449 447 r = self.api.new_checkpoint('a.ipynb', 'foo')
450 448 self.assertEqual(r.status_code, 201)
451 449 cp1 = r.json()
452 450 self.assertEqual(set(cp1), {'id', 'last_modified'})
453 451 self.assertEqual(r.headers['Location'].split('/')[-1], cp1['id'])
454 452
455 453 # Modify it
456 454 nbcontent = json.loads(resp.text)['content']
457 nb = to_notebook_json(nbcontent)
458 ws = new_worksheet()
459 nb.worksheets = [ws]
460 hcell = new_heading_cell('Created by test')
461 ws.cells.append(hcell)
455 nb = from_dict(nbcontent)
456 hcell = new_markdown_cell('Created by test')
457 nb.cells.append(hcell)
462 458 # Save
463 459 nbmodel= {'name': 'a.ipynb', 'path':'foo', 'content': nb, 'type': 'notebook'}
464 460 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
465 461
466 462 # List checkpoints
467 463 cps = self.api.get_checkpoints('a.ipynb', 'foo').json()
468 464 self.assertEqual(cps, [cp1])
469 465
470 466 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
471 nb = to_notebook_json(nbcontent)
472 self.assertEqual(nb.worksheets[0].cells[0].source, 'Created by test')
467 nb = from_dict(nbcontent)
468 self.assertEqual(nb.cells[0].source, 'Created by test')
473 469
474 470 # Restore cp1
475 471 r = self.api.restore_checkpoint('a.ipynb', 'foo', cp1['id'])
476 472 self.assertEqual(r.status_code, 204)
477 473 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
478 nb = to_notebook_json(nbcontent)
479 self.assertEqual(nb.worksheets, [])
474 nb = from_dict(nbcontent)
475 self.assertEqual(nb.cells, [])
480 476
481 477 # Delete cp1
482 478 r = self.api.delete_checkpoint('a.ipynb', 'foo', cp1['id'])
483 479 self.assertEqual(r.status_code, 204)
484 480 cps = self.api.get_checkpoints('a.ipynb', 'foo').json()
485 481 self.assertEqual(cps, [])
@@ -1,334 +1,332 b''
1 1 # coding: utf-8
2 2 """Tests for the notebook manager."""
3 3 from __future__ import print_function
4 4
5 5 import logging
6 6 import os
7 7
8 8 from tornado.web import HTTPError
9 9 from unittest import TestCase
10 10 from tempfile import NamedTemporaryFile
11 11
12 from IPython.nbformat import current
12 from IPython.nbformat import v4 as nbformat
13 13
14 14 from IPython.utils.tempdir import TemporaryDirectory
15 15 from IPython.utils.traitlets import TraitError
16 16 from IPython.html.utils import url_path_join
17 17 from IPython.testing import decorators as dec
18 18
19 19 from ..filemanager import FileContentsManager
20 20 from ..manager import ContentsManager
21 21
22 22
23 23 class TestFileContentsManager(TestCase):
24 24
25 25 def test_root_dir(self):
26 26 with TemporaryDirectory() as td:
27 27 fm = FileContentsManager(root_dir=td)
28 28 self.assertEqual(fm.root_dir, td)
29 29
30 30 def test_missing_root_dir(self):
31 31 with TemporaryDirectory() as td:
32 32 root = os.path.join(td, 'notebook', 'dir', 'is', 'missing')
33 33 self.assertRaises(TraitError, FileContentsManager, root_dir=root)
34 34
35 35 def test_invalid_root_dir(self):
36 36 with NamedTemporaryFile() as tf:
37 37 self.assertRaises(TraitError, FileContentsManager, root_dir=tf.name)
38 38
39 39 def test_get_os_path(self):
40 40 # full filesystem path should be returned with correct operating system
41 41 # separators.
42 42 with TemporaryDirectory() as td:
43 43 root = td
44 44 fm = FileContentsManager(root_dir=root)
45 45 path = fm._get_os_path('test.ipynb', '/path/to/notebook/')
46 46 rel_path_list = '/path/to/notebook/test.ipynb'.split('/')
47 47 fs_path = os.path.join(fm.root_dir, *rel_path_list)
48 48 self.assertEqual(path, fs_path)
49 49
50 50 fm = FileContentsManager(root_dir=root)
51 51 path = fm._get_os_path('test.ipynb')
52 52 fs_path = os.path.join(fm.root_dir, 'test.ipynb')
53 53 self.assertEqual(path, fs_path)
54 54
55 55 fm = FileContentsManager(root_dir=root)
56 56 path = fm._get_os_path('test.ipynb', '////')
57 57 fs_path = os.path.join(fm.root_dir, 'test.ipynb')
58 58 self.assertEqual(path, fs_path)
59 59
60 60 def test_checkpoint_subdir(self):
61 61 subd = u'sub ∂ir'
62 62 cp_name = 'test-cp.ipynb'
63 63 with TemporaryDirectory() as td:
64 64 root = td
65 65 os.mkdir(os.path.join(td, subd))
66 66 fm = FileContentsManager(root_dir=root)
67 67 cp_dir = fm.get_checkpoint_path('cp', 'test.ipynb', '/')
68 68 cp_subdir = fm.get_checkpoint_path('cp', 'test.ipynb', '/%s/' % subd)
69 69 self.assertNotEqual(cp_dir, cp_subdir)
70 70 self.assertEqual(cp_dir, os.path.join(root, fm.checkpoint_dir, cp_name))
71 71 self.assertEqual(cp_subdir, os.path.join(root, subd, fm.checkpoint_dir, cp_name))
72 72
73 73
74 74 class TestContentsManager(TestCase):
75 75
76 76 def setUp(self):
77 77 self._temp_dir = TemporaryDirectory()
78 78 self.td = self._temp_dir.name
79 79 self.contents_manager = FileContentsManager(
80 80 root_dir=self.td,
81 81 log=logging.getLogger()
82 82 )
83 83
84 84 def tearDown(self):
85 85 self._temp_dir.cleanup()
86 86
87 87 def make_dir(self, abs_path, rel_path):
88 88 """make subdirectory, rel_path is the relative path
89 89 to that directory from the location where the server started"""
90 90 os_path = os.path.join(abs_path, rel_path)
91 91 try:
92 92 os.makedirs(os_path)
93 93 except OSError:
94 94 print("Directory already exists: %r" % os_path)
95 95 return os_path
96 96
97 97 def add_code_cell(self, nb):
98 output = current.new_output("display_data", output_javascript="alert('hi');")
99 cell = current.new_code_cell("print('hi')", outputs=[output])
100 if not nb.worksheets:
101 nb.worksheets.append(current.new_worksheet())
102 nb.worksheets[0].cells.append(cell)
98 output = nbformat.new_output("display_data", {'application/javascript': "alert('hi');"})
99 cell = nbformat.new_code_cell("print('hi')", outputs=[output])
100 nb.cells.append(cell)
103 101
104 102 def new_notebook(self):
105 103 cm = self.contents_manager
106 104 model = cm.create_file()
107 105 name = model['name']
108 106 path = model['path']
109 107
110 108 full_model = cm.get_model(name, path)
111 109 nb = full_model['content']
112 110 self.add_code_cell(nb)
113 111
114 112 cm.save(full_model, name, path)
115 113 return nb, name, path
116 114
117 115 def test_create_file(self):
118 116 cm = self.contents_manager
119 117 # Test in root directory
120 118 model = cm.create_file()
121 119 assert isinstance(model, dict)
122 120 self.assertIn('name', model)
123 121 self.assertIn('path', model)
124 122 self.assertEqual(model['name'], 'Untitled0.ipynb')
125 123 self.assertEqual(model['path'], '')
126 124
127 125 # Test in sub-directory
128 126 sub_dir = '/foo/'
129 127 self.make_dir(cm.root_dir, 'foo')
130 128 model = cm.create_file(None, sub_dir)
131 129 assert isinstance(model, dict)
132 130 self.assertIn('name', model)
133 131 self.assertIn('path', model)
134 132 self.assertEqual(model['name'], 'Untitled0.ipynb')
135 133 self.assertEqual(model['path'], sub_dir.strip('/'))
136 134
137 135 def test_get(self):
138 136 cm = self.contents_manager
139 137 # Create a notebook
140 138 model = cm.create_file()
141 139 name = model['name']
142 140 path = model['path']
143 141
144 142 # Check that we 'get' on the notebook we just created
145 143 model2 = cm.get_model(name, path)
146 144 assert isinstance(model2, dict)
147 145 self.assertIn('name', model2)
148 146 self.assertIn('path', model2)
149 147 self.assertEqual(model['name'], name)
150 148 self.assertEqual(model['path'], path)
151 149
152 150 # Test in sub-directory
153 151 sub_dir = '/foo/'
154 152 self.make_dir(cm.root_dir, 'foo')
155 153 model = cm.create_file(None, sub_dir)
156 154 model2 = cm.get_model(name, sub_dir)
157 155 assert isinstance(model2, dict)
158 156 self.assertIn('name', model2)
159 157 self.assertIn('path', model2)
160 158 self.assertIn('content', model2)
161 159 self.assertEqual(model2['name'], 'Untitled0.ipynb')
162 160 self.assertEqual(model2['path'], sub_dir.strip('/'))
163 161
164 162 @dec.skip_win32
165 163 def test_bad_symlink(self):
166 164 cm = self.contents_manager
167 165 path = 'test bad symlink'
168 166 os_path = self.make_dir(cm.root_dir, path)
169 167
170 168 file_model = cm.create_file(path=path, ext='.txt')
171 169
172 170 # create a broken symlink
173 171 os.symlink("target", os.path.join(os_path, "bad symlink"))
174 172 model = cm.get_model(path)
175 173 self.assertEqual(model['content'], [file_model])
176 174
177 175 @dec.skip_win32
178 176 def test_good_symlink(self):
179 177 cm = self.contents_manager
180 178 path = 'test good symlink'
181 179 os_path = self.make_dir(cm.root_dir, path)
182 180
183 181 file_model = cm.create_file(path=path, ext='.txt')
184 182
185 183 # create a good symlink
186 184 os.symlink(file_model['name'], os.path.join(os_path, "good symlink"))
187 185 symlink_model = cm.get_model(name="good symlink", path=path, content=False)
188 186
189 187 dir_model = cm.get_model(path)
190 188 self.assertEqual(
191 189 sorted(dir_model['content'], key=lambda x: x['name']),
192 190 [symlink_model, file_model],
193 191 )
194 192
195 193 def test_update(self):
196 194 cm = self.contents_manager
197 195 # Create a notebook
198 196 model = cm.create_file()
199 197 name = model['name']
200 198 path = model['path']
201 199
202 200 # Change the name in the model for rename
203 201 model['name'] = 'test.ipynb'
204 202 model = cm.update(model, name, path)
205 203 assert isinstance(model, dict)
206 204 self.assertIn('name', model)
207 205 self.assertIn('path', model)
208 206 self.assertEqual(model['name'], 'test.ipynb')
209 207
210 208 # Make sure the old name is gone
211 209 self.assertRaises(HTTPError, cm.get_model, name, path)
212 210
213 211 # Test in sub-directory
214 212 # Create a directory and notebook in that directory
215 213 sub_dir = '/foo/'
216 214 self.make_dir(cm.root_dir, 'foo')
217 215 model = cm.create_file(None, sub_dir)
218 216 name = model['name']
219 217 path = model['path']
220 218
221 219 # Change the name in the model for rename
222 220 model['name'] = 'test_in_sub.ipynb'
223 221 model = cm.update(model, name, path)
224 222 assert isinstance(model, dict)
225 223 self.assertIn('name', model)
226 224 self.assertIn('path', model)
227 225 self.assertEqual(model['name'], 'test_in_sub.ipynb')
228 226 self.assertEqual(model['path'], sub_dir.strip('/'))
229 227
230 228 # Make sure the old name is gone
231 229 self.assertRaises(HTTPError, cm.get_model, name, path)
232 230
233 231 def test_save(self):
234 232 cm = self.contents_manager
235 233 # Create a notebook
236 234 model = cm.create_file()
237 235 name = model['name']
238 236 path = model['path']
239 237
240 238 # Get the model with 'content'
241 239 full_model = cm.get_model(name, path)
242 240
243 241 # Save the notebook
244 242 model = cm.save(full_model, name, path)
245 243 assert isinstance(model, dict)
246 244 self.assertIn('name', model)
247 245 self.assertIn('path', model)
248 246 self.assertEqual(model['name'], name)
249 247 self.assertEqual(model['path'], path)
250 248
251 249 # Test in sub-directory
252 250 # Create a directory and notebook in that directory
253 251 sub_dir = '/foo/'
254 252 self.make_dir(cm.root_dir, 'foo')
255 253 model = cm.create_file(None, sub_dir)
256 254 name = model['name']
257 255 path = model['path']
258 256 model = cm.get_model(name, path)
259 257
260 258 # Change the name in the model for rename
261 259 model = cm.save(model, name, path)
262 260 assert isinstance(model, dict)
263 261 self.assertIn('name', model)
264 262 self.assertIn('path', model)
265 263 self.assertEqual(model['name'], 'Untitled0.ipynb')
266 264 self.assertEqual(model['path'], sub_dir.strip('/'))
267 265
268 266 def test_delete(self):
269 267 cm = self.contents_manager
270 268 # Create a notebook
271 269 nb, name, path = self.new_notebook()
272 270
273 271 # Delete the notebook
274 272 cm.delete(name, path)
275 273
276 274 # Check that a 'get' on the deleted notebook raises and error
277 275 self.assertRaises(HTTPError, cm.get_model, name, path)
278 276
279 277 def test_copy(self):
280 278 cm = self.contents_manager
281 279 path = u'å b'
282 280 name = u'nb √.ipynb'
283 281 os.mkdir(os.path.join(cm.root_dir, path))
284 282 orig = cm.create_file({'name' : name}, path=path)
285 283
286 284 # copy with unspecified name
287 285 copy = cm.copy(name, path=path)
288 286 self.assertEqual(copy['name'], orig['name'].replace('.ipynb', '-Copy0.ipynb'))
289 287
290 288 # copy with specified name
291 289 copy2 = cm.copy(name, u'copy 2.ipynb', path=path)
292 290 self.assertEqual(copy2['name'], u'copy 2.ipynb')
293 291
294 292 def test_trust_notebook(self):
295 293 cm = self.contents_manager
296 294 nb, name, path = self.new_notebook()
297 295
298 296 untrusted = cm.get_model(name, path)['content']
299 297 assert not cm.notary.check_cells(untrusted)
300 298
301 299 # print(untrusted)
302 300 cm.trust_notebook(name, path)
303 301 trusted = cm.get_model(name, path)['content']
304 302 # print(trusted)
305 303 assert cm.notary.check_cells(trusted)
306 304
307 305 def test_mark_trusted_cells(self):
308 306 cm = self.contents_manager
309 307 nb, name, path = self.new_notebook()
310 308
311 309 cm.mark_trusted_cells(nb, name, path)
312 for cell in nb.worksheets[0].cells:
310 for cell in nb.cells:
313 311 if cell.cell_type == 'code':
314 312 assert not cell.metadata.trusted
315 313
316 314 cm.trust_notebook(name, path)
317 315 nb = cm.get_model(name, path)['content']
318 for cell in nb.worksheets[0].cells:
316 for cell in nb.cells:
319 317 if cell.cell_type == 'code':
320 318 assert cell.metadata.trusted
321 319
322 320 def test_check_and_sign(self):
323 321 cm = self.contents_manager
324 322 nb, name, path = self.new_notebook()
325 323
326 324 cm.mark_trusted_cells(nb, name, path)
327 325 cm.check_and_sign(nb, name, path)
328 326 assert not cm.notary.check_signature(nb)
329 327
330 328 cm.trust_notebook(name, path)
331 329 nb = cm.get_model(name, path)['content']
332 330 cm.mark_trusted_cells(nb, name, path)
333 331 cm.check_and_sign(nb, name, path)
334 332 assert cm.notary.check_signature(nb)
@@ -1,116 +1,117 b''
1 1 """Test the sessions web service API."""
2 2
3 3 import errno
4 4 import io
5 5 import os
6 6 import json
7 7 import requests
8 8 import shutil
9 9
10 10 pjoin = os.path.join
11 11
12 12 from IPython.html.utils import url_path_join
13 13 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
14 from IPython.nbformat.current import new_notebook, write
14 from IPython.nbformat.v4 import new_notebook
15 from IPython.nbformat import write
15 16
16 17 class SessionAPI(object):
17 18 """Wrapper for notebook API calls."""
18 19 def __init__(self, base_url):
19 20 self.base_url = base_url
20 21
21 22 def _req(self, verb, path, body=None):
22 23 response = requests.request(verb,
23 24 url_path_join(self.base_url, 'api/sessions', path), data=body)
24 25
25 26 if 400 <= response.status_code < 600:
26 27 try:
27 28 response.reason = response.json()['message']
28 29 except:
29 30 pass
30 31 response.raise_for_status()
31 32
32 33 return response
33 34
34 35 def list(self):
35 36 return self._req('GET', '')
36 37
37 38 def get(self, id):
38 39 return self._req('GET', id)
39 40
40 41 def create(self, name, path, kernel_name='python'):
41 42 body = json.dumps({'notebook': {'name':name, 'path':path},
42 43 'kernel': {'name': kernel_name}})
43 44 return self._req('POST', '', body)
44 45
45 46 def modify(self, id, name, path):
46 47 body = json.dumps({'notebook': {'name':name, 'path':path}})
47 48 return self._req('PATCH', id, body)
48 49
49 50 def delete(self, id):
50 51 return self._req('DELETE', id)
51 52
52 53 class SessionAPITest(NotebookTestBase):
53 54 """Test the sessions web service API"""
54 55 def setUp(self):
55 56 nbdir = self.notebook_dir.name
56 57 try:
57 58 os.mkdir(pjoin(nbdir, 'foo'))
58 59 except OSError as e:
59 60 # Deleting the folder in an earlier test may have failed
60 61 if e.errno != errno.EEXIST:
61 62 raise
62 63
63 64 with io.open(pjoin(nbdir, 'foo', 'nb1.ipynb'), 'w',
64 65 encoding='utf-8') as f:
65 nb = new_notebook(name='nb1')
66 write(nb, f, format='ipynb')
66 nb = new_notebook()
67 write(nb, f, version=4)
67 68
68 69 self.sess_api = SessionAPI(self.base_url())
69 70
70 71 def tearDown(self):
71 72 for session in self.sess_api.list().json():
72 73 self.sess_api.delete(session['id'])
73 74 shutil.rmtree(pjoin(self.notebook_dir.name, 'foo'),
74 75 ignore_errors=True)
75 76
76 77 def test_create(self):
77 78 sessions = self.sess_api.list().json()
78 79 self.assertEqual(len(sessions), 0)
79 80
80 81 resp = self.sess_api.create('nb1.ipynb', 'foo')
81 82 self.assertEqual(resp.status_code, 201)
82 83 newsession = resp.json()
83 84 self.assertIn('id', newsession)
84 85 self.assertEqual(newsession['notebook']['name'], 'nb1.ipynb')
85 86 self.assertEqual(newsession['notebook']['path'], 'foo')
86 87 self.assertEqual(resp.headers['Location'], '/api/sessions/{0}'.format(newsession['id']))
87 88
88 89 sessions = self.sess_api.list().json()
89 90 self.assertEqual(sessions, [newsession])
90 91
91 92 # Retrieve it
92 93 sid = newsession['id']
93 94 got = self.sess_api.get(sid).json()
94 95 self.assertEqual(got, newsession)
95 96
96 97 def test_delete(self):
97 98 newsession = self.sess_api.create('nb1.ipynb', 'foo').json()
98 99 sid = newsession['id']
99 100
100 101 resp = self.sess_api.delete(sid)
101 102 self.assertEqual(resp.status_code, 204)
102 103
103 104 sessions = self.sess_api.list().json()
104 105 self.assertEqual(sessions, [])
105 106
106 107 with assert_http_error(404):
107 108 self.sess_api.get(sid)
108 109
109 110 def test_modify(self):
110 111 newsession = self.sess_api.create('nb1.ipynb', 'foo').json()
111 112 sid = newsession['id']
112 113
113 114 changed = self.sess_api.modify(sid, 'nb2.ipynb', '').json()
114 115 self.assertEqual(changed['id'], sid)
115 116 self.assertEqual(changed['notebook']['name'], 'nb2.ipynb')
116 117 self.assertEqual(changed['notebook']['path'], '')
@@ -1,532 +1,526 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3 /**
4 4 *
5 5 *
6 6 * @module codecell
7 7 * @namespace codecell
8 8 * @class CodeCell
9 9 */
10 10
11 11
12 12 define([
13 13 'base/js/namespace',
14 14 'jquery',
15 15 'base/js/utils',
16 16 'base/js/keyboard',
17 17 'notebook/js/cell',
18 18 'notebook/js/outputarea',
19 19 'notebook/js/completer',
20 20 'notebook/js/celltoolbar',
21 21 'codemirror/lib/codemirror',
22 22 'codemirror/mode/python/python',
23 23 'notebook/js/codemirror-ipython'
24 24 ], function(IPython, $, utils, keyboard, cell, outputarea, completer, celltoolbar, CodeMirror, cmpython, cmip) {
25 25 "use strict";
26 26 var Cell = cell.Cell;
27 27
28 28 /* local util for codemirror */
29 29 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;};
30 30
31 31 /**
32 32 *
33 33 * function to delete until previous non blanking space character
34 34 * or first multiple of 4 tabstop.
35 35 * @private
36 36 */
37 37 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
38 38 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
39 39 if (!posEq(from, to)) { cm.replaceRange("", from, to); return; }
40 40 var cur = cm.getCursor(), line = cm.getLine(cur.line);
41 41 var tabsize = cm.getOption('tabSize');
42 42 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
43 43 from = {ch:cur.ch-chToPrevTabStop,line:cur.line};
44 44 var select = cm.getRange(from,cur);
45 45 if( select.match(/^\ +$/) !== null){
46 46 cm.replaceRange("",from,cur);
47 47 } else {
48 48 cm.deleteH(-1,"char");
49 49 }
50 50 };
51 51
52 52 var keycodes = keyboard.keycodes;
53 53
54 54 var CodeCell = function (kernel, options) {
55 55 // Constructor
56 56 //
57 57 // A Cell conceived to write code.
58 58 //
59 59 // Parameters:
60 60 // kernel: Kernel instance
61 61 // The kernel doesn't have to be set at creation time, in that case
62 62 // it will be null and set_kernel has to be called later.
63 63 // options: dictionary
64 64 // Dictionary of keyword arguments.
65 65 // events: $(Events) instance
66 66 // config: dictionary
67 67 // keyboard_manager: KeyboardManager instance
68 68 // notebook: Notebook instance
69 69 // tooltip: Tooltip instance
70 70 this.kernel = kernel || null;
71 71 this.notebook = options.notebook;
72 72 this.collapsed = false;
73 73 this.events = options.events;
74 74 this.tooltip = options.tooltip;
75 75 this.config = options.config;
76 76
77 77 // create all attributed in constructor function
78 78 // even if null for V8 VM optimisation
79 79 this.input_prompt_number = null;
80 80 this.celltoolbar = null;
81 81 this.output_area = null;
82 82 this.last_msg_id = null;
83 83 this.completer = null;
84 84
85 85
86 86 var config = utils.mergeopt(CodeCell, this.config);
87 87 Cell.apply(this,[{
88 88 config: config,
89 89 keyboard_manager: options.keyboard_manager,
90 90 events: this.events}]);
91 91
92 92 // Attributes we want to override in this subclass.
93 93 this.cell_type = "code";
94 94
95 95 var that = this;
96 96 this.element.focusout(
97 97 function() { that.auto_highlight(); }
98 98 );
99 99 };
100 100
101 101 CodeCell.options_default = {
102 102 cm_config : {
103 103 extraKeys: {
104 104 "Tab" : "indentMore",
105 105 "Shift-Tab" : "indentLess",
106 106 "Backspace" : "delSpaceToPrevTabStop",
107 107 "Cmd-/" : "toggleComment",
108 108 "Ctrl-/" : "toggleComment"
109 109 },
110 110 mode: 'ipython',
111 111 theme: 'ipython',
112 112 matchBrackets: true
113 113 }
114 114 };
115 115
116 116 CodeCell.msg_cells = {};
117 117
118 118 CodeCell.prototype = Object.create(Cell.prototype);
119 119
120 120 /**
121 121 * @method auto_highlight
122 122 */
123 123 CodeCell.prototype.auto_highlight = function () {
124 124 this._auto_highlight(this.config.cell_magic_highlight);
125 125 };
126 126
127 127 /** @method create_element */
128 128 CodeCell.prototype.create_element = function () {
129 129 Cell.prototype.create_element.apply(this, arguments);
130 130
131 131 var cell = $('<div></div>').addClass('cell code_cell');
132 132 cell.attr('tabindex','2');
133 133
134 134 var input = $('<div></div>').addClass('input');
135 135 var prompt = $('<div/>').addClass('prompt input_prompt');
136 136 var inner_cell = $('<div/>').addClass('inner_cell');
137 137 this.celltoolbar = new celltoolbar.CellToolbar({
138 138 cell: this,
139 139 notebook: this.notebook});
140 140 inner_cell.append(this.celltoolbar.element);
141 141 var input_area = $('<div/>').addClass('input_area');
142 142 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
143 143 this.code_mirror.on('keydown', $.proxy(this.handle_keyevent,this))
144 144 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
145 145 inner_cell.append(input_area);
146 146 input.append(prompt).append(inner_cell);
147 147
148 148 var widget_area = $('<div/>')
149 149 .addClass('widget-area')
150 150 .hide();
151 151 this.widget_area = widget_area;
152 152 var widget_prompt = $('<div/>')
153 153 .addClass('prompt')
154 154 .appendTo(widget_area);
155 155 var widget_subarea = $('<div/>')
156 156 .addClass('widget-subarea')
157 157 .appendTo(widget_area);
158 158 this.widget_subarea = widget_subarea;
159 159 var widget_clear_buton = $('<button />')
160 160 .addClass('close')
161 161 .html('&times;')
162 162 .click(function() {
163 163 widget_area.slideUp('', function(){ widget_subarea.html(''); });
164 164 })
165 165 .appendTo(widget_prompt);
166 166
167 167 var output = $('<div></div>');
168 168 cell.append(input).append(widget_area).append(output);
169 169 this.element = cell;
170 170 this.output_area = new outputarea.OutputArea({
171 171 selector: output,
172 172 prompt_area: true,
173 173 events: this.events,
174 174 keyboard_manager: this.keyboard_manager});
175 175 this.completer = new completer.Completer(this, this.events);
176 176 };
177 177
178 178 /** @method bind_events */
179 179 CodeCell.prototype.bind_events = function () {
180 180 Cell.prototype.bind_events.apply(this);
181 181 var that = this;
182 182
183 183 this.element.focusout(
184 184 function() { that.auto_highlight(); }
185 185 );
186 186 };
187 187
188 188
189 189 /**
190 190 * This method gets called in CodeMirror's onKeyDown/onKeyPress
191 191 * handlers and is used to provide custom key handling. Its return
192 192 * value is used to determine if CodeMirror should ignore the event:
193 193 * true = ignore, false = don't ignore.
194 194 * @method handle_codemirror_keyevent
195 195 */
196 196 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
197 197
198 198 var that = this;
199 199 // whatever key is pressed, first, cancel the tooltip request before
200 200 // they are sent, and remove tooltip if any, except for tab again
201 201 var tooltip_closed = null;
202 202 if (event.type === 'keydown' && event.which != keycodes.tab ) {
203 203 tooltip_closed = this.tooltip.remove_and_cancel_tooltip();
204 204 }
205 205
206 206 var cur = editor.getCursor();
207 207 if (event.keyCode === keycodes.enter){
208 208 this.auto_highlight();
209 209 }
210 210
211 211 if (event.which === keycodes.down && event.type === 'keypress' && this.tooltip.time_before_tooltip >= 0) {
212 212 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
213 213 // browser and keyboard layout !
214 214 // Pressing '(' , request tooltip, don't forget to reappend it
215 215 // The second argument says to hide the tooltip if the docstring
216 216 // is actually empty
217 217 this.tooltip.pending(that, true);
218 218 } else if ( tooltip_closed && event.which === keycodes.esc && event.type === 'keydown') {
219 219 // If tooltip is active, cancel it. The call to
220 220 // remove_and_cancel_tooltip above doesn't pass, force=true.
221 221 // Because of this it won't actually close the tooltip
222 222 // if it is in sticky mode. Thus, we have to check again if it is open
223 223 // and close it with force=true.
224 224 if (!this.tooltip._hidden) {
225 225 this.tooltip.remove_and_cancel_tooltip(true);
226 226 }
227 227 // If we closed the tooltip, don't let CM or the global handlers
228 228 // handle this event.
229 229 event.codemirrorIgnore = true;
230 230 event.preventDefault();
231 231 return true;
232 232 } else if (event.keyCode === keycodes.tab && event.type === 'keydown' && event.shiftKey) {
233 233 if (editor.somethingSelected() || editor.getSelections().length !== 1){
234 234 var anchor = editor.getCursor("anchor");
235 235 var head = editor.getCursor("head");
236 236 if( anchor.line != head.line){
237 237 return false;
238 238 }
239 239 }
240 240 this.tooltip.request(that);
241 241 event.codemirrorIgnore = true;
242 242 event.preventDefault();
243 243 return true;
244 244 } else if (event.keyCode === keycodes.tab && event.type == 'keydown') {
245 245 // Tab completion.
246 246 this.tooltip.remove_and_cancel_tooltip();
247 247
248 248 // completion does not work on multicursor, it might be possible though in some cases
249 249 if (editor.somethingSelected() || editor.getSelections().length > 1) {
250 250 return false;
251 251 }
252 252 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
253 253 if (pre_cursor.trim() === "") {
254 254 // Don't autocomplete if the part of the line before the cursor
255 255 // is empty. In this case, let CodeMirror handle indentation.
256 256 return false;
257 257 } else {
258 258 event.codemirrorIgnore = true;
259 259 event.preventDefault();
260 260 this.completer.startCompletion();
261 261 return true;
262 262 }
263 263 }
264 264
265 265 // keyboard event wasn't one of those unique to code cells, let's see
266 266 // if it's one of the generic ones (i.e. check edit mode shortcuts)
267 267 return Cell.prototype.handle_codemirror_keyevent.apply(this, [editor, event]);
268 268 };
269 269
270 270 // Kernel related calls.
271 271
272 272 CodeCell.prototype.set_kernel = function (kernel) {
273 273 this.kernel = kernel;
274 274 };
275 275
276 276 /**
277 277 * Execute current code cell to the kernel
278 278 * @method execute
279 279 */
280 280 CodeCell.prototype.execute = function () {
281 281 this.output_area.clear_output();
282 282
283 283 // Clear widget area
284 284 this.widget_subarea.html('');
285 285 this.widget_subarea.height('');
286 286 this.widget_area.height('');
287 287 this.widget_area.hide();
288 288
289 289 this.set_input_prompt('*');
290 290 this.element.addClass("running");
291 291 if (this.last_msg_id) {
292 292 this.kernel.clear_callbacks_for_msg(this.last_msg_id);
293 293 }
294 294 var callbacks = this.get_callbacks();
295 295
296 296 var old_msg_id = this.last_msg_id;
297 297 this.last_msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
298 298 if (old_msg_id) {
299 299 delete CodeCell.msg_cells[old_msg_id];
300 300 }
301 301 CodeCell.msg_cells[this.last_msg_id] = this;
302 302 this.render();
303 303 };
304 304
305 305 /**
306 306 * Construct the default callbacks for
307 307 * @method get_callbacks
308 308 */
309 309 CodeCell.prototype.get_callbacks = function () {
310 310 return {
311 311 shell : {
312 312 reply : $.proxy(this._handle_execute_reply, this),
313 313 payload : {
314 314 set_next_input : $.proxy(this._handle_set_next_input, this),
315 315 page : $.proxy(this._open_with_pager, this)
316 316 }
317 317 },
318 318 iopub : {
319 319 output : $.proxy(this.output_area.handle_output, this.output_area),
320 320 clear_output : $.proxy(this.output_area.handle_clear_output, this.output_area),
321 321 },
322 322 input : $.proxy(this._handle_input_request, this)
323 323 };
324 324 };
325 325
326 326 CodeCell.prototype._open_with_pager = function (payload) {
327 327 this.events.trigger('open_with_text.Pager', payload);
328 328 };
329 329
330 330 /**
331 331 * @method _handle_execute_reply
332 332 * @private
333 333 */
334 334 CodeCell.prototype._handle_execute_reply = function (msg) {
335 335 this.set_input_prompt(msg.content.execution_count);
336 336 this.element.removeClass("running");
337 337 this.events.trigger('set_dirty.Notebook', {value: true});
338 338 };
339 339
340 340 /**
341 341 * @method _handle_set_next_input
342 342 * @private
343 343 */
344 344 CodeCell.prototype._handle_set_next_input = function (payload) {
345 345 var data = {'cell': this, 'text': payload.text};
346 346 this.events.trigger('set_next_input.Notebook', data);
347 347 };
348 348
349 349 /**
350 350 * @method _handle_input_request
351 351 * @private
352 352 */
353 353 CodeCell.prototype._handle_input_request = function (msg) {
354 354 this.output_area.append_raw_input(msg);
355 355 };
356 356
357 357
358 358 // Basic cell manipulation.
359 359
360 360 CodeCell.prototype.select = function () {
361 361 var cont = Cell.prototype.select.apply(this);
362 362 if (cont) {
363 363 this.code_mirror.refresh();
364 364 this.auto_highlight();
365 365 }
366 366 return cont;
367 367 };
368 368
369 369 CodeCell.prototype.render = function () {
370 370 var cont = Cell.prototype.render.apply(this);
371 371 // Always execute, even if we are already in the rendered state
372 372 return cont;
373 373 };
374 374
375 375 CodeCell.prototype.select_all = function () {
376 376 var start = {line: 0, ch: 0};
377 377 var nlines = this.code_mirror.lineCount();
378 378 var last_line = this.code_mirror.getLine(nlines-1);
379 379 var end = {line: nlines-1, ch: last_line.length};
380 380 this.code_mirror.setSelection(start, end);
381 381 };
382 382
383 383
384 384 CodeCell.prototype.collapse_output = function () {
385 this.collapsed = true;
386 385 this.output_area.collapse();
387 386 };
388 387
389 388
390 389 CodeCell.prototype.expand_output = function () {
391 this.collapsed = false;
392 390 this.output_area.expand();
393 391 this.output_area.unscroll_area();
394 392 };
395 393
396 394 CodeCell.prototype.scroll_output = function () {
397 395 this.output_area.expand();
398 396 this.output_area.scroll_if_long();
399 397 };
400 398
401 399 CodeCell.prototype.toggle_output = function () {
402 this.collapsed = Boolean(1 - this.collapsed);
403 400 this.output_area.toggle_output();
404 401 };
405 402
406 403 CodeCell.prototype.toggle_output_scroll = function () {
407 404 this.output_area.toggle_scroll();
408 405 };
409 406
410 407
411 408 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
412 409 var ns;
413 410 if (prompt_value === undefined || prompt_value === null) {
414 411 ns = "&nbsp;";
415 412 } else {
416 413 ns = encodeURIComponent(prompt_value);
417 414 }
418 415 return 'In&nbsp;[' + ns + ']:';
419 416 };
420 417
421 418 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
422 419 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
423 420 for(var i=1; i < lines_number; i++) {
424 421 html.push(['...:']);
425 422 }
426 423 return html.join('<br/>');
427 424 };
428 425
429 426 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
430 427
431 428
432 429 CodeCell.prototype.set_input_prompt = function (number) {
433 430 var nline = 1;
434 431 if (this.code_mirror !== undefined) {
435 432 nline = this.code_mirror.lineCount();
436 433 }
437 434 this.input_prompt_number = number;
438 435 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
439 436 // This HTML call is okay because the user contents are escaped.
440 437 this.element.find('div.input_prompt').html(prompt_html);
441 438 };
442 439
443 440
444 441 CodeCell.prototype.clear_input = function () {
445 442 this.code_mirror.setValue('');
446 443 };
447 444
448 445
449 446 CodeCell.prototype.get_text = function () {
450 447 return this.code_mirror.getValue();
451 448 };
452 449
453 450
454 451 CodeCell.prototype.set_text = function (code) {
455 452 return this.code_mirror.setValue(code);
456 453 };
457 454
458 455
459 456 CodeCell.prototype.clear_output = function (wait) {
460 457 this.output_area.clear_output(wait);
461 458 this.set_input_prompt();
462 459 };
463 460
464 461
465 462 // JSON serialization
466 463
467 464 CodeCell.prototype.fromJSON = function (data) {
468 465 Cell.prototype.fromJSON.apply(this, arguments);
469 466 if (data.cell_type === 'code') {
470 if (data.input !== undefined) {
471 this.set_text(data.input);
467 if (data.source !== undefined) {
468 this.set_text(data.source);
472 469 // make this value the starting point, so that we can only undo
473 470 // to this state, instead of a blank cell
474 471 this.code_mirror.clearHistory();
475 472 this.auto_highlight();
476 473 }
477 if (data.prompt_number !== undefined) {
478 this.set_input_prompt(data.prompt_number);
479 } else {
480 this.set_input_prompt();
481 }
474 this.set_input_prompt(data.execution_count);
482 475 this.output_area.trusted = data.metadata.trusted || false;
483 476 this.output_area.fromJSON(data.outputs);
484 if (data.collapsed !== undefined) {
485 if (data.collapsed) {
477 if (data.metadata.collapsed !== undefined) {
478 if (data.metadata.collapsed) {
486 479 this.collapse_output();
487 480 } else {
488 481 this.expand_output();
489 482 }
490 483 }
491 484 }
492 485 };
493 486
494 487
495 488 CodeCell.prototype.toJSON = function () {
496 489 var data = Cell.prototype.toJSON.apply(this);
497 data.input = this.get_text();
490 data.source = this.get_text();
498 491 // is finite protect against undefined and '*' value
499 492 if (isFinite(this.input_prompt_number)) {
500 data.prompt_number = this.input_prompt_number;
493 data.execution_count = this.input_prompt_number;
494 } else {
495 data.execution_count = null;
501 496 }
502 497 var outputs = this.output_area.toJSON();
503 498 data.outputs = outputs;
504 data.language = 'python';
505 499 data.metadata.trusted = this.output_area.trusted;
506 data.collapsed = this.output_area.collapsed;
500 data.metadata.collapsed = this.output_area.collapsed;
507 501 return data;
508 502 };
509 503
510 504 /**
511 505 * handle cell level logic when a cell is unselected
512 506 * @method unselect
513 507 * @return is the action being taken
514 508 */
515 509 CodeCell.prototype.unselect = function () {
516 510 var cont = Cell.prototype.unselect.apply(this);
517 511 if (cont) {
518 512 // When a code cell is usnelected, make sure that the corresponding
519 513 // tooltip and completer to that cell is closed.
520 514 this.tooltip.remove_and_cancel_tooltip(true);
521 515 if (this.completer !== null) {
522 516 this.completer.close();
523 517 }
524 518 }
525 519 return cont;
526 520 };
527 521
528 522 // Backwards compatability.
529 523 IPython.CodeCell = CodeCell;
530 524
531 525 return {'CodeCell': CodeCell};
532 526 });
@@ -1,226 +1,214 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'notebook/js/toolbar',
8 8 'notebook/js/celltoolbar',
9 9 ], function(IPython, $, toolbar, celltoolbar) {
10 10 "use strict";
11 11
12 12 var MainToolBar = function (selector, options) {
13 13 // Constructor
14 14 //
15 15 // Parameters:
16 16 // selector: string
17 17 // options: dictionary
18 18 // Dictionary of keyword arguments.
19 19 // events: $(Events) instance
20 20 // notebook: Notebook instance
21 21 toolbar.ToolBar.apply(this, arguments);
22 22 this.events = options.events;
23 23 this.notebook = options.notebook;
24 24 this.construct();
25 25 this.add_celltype_list();
26 26 this.add_celltoolbar_list();
27 27 this.bind_events();
28 28 };
29 29
30 30 MainToolBar.prototype = Object.create(toolbar.ToolBar.prototype);
31 31
32 32 MainToolBar.prototype.construct = function () {
33 33 var that = this;
34 34 this.add_buttons_group([
35 35 {
36 36 id : 'save_b',
37 37 label : 'Save and Checkpoint',
38 38 icon : 'fa-save',
39 39 callback : function () {
40 40 that.notebook.save_checkpoint();
41 41 }
42 42 }
43 43 ]);
44 44
45 45 this.add_buttons_group([
46 46 {
47 47 id : 'insert_below_b',
48 48 label : 'Insert Cell Below',
49 49 icon : 'fa-plus',
50 50 callback : function () {
51 51 that.notebook.insert_cell_below('code');
52 52 that.notebook.select_next();
53 53 that.notebook.focus_cell();
54 54 }
55 55 }
56 56 ],'insert_above_below');
57 57
58 58 this.add_buttons_group([
59 59 {
60 60 id : 'cut_b',
61 61 label : 'Cut Cell',
62 62 icon : 'fa-cut',
63 63 callback : function () {
64 64 that.notebook.cut_cell();
65 65 }
66 66 },
67 67 {
68 68 id : 'copy_b',
69 69 label : 'Copy Cell',
70 70 icon : 'fa-copy',
71 71 callback : function () {
72 72 that.notebook.copy_cell();
73 73 }
74 74 },
75 75 {
76 76 id : 'paste_b',
77 77 label : 'Paste Cell Below',
78 78 icon : 'fa-paste',
79 79 callback : function () {
80 80 that.notebook.paste_cell_below();
81 81 }
82 82 }
83 83 ],'cut_copy_paste');
84 84
85 85 this.add_buttons_group([
86 86 {
87 87 id : 'move_up_b',
88 88 label : 'Move Cell Up',
89 89 icon : 'fa-arrow-up',
90 90 callback : function () {
91 91 that.notebook.move_cell_up();
92 92 }
93 93 },
94 94 {
95 95 id : 'move_down_b',
96 96 label : 'Move Cell Down',
97 97 icon : 'fa-arrow-down',
98 98 callback : function () {
99 99 that.notebook.move_cell_down();
100 100 }
101 101 }
102 102 ],'move_up_down');
103 103
104 104
105 105 this.add_buttons_group([
106 106 {
107 107 id : 'run_b',
108 108 label : 'Run Cell',
109 109 icon : 'fa-play',
110 110 callback : function () {
111 111 // emulate default shift-enter behavior
112 112 that.notebook.execute_cell_and_select_below();
113 113 }
114 114 },
115 115 {
116 116 id : 'interrupt_b',
117 117 label : 'Interrupt',
118 118 icon : 'fa-stop',
119 119 callback : function () {
120 120 that.notebook.kernel.interrupt();
121 121 }
122 122 },
123 123 {
124 124 id : 'repeat_b',
125 125 label : 'Restart Kernel',
126 126 icon : 'fa-repeat',
127 127 callback : function () {
128 128 that.notebook.restart_kernel();
129 129 }
130 130 }
131 131 ],'run_int');
132 132 };
133 133
134 134 MainToolBar.prototype.add_celltype_list = function () {
135 135 this.element
136 136 .append($('<select/>')
137 137 .attr('id','cell_type')
138 138 .addClass('form-control select-xs')
139 139 .append($('<option/>').attr('value','code').text('Code'))
140 140 .append($('<option/>').attr('value','markdown').text('Markdown'))
141 141 .append($('<option/>').attr('value','raw').text('Raw NBConvert'))
142 .append($('<option/>').attr('value','heading1').text('Heading 1'))
143 .append($('<option/>').attr('value','heading2').text('Heading 2'))
144 .append($('<option/>').attr('value','heading3').text('Heading 3'))
145 .append($('<option/>').attr('value','heading4').text('Heading 4'))
146 .append($('<option/>').attr('value','heading5').text('Heading 5'))
147 .append($('<option/>').attr('value','heading6').text('Heading 6'))
148 142 );
149 143 };
150 144
151 145 MainToolBar.prototype.add_celltoolbar_list = function () {
152 146 var label = $('<span/>').addClass("navbar-text").text('Cell Toolbar:');
153 147 var select = $('<select/>')
154 148 .attr('id', 'ctb_select')
155 149 .addClass('form-control select-xs')
156 150 .append($('<option/>').attr('value', '').text('None'));
157 151 this.element.append(label).append(select);
158 152 var that = this;
159 153 select.change(function() {
160 154 var val = $(this).val();
161 155 if (val ==='') {
162 156 celltoolbar.CellToolbar.global_hide();
163 157 delete that.notebook.metadata.celltoolbar;
164 158 } else {
165 159 celltoolbar.CellToolbar.global_show();
166 160 celltoolbar.CellToolbar.activate_preset(val, that.events);
167 161 that.notebook.metadata.celltoolbar = val;
168 162 }
169 163 });
170 164 // Setup the currently registered presets.
171 165 var presets = celltoolbar.CellToolbar.list_presets();
172 166 for (var i=0; i<presets.length; i++) {
173 167 var name = presets[i];
174 168 select.append($('<option/>').attr('value', name).text(name));
175 169 }
176 170 // Setup future preset registrations.
177 171 this.events.on('preset_added.CellToolbar', function (event, data) {
178 172 var name = data.name;
179 173 select.append($('<option/>').attr('value', name).text(name));
180 174 });
181 175 // Update select value when a preset is activated.
182 176 this.events.on('preset_activated.CellToolbar', function (event, data) {
183 177 if (select.val() !== data.name)
184 178 select.val(data.name);
185 179 });
186 180 };
187 181
188 182 MainToolBar.prototype.bind_events = function () {
189 183 var that = this;
190 184
191 185 this.element.find('#cell_type').change(function () {
192 186 var cell_type = $(this).val();
193 if (cell_type === 'code') {
187 switch (cell_type) {
188 case 'code':
194 189 that.notebook.to_code();
195 } else if (cell_type === 'markdown') {
190 break;
191 case 'markdown':
196 192 that.notebook.to_markdown();
197 } else if (cell_type === 'raw') {
193 break;
194 case 'raw':
198 195 that.notebook.to_raw();
199 } else if (cell_type === 'heading1') {
200 that.notebook.to_heading(undefined, 1);
201 } else if (cell_type === 'heading2') {
202 that.notebook.to_heading(undefined, 2);
203 } else if (cell_type === 'heading3') {
204 that.notebook.to_heading(undefined, 3);
205 } else if (cell_type === 'heading4') {
206 that.notebook.to_heading(undefined, 4);
207 } else if (cell_type === 'heading5') {
208 that.notebook.to_heading(undefined, 5);
209 } else if (cell_type === 'heading6') {
210 that.notebook.to_heading(undefined, 6);
196 break;
197 default:
198 console.log("unrecognized cell type:", cell_type);
211 199 }
212 200 });
213 201 this.events.on('selected_cell_type_changed.Notebook', function (event, data) {
214 202 if (data.cell_type === 'heading') {
215 203 that.element.find('#cell_type').val(data.cell_type+data.level);
216 204 } else {
217 205 that.element.find('#cell_type').val(data.cell_type);
218 206 }
219 207 });
220 208 };
221 209
222 210 // Backwards compatability.
223 211 IPython.MainToolBar = MainToolBar;
224 212
225 213 return {'MainToolBar': MainToolBar};
226 214 });
@@ -1,2707 +1,2682 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jquery',
7 7 'base/js/utils',
8 8 'base/js/dialog',
9 9 'notebook/js/textcell',
10 10 'notebook/js/codecell',
11 11 'services/sessions/session',
12 12 'notebook/js/celltoolbar',
13 13 'components/marked/lib/marked',
14 14 'highlight',
15 15 'notebook/js/mathjaxutils',
16 16 'base/js/keyboard',
17 17 'notebook/js/tooltip',
18 18 'notebook/js/celltoolbarpresets/default',
19 19 'notebook/js/celltoolbarpresets/rawcell',
20 20 'notebook/js/celltoolbarpresets/slideshow',
21 21 'notebook/js/scrollmanager'
22 22 ], function (
23 23 IPython,
24 24 $,
25 25 utils,
26 26 dialog,
27 27 textcell,
28 28 codecell,
29 29 session,
30 30 celltoolbar,
31 31 marked,
32 32 hljs,
33 33 mathjaxutils,
34 34 keyboard,
35 35 tooltip,
36 36 default_celltoolbar,
37 37 rawcell_celltoolbar,
38 38 slideshow_celltoolbar,
39 39 scrollmanager
40 40 ) {
41 41
42 42 var Notebook = function (selector, options) {
43 43 // Constructor
44 44 //
45 45 // A notebook contains and manages cells.
46 46 //
47 47 // Parameters:
48 48 // selector: string
49 49 // options: dictionary
50 50 // Dictionary of keyword arguments.
51 51 // events: $(Events) instance
52 52 // keyboard_manager: KeyboardManager instance
53 53 // save_widget: SaveWidget instance
54 54 // config: dictionary
55 55 // base_url : string
56 56 // notebook_path : string
57 57 // notebook_name : string
58 58 this.config = utils.mergeopt(Notebook, options.config);
59 59 this.base_url = options.base_url;
60 60 this.notebook_path = options.notebook_path;
61 61 this.notebook_name = options.notebook_name;
62 62 this.events = options.events;
63 63 this.keyboard_manager = options.keyboard_manager;
64 64 this.save_widget = options.save_widget;
65 65 this.tooltip = new tooltip.Tooltip(this.events);
66 66 this.ws_url = options.ws_url;
67 67 this._session_starting = false;
68 68 this.default_cell_type = this.config.default_cell_type || 'code';
69 69
70 70 // Create default scroll manager.
71 71 this.scroll_manager = new scrollmanager.ScrollManager(this);
72 72
73 73 // TODO: This code smells (and the other `= this` line a couple lines down)
74 74 // We need a better way to deal with circular instance references.
75 75 this.keyboard_manager.notebook = this;
76 76 this.save_widget.notebook = this;
77 77
78 78 mathjaxutils.init();
79 79
80 80 if (marked) {
81 81 marked.setOptions({
82 82 gfm : true,
83 83 tables: true,
84 84 langPrefix: "language-",
85 85 highlight: function(code, lang) {
86 86 if (!lang) {
87 87 // no language, no highlight
88 88 return code;
89 89 }
90 90 var highlighted;
91 91 try {
92 92 highlighted = hljs.highlight(lang, code, false);
93 93 } catch(err) {
94 94 highlighted = hljs.highlightAuto(code);
95 95 }
96 96 return highlighted.value;
97 97 }
98 98 });
99 99 }
100 100
101 101 this.element = $(selector);
102 102 this.element.scroll();
103 103 this.element.data("notebook", this);
104 104 this.next_prompt_number = 1;
105 105 this.session = null;
106 106 this.kernel = null;
107 107 this.clipboard = null;
108 108 this.undelete_backup = null;
109 109 this.undelete_index = null;
110 110 this.undelete_below = false;
111 111 this.paste_enabled = false;
112 112 // It is important to start out in command mode to match the intial mode
113 113 // of the KeyboardManager.
114 114 this.mode = 'command';
115 115 this.set_dirty(false);
116 116 this.metadata = {};
117 117 this._checkpoint_after_save = false;
118 118 this.last_checkpoint = null;
119 119 this.checkpoints = [];
120 120 this.autosave_interval = 0;
121 121 this.autosave_timer = null;
122 122 // autosave *at most* every two minutes
123 123 this.minimum_autosave_interval = 120000;
124 // single worksheet for now
125 this.worksheet_metadata = {};
126 124 this.notebook_name_blacklist_re = /[\/\\:]/;
127 this.nbformat = 3; // Increment this when changing the nbformat
125 this.nbformat = 4; // Increment this when changing the nbformat
128 126 this.nbformat_minor = 0; // Increment this when changing the nbformat
129 127 this.codemirror_mode = 'ipython';
130 128 this.create_elements();
131 129 this.bind_events();
132 130 this.save_notebook = function() { // don't allow save until notebook_loaded
133 131 this.save_notebook_error(null, null, "Load failed, save is disabled");
134 132 };
135 133
136 134 // Trigger cell toolbar registration.
137 135 default_celltoolbar.register(this);
138 136 rawcell_celltoolbar.register(this);
139 137 slideshow_celltoolbar.register(this);
140 138 };
141 139
142 140 Notebook.options_default = {
143 141 // can be any cell type, or the special values of
144 142 // 'above', 'below', or 'selected' to get the value from another cell.
145 143 Notebook: {
146 144 default_cell_type: 'code',
147 145 }
148 146 };
149 147
150 148
151 149 /**
152 150 * Create an HTML and CSS representation of the notebook.
153 151 *
154 152 * @method create_elements
155 153 */
156 154 Notebook.prototype.create_elements = function () {
157 155 var that = this;
158 156 this.element.attr('tabindex','-1');
159 157 this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
160 158 // We add this end_space div to the end of the notebook div to:
161 159 // i) provide a margin between the last cell and the end of the notebook
162 160 // ii) to prevent the div from scrolling up when the last cell is being
163 161 // edited, but is too low on the page, which browsers will do automatically.
164 162 var end_space = $('<div/>').addClass('end_space');
165 163 end_space.dblclick(function (e) {
166 164 var ncells = that.ncells();
167 165 that.insert_cell_below('code',ncells-1);
168 166 });
169 167 this.element.append(this.container);
170 168 this.container.append(end_space);
171 169 };
172 170
173 171 /**
174 172 * Bind JavaScript events: key presses and custom IPython events.
175 173 *
176 174 * @method bind_events
177 175 */
178 176 Notebook.prototype.bind_events = function () {
179 177 var that = this;
180 178
181 179 this.events.on('set_next_input.Notebook', function (event, data) {
182 180 var index = that.find_cell_index(data.cell);
183 181 var new_cell = that.insert_cell_below('code',index);
184 182 new_cell.set_text(data.text);
185 183 that.dirty = true;
186 184 });
187 185
188 186 this.events.on('set_dirty.Notebook', function (event, data) {
189 187 that.dirty = data.value;
190 188 });
191 189
192 190 this.events.on('trust_changed.Notebook', function (event, trusted) {
193 191 that.trusted = trusted;
194 192 });
195 193
196 194 this.events.on('select.Cell', function (event, data) {
197 195 var index = that.find_cell_index(data.cell);
198 196 that.select(index);
199 197 });
200 198
201 199 this.events.on('edit_mode.Cell', function (event, data) {
202 200 that.handle_edit_mode(data.cell);
203 201 });
204 202
205 203 this.events.on('command_mode.Cell', function (event, data) {
206 204 that.handle_command_mode(data.cell);
207 205 });
208 206
209 207 this.events.on('spec_changed.Kernel', function(event, data) {
210 208 that.metadata.kernelspec =
211 209 {name: data.name, display_name: data.display_name};
212 210 });
213 211
214 212 this.events.on('kernel_ready.Kernel', function(event, data) {
215 213 var kinfo = data.kernel.info_reply
216 214 var langinfo = kinfo.language_info || {};
217 215 if (!langinfo.name) langinfo.name = kinfo.language;
218 216
219 217 that.metadata.language_info = langinfo;
220 218 // Mode 'null' should be plain, unhighlighted text.
221 219 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null'
222 220 that.set_codemirror_mode(cm_mode);
223 221 });
224 222
225 223 var collapse_time = function (time) {
226 224 var app_height = $('#ipython-main-app').height(); // content height
227 225 var splitter_height = $('div#pager_splitter').outerHeight(true);
228 226 var new_height = app_height - splitter_height;
229 227 that.element.animate({height : new_height + 'px'}, time);
230 228 };
231 229
232 230 this.element.bind('collapse_pager', function (event, extrap) {
233 231 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
234 232 collapse_time(time);
235 233 });
236 234
237 235 var expand_time = function (time) {
238 236 var app_height = $('#ipython-main-app').height(); // content height
239 237 var splitter_height = $('div#pager_splitter').outerHeight(true);
240 238 var pager_height = $('div#pager').outerHeight(true);
241 239 var new_height = app_height - pager_height - splitter_height;
242 240 that.element.animate({height : new_height + 'px'}, time);
243 241 };
244 242
245 243 this.element.bind('expand_pager', function (event, extrap) {
246 244 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
247 245 expand_time(time);
248 246 });
249 247
250 248 // Firefox 22 broke $(window).on("beforeunload")
251 249 // I'm not sure why or how.
252 250 window.onbeforeunload = function (e) {
253 251 // TODO: Make killing the kernel configurable.
254 252 var kill_kernel = false;
255 253 if (kill_kernel) {
256 254 that.session.delete();
257 255 }
258 256 // if we are autosaving, trigger an autosave on nav-away.
259 257 // still warn, because if we don't the autosave may fail.
260 258 if (that.dirty) {
261 259 if ( that.autosave_interval ) {
262 260 // schedule autosave in a timeout
263 261 // this gives you a chance to forcefully discard changes
264 262 // by reloading the page if you *really* want to.
265 263 // the timer doesn't start until you *dismiss* the dialog.
266 264 setTimeout(function () {
267 265 if (that.dirty) {
268 266 that.save_notebook();
269 267 }
270 268 }, 1000);
271 269 return "Autosave in progress, latest changes may be lost.";
272 270 } else {
273 271 return "Unsaved changes will be lost.";
274 272 }
275 273 }
276 274 // Null is the *only* return value that will make the browser not
277 275 // pop up the "don't leave" dialog.
278 276 return null;
279 277 };
280 278 };
281 279
282 280 /**
283 281 * Set the dirty flag, and trigger the set_dirty.Notebook event
284 282 *
285 283 * @method set_dirty
286 284 */
287 285 Notebook.prototype.set_dirty = function (value) {
288 286 if (value === undefined) {
289 287 value = true;
290 288 }
291 289 if (this.dirty == value) {
292 290 return;
293 291 }
294 292 this.events.trigger('set_dirty.Notebook', {value: value});
295 293 };
296 294
297 295 /**
298 296 * Scroll the top of the page to a given cell.
299 297 *
300 298 * @method scroll_to_cell
301 299 * @param {Number} cell_number An index of the cell to view
302 300 * @param {Number} time Animation time in milliseconds
303 301 * @return {Number} Pixel offset from the top of the container
304 302 */
305 303 Notebook.prototype.scroll_to_cell = function (cell_number, time) {
306 304 var cells = this.get_cells();
307 305 time = time || 0;
308 306 cell_number = Math.min(cells.length-1,cell_number);
309 307 cell_number = Math.max(0 ,cell_number);
310 308 var scroll_value = cells[cell_number].element.position().top-cells[0].element.position().top ;
311 309 this.element.animate({scrollTop:scroll_value}, time);
312 310 return scroll_value;
313 311 };
314 312
315 313 /**
316 314 * Scroll to the bottom of the page.
317 315 *
318 316 * @method scroll_to_bottom
319 317 */
320 318 Notebook.prototype.scroll_to_bottom = function () {
321 319 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
322 320 };
323 321
324 322 /**
325 323 * Scroll to the top of the page.
326 324 *
327 325 * @method scroll_to_top
328 326 */
329 327 Notebook.prototype.scroll_to_top = function () {
330 328 this.element.animate({scrollTop:0}, 0);
331 329 };
332 330
333 331 // Edit Notebook metadata
334 332
335 333 Notebook.prototype.edit_metadata = function () {
336 334 var that = this;
337 335 dialog.edit_metadata({
338 336 md: this.metadata,
339 337 callback: function (md) {
340 338 that.metadata = md;
341 339 },
342 340 name: 'Notebook',
343 341 notebook: this,
344 342 keyboard_manager: this.keyboard_manager});
345 343 };
346 344
347 345 // Cell indexing, retrieval, etc.
348 346
349 347 /**
350 348 * Get all cell elements in the notebook.
351 349 *
352 350 * @method get_cell_elements
353 351 * @return {jQuery} A selector of all cell elements
354 352 */
355 353 Notebook.prototype.get_cell_elements = function () {
356 354 return this.container.children("div.cell");
357 355 };
358 356
359 357 /**
360 358 * Get a particular cell element.
361 359 *
362 360 * @method get_cell_element
363 361 * @param {Number} index An index of a cell to select
364 362 * @return {jQuery} A selector of the given cell.
365 363 */
366 364 Notebook.prototype.get_cell_element = function (index) {
367 365 var result = null;
368 366 var e = this.get_cell_elements().eq(index);
369 367 if (e.length !== 0) {
370 368 result = e;
371 369 }
372 370 return result;
373 371 };
374 372
375 373 /**
376 374 * Try to get a particular cell by msg_id.
377 375 *
378 376 * @method get_msg_cell
379 377 * @param {String} msg_id A message UUID
380 378 * @return {Cell} Cell or null if no cell was found.
381 379 */
382 380 Notebook.prototype.get_msg_cell = function (msg_id) {
383 381 return codecell.CodeCell.msg_cells[msg_id] || null;
384 382 };
385 383
386 384 /**
387 385 * Count the cells in this notebook.
388 386 *
389 387 * @method ncells
390 388 * @return {Number} The number of cells in this notebook
391 389 */
392 390 Notebook.prototype.ncells = function () {
393 391 return this.get_cell_elements().length;
394 392 };
395 393
396 394 /**
397 395 * Get all Cell objects in this notebook.
398 396 *
399 397 * @method get_cells
400 398 * @return {Array} This notebook's Cell objects
401 399 */
402 400 // TODO: we are often calling cells as cells()[i], which we should optimize
403 401 // to cells(i) or a new method.
404 402 Notebook.prototype.get_cells = function () {
405 403 return this.get_cell_elements().toArray().map(function (e) {
406 404 return $(e).data("cell");
407 405 });
408 406 };
409 407
410 408 /**
411 409 * Get a Cell object from this notebook.
412 410 *
413 411 * @method get_cell
414 412 * @param {Number} index An index of a cell to retrieve
415 413 * @return {Cell} Cell or null if no cell was found.
416 414 */
417 415 Notebook.prototype.get_cell = function (index) {
418 416 var result = null;
419 417 var ce = this.get_cell_element(index);
420 418 if (ce !== null) {
421 419 result = ce.data('cell');
422 420 }
423 421 return result;
424 422 };
425 423
426 424 /**
427 425 * Get the cell below a given cell.
428 426 *
429 427 * @method get_next_cell
430 428 * @param {Cell} cell The provided cell
431 429 * @return {Cell} the next cell or null if no cell was found.
432 430 */
433 431 Notebook.prototype.get_next_cell = function (cell) {
434 432 var result = null;
435 433 var index = this.find_cell_index(cell);
436 434 if (this.is_valid_cell_index(index+1)) {
437 435 result = this.get_cell(index+1);
438 436 }
439 437 return result;
440 438 };
441 439
442 440 /**
443 441 * Get the cell above a given cell.
444 442 *
445 443 * @method get_prev_cell
446 444 * @param {Cell} cell The provided cell
447 445 * @return {Cell} The previous cell or null if no cell was found.
448 446 */
449 447 Notebook.prototype.get_prev_cell = function (cell) {
450 448 var result = null;
451 449 var index = this.find_cell_index(cell);
452 450 if (index !== null && index > 0) {
453 451 result = this.get_cell(index-1);
454 452 }
455 453 return result;
456 454 };
457 455
458 456 /**
459 457 * Get the numeric index of a given cell.
460 458 *
461 459 * @method find_cell_index
462 460 * @param {Cell} cell The provided cell
463 461 * @return {Number} The cell's numeric index or null if no cell was found.
464 462 */
465 463 Notebook.prototype.find_cell_index = function (cell) {
466 464 var result = null;
467 465 this.get_cell_elements().filter(function (index) {
468 466 if ($(this).data("cell") === cell) {
469 467 result = index;
470 468 }
471 469 });
472 470 return result;
473 471 };
474 472
475 473 /**
476 474 * Get a given index , or the selected index if none is provided.
477 475 *
478 476 * @method index_or_selected
479 477 * @param {Number} index A cell's index
480 478 * @return {Number} The given index, or selected index if none is provided.
481 479 */
482 480 Notebook.prototype.index_or_selected = function (index) {
483 481 var i;
484 482 if (index === undefined || index === null) {
485 483 i = this.get_selected_index();
486 484 if (i === null) {
487 485 i = 0;
488 486 }
489 487 } else {
490 488 i = index;
491 489 }
492 490 return i;
493 491 };
494 492
495 493 /**
496 494 * Get the currently selected cell.
497 495 * @method get_selected_cell
498 496 * @return {Cell} The selected cell
499 497 */
500 498 Notebook.prototype.get_selected_cell = function () {
501 499 var index = this.get_selected_index();
502 500 return this.get_cell(index);
503 501 };
504 502
505 503 /**
506 504 * Check whether a cell index is valid.
507 505 *
508 506 * @method is_valid_cell_index
509 507 * @param {Number} index A cell index
510 508 * @return True if the index is valid, false otherwise
511 509 */
512 510 Notebook.prototype.is_valid_cell_index = function (index) {
513 511 if (index !== null && index >= 0 && index < this.ncells()) {
514 512 return true;
515 513 } else {
516 514 return false;
517 515 }
518 516 };
519 517
520 518 /**
521 519 * Get the index of the currently selected cell.
522 520
523 521 * @method get_selected_index
524 522 * @return {Number} The selected cell's numeric index
525 523 */
526 524 Notebook.prototype.get_selected_index = function () {
527 525 var result = null;
528 526 this.get_cell_elements().filter(function (index) {
529 527 if ($(this).data("cell").selected === true) {
530 528 result = index;
531 529 }
532 530 });
533 531 return result;
534 532 };
535 533
536 534
537 535 // Cell selection.
538 536
539 537 /**
540 538 * Programmatically select a cell.
541 539 *
542 540 * @method select
543 541 * @param {Number} index A cell's index
544 542 * @return {Notebook} This notebook
545 543 */
546 544 Notebook.prototype.select = function (index) {
547 545 if (this.is_valid_cell_index(index)) {
548 546 var sindex = this.get_selected_index();
549 547 if (sindex !== null && index !== sindex) {
550 548 // If we are about to select a different cell, make sure we are
551 549 // first in command mode.
552 550 if (this.mode !== 'command') {
553 551 this.command_mode();
554 552 }
555 553 this.get_cell(sindex).unselect();
556 554 }
557 555 var cell = this.get_cell(index);
558 556 cell.select();
559 557 if (cell.cell_type === 'heading') {
560 558 this.events.trigger('selected_cell_type_changed.Notebook',
561 559 {'cell_type':cell.cell_type,level:cell.level}
562 560 );
563 561 } else {
564 562 this.events.trigger('selected_cell_type_changed.Notebook',
565 563 {'cell_type':cell.cell_type}
566 564 );
567 565 }
568 566 }
569 567 return this;
570 568 };
571 569
572 570 /**
573 571 * Programmatically select the next cell.
574 572 *
575 573 * @method select_next
576 574 * @return {Notebook} This notebook
577 575 */
578 576 Notebook.prototype.select_next = function () {
579 577 var index = this.get_selected_index();
580 578 this.select(index+1);
581 579 return this;
582 580 };
583 581
584 582 /**
585 583 * Programmatically select the previous cell.
586 584 *
587 585 * @method select_prev
588 586 * @return {Notebook} This notebook
589 587 */
590 588 Notebook.prototype.select_prev = function () {
591 589 var index = this.get_selected_index();
592 590 this.select(index-1);
593 591 return this;
594 592 };
595 593
596 594
597 595 // Edit/Command mode
598 596
599 597 /**
600 598 * Gets the index of the cell that is in edit mode.
601 599 *
602 600 * @method get_edit_index
603 601 *
604 602 * @return index {int}
605 603 **/
606 604 Notebook.prototype.get_edit_index = function () {
607 605 var result = null;
608 606 this.get_cell_elements().filter(function (index) {
609 607 if ($(this).data("cell").mode === 'edit') {
610 608 result = index;
611 609 }
612 610 });
613 611 return result;
614 612 };
615 613
616 614 /**
617 615 * Handle when a a cell blurs and the notebook should enter command mode.
618 616 *
619 617 * @method handle_command_mode
620 618 * @param [cell] {Cell} Cell to enter command mode on.
621 619 **/
622 620 Notebook.prototype.handle_command_mode = function (cell) {
623 621 if (this.mode !== 'command') {
624 622 cell.command_mode();
625 623 this.mode = 'command';
626 624 this.events.trigger('command_mode.Notebook');
627 625 this.keyboard_manager.command_mode();
628 626 }
629 627 };
630 628
631 629 /**
632 630 * Make the notebook enter command mode.
633 631 *
634 632 * @method command_mode
635 633 **/
636 634 Notebook.prototype.command_mode = function () {
637 635 var cell = this.get_cell(this.get_edit_index());
638 636 if (cell && this.mode !== 'command') {
639 637 // We don't call cell.command_mode, but rather call cell.focus_cell()
640 638 // which will blur and CM editor and trigger the call to
641 639 // handle_command_mode.
642 640 cell.focus_cell();
643 641 }
644 642 };
645 643
646 644 /**
647 645 * Handle when a cell fires it's edit_mode event.
648 646 *
649 647 * @method handle_edit_mode
650 648 * @param [cell] {Cell} Cell to enter edit mode on.
651 649 **/
652 650 Notebook.prototype.handle_edit_mode = function (cell) {
653 651 if (cell && this.mode !== 'edit') {
654 652 cell.edit_mode();
655 653 this.mode = 'edit';
656 654 this.events.trigger('edit_mode.Notebook');
657 655 this.keyboard_manager.edit_mode();
658 656 }
659 657 };
660 658
661 659 /**
662 660 * Make a cell enter edit mode.
663 661 *
664 662 * @method edit_mode
665 663 **/
666 664 Notebook.prototype.edit_mode = function () {
667 665 var cell = this.get_selected_cell();
668 666 if (cell && this.mode !== 'edit') {
669 667 cell.unrender();
670 668 cell.focus_editor();
671 669 }
672 670 };
673 671
674 672 /**
675 673 * Focus the currently selected cell.
676 674 *
677 675 * @method focus_cell
678 676 **/
679 677 Notebook.prototype.focus_cell = function () {
680 678 var cell = this.get_selected_cell();
681 679 if (cell === null) {return;} // No cell is selected
682 680 cell.focus_cell();
683 681 };
684 682
685 683 // Cell movement
686 684
687 685 /**
688 686 * Move given (or selected) cell up and select it.
689 687 *
690 688 * @method move_cell_up
691 689 * @param [index] {integer} cell index
692 690 * @return {Notebook} This notebook
693 691 **/
694 692 Notebook.prototype.move_cell_up = function (index) {
695 693 var i = this.index_or_selected(index);
696 694 if (this.is_valid_cell_index(i) && i > 0) {
697 695 var pivot = this.get_cell_element(i-1);
698 696 var tomove = this.get_cell_element(i);
699 697 if (pivot !== null && tomove !== null) {
700 698 tomove.detach();
701 699 pivot.before(tomove);
702 700 this.select(i-1);
703 701 var cell = this.get_selected_cell();
704 702 cell.focus_cell();
705 703 }
706 704 this.set_dirty(true);
707 705 }
708 706 return this;
709 707 };
710 708
711 709
712 710 /**
713 711 * Move given (or selected) cell down and select it
714 712 *
715 713 * @method move_cell_down
716 714 * @param [index] {integer} cell index
717 715 * @return {Notebook} This notebook
718 716 **/
719 717 Notebook.prototype.move_cell_down = function (index) {
720 718 var i = this.index_or_selected(index);
721 719 if (this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
722 720 var pivot = this.get_cell_element(i+1);
723 721 var tomove = this.get_cell_element(i);
724 722 if (pivot !== null && tomove !== null) {
725 723 tomove.detach();
726 724 pivot.after(tomove);
727 725 this.select(i+1);
728 726 var cell = this.get_selected_cell();
729 727 cell.focus_cell();
730 728 }
731 729 }
732 730 this.set_dirty();
733 731 return this;
734 732 };
735 733
736 734
737 735 // Insertion, deletion.
738 736
739 737 /**
740 738 * Delete a cell from the notebook.
741 739 *
742 740 * @method delete_cell
743 741 * @param [index] A cell's numeric index
744 742 * @return {Notebook} This notebook
745 743 */
746 744 Notebook.prototype.delete_cell = function (index) {
747 745 var i = this.index_or_selected(index);
748 746 var cell = this.get_cell(i);
749 747 if (!cell.is_deletable()) {
750 748 return this;
751 749 }
752 750
753 751 this.undelete_backup = cell.toJSON();
754 752 $('#undelete_cell').removeClass('disabled');
755 753 if (this.is_valid_cell_index(i)) {
756 754 var old_ncells = this.ncells();
757 755 var ce = this.get_cell_element(i);
758 756 ce.remove();
759 757 if (i === 0) {
760 758 // Always make sure we have at least one cell.
761 759 if (old_ncells === 1) {
762 760 this.insert_cell_below('code');
763 761 }
764 762 this.select(0);
765 763 this.undelete_index = 0;
766 764 this.undelete_below = false;
767 765 } else if (i === old_ncells-1 && i !== 0) {
768 766 this.select(i-1);
769 767 this.undelete_index = i - 1;
770 768 this.undelete_below = true;
771 769 } else {
772 770 this.select(i);
773 771 this.undelete_index = i;
774 772 this.undelete_below = false;
775 773 }
776 774 this.events.trigger('delete.Cell', {'cell': cell, 'index': i});
777 775 this.set_dirty(true);
778 776 }
779 777 return this;
780 778 };
781 779
782 780 /**
783 781 * Restore the most recently deleted cell.
784 782 *
785 783 * @method undelete
786 784 */
787 785 Notebook.prototype.undelete_cell = function() {
788 786 if (this.undelete_backup !== null && this.undelete_index !== null) {
789 787 var current_index = this.get_selected_index();
790 788 if (this.undelete_index < current_index) {
791 789 current_index = current_index + 1;
792 790 }
793 791 if (this.undelete_index >= this.ncells()) {
794 792 this.select(this.ncells() - 1);
795 793 }
796 794 else {
797 795 this.select(this.undelete_index);
798 796 }
799 797 var cell_data = this.undelete_backup;
800 798 var new_cell = null;
801 799 if (this.undelete_below) {
802 800 new_cell = this.insert_cell_below(cell_data.cell_type);
803 801 } else {
804 802 new_cell = this.insert_cell_above(cell_data.cell_type);
805 803 }
806 804 new_cell.fromJSON(cell_data);
807 805 if (this.undelete_below) {
808 806 this.select(current_index+1);
809 807 } else {
810 808 this.select(current_index);
811 809 }
812 810 this.undelete_backup = null;
813 811 this.undelete_index = null;
814 812 }
815 813 $('#undelete_cell').addClass('disabled');
816 814 };
817 815
818 816 /**
819 817 * Insert a cell so that after insertion the cell is at given index.
820 818 *
821 819 * If cell type is not provided, it will default to the type of the
822 820 * currently active cell.
823 821 *
824 822 * Similar to insert_above, but index parameter is mandatory
825 823 *
826 824 * Index will be brought back into the accessible range [0,n]
827 825 *
828 826 * @method insert_cell_at_index
829 * @param [type] {string} in ['code','markdown','heading'], defaults to 'code'
827 * @param [type] {string} in ['code','markdown', 'raw'], defaults to 'code'
830 828 * @param [index] {int} a valid index where to insert cell
831 829 *
832 830 * @return cell {cell|null} created cell or null
833 831 **/
834 832 Notebook.prototype.insert_cell_at_index = function(type, index){
835 833
836 834 var ncells = this.ncells();
837 835 index = Math.min(index, ncells);
838 836 index = Math.max(index, 0);
839 837 var cell = null;
840 838 type = type || this.default_cell_type;
841 839 if (type === 'above') {
842 840 if (index > 0) {
843 841 type = this.get_cell(index-1).cell_type;
844 842 } else {
845 843 type = 'code';
846 844 }
847 845 } else if (type === 'below') {
848 846 if (index < ncells) {
849 847 type = this.get_cell(index).cell_type;
850 848 } else {
851 849 type = 'code';
852 850 }
853 851 } else if (type === 'selected') {
854 852 type = this.get_selected_cell().cell_type;
855 853 }
856 854
857 855 if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
858 856 var cell_options = {
859 857 events: this.events,
860 858 config: this.config,
861 859 keyboard_manager: this.keyboard_manager,
862 860 notebook: this,
863 861 tooltip: this.tooltip,
864 862 };
865 if (type === 'code') {
863 switch(type) {
864 case 'code':
866 865 cell = new codecell.CodeCell(this.kernel, cell_options);
867 866 cell.set_input_prompt();
868 } else if (type === 'markdown') {
867 break;
868 case 'markdown':
869 869 cell = new textcell.MarkdownCell(cell_options);
870 } else if (type === 'raw') {
870 break;
871 case 'raw':
871 872 cell = new textcell.RawCell(cell_options);
872 } else if (type === 'heading') {
873 cell = new textcell.HeadingCell(cell_options);
873 break;
874 default:
875 console.log("invalid cell type: ", type);
874 876 }
875 877
876 878 if(this._insert_element_at_index(cell.element,index)) {
877 879 cell.render();
878 880 this.events.trigger('create.Cell', {'cell': cell, 'index': index});
879 881 cell.refresh();
880 882 // We used to select the cell after we refresh it, but there
881 883 // are now cases were this method is called where select is
882 884 // not appropriate. The selection logic should be handled by the
883 885 // caller of the the top level insert_cell methods.
884 886 this.set_dirty(true);
885 887 }
886 888 }
887 889 return cell;
888 890
889 891 };
890 892
891 893 /**
892 894 * Insert an element at given cell index.
893 895 *
894 896 * @method _insert_element_at_index
895 897 * @param element {dom_element} a cell element
896 898 * @param [index] {int} a valid index where to inser cell
897 899 * @private
898 900 *
899 901 * return true if everything whent fine.
900 902 **/
901 903 Notebook.prototype._insert_element_at_index = function(element, index){
902 904 if (element === undefined){
903 905 return false;
904 906 }
905 907
906 908 var ncells = this.ncells();
907 909
908 910 if (ncells === 0) {
909 911 // special case append if empty
910 912 this.element.find('div.end_space').before(element);
911 913 } else if ( ncells === index ) {
912 914 // special case append it the end, but not empty
913 915 this.get_cell_element(index-1).after(element);
914 916 } else if (this.is_valid_cell_index(index)) {
915 917 // otherwise always somewhere to append to
916 918 this.get_cell_element(index).before(element);
917 919 } else {
918 920 return false;
919 921 }
920 922
921 923 if (this.undelete_index !== null && index <= this.undelete_index) {
922 924 this.undelete_index = this.undelete_index + 1;
923 925 this.set_dirty(true);
924 926 }
925 927 return true;
926 928 };
927 929
928 930 /**
929 931 * Insert a cell of given type above given index, or at top
930 932 * of notebook if index smaller than 0.
931 933 *
932 934 * default index value is the one of currently selected cell
933 935 *
934 936 * @method insert_cell_above
935 937 * @param [type] {string} cell type
936 938 * @param [index] {integer}
937 939 *
938 940 * @return handle to created cell or null
939 941 **/
940 942 Notebook.prototype.insert_cell_above = function (type, index) {
941 943 index = this.index_or_selected(index);
942 944 return this.insert_cell_at_index(type, index);
943 945 };
944 946
945 947 /**
946 948 * Insert a cell of given type below given index, or at bottom
947 949 * of notebook if index greater than number of cells
948 950 *
949 951 * default index value is the one of currently selected cell
950 952 *
951 953 * @method insert_cell_below
952 954 * @param [type] {string} cell type
953 955 * @param [index] {integer}
954 956 *
955 957 * @return handle to created cell or null
956 958 *
957 959 **/
958 960 Notebook.prototype.insert_cell_below = function (type, index) {
959 961 index = this.index_or_selected(index);
960 962 return this.insert_cell_at_index(type, index+1);
961 963 };
962 964
963 965
964 966 /**
965 967 * Insert cell at end of notebook
966 968 *
967 969 * @method insert_cell_at_bottom
968 970 * @param {String} type cell type
969 971 *
970 972 * @return the added cell; or null
971 973 **/
972 974 Notebook.prototype.insert_cell_at_bottom = function (type){
973 975 var len = this.ncells();
974 976 return this.insert_cell_below(type,len-1);
975 977 };
976 978
977 979 /**
978 980 * Turn a cell into a code cell.
979 981 *
980 982 * @method to_code
981 983 * @param {Number} [index] A cell's index
982 984 */
983 985 Notebook.prototype.to_code = function (index) {
984 986 var i = this.index_or_selected(index);
985 987 if (this.is_valid_cell_index(i)) {
986 988 var source_cell = this.get_cell(i);
987 989 if (!(source_cell instanceof codecell.CodeCell)) {
988 990 var target_cell = this.insert_cell_below('code',i);
989 991 var text = source_cell.get_text();
990 992 if (text === source_cell.placeholder) {
991 993 text = '';
992 994 }
993 995 //metadata
994 996 target_cell.metadata = source_cell.metadata;
995 997
996 998 target_cell.set_text(text);
997 999 // make this value the starting point, so that we can only undo
998 1000 // to this state, instead of a blank cell
999 1001 target_cell.code_mirror.clearHistory();
1000 1002 source_cell.element.remove();
1001 1003 this.select(i);
1002 1004 var cursor = source_cell.code_mirror.getCursor();
1003 1005 target_cell.code_mirror.setCursor(cursor);
1004 1006 this.set_dirty(true);
1005 1007 }
1006 1008 }
1007 1009 };
1008 1010
1009 1011 /**
1010 1012 * Turn a cell into a Markdown cell.
1011 1013 *
1012 1014 * @method to_markdown
1013 1015 * @param {Number} [index] A cell's index
1014 1016 */
1015 1017 Notebook.prototype.to_markdown = function (index) {
1016 1018 var i = this.index_or_selected(index);
1017 1019 if (this.is_valid_cell_index(i)) {
1018 1020 var source_cell = this.get_cell(i);
1019 1021
1020 1022 if (!(source_cell instanceof textcell.MarkdownCell)) {
1021 1023 var target_cell = this.insert_cell_below('markdown',i);
1022 1024 var text = source_cell.get_text();
1023 1025
1024 1026 if (text === source_cell.placeholder) {
1025 1027 text = '';
1026 1028 }
1027 1029 // metadata
1028 1030 target_cell.metadata = source_cell.metadata
1029 1031 // We must show the editor before setting its contents
1030 1032 target_cell.unrender();
1031 1033 target_cell.set_text(text);
1032 1034 // make this value the starting point, so that we can only undo
1033 1035 // to this state, instead of a blank cell
1034 1036 target_cell.code_mirror.clearHistory();
1035 1037 source_cell.element.remove();
1036 1038 this.select(i);
1037 1039 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1038 1040 target_cell.render();
1039 1041 }
1040 1042 var cursor = source_cell.code_mirror.getCursor();
1041 1043 target_cell.code_mirror.setCursor(cursor);
1042 1044 this.set_dirty(true);
1043 1045 }
1044 1046 }
1045 1047 };
1046 1048
1047 1049 /**
1048 1050 * Turn a cell into a raw text cell.
1049 1051 *
1050 1052 * @method to_raw
1051 1053 * @param {Number} [index] A cell's index
1052 1054 */
1053 1055 Notebook.prototype.to_raw = function (index) {
1054 1056 var i = this.index_or_selected(index);
1055 1057 if (this.is_valid_cell_index(i)) {
1056 1058 var target_cell = null;
1057 1059 var source_cell = this.get_cell(i);
1058 1060
1059 1061 if (!(source_cell instanceof textcell.RawCell)) {
1060 1062 target_cell = this.insert_cell_below('raw',i);
1061 1063 var text = source_cell.get_text();
1062 1064 if (text === source_cell.placeholder) {
1063 1065 text = '';
1064 1066 }
1065 1067 //metadata
1066 1068 target_cell.metadata = source_cell.metadata;
1067 1069 // We must show the editor before setting its contents
1068 1070 target_cell.unrender();
1069 1071 target_cell.set_text(text);
1070 1072 // make this value the starting point, so that we can only undo
1071 1073 // to this state, instead of a blank cell
1072 1074 target_cell.code_mirror.clearHistory();
1073 1075 source_cell.element.remove();
1074 1076 this.select(i);
1075 1077 var cursor = source_cell.code_mirror.getCursor();
1076 1078 target_cell.code_mirror.setCursor(cursor);
1077 1079 this.set_dirty(true);
1078 1080 }
1079 1081 }
1080 1082 };
1081 1083
1082 1084 /**
1083 1085 * Turn a cell into a heading cell.
1084 1086 *
1085 1087 * @method to_heading
1086 1088 * @param {Number} [index] A cell's index
1087 1089 * @param {Number} [level] A heading level (e.g., 1 becomes &lt;h1&gt;)
1088 1090 */
1089 1091 Notebook.prototype.to_heading = function (index, level) {
1090 1092 level = level || 1;
1091 1093 var i = this.index_or_selected(index);
1092 1094 if (this.is_valid_cell_index(i)) {
1093 1095 var source_cell = this.get_cell(i);
1094 1096 var target_cell = null;
1095 if (source_cell instanceof textcell.HeadingCell) {
1096 source_cell.set_level(level);
1097 if (source_cell instanceof textcell.MarkdownCell) {
1098 source_cell.set_heading_level(level);
1097 1099 } else {
1098 target_cell = this.insert_cell_below('heading',i);
1100 target_cell = this.insert_cell_below('markdown',i);
1099 1101 var text = source_cell.get_text();
1100 1102 if (text === source_cell.placeholder) {
1101 1103 text = '';
1102 1104 }
1103 1105 //metadata
1104 1106 target_cell.metadata = source_cell.metadata;
1105 1107 // We must show the editor before setting its contents
1106 target_cell.set_level(level);
1107 1108 target_cell.unrender();
1108 1109 target_cell.set_text(text);
1110 target_cell.set_heading_level(level);
1109 1111 // make this value the starting point, so that we can only undo
1110 1112 // to this state, instead of a blank cell
1111 1113 target_cell.code_mirror.clearHistory();
1112 1114 source_cell.element.remove();
1113 1115 this.select(i);
1114 1116 var cursor = source_cell.code_mirror.getCursor();
1115 1117 target_cell.code_mirror.setCursor(cursor);
1116 1118 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1117 1119 target_cell.render();
1118 1120 }
1119 1121 }
1120 1122 this.set_dirty(true);
1121 1123 this.events.trigger('selected_cell_type_changed.Notebook',
1122 {'cell_type':'heading',level:level}
1124 {'cell_type':'markdown',level:level}
1123 1125 );
1124 1126 }
1125 1127 };
1126 1128
1127 1129
1128 1130 // Cut/Copy/Paste
1129 1131
1130 1132 /**
1131 1133 * Enable UI elements for pasting cells.
1132 1134 *
1133 1135 * @method enable_paste
1134 1136 */
1135 1137 Notebook.prototype.enable_paste = function () {
1136 1138 var that = this;
1137 1139 if (!this.paste_enabled) {
1138 1140 $('#paste_cell_replace').removeClass('disabled')
1139 1141 .on('click', function () {that.paste_cell_replace();});
1140 1142 $('#paste_cell_above').removeClass('disabled')
1141 1143 .on('click', function () {that.paste_cell_above();});
1142 1144 $('#paste_cell_below').removeClass('disabled')
1143 1145 .on('click', function () {that.paste_cell_below();});
1144 1146 this.paste_enabled = true;
1145 1147 }
1146 1148 };
1147 1149
1148 1150 /**
1149 1151 * Disable UI elements for pasting cells.
1150 1152 *
1151 1153 * @method disable_paste
1152 1154 */
1153 1155 Notebook.prototype.disable_paste = function () {
1154 1156 if (this.paste_enabled) {
1155 1157 $('#paste_cell_replace').addClass('disabled').off('click');
1156 1158 $('#paste_cell_above').addClass('disabled').off('click');
1157 1159 $('#paste_cell_below').addClass('disabled').off('click');
1158 1160 this.paste_enabled = false;
1159 1161 }
1160 1162 };
1161 1163
1162 1164 /**
1163 1165 * Cut a cell.
1164 1166 *
1165 1167 * @method cut_cell
1166 1168 */
1167 1169 Notebook.prototype.cut_cell = function () {
1168 1170 this.copy_cell();
1169 1171 this.delete_cell();
1170 1172 };
1171 1173
1172 1174 /**
1173 1175 * Copy a cell.
1174 1176 *
1175 1177 * @method copy_cell
1176 1178 */
1177 1179 Notebook.prototype.copy_cell = function () {
1178 1180 var cell = this.get_selected_cell();
1179 1181 this.clipboard = cell.toJSON();
1180 1182 // remove undeletable status from the copied cell
1181 1183 if (this.clipboard.metadata.deletable !== undefined) {
1182 1184 delete this.clipboard.metadata.deletable;
1183 1185 }
1184 1186 this.enable_paste();
1185 1187 };
1186 1188
1187 1189 /**
1188 1190 * Replace the selected cell with a cell in the clipboard.
1189 1191 *
1190 1192 * @method paste_cell_replace
1191 1193 */
1192 1194 Notebook.prototype.paste_cell_replace = function () {
1193 1195 if (this.clipboard !== null && this.paste_enabled) {
1194 1196 var cell_data = this.clipboard;
1195 1197 var new_cell = this.insert_cell_above(cell_data.cell_type);
1196 1198 new_cell.fromJSON(cell_data);
1197 1199 var old_cell = this.get_next_cell(new_cell);
1198 1200 this.delete_cell(this.find_cell_index(old_cell));
1199 1201 this.select(this.find_cell_index(new_cell));
1200 1202 }
1201 1203 };
1202 1204
1203 1205 /**
1204 1206 * Paste a cell from the clipboard above the selected cell.
1205 1207 *
1206 1208 * @method paste_cell_above
1207 1209 */
1208 1210 Notebook.prototype.paste_cell_above = function () {
1209 1211 if (this.clipboard !== null && this.paste_enabled) {
1210 1212 var cell_data = this.clipboard;
1211 1213 var new_cell = this.insert_cell_above(cell_data.cell_type);
1212 1214 new_cell.fromJSON(cell_data);
1213 1215 new_cell.focus_cell();
1214 1216 }
1215 1217 };
1216 1218
1217 1219 /**
1218 1220 * Paste a cell from the clipboard below the selected cell.
1219 1221 *
1220 1222 * @method paste_cell_below
1221 1223 */
1222 1224 Notebook.prototype.paste_cell_below = function () {
1223 1225 if (this.clipboard !== null && this.paste_enabled) {
1224 1226 var cell_data = this.clipboard;
1225 1227 var new_cell = this.insert_cell_below(cell_data.cell_type);
1226 1228 new_cell.fromJSON(cell_data);
1227 1229 new_cell.focus_cell();
1228 1230 }
1229 1231 };
1230 1232
1231 1233 // Split/merge
1232 1234
1233 1235 /**
1234 1236 * Split the selected cell into two, at the cursor.
1235 1237 *
1236 1238 * @method split_cell
1237 1239 */
1238 1240 Notebook.prototype.split_cell = function () {
1239 1241 var mdc = textcell.MarkdownCell;
1240 1242 var rc = textcell.RawCell;
1241 1243 var cell = this.get_selected_cell();
1242 1244 if (cell.is_splittable()) {
1243 1245 var texta = cell.get_pre_cursor();
1244 1246 var textb = cell.get_post_cursor();
1245 1247 cell.set_text(textb);
1246 1248 var new_cell = this.insert_cell_above(cell.cell_type);
1247 1249 // Unrender the new cell so we can call set_text.
1248 1250 new_cell.unrender();
1249 1251 new_cell.set_text(texta);
1250 1252 }
1251 1253 };
1252 1254
1253 1255 /**
1254 1256 * Combine the selected cell into the cell above it.
1255 1257 *
1256 1258 * @method merge_cell_above
1257 1259 */
1258 1260 Notebook.prototype.merge_cell_above = function () {
1259 1261 var mdc = textcell.MarkdownCell;
1260 1262 var rc = textcell.RawCell;
1261 1263 var index = this.get_selected_index();
1262 1264 var cell = this.get_cell(index);
1263 1265 var render = cell.rendered;
1264 1266 if (!cell.is_mergeable()) {
1265 1267 return;
1266 1268 }
1267 1269 if (index > 0) {
1268 1270 var upper_cell = this.get_cell(index-1);
1269 1271 if (!upper_cell.is_mergeable()) {
1270 1272 return;
1271 1273 }
1272 1274 var upper_text = upper_cell.get_text();
1273 1275 var text = cell.get_text();
1274 1276 if (cell instanceof codecell.CodeCell) {
1275 1277 cell.set_text(upper_text+'\n'+text);
1276 1278 } else {
1277 1279 cell.unrender(); // Must unrender before we set_text.
1278 1280 cell.set_text(upper_text+'\n\n'+text);
1279 1281 if (render) {
1280 1282 // The rendered state of the final cell should match
1281 1283 // that of the original selected cell;
1282 1284 cell.render();
1283 1285 }
1284 1286 }
1285 1287 this.delete_cell(index-1);
1286 1288 this.select(this.find_cell_index(cell));
1287 1289 }
1288 1290 };
1289 1291
1290 1292 /**
1291 1293 * Combine the selected cell into the cell below it.
1292 1294 *
1293 1295 * @method merge_cell_below
1294 1296 */
1295 1297 Notebook.prototype.merge_cell_below = function () {
1296 1298 var mdc = textcell.MarkdownCell;
1297 1299 var rc = textcell.RawCell;
1298 1300 var index = this.get_selected_index();
1299 1301 var cell = this.get_cell(index);
1300 1302 var render = cell.rendered;
1301 1303 if (!cell.is_mergeable()) {
1302 1304 return;
1303 1305 }
1304 1306 if (index < this.ncells()-1) {
1305 1307 var lower_cell = this.get_cell(index+1);
1306 1308 if (!lower_cell.is_mergeable()) {
1307 1309 return;
1308 1310 }
1309 1311 var lower_text = lower_cell.get_text();
1310 1312 var text = cell.get_text();
1311 1313 if (cell instanceof codecell.CodeCell) {
1312 1314 cell.set_text(text+'\n'+lower_text);
1313 1315 } else {
1314 1316 cell.unrender(); // Must unrender before we set_text.
1315 1317 cell.set_text(text+'\n\n'+lower_text);
1316 1318 if (render) {
1317 1319 // The rendered state of the final cell should match
1318 1320 // that of the original selected cell;
1319 1321 cell.render();
1320 1322 }
1321 1323 }
1322 1324 this.delete_cell(index+1);
1323 1325 this.select(this.find_cell_index(cell));
1324 1326 }
1325 1327 };
1326 1328
1327 1329
1328 1330 // Cell collapsing and output clearing
1329 1331
1330 1332 /**
1331 1333 * Hide a cell's output.
1332 1334 *
1333 1335 * @method collapse_output
1334 1336 * @param {Number} index A cell's numeric index
1335 1337 */
1336 1338 Notebook.prototype.collapse_output = function (index) {
1337 1339 var i = this.index_or_selected(index);
1338 1340 var cell = this.get_cell(i);
1339 1341 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1340 1342 cell.collapse_output();
1341 1343 this.set_dirty(true);
1342 1344 }
1343 1345 };
1344 1346
1345 1347 /**
1346 1348 * Hide each code cell's output area.
1347 1349 *
1348 1350 * @method collapse_all_output
1349 1351 */
1350 1352 Notebook.prototype.collapse_all_output = function () {
1351 1353 $.map(this.get_cells(), function (cell, i) {
1352 1354 if (cell instanceof codecell.CodeCell) {
1353 1355 cell.collapse_output();
1354 1356 }
1355 1357 });
1356 1358 // this should not be set if the `collapse` key is removed from nbformat
1357 1359 this.set_dirty(true);
1358 1360 };
1359 1361
1360 1362 /**
1361 1363 * Show a cell's output.
1362 1364 *
1363 1365 * @method expand_output
1364 1366 * @param {Number} index A cell's numeric index
1365 1367 */
1366 1368 Notebook.prototype.expand_output = function (index) {
1367 1369 var i = this.index_or_selected(index);
1368 1370 var cell = this.get_cell(i);
1369 1371 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1370 1372 cell.expand_output();
1371 1373 this.set_dirty(true);
1372 1374 }
1373 1375 };
1374 1376
1375 1377 /**
1376 1378 * Expand each code cell's output area, and remove scrollbars.
1377 1379 *
1378 1380 * @method expand_all_output
1379 1381 */
1380 1382 Notebook.prototype.expand_all_output = function () {
1381 1383 $.map(this.get_cells(), function (cell, i) {
1382 1384 if (cell instanceof codecell.CodeCell) {
1383 1385 cell.expand_output();
1384 1386 }
1385 1387 });
1386 1388 // this should not be set if the `collapse` key is removed from nbformat
1387 1389 this.set_dirty(true);
1388 1390 };
1389 1391
1390 1392 /**
1391 1393 * Clear the selected CodeCell's output area.
1392 1394 *
1393 1395 * @method clear_output
1394 1396 * @param {Number} index A cell's numeric index
1395 1397 */
1396 1398 Notebook.prototype.clear_output = function (index) {
1397 1399 var i = this.index_or_selected(index);
1398 1400 var cell = this.get_cell(i);
1399 1401 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1400 1402 cell.clear_output();
1401 1403 this.set_dirty(true);
1402 1404 }
1403 1405 };
1404 1406
1405 1407 /**
1406 1408 * Clear each code cell's output area.
1407 1409 *
1408 1410 * @method clear_all_output
1409 1411 */
1410 1412 Notebook.prototype.clear_all_output = function () {
1411 1413 $.map(this.get_cells(), function (cell, i) {
1412 1414 if (cell instanceof codecell.CodeCell) {
1413 1415 cell.clear_output();
1414 1416 }
1415 1417 });
1416 1418 this.set_dirty(true);
1417 1419 };
1418 1420
1419 1421 /**
1420 1422 * Scroll the selected CodeCell's output area.
1421 1423 *
1422 1424 * @method scroll_output
1423 1425 * @param {Number} index A cell's numeric index
1424 1426 */
1425 1427 Notebook.prototype.scroll_output = function (index) {
1426 1428 var i = this.index_or_selected(index);
1427 1429 var cell = this.get_cell(i);
1428 1430 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1429 1431 cell.scroll_output();
1430 1432 this.set_dirty(true);
1431 1433 }
1432 1434 };
1433 1435
1434 1436 /**
1435 1437 * Expand each code cell's output area, and add a scrollbar for long output.
1436 1438 *
1437 1439 * @method scroll_all_output
1438 1440 */
1439 1441 Notebook.prototype.scroll_all_output = function () {
1440 1442 $.map(this.get_cells(), function (cell, i) {
1441 1443 if (cell instanceof codecell.CodeCell) {
1442 1444 cell.scroll_output();
1443 1445 }
1444 1446 });
1445 1447 // this should not be set if the `collapse` key is removed from nbformat
1446 1448 this.set_dirty(true);
1447 1449 };
1448 1450
1449 1451 /** Toggle whether a cell's output is collapsed or expanded.
1450 1452 *
1451 1453 * @method toggle_output
1452 1454 * @param {Number} index A cell's numeric index
1453 1455 */
1454 1456 Notebook.prototype.toggle_output = function (index) {
1455 1457 var i = this.index_or_selected(index);
1456 1458 var cell = this.get_cell(i);
1457 1459 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1458 1460 cell.toggle_output();
1459 1461 this.set_dirty(true);
1460 1462 }
1461 1463 };
1462 1464
1463 1465 /**
1464 1466 * Hide/show the output of all cells.
1465 1467 *
1466 1468 * @method toggle_all_output
1467 1469 */
1468 1470 Notebook.prototype.toggle_all_output = function () {
1469 1471 $.map(this.get_cells(), function (cell, i) {
1470 1472 if (cell instanceof codecell.CodeCell) {
1471 1473 cell.toggle_output();
1472 1474 }
1473 1475 });
1474 1476 // this should not be set if the `collapse` key is removed from nbformat
1475 1477 this.set_dirty(true);
1476 1478 };
1477 1479
1478 1480 /**
1479 1481 * Toggle a scrollbar for long cell outputs.
1480 1482 *
1481 1483 * @method toggle_output_scroll
1482 1484 * @param {Number} index A cell's numeric index
1483 1485 */
1484 1486 Notebook.prototype.toggle_output_scroll = function (index) {
1485 1487 var i = this.index_or_selected(index);
1486 1488 var cell = this.get_cell(i);
1487 1489 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1488 1490 cell.toggle_output_scroll();
1489 1491 this.set_dirty(true);
1490 1492 }
1491 1493 };
1492 1494
1493 1495 /**
1494 1496 * Toggle the scrolling of long output on all cells.
1495 1497 *
1496 1498 * @method toggle_all_output_scrolling
1497 1499 */
1498 1500 Notebook.prototype.toggle_all_output_scroll = function () {
1499 1501 $.map(this.get_cells(), function (cell, i) {
1500 1502 if (cell instanceof codecell.CodeCell) {
1501 1503 cell.toggle_output_scroll();
1502 1504 }
1503 1505 });
1504 1506 // this should not be set if the `collapse` key is removed from nbformat
1505 1507 this.set_dirty(true);
1506 1508 };
1507 1509
1508 1510 // Other cell functions: line numbers, ...
1509 1511
1510 1512 /**
1511 1513 * Toggle line numbers in the selected cell's input area.
1512 1514 *
1513 1515 * @method cell_toggle_line_numbers
1514 1516 */
1515 1517 Notebook.prototype.cell_toggle_line_numbers = function() {
1516 1518 this.get_selected_cell().toggle_line_numbers();
1517 1519 };
1518 1520
1519 1521 /**
1520 1522 * Set the codemirror mode for all code cells, including the default for
1521 1523 * new code cells.
1522 1524 *
1523 1525 * @method set_codemirror_mode
1524 1526 */
1525 1527 Notebook.prototype.set_codemirror_mode = function(newmode){
1526 1528 if (newmode === this.codemirror_mode) {
1527 1529 return;
1528 1530 }
1529 1531 this.codemirror_mode = newmode;
1530 1532 codecell.CodeCell.options_default.cm_config.mode = newmode;
1531 modename = newmode.mode || newmode.name || newmode
1532
1533 modename = newmode.mode || newmode.name || newmode;
1534
1533 1535 that = this;
1534 1536 utils.requireCodeMirrorMode(modename, function () {
1535 1537 $.map(that.get_cells(), function(cell, i) {
1536 1538 if (cell.cell_type === 'code'){
1537 1539 cell.code_mirror.setOption('mode', newmode);
1538 1540 // This is currently redundant, because cm_config ends up as
1539 1541 // codemirror's own .options object, but I don't want to
1540 1542 // rely on that.
1541 1543 cell.cm_config.mode = newmode;
1542 1544 }
1543 1545 });
1544 })
1546 });
1545 1547 };
1546 1548
1547 1549 // Session related things
1548 1550
1549 1551 /**
1550 1552 * Start a new session and set it on each code cell.
1551 1553 *
1552 1554 * @method start_session
1553 1555 */
1554 1556 Notebook.prototype.start_session = function (kernel_name) {
1555 1557 var that = this;
1556 1558 if (this._session_starting) {
1557 1559 throw new session.SessionAlreadyStarting();
1558 1560 }
1559 1561 this._session_starting = true;
1560 1562
1561 1563 var options = {
1562 1564 base_url: this.base_url,
1563 1565 ws_url: this.ws_url,
1564 1566 notebook_path: this.notebook_path,
1565 1567 notebook_name: this.notebook_name,
1566 1568 kernel_name: kernel_name,
1567 1569 notebook: this
1568 1570 };
1569 1571
1570 1572 var success = $.proxy(this._session_started, this);
1571 1573 var failure = $.proxy(this._session_start_failed, this);
1572 1574
1573 1575 if (this.session !== null) {
1574 1576 this.session.restart(options, success, failure);
1575 1577 } else {
1576 1578 this.session = new session.Session(options);
1577 1579 this.session.start(success, failure);
1578 1580 }
1579 1581 };
1580 1582
1581 1583
1582 1584 /**
1583 1585 * Once a session is started, link the code cells to the kernel and pass the
1584 1586 * comm manager to the widget manager
1585 1587 *
1586 1588 */
1587 1589 Notebook.prototype._session_started = function (){
1588 1590 this._session_starting = false;
1589 1591 this.kernel = this.session.kernel;
1590 1592 var ncells = this.ncells();
1591 1593 for (var i=0; i<ncells; i++) {
1592 1594 var cell = this.get_cell(i);
1593 1595 if (cell instanceof codecell.CodeCell) {
1594 1596 cell.set_kernel(this.session.kernel);
1595 1597 }
1596 1598 }
1597 1599 };
1598 1600 Notebook.prototype._session_start_failed = function (jqxhr, status, error){
1599 1601 this._session_starting = false;
1600 1602 utils.log_ajax_error(jqxhr, status, error);
1601 1603 };
1602 1604
1603 1605 /**
1604 1606 * Prompt the user to restart the IPython kernel.
1605 1607 *
1606 1608 * @method restart_kernel
1607 1609 */
1608 1610 Notebook.prototype.restart_kernel = function () {
1609 1611 var that = this;
1610 1612 dialog.modal({
1611 1613 notebook: this,
1612 1614 keyboard_manager: this.keyboard_manager,
1613 1615 title : "Restart kernel or continue running?",
1614 1616 body : $("<p/>").text(
1615 1617 'Do you want to restart the current kernel? You will lose all variables defined in it.'
1616 1618 ),
1617 1619 buttons : {
1618 1620 "Continue running" : {},
1619 1621 "Restart" : {
1620 1622 "class" : "btn-danger",
1621 1623 "click" : function() {
1622 1624 that.kernel.restart();
1623 1625 }
1624 1626 }
1625 1627 }
1626 1628 });
1627 1629 };
1628 1630
1629 1631 /**
1630 1632 * Execute or render cell outputs and go into command mode.
1631 1633 *
1632 1634 * @method execute_cell
1633 1635 */
1634 1636 Notebook.prototype.execute_cell = function () {
1635 1637 // mode = shift, ctrl, alt
1636 1638 var cell = this.get_selected_cell();
1637 1639 var cell_index = this.find_cell_index(cell);
1638 1640
1639 1641 cell.execute();
1640 1642 this.command_mode();
1641 1643 this.set_dirty(true);
1642 1644 };
1643 1645
1644 1646 /**
1645 1647 * Execute or render cell outputs and insert a new cell below.
1646 1648 *
1647 1649 * @method execute_cell_and_insert_below
1648 1650 */
1649 1651 Notebook.prototype.execute_cell_and_insert_below = function () {
1650 1652 var cell = this.get_selected_cell();
1651 1653 var cell_index = this.find_cell_index(cell);
1652 1654
1653 1655 cell.execute();
1654 1656
1655 1657 // If we are at the end always insert a new cell and return
1656 1658 if (cell_index === (this.ncells()-1)) {
1657 1659 this.command_mode();
1658 1660 this.insert_cell_below();
1659 1661 this.select(cell_index+1);
1660 1662 this.edit_mode();
1661 1663 this.scroll_to_bottom();
1662 1664 this.set_dirty(true);
1663 1665 return;
1664 1666 }
1665 1667
1666 1668 this.command_mode();
1667 1669 this.insert_cell_below();
1668 1670 this.select(cell_index+1);
1669 1671 this.edit_mode();
1670 1672 this.set_dirty(true);
1671 1673 };
1672 1674
1673 1675 /**
1674 1676 * Execute or render cell outputs and select the next cell.
1675 1677 *
1676 1678 * @method execute_cell_and_select_below
1677 1679 */
1678 1680 Notebook.prototype.execute_cell_and_select_below = function () {
1679 1681
1680 1682 var cell = this.get_selected_cell();
1681 1683 var cell_index = this.find_cell_index(cell);
1682 1684
1683 1685 cell.execute();
1684 1686
1685 1687 // If we are at the end always insert a new cell and return
1686 1688 if (cell_index === (this.ncells()-1)) {
1687 1689 this.command_mode();
1688 1690 this.insert_cell_below();
1689 1691 this.select(cell_index+1);
1690 1692 this.edit_mode();
1691 1693 this.scroll_to_bottom();
1692 1694 this.set_dirty(true);
1693 1695 return;
1694 1696 }
1695 1697
1696 1698 this.command_mode();
1697 1699 this.select(cell_index+1);
1698 1700 this.focus_cell();
1699 1701 this.set_dirty(true);
1700 1702 };
1701 1703
1702 1704 /**
1703 1705 * Execute all cells below the selected cell.
1704 1706 *
1705 1707 * @method execute_cells_below
1706 1708 */
1707 1709 Notebook.prototype.execute_cells_below = function () {
1708 1710 this.execute_cell_range(this.get_selected_index(), this.ncells());
1709 1711 this.scroll_to_bottom();
1710 1712 };
1711 1713
1712 1714 /**
1713 1715 * Execute all cells above the selected cell.
1714 1716 *
1715 1717 * @method execute_cells_above
1716 1718 */
1717 1719 Notebook.prototype.execute_cells_above = function () {
1718 1720 this.execute_cell_range(0, this.get_selected_index());
1719 1721 };
1720 1722
1721 1723 /**
1722 1724 * Execute all cells.
1723 1725 *
1724 1726 * @method execute_all_cells
1725 1727 */
1726 1728 Notebook.prototype.execute_all_cells = function () {
1727 1729 this.execute_cell_range(0, this.ncells());
1728 1730 this.scroll_to_bottom();
1729 1731 };
1730 1732
1731 1733 /**
1732 1734 * Execute a contiguous range of cells.
1733 1735 *
1734 1736 * @method execute_cell_range
1735 1737 * @param {Number} start Index of the first cell to execute (inclusive)
1736 1738 * @param {Number} end Index of the last cell to execute (exclusive)
1737 1739 */
1738 1740 Notebook.prototype.execute_cell_range = function (start, end) {
1739 1741 this.command_mode();
1740 1742 for (var i=start; i<end; i++) {
1741 1743 this.select(i);
1742 1744 this.execute_cell();
1743 1745 }
1744 1746 };
1745 1747
1746 1748 // Persistance and loading
1747 1749
1748 1750 /**
1749 1751 * Getter method for this notebook's name.
1750 1752 *
1751 1753 * @method get_notebook_name
1752 1754 * @return {String} This notebook's name (excluding file extension)
1753 1755 */
1754 1756 Notebook.prototype.get_notebook_name = function () {
1755 1757 var nbname = this.notebook_name.substring(0,this.notebook_name.length-6);
1756 1758 return nbname;
1757 1759 };
1758 1760
1759 1761 /**
1760 1762 * Setter method for this notebook's name.
1761 1763 *
1762 1764 * @method set_notebook_name
1763 1765 * @param {String} name A new name for this notebook
1764 1766 */
1765 1767 Notebook.prototype.set_notebook_name = function (name) {
1766 1768 this.notebook_name = name;
1767 1769 };
1768 1770
1769 1771 /**
1770 1772 * Check that a notebook's name is valid.
1771 1773 *
1772 1774 * @method test_notebook_name
1773 1775 * @param {String} nbname A name for this notebook
1774 1776 * @return {Boolean} True if the name is valid, false if invalid
1775 1777 */
1776 1778 Notebook.prototype.test_notebook_name = function (nbname) {
1777 1779 nbname = nbname || '';
1778 1780 if (nbname.length>0 && !this.notebook_name_blacklist_re.test(nbname)) {
1779 1781 return true;
1780 1782 } else {
1781 1783 return false;
1782 1784 }
1783 1785 };
1784 1786
1785 1787 /**
1786 1788 * Load a notebook from JSON (.ipynb).
1787 1789 *
1788 * This currently handles one worksheet: others are deleted.
1789 *
1790 1790 * @method fromJSON
1791 1791 * @param {Object} data JSON representation of a notebook
1792 1792 */
1793 1793 Notebook.prototype.fromJSON = function (data) {
1794 1794
1795 1795 var content = data.content;
1796 1796 var ncells = this.ncells();
1797 1797 var i;
1798 1798 for (i=0; i<ncells; i++) {
1799 1799 // Always delete cell 0 as they get renumbered as they are deleted.
1800 1800 this.delete_cell(0);
1801 1801 }
1802 1802 // Save the metadata and name.
1803 1803 this.metadata = content.metadata;
1804 1804 this.notebook_name = data.name;
1805 1805 var trusted = true;
1806 1806
1807 1807 // Trigger an event changing the kernel spec - this will set the default
1808 1808 // codemirror mode
1809 1809 if (this.metadata.kernelspec !== undefined) {
1810 1810 this.events.trigger('spec_changed.Kernel', this.metadata.kernelspec);
1811 1811 }
1812 1812
1813 1813 // Set the codemirror mode from language_info metadata
1814 1814 if (this.metadata.language_info !== undefined) {
1815 1815 var langinfo = this.metadata.language_info;
1816 1816 // Mode 'null' should be plain, unhighlighted text.
1817 1817 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null'
1818 1818 this.set_codemirror_mode(cm_mode);
1819 1819 }
1820 1820
1821 // Only handle 1 worksheet for now.
1822 var worksheet = content.worksheets[0];
1823 if (worksheet !== undefined) {
1824 if (worksheet.metadata) {
1825 this.worksheet_metadata = worksheet.metadata;
1826 }
1827 var new_cells = worksheet.cells;
1828 ncells = new_cells.length;
1829 var cell_data = null;
1830 var new_cell = null;
1831 for (i=0; i<ncells; i++) {
1832 cell_data = new_cells[i];
1833 // VERSIONHACK: plaintext -> raw
1834 // handle never-released plaintext name for raw cells
1835 if (cell_data.cell_type === 'plaintext'){
1836 cell_data.cell_type = 'raw';
1837 }
1838
1839 new_cell = this.insert_cell_at_index(cell_data.cell_type, i);
1840 new_cell.fromJSON(cell_data);
1841 if (new_cell.cell_type == 'code' && !new_cell.output_area.trusted) {
1842 trusted = false;
1843 }
1821 var new_cells = content.cells;
1822 ncells = new_cells.length;
1823 var cell_data = null;
1824 var new_cell = null;
1825 for (i=0; i<ncells; i++) {
1826 cell_data = new_cells[i];
1827 new_cell = this.insert_cell_at_index(cell_data.cell_type, i);
1828 new_cell.fromJSON(cell_data);
1829 if (new_cell.cell_type == 'code' && !new_cell.output_area.trusted) {
1830 trusted = false;
1844 1831 }
1845 1832 }
1846 1833 if (trusted !== this.trusted) {
1847 1834 this.trusted = trusted;
1848 1835 this.events.trigger("trust_changed.Notebook", trusted);
1849 1836 }
1850 if (content.worksheets.length > 1) {
1851 dialog.modal({
1852 notebook: this,
1853 keyboard_manager: this.keyboard_manager,
1854 title : "Multiple worksheets",
1855 body : "This notebook has " + data.worksheets.length + " worksheets, " +
1856 "but this version of IPython can only handle the first. " +
1857 "If you save this notebook, worksheets after the first will be lost.",
1858 buttons : {
1859 OK : {
1860 class : "btn-danger"
1861 }
1862 }
1863 });
1864 }
1865 1837 };
1866 1838
1867 1839 /**
1868 1840 * Dump this notebook into a JSON-friendly object.
1869 1841 *
1870 1842 * @method toJSON
1871 1843 * @return {Object} A JSON-friendly representation of this notebook.
1872 1844 */
1873 1845 Notebook.prototype.toJSON = function () {
1846 // remove the conversion indicator, which only belongs in-memory
1847 delete this.metadata.orig_nbformat;
1848 delete this.metadata.orig_nbformat_minor;
1849
1874 1850 var cells = this.get_cells();
1875 1851 var ncells = cells.length;
1876 1852 var cell_array = new Array(ncells);
1877 1853 var trusted = true;
1878 1854 for (var i=0; i<ncells; i++) {
1879 1855 var cell = cells[i];
1880 1856 if (cell.cell_type == 'code' && !cell.output_area.trusted) {
1881 1857 trusted = false;
1882 1858 }
1883 1859 cell_array[i] = cell.toJSON();
1884 1860 }
1885 1861 var data = {
1886 // Only handle 1 worksheet for now.
1887 worksheets : [{
1888 cells: cell_array,
1889 metadata: this.worksheet_metadata
1890 }],
1862 cells: cell_array,
1891 1863 metadata : this.metadata
1892 1864 };
1893 1865 if (trusted != this.trusted) {
1894 1866 this.trusted = trusted;
1895 1867 this.events.trigger("trust_changed.Notebook", trusted);
1896 1868 }
1897 1869 return data;
1898 1870 };
1899 1871
1900 1872 /**
1901 1873 * Start an autosave timer, for periodically saving the notebook.
1902 1874 *
1903 1875 * @method set_autosave_interval
1904 1876 * @param {Integer} interval the autosave interval in milliseconds
1905 1877 */
1906 1878 Notebook.prototype.set_autosave_interval = function (interval) {
1907 1879 var that = this;
1908 1880 // clear previous interval, so we don't get simultaneous timers
1909 1881 if (this.autosave_timer) {
1910 1882 clearInterval(this.autosave_timer);
1911 1883 }
1912 1884
1913 1885 this.autosave_interval = this.minimum_autosave_interval = interval;
1914 1886 if (interval) {
1915 1887 this.autosave_timer = setInterval(function() {
1916 1888 if (that.dirty) {
1917 1889 that.save_notebook();
1918 1890 }
1919 1891 }, interval);
1920 1892 this.events.trigger("autosave_enabled.Notebook", interval);
1921 1893 } else {
1922 1894 this.autosave_timer = null;
1923 1895 this.events.trigger("autosave_disabled.Notebook");
1924 1896 }
1925 1897 };
1926 1898
1927 1899 /**
1928 1900 * Save this notebook on the server. This becomes a notebook instance's
1929 1901 * .save_notebook method *after* the entire notebook has been loaded.
1930 1902 *
1931 1903 * @method save_notebook
1932 1904 */
1933 1905 Notebook.prototype.save_notebook = function (extra_settings) {
1934 1906 // Create a JSON model to be sent to the server.
1935 1907 var model = {};
1936 1908 model.name = this.notebook_name;
1937 1909 model.path = this.notebook_path;
1938 1910 model.type = 'notebook';
1939 1911 model.format = 'json';
1940 1912 model.content = this.toJSON();
1941 1913 model.content.nbformat = this.nbformat;
1942 1914 model.content.nbformat_minor = this.nbformat_minor;
1943 1915 // time the ajax call for autosave tuning purposes.
1944 1916 var start = new Date().getTime();
1945 1917 // We do the call with settings so we can set cache to false.
1946 1918 var settings = {
1947 1919 processData : false,
1948 1920 cache : false,
1949 1921 type : "PUT",
1950 1922 data : JSON.stringify(model),
1951 1923 contentType: 'application/json',
1952 1924 dataType : "json",
1953 1925 success : $.proxy(this.save_notebook_success, this, start),
1954 1926 error : $.proxy(this.save_notebook_error, this)
1955 1927 };
1956 1928 if (extra_settings) {
1957 1929 for (var key in extra_settings) {
1958 1930 settings[key] = extra_settings[key];
1959 1931 }
1960 1932 }
1961 1933 this.events.trigger('notebook_saving.Notebook');
1962 1934 var url = utils.url_join_encode(
1963 1935 this.base_url,
1964 1936 'api/contents',
1965 1937 this.notebook_path,
1966 1938 this.notebook_name
1967 1939 );
1968 1940 $.ajax(url, settings);
1969 1941 };
1970 1942
1971 1943 /**
1972 1944 * Success callback for saving a notebook.
1973 1945 *
1974 1946 * @method save_notebook_success
1975 1947 * @param {Integer} start the time when the save request started
1976 1948 * @param {Object} data JSON representation of a notebook
1977 1949 * @param {String} status Description of response status
1978 1950 * @param {jqXHR} xhr jQuery Ajax object
1979 1951 */
1980 1952 Notebook.prototype.save_notebook_success = function (start, data, status, xhr) {
1981 1953 this.set_dirty(false);
1982 1954 if (data.message) {
1983 1955 // save succeeded, but validation failed.
1984 1956 var body = $("<div>");
1985 1957 var title = "Notebook validation failed";
1986 1958
1987 1959 body.append($("<p>").text(
1988 1960 "The save operation succeeded," +
1989 1961 " but the notebook does not appear to be valid." +
1990 1962 " The validation error was:"
1991 1963 )).append($("<div>").addClass("validation-error").append(
1992 1964 $("<pre>").text(data.message)
1993 1965 ));
1994 1966 dialog.modal({
1995 1967 notebook: this,
1996 1968 keyboard_manager: this.keyboard_manager,
1997 1969 title: title,
1998 1970 body: body,
1999 1971 buttons : {
2000 1972 OK : {
2001 1973 "class" : "btn-primary"
2002 1974 }
2003 1975 }
2004 1976 });
2005 1977 }
2006 1978 this.events.trigger('notebook_saved.Notebook');
2007 1979 this._update_autosave_interval(start);
2008 1980 if (this._checkpoint_after_save) {
2009 1981 this.create_checkpoint();
2010 1982 this._checkpoint_after_save = false;
2011 1983 }
2012 1984 };
2013 1985
2014 1986 /**
2015 1987 * update the autosave interval based on how long the last save took
2016 1988 *
2017 1989 * @method _update_autosave_interval
2018 1990 * @param {Integer} timestamp when the save request started
2019 1991 */
2020 1992 Notebook.prototype._update_autosave_interval = function (start) {
2021 1993 var duration = (new Date().getTime() - start);
2022 1994 if (this.autosave_interval) {
2023 1995 // new save interval: higher of 10x save duration or parameter (default 30 seconds)
2024 1996 var interval = Math.max(10 * duration, this.minimum_autosave_interval);
2025 1997 // round to 10 seconds, otherwise we will be setting a new interval too often
2026 1998 interval = 10000 * Math.round(interval / 10000);
2027 1999 // set new interval, if it's changed
2028 2000 if (interval != this.autosave_interval) {
2029 2001 this.set_autosave_interval(interval);
2030 2002 }
2031 2003 }
2032 2004 };
2033 2005
2034 2006 /**
2035 2007 * Failure callback for saving a notebook.
2036 2008 *
2037 2009 * @method save_notebook_error
2038 2010 * @param {jqXHR} xhr jQuery Ajax object
2039 2011 * @param {String} status Description of response status
2040 2012 * @param {String} error HTTP error message
2041 2013 */
2042 2014 Notebook.prototype.save_notebook_error = function (xhr, status, error) {
2043 2015 this.events.trigger('notebook_save_failed.Notebook', [xhr, status, error]);
2044 2016 };
2045 2017
2046 2018 /**
2047 2019 * Explicitly trust the output of this notebook.
2048 2020 *
2049 2021 * @method trust_notebook
2050 2022 */
2051 2023 Notebook.prototype.trust_notebook = function (extra_settings) {
2052 2024 var body = $("<div>").append($("<p>")
2053 2025 .text("A trusted IPython notebook may execute hidden malicious code ")
2054 2026 .append($("<strong>")
2055 2027 .append(
2056 2028 $("<em>").text("when you open it")
2057 2029 )
2058 2030 ).append(".").append(
2059 2031 " Selecting trust will immediately reload this notebook in a trusted state."
2060 2032 ).append(
2061 2033 " For more information, see the "
2062 2034 ).append($("<a>").attr("href", "http://ipython.org/ipython-doc/2/notebook/security.html")
2063 2035 .text("IPython security documentation")
2064 2036 ).append(".")
2065 2037 );
2066 2038
2067 2039 var nb = this;
2068 2040 dialog.modal({
2069 2041 notebook: this,
2070 2042 keyboard_manager: this.keyboard_manager,
2071 2043 title: "Trust this notebook?",
2072 2044 body: body,
2073 2045
2074 2046 buttons: {
2075 2047 Cancel : {},
2076 2048 Trust : {
2077 2049 class : "btn-danger",
2078 2050 click : function () {
2079 2051 var cells = nb.get_cells();
2080 2052 for (var i = 0; i < cells.length; i++) {
2081 2053 var cell = cells[i];
2082 2054 if (cell.cell_type == 'code') {
2083 2055 cell.output_area.trusted = true;
2084 2056 }
2085 2057 }
2086 2058 nb.events.on('notebook_saved.Notebook', function () {
2087 2059 window.location.reload();
2088 2060 });
2089 2061 nb.save_notebook();
2090 2062 }
2091 2063 }
2092 2064 }
2093 2065 });
2094 2066 };
2095 2067
2096 2068 Notebook.prototype.new_notebook = function(){
2097 2069 var path = this.notebook_path;
2098 2070 var base_url = this.base_url;
2099 2071 var settings = {
2100 2072 processData : false,
2101 2073 cache : false,
2102 2074 type : "POST",
2103 2075 dataType : "json",
2104 2076 async : false,
2105 2077 success : function (data, status, xhr){
2106 2078 var notebook_name = data.name;
2107 2079 window.open(
2108 2080 utils.url_join_encode(
2109 2081 base_url,
2110 2082 'notebooks',
2111 2083 path,
2112 2084 notebook_name
2113 2085 ),
2114 2086 '_blank'
2115 2087 );
2116 2088 },
2117 2089 error : utils.log_ajax_error,
2118 2090 };
2119 2091 var url = utils.url_join_encode(
2120 2092 base_url,
2121 2093 'api/contents',
2122 2094 path
2123 2095 );
2124 2096 $.ajax(url,settings);
2125 2097 };
2126 2098
2127 2099
2128 2100 Notebook.prototype.copy_notebook = function(){
2129 2101 var path = this.notebook_path;
2130 2102 var base_url = this.base_url;
2131 2103 var settings = {
2132 2104 processData : false,
2133 2105 cache : false,
2134 2106 type : "POST",
2135 2107 dataType : "json",
2136 2108 data : JSON.stringify({copy_from : this.notebook_name}),
2137 2109 async : false,
2138 2110 success : function (data, status, xhr) {
2139 2111 window.open(utils.url_join_encode(
2140 2112 base_url,
2141 2113 'notebooks',
2142 2114 data.path,
2143 2115 data.name
2144 2116 ), '_blank');
2145 2117 },
2146 2118 error : utils.log_ajax_error,
2147 2119 };
2148 2120 var url = utils.url_join_encode(
2149 2121 base_url,
2150 2122 'api/contents',
2151 2123 path
2152 2124 );
2153 2125 $.ajax(url,settings);
2154 2126 };
2155 2127
2156 2128 Notebook.prototype.rename = function (nbname) {
2157 2129 var that = this;
2158 2130 if (!nbname.match(/\.ipynb$/)) {
2159 2131 nbname = nbname + ".ipynb";
2160 2132 }
2161 2133 var data = {name: nbname};
2162 2134 var settings = {
2163 2135 processData : false,
2164 2136 cache : false,
2165 2137 type : "PATCH",
2166 2138 data : JSON.stringify(data),
2167 2139 dataType: "json",
2168 2140 contentType: 'application/json',
2169 2141 success : $.proxy(that.rename_success, this),
2170 2142 error : $.proxy(that.rename_error, this)
2171 2143 };
2172 2144 this.events.trigger('rename_notebook.Notebook', data);
2173 2145 var url = utils.url_join_encode(
2174 2146 this.base_url,
2175 2147 'api/contents',
2176 2148 this.notebook_path,
2177 2149 this.notebook_name
2178 2150 );
2179 2151 $.ajax(url, settings);
2180 2152 };
2181 2153
2182 2154 Notebook.prototype.delete = function () {
2183 2155 var that = this;
2184 2156 var settings = {
2185 2157 processData : false,
2186 2158 cache : false,
2187 2159 type : "DELETE",
2188 2160 dataType: "json",
2189 2161 error : utils.log_ajax_error,
2190 2162 };
2191 2163 var url = utils.url_join_encode(
2192 2164 this.base_url,
2193 2165 'api/contents',
2194 2166 this.notebook_path,
2195 2167 this.notebook_name
2196 2168 );
2197 2169 $.ajax(url, settings);
2198 2170 };
2199 2171
2200 2172
2201 2173 Notebook.prototype.rename_success = function (json, status, xhr) {
2202 2174 var name = this.notebook_name = json.name;
2203 2175 var path = json.path;
2204 2176 this.session.rename_notebook(name, path);
2205 2177 this.events.trigger('notebook_renamed.Notebook', json);
2206 2178 };
2207 2179
2208 2180 Notebook.prototype.rename_error = function (xhr, status, error) {
2209 2181 var that = this;
2210 2182 var dialog_body = $('<div/>').append(
2211 2183 $("<p/>").text('This notebook name already exists.')
2212 2184 );
2213 2185 this.events.trigger('notebook_rename_failed.Notebook', [xhr, status, error]);
2214 2186 dialog.modal({
2215 2187 notebook: this,
2216 2188 keyboard_manager: this.keyboard_manager,
2217 2189 title: "Notebook Rename Error!",
2218 2190 body: dialog_body,
2219 2191 buttons : {
2220 2192 "Cancel": {},
2221 2193 "OK": {
2222 2194 class: "btn-primary",
2223 2195 click: function () {
2224 2196 this.save_widget.rename_notebook({notebook:that});
2225 2197 }}
2226 2198 },
2227 2199 open : function (event, ui) {
2228 2200 var that = $(this);
2229 2201 // Upon ENTER, click the OK button.
2230 2202 that.find('input[type="text"]').keydown(function (event, ui) {
2231 2203 if (event.which === this.keyboard.keycodes.enter) {
2232 2204 that.find('.btn-primary').first().click();
2233 2205 }
2234 2206 });
2235 2207 that.find('input[type="text"]').focus();
2236 2208 }
2237 2209 });
2238 2210 };
2239 2211
2240 2212 /**
2241 2213 * Request a notebook's data from the server.
2242 2214 *
2243 2215 * @method load_notebook
2244 2216 * @param {String} notebook_name and path A notebook to load
2245 2217 */
2246 2218 Notebook.prototype.load_notebook = function (notebook_name, notebook_path) {
2247 2219 var that = this;
2248 2220 this.notebook_name = notebook_name;
2249 2221 this.notebook_path = notebook_path;
2250 2222 // We do the call with settings so we can set cache to false.
2251 2223 var settings = {
2252 2224 processData : false,
2253 2225 cache : false,
2254 2226 type : "GET",
2255 2227 dataType : "json",
2256 2228 success : $.proxy(this.load_notebook_success,this),
2257 2229 error : $.proxy(this.load_notebook_error,this),
2258 2230 };
2259 2231 this.events.trigger('notebook_loading.Notebook');
2260 2232 var url = utils.url_join_encode(
2261 2233 this.base_url,
2262 2234 'api/contents',
2263 2235 this.notebook_path,
2264 2236 this.notebook_name
2265 2237 );
2266 2238 $.ajax(url, settings);
2267 2239 };
2268 2240
2269 2241 /**
2270 2242 * Success callback for loading a notebook from the server.
2271 2243 *
2272 2244 * Load notebook data from the JSON response.
2273 2245 *
2274 2246 * @method load_notebook_success
2275 2247 * @param {Object} data JSON representation of a notebook
2276 2248 * @param {String} status Description of response status
2277 2249 * @param {jqXHR} xhr jQuery Ajax object
2278 2250 */
2279 2251 Notebook.prototype.load_notebook_success = function (data, status, xhr) {
2280 2252 var failed;
2281 2253 try {
2282 2254 this.fromJSON(data);
2283 2255 } catch (e) {
2284 2256 failed = e;
2285 2257 console.log("Notebook failed to load from JSON:", e);
2286 2258 }
2287 2259 if (failed || data.message) {
2288 2260 // *either* fromJSON failed or validation failed
2289 2261 var body = $("<div>");
2290 2262 var title;
2291 2263 if (failed) {
2292 2264 title = "Notebook failed to load";
2293 2265 body.append($("<p>").text(
2294 2266 "The error was: "
2295 2267 )).append($("<div>").addClass("js-error").text(
2296 2268 failed.toString()
2297 2269 )).append($("<p>").text(
2298 2270 "See the error console for details."
2299 2271 ));
2300 2272 } else {
2301 2273 title = "Notebook validation failed";
2302 2274 }
2303 2275
2304 2276 if (data.message) {
2305 2277 var msg;
2306 2278 if (failed) {
2307 2279 msg = "The notebook also failed validation:"
2308 2280 } else {
2309 2281 msg = "An invalid notebook may not function properly." +
2310 2282 " The validation error was:"
2311 2283 }
2312 2284 body.append($("<p>").text(
2313 2285 msg
2314 2286 )).append($("<div>").addClass("validation-error").append(
2315 2287 $("<pre>").text(data.message)
2316 2288 ));
2317 2289 }
2318 2290
2319 2291 dialog.modal({
2320 2292 notebook: this,
2321 2293 keyboard_manager: this.keyboard_manager,
2322 2294 title: title,
2323 2295 body: body,
2324 2296 buttons : {
2325 2297 OK : {
2326 2298 "class" : "btn-primary"
2327 2299 }
2328 2300 }
2329 2301 });
2330 2302 }
2331 2303 if (this.ncells() === 0) {
2332 2304 this.insert_cell_below('code');
2333 2305 this.edit_mode(0);
2334 2306 } else {
2335 2307 this.select(0);
2336 2308 this.handle_command_mode(this.get_cell(0));
2337 2309 }
2338 2310 this.set_dirty(false);
2339 2311 this.scroll_to_top();
2340 if (data.orig_nbformat !== undefined && data.nbformat !== data.orig_nbformat) {
2312 var nbmodel = data.content;
2313 var orig_nbformat = nbmodel.metadata.orig_nbformat;
2314 var orig_nbformat_minor = nbmodel.metadata.orig_nbformat_minor;
2315 if (orig_nbformat !== undefined && nbmodel.nbformat !== orig_nbformat) {
2341 2316 var msg = "This notebook has been converted from an older " +
2342 "notebook format (v"+data.orig_nbformat+") to the current notebook " +
2343 "format (v"+data.nbformat+"). The next time you save this notebook, the " +
2317 "notebook format (v"+orig_nbformat+") to the current notebook " +
2318 "format (v"+nbmodel.nbformat+"). The next time you save this notebook, the " +
2344 2319 "newer notebook format will be used and older versions of IPython " +
2345 2320 "may not be able to read it. To keep the older version, close the " +
2346 2321 "notebook without saving it.";
2347 2322 dialog.modal({
2348 2323 notebook: this,
2349 2324 keyboard_manager: this.keyboard_manager,
2350 2325 title : "Notebook converted",
2351 2326 body : msg,
2352 2327 buttons : {
2353 2328 OK : {
2354 2329 class : "btn-primary"
2355 2330 }
2356 2331 }
2357 2332 });
2358 } else if (data.orig_nbformat_minor !== undefined && data.nbformat_minor !== data.orig_nbformat_minor) {
2333 } else if (orig_nbformat_minor !== undefined && nbmodel.nbformat_minor !== orig_nbformat_minor) {
2359 2334 var that = this;
2360 var orig_vs = 'v' + data.nbformat + '.' + data.orig_nbformat_minor;
2361 var this_vs = 'v' + data.nbformat + '.' + this.nbformat_minor;
2335 var orig_vs = 'v' + nbmodel.nbformat + '.' + orig_nbformat_minor;
2336 var this_vs = 'v' + nbmodel.nbformat + '.' + this.nbformat_minor;
2362 2337 var msg = "This notebook is version " + orig_vs + ", but we only fully support up to " +
2363 2338 this_vs + ". You can still work with this notebook, but some features " +
2364 2339 "introduced in later notebook versions may not be available.";
2365 2340
2366 2341 dialog.modal({
2367 2342 notebook: this,
2368 2343 keyboard_manager: this.keyboard_manager,
2369 2344 title : "Newer Notebook",
2370 2345 body : msg,
2371 2346 buttons : {
2372 2347 OK : {
2373 2348 class : "btn-danger"
2374 2349 }
2375 2350 }
2376 2351 });
2377 2352
2378 2353 }
2379 2354
2380 2355 // Create the session after the notebook is completely loaded to prevent
2381 2356 // code execution upon loading, which is a security risk.
2382 2357 if (this.session === null) {
2383 2358 var kernelspec = this.metadata.kernelspec || {};
2384 2359 var kernel_name = kernelspec.name;
2385 2360
2386 2361 this.start_session(kernel_name);
2387 2362 }
2388 2363 // load our checkpoint list
2389 2364 this.list_checkpoints();
2390 2365
2391 2366 // load toolbar state
2392 2367 if (this.metadata.celltoolbar) {
2393 2368 celltoolbar.CellToolbar.global_show();
2394 2369 celltoolbar.CellToolbar.activate_preset(this.metadata.celltoolbar);
2395 2370 } else {
2396 2371 celltoolbar.CellToolbar.global_hide();
2397 2372 }
2398 2373
2399 2374 // now that we're fully loaded, it is safe to restore save functionality
2400 2375 delete(this.save_notebook);
2401 2376 this.events.trigger('notebook_loaded.Notebook');
2402 2377 };
2403 2378
2404 2379 /**
2405 2380 * Failure callback for loading a notebook from the server.
2406 2381 *
2407 2382 * @method load_notebook_error
2408 2383 * @param {jqXHR} xhr jQuery Ajax object
2409 2384 * @param {String} status Description of response status
2410 2385 * @param {String} error HTTP error message
2411 2386 */
2412 2387 Notebook.prototype.load_notebook_error = function (xhr, status, error) {
2413 2388 this.events.trigger('notebook_load_failed.Notebook', [xhr, status, error]);
2414 2389 utils.log_ajax_error(xhr, status, error);
2415 var msg;
2390 var msg = $("<div>");
2416 2391 if (xhr.status === 400) {
2417 msg = escape(utils.ajax_error_msg(xhr));
2392 msg.text(utils.ajax_error_msg(xhr));
2418 2393 } else if (xhr.status === 500) {
2419 msg = "An unknown error occurred while loading this notebook. " +
2394 msg.text("An unknown error occurred while loading this notebook. " +
2420 2395 "This version can load notebook formats " +
2421 "v" + this.nbformat + " or earlier. See the server log for details.";
2396 "v" + this.nbformat + " or earlier. See the server log for details.");
2422 2397 }
2423 2398 dialog.modal({
2424 2399 notebook: this,
2425 2400 keyboard_manager: this.keyboard_manager,
2426 2401 title: "Error loading notebook",
2427 2402 body : msg,
2428 2403 buttons : {
2429 2404 "OK": {}
2430 2405 }
2431 2406 });
2432 2407 };
2433 2408
2434 2409 /********************* checkpoint-related *********************/
2435 2410
2436 2411 /**
2437 2412 * Save the notebook then immediately create a checkpoint.
2438 2413 *
2439 2414 * @method save_checkpoint
2440 2415 */
2441 2416 Notebook.prototype.save_checkpoint = function () {
2442 2417 this._checkpoint_after_save = true;
2443 2418 this.save_notebook();
2444 2419 };
2445 2420
2446 2421 /**
2447 2422 * Add a checkpoint for this notebook.
2448 2423 * for use as a callback from checkpoint creation.
2449 2424 *
2450 2425 * @method add_checkpoint
2451 2426 */
2452 2427 Notebook.prototype.add_checkpoint = function (checkpoint) {
2453 2428 var found = false;
2454 2429 for (var i = 0; i < this.checkpoints.length; i++) {
2455 2430 var existing = this.checkpoints[i];
2456 2431 if (existing.id == checkpoint.id) {
2457 2432 found = true;
2458 2433 this.checkpoints[i] = checkpoint;
2459 2434 break;
2460 2435 }
2461 2436 }
2462 2437 if (!found) {
2463 2438 this.checkpoints.push(checkpoint);
2464 2439 }
2465 2440 this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
2466 2441 };
2467 2442
2468 2443 /**
2469 2444 * List checkpoints for this notebook.
2470 2445 *
2471 2446 * @method list_checkpoints
2472 2447 */
2473 2448 Notebook.prototype.list_checkpoints = function () {
2474 2449 var url = utils.url_join_encode(
2475 2450 this.base_url,
2476 2451 'api/contents',
2477 2452 this.notebook_path,
2478 2453 this.notebook_name,
2479 2454 'checkpoints'
2480 2455 );
2481 2456 $.get(url).done(
2482 2457 $.proxy(this.list_checkpoints_success, this)
2483 2458 ).fail(
2484 2459 $.proxy(this.list_checkpoints_error, this)
2485 2460 );
2486 2461 };
2487 2462
2488 2463 /**
2489 2464 * Success callback for listing checkpoints.
2490 2465 *
2491 2466 * @method list_checkpoint_success
2492 2467 * @param {Object} data JSON representation of a checkpoint
2493 2468 * @param {String} status Description of response status
2494 2469 * @param {jqXHR} xhr jQuery Ajax object
2495 2470 */
2496 2471 Notebook.prototype.list_checkpoints_success = function (data, status, xhr) {
2497 2472 data = $.parseJSON(data);
2498 2473 this.checkpoints = data;
2499 2474 if (data.length) {
2500 2475 this.last_checkpoint = data[data.length - 1];
2501 2476 } else {
2502 2477 this.last_checkpoint = null;
2503 2478 }
2504 2479 this.events.trigger('checkpoints_listed.Notebook', [data]);
2505 2480 };
2506 2481
2507 2482 /**
2508 2483 * Failure callback for listing a checkpoint.
2509 2484 *
2510 2485 * @method list_checkpoint_error
2511 2486 * @param {jqXHR} xhr jQuery Ajax object
2512 2487 * @param {String} status Description of response status
2513 2488 * @param {String} error_msg HTTP error message
2514 2489 */
2515 2490 Notebook.prototype.list_checkpoints_error = function (xhr, status, error_msg) {
2516 2491 this.events.trigger('list_checkpoints_failed.Notebook');
2517 2492 };
2518 2493
2519 2494 /**
2520 2495 * Create a checkpoint of this notebook on the server from the most recent save.
2521 2496 *
2522 2497 * @method create_checkpoint
2523 2498 */
2524 2499 Notebook.prototype.create_checkpoint = function () {
2525 2500 var url = utils.url_join_encode(
2526 2501 this.base_url,
2527 2502 'api/contents',
2528 2503 this.notebook_path,
2529 2504 this.notebook_name,
2530 2505 'checkpoints'
2531 2506 );
2532 2507 $.post(url).done(
2533 2508 $.proxy(this.create_checkpoint_success, this)
2534 2509 ).fail(
2535 2510 $.proxy(this.create_checkpoint_error, this)
2536 2511 );
2537 2512 };
2538 2513
2539 2514 /**
2540 2515 * Success callback for creating a checkpoint.
2541 2516 *
2542 2517 * @method create_checkpoint_success
2543 2518 * @param {Object} data JSON representation of a checkpoint
2544 2519 * @param {String} status Description of response status
2545 2520 * @param {jqXHR} xhr jQuery Ajax object
2546 2521 */
2547 2522 Notebook.prototype.create_checkpoint_success = function (data, status, xhr) {
2548 2523 data = $.parseJSON(data);
2549 2524 this.add_checkpoint(data);
2550 2525 this.events.trigger('checkpoint_created.Notebook', data);
2551 2526 };
2552 2527
2553 2528 /**
2554 2529 * Failure callback for creating a checkpoint.
2555 2530 *
2556 2531 * @method create_checkpoint_error
2557 2532 * @param {jqXHR} xhr jQuery Ajax object
2558 2533 * @param {String} status Description of response status
2559 2534 * @param {String} error_msg HTTP error message
2560 2535 */
2561 2536 Notebook.prototype.create_checkpoint_error = function (xhr, status, error_msg) {
2562 2537 this.events.trigger('checkpoint_failed.Notebook');
2563 2538 };
2564 2539
2565 2540 Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
2566 2541 var that = this;
2567 2542 checkpoint = checkpoint || this.last_checkpoint;
2568 2543 if ( ! checkpoint ) {
2569 2544 console.log("restore dialog, but no checkpoint to restore to!");
2570 2545 return;
2571 2546 }
2572 2547 var body = $('<div/>').append(
2573 2548 $('<p/>').addClass("p-space").text(
2574 2549 "Are you sure you want to revert the notebook to " +
2575 2550 "the latest checkpoint?"
2576 2551 ).append(
2577 2552 $("<strong/>").text(
2578 2553 " This cannot be undone."
2579 2554 )
2580 2555 )
2581 2556 ).append(
2582 2557 $('<p/>').addClass("p-space").text("The checkpoint was last updated at:")
2583 2558 ).append(
2584 2559 $('<p/>').addClass("p-space").text(
2585 2560 Date(checkpoint.last_modified)
2586 2561 ).css("text-align", "center")
2587 2562 );
2588 2563
2589 2564 dialog.modal({
2590 2565 notebook: this,
2591 2566 keyboard_manager: this.keyboard_manager,
2592 2567 title : "Revert notebook to checkpoint",
2593 2568 body : body,
2594 2569 buttons : {
2595 2570 Revert : {
2596 2571 class : "btn-danger",
2597 2572 click : function () {
2598 2573 that.restore_checkpoint(checkpoint.id);
2599 2574 }
2600 2575 },
2601 2576 Cancel : {}
2602 2577 }
2603 2578 });
2604 2579 };
2605 2580
2606 2581 /**
2607 2582 * Restore the notebook to a checkpoint state.
2608 2583 *
2609 2584 * @method restore_checkpoint
2610 2585 * @param {String} checkpoint ID
2611 2586 */
2612 2587 Notebook.prototype.restore_checkpoint = function (checkpoint) {
2613 2588 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2614 2589 var url = utils.url_join_encode(
2615 2590 this.base_url,
2616 2591 'api/contents',
2617 2592 this.notebook_path,
2618 2593 this.notebook_name,
2619 2594 'checkpoints',
2620 2595 checkpoint
2621 2596 );
2622 2597 $.post(url).done(
2623 2598 $.proxy(this.restore_checkpoint_success, this)
2624 2599 ).fail(
2625 2600 $.proxy(this.restore_checkpoint_error, this)
2626 2601 );
2627 2602 };
2628 2603
2629 2604 /**
2630 2605 * Success callback for restoring a notebook to a checkpoint.
2631 2606 *
2632 2607 * @method restore_checkpoint_success
2633 2608 * @param {Object} data (ignored, should be empty)
2634 2609 * @param {String} status Description of response status
2635 2610 * @param {jqXHR} xhr jQuery Ajax object
2636 2611 */
2637 2612 Notebook.prototype.restore_checkpoint_success = function (data, status, xhr) {
2638 2613 this.events.trigger('checkpoint_restored.Notebook');
2639 2614 this.load_notebook(this.notebook_name, this.notebook_path);
2640 2615 };
2641 2616
2642 2617 /**
2643 2618 * Failure callback for restoring a notebook to a checkpoint.
2644 2619 *
2645 2620 * @method restore_checkpoint_error
2646 2621 * @param {jqXHR} xhr jQuery Ajax object
2647 2622 * @param {String} status Description of response status
2648 2623 * @param {String} error_msg HTTP error message
2649 2624 */
2650 2625 Notebook.prototype.restore_checkpoint_error = function (xhr, status, error_msg) {
2651 2626 this.events.trigger('checkpoint_restore_failed.Notebook');
2652 2627 };
2653 2628
2654 2629 /**
2655 2630 * Delete a notebook checkpoint.
2656 2631 *
2657 2632 * @method delete_checkpoint
2658 2633 * @param {String} checkpoint ID
2659 2634 */
2660 2635 Notebook.prototype.delete_checkpoint = function (checkpoint) {
2661 2636 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2662 2637 var url = utils.url_join_encode(
2663 2638 this.base_url,
2664 2639 'api/contents',
2665 2640 this.notebook_path,
2666 2641 this.notebook_name,
2667 2642 'checkpoints',
2668 2643 checkpoint
2669 2644 );
2670 2645 $.ajax(url, {
2671 2646 type: 'DELETE',
2672 2647 success: $.proxy(this.delete_checkpoint_success, this),
2673 2648 error: $.proxy(this.delete_checkpoint_error, this)
2674 2649 });
2675 2650 };
2676 2651
2677 2652 /**
2678 2653 * Success callback for deleting a notebook checkpoint
2679 2654 *
2680 2655 * @method delete_checkpoint_success
2681 2656 * @param {Object} data (ignored, should be empty)
2682 2657 * @param {String} status Description of response status
2683 2658 * @param {jqXHR} xhr jQuery Ajax object
2684 2659 */
2685 2660 Notebook.prototype.delete_checkpoint_success = function (data, status, xhr) {
2686 2661 this.events.trigger('checkpoint_deleted.Notebook', data);
2687 2662 this.load_notebook(this.notebook_name, this.notebook_path);
2688 2663 };
2689 2664
2690 2665 /**
2691 2666 * Failure callback for deleting a notebook checkpoint.
2692 2667 *
2693 2668 * @method delete_checkpoint_error
2694 2669 * @param {jqXHR} xhr jQuery Ajax object
2695 2670 * @param {String} status Description of response status
2696 2671 * @param {String} error HTTP error message
2697 2672 */
2698 2673 Notebook.prototype.delete_checkpoint_error = function (xhr, status, error) {
2699 2674 this.events.trigger('checkpoint_delete_failed.Notebook', [xhr, status, error]);
2700 2675 };
2701 2676
2702 2677
2703 2678 // For backwards compatability.
2704 2679 IPython.Notebook = Notebook;
2705 2680
2706 2681 return {'Notebook': Notebook};
2707 2682 });
@@ -1,1002 +1,931 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'jqueryui',
7 7 'base/js/utils',
8 8 'base/js/security',
9 9 'base/js/keyboard',
10 10 'notebook/js/mathjaxutils',
11 11 'components/marked/lib/marked',
12 12 ], function(IPython, $, utils, security, keyboard, mathjaxutils, marked) {
13 13 "use strict";
14 14
15 15 /**
16 16 * @class OutputArea
17 17 *
18 18 * @constructor
19 19 */
20 20
21 21 var OutputArea = function (options) {
22 22 this.selector = options.selector;
23 23 this.events = options.events;
24 24 this.keyboard_manager = options.keyboard_manager;
25 25 this.wrapper = $(options.selector);
26 26 this.outputs = [];
27 27 this.collapsed = false;
28 28 this.scrolled = false;
29 29 this.trusted = true;
30 30 this.clear_queued = null;
31 31 if (options.prompt_area === undefined) {
32 32 this.prompt_area = true;
33 33 } else {
34 34 this.prompt_area = options.prompt_area;
35 35 }
36 36 this.create_elements();
37 37 this.style();
38 38 this.bind_events();
39 39 };
40 40
41 41
42 42 /**
43 43 * Class prototypes
44 44 **/
45 45
46 46 OutputArea.prototype.create_elements = function () {
47 47 this.element = $("<div/>");
48 48 this.collapse_button = $("<div/>");
49 49 this.prompt_overlay = $("<div/>");
50 50 this.wrapper.append(this.prompt_overlay);
51 51 this.wrapper.append(this.element);
52 52 this.wrapper.append(this.collapse_button);
53 53 };
54 54
55 55
56 56 OutputArea.prototype.style = function () {
57 57 this.collapse_button.hide();
58 58 this.prompt_overlay.hide();
59 59
60 60 this.wrapper.addClass('output_wrapper');
61 61 this.element.addClass('output');
62 62
63 63 this.collapse_button.addClass("btn btn-default output_collapsed");
64 64 this.collapse_button.attr('title', 'click to expand output');
65 65 this.collapse_button.text('. . .');
66 66
67 67 this.prompt_overlay.addClass('out_prompt_overlay prompt');
68 68 this.prompt_overlay.attr('title', 'click to expand output; double click to hide output');
69 69
70 70 this.collapse();
71 71 };
72 72
73 73 /**
74 74 * Should the OutputArea scroll?
75 75 * Returns whether the height (in lines) exceeds a threshold.
76 76 *
77 77 * @private
78 78 * @method _should_scroll
79 79 * @param [lines=100]{Integer}
80 80 * @return {Bool}
81 81 *
82 82 */
83 83 OutputArea.prototype._should_scroll = function (lines) {
84 if (lines <=0 ){ return }
84 if (lines <=0 ){ return; }
85 85 if (!lines) {
86 86 lines = 100;
87 87 }
88 88 // line-height from http://stackoverflow.com/questions/1185151
89 89 var fontSize = this.element.css('font-size');
90 90 var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
91 91
92 92 return (this.element.height() > lines * lineHeight);
93 93 };
94 94
95 95
96 96 OutputArea.prototype.bind_events = function () {
97 97 var that = this;
98 98 this.prompt_overlay.dblclick(function () { that.toggle_output(); });
99 99 this.prompt_overlay.click(function () { that.toggle_scroll(); });
100 100
101 101 this.element.resize(function () {
102 102 // FIXME: Firefox on Linux misbehaves, so automatic scrolling is disabled
103 103 if ( utils.browser[0] === "Firefox" ) {
104 104 return;
105 105 }
106 106 // maybe scroll output,
107 107 // if it's grown large enough and hasn't already been scrolled.
108 108 if ( !that.scrolled && that._should_scroll(OutputArea.auto_scroll_threshold)) {
109 109 that.scroll_area();
110 110 }
111 111 });
112 112 this.collapse_button.click(function () {
113 113 that.expand();
114 114 });
115 115 };
116 116
117 117
118 118 OutputArea.prototype.collapse = function () {
119 119 if (!this.collapsed) {
120 120 this.element.hide();
121 121 this.prompt_overlay.hide();
122 122 if (this.element.html()){
123 123 this.collapse_button.show();
124 124 }
125 125 this.collapsed = true;
126 126 }
127 127 };
128 128
129 129
130 130 OutputArea.prototype.expand = function () {
131 131 if (this.collapsed) {
132 132 this.collapse_button.hide();
133 133 this.element.show();
134 134 this.prompt_overlay.show();
135 135 this.collapsed = false;
136 136 }
137 137 };
138 138
139 139
140 140 OutputArea.prototype.toggle_output = function () {
141 141 if (this.collapsed) {
142 142 this.expand();
143 143 } else {
144 144 this.collapse();
145 145 }
146 146 };
147 147
148 148
149 149 OutputArea.prototype.scroll_area = function () {
150 150 this.element.addClass('output_scroll');
151 151 this.prompt_overlay.attr('title', 'click to unscroll output; double click to hide');
152 152 this.scrolled = true;
153 153 };
154 154
155 155
156 156 OutputArea.prototype.unscroll_area = function () {
157 157 this.element.removeClass('output_scroll');
158 158 this.prompt_overlay.attr('title', 'click to scroll output; double click to hide');
159 159 this.scrolled = false;
160 160 };
161 161
162 162 /**
163 163 *
164 164 * Scroll OutputArea if height supperior than a threshold (in lines).
165 165 *
166 166 * Threshold is a maximum number of lines. If unspecified, defaults to
167 167 * OutputArea.minimum_scroll_threshold.
168 168 *
169 169 * Negative threshold will prevent the OutputArea from ever scrolling.
170 170 *
171 171 * @method scroll_if_long
172 172 *
173 173 * @param [lines=20]{Number} Default to 20 if not set,
174 174 * behavior undefined for value of `0`.
175 175 *
176 176 **/
177 177 OutputArea.prototype.scroll_if_long = function (lines) {
178 178 var n = lines | OutputArea.minimum_scroll_threshold;
179 179 if(n <= 0){
180 return
180 return;
181 181 }
182 182
183 183 if (this._should_scroll(n)) {
184 184 // only allow scrolling long-enough output
185 185 this.scroll_area();
186 186 }
187 187 };
188 188
189 189
190 190 OutputArea.prototype.toggle_scroll = function () {
191 191 if (this.scrolled) {
192 192 this.unscroll_area();
193 193 } else {
194 194 // only allow scrolling long-enough output
195 195 this.scroll_if_long();
196 196 }
197 197 };
198 198
199 199
200 200 // typeset with MathJax if MathJax is available
201 201 OutputArea.prototype.typeset = function () {
202 202 if (window.MathJax){
203 203 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
204 204 }
205 205 };
206 206
207 207
208 208 OutputArea.prototype.handle_output = function (msg) {
209 209 var json = {};
210 210 var msg_type = json.output_type = msg.header.msg_type;
211 211 var content = msg.content;
212 212 if (msg_type === "stream") {
213 213 json.text = content.text;
214 json.stream = content.name;
214 json.name = content.name;
215 215 } else if (msg_type === "display_data") {
216 json = content.data;
216 json.data = content.data;
217 217 json.output_type = msg_type;
218 218 json.metadata = content.metadata;
219 219 } else if (msg_type === "execute_result") {
220 json = content.data;
220 json.data = content.data;
221 221 json.output_type = msg_type;
222 222 json.metadata = content.metadata;
223 json.prompt_number = content.execution_count;
223 json.execution_count = content.execution_count;
224 224 } else if (msg_type === "error") {
225 225 json.ename = content.ename;
226 226 json.evalue = content.evalue;
227 227 json.traceback = content.traceback;
228 228 } else {
229 229 console.log("unhandled output message", msg);
230 230 return;
231 231 }
232 232 this.append_output(json);
233 233 };
234 234
235 235
236 OutputArea.prototype.rename_keys = function (data, key_map) {
237 var remapped = {};
238 for (var key in data) {
239 var new_key = key_map[key] || key;
240 remapped[new_key] = data[key];
241 }
242 return remapped;
243 };
244
245
246 236 OutputArea.output_types = [
247 237 'application/javascript',
248 238 'text/html',
249 239 'text/markdown',
250 240 'text/latex',
251 241 'image/svg+xml',
252 242 'image/png',
253 243 'image/jpeg',
254 244 'application/pdf',
255 245 'text/plain'
256 246 ];
257 247
258 248 OutputArea.prototype.validate_output = function (json) {
259 249 // scrub invalid outputs
260 // TODO: right now everything is a string, but JSON really shouldn't be.
261 // nbformat 4 will fix that.
250 var data = json.data;
262 251 $.map(OutputArea.output_types, function(key){
263 if (json[key] !== undefined && typeof json[key] !== 'string') {
264 console.log("Invalid type for " + key, json[key]);
265 delete json[key];
252 if (key !== 'application/json' &&
253 data[key] !== undefined &&
254 typeof data[key] !== 'string'
255 ) {
256 console.log("Invalid type for " + key, data[key]);
257 delete data[key];
266 258 }
267 259 });
268 260 return json;
269 261 };
270 262
271 263 OutputArea.prototype.append_output = function (json) {
272 264 this.expand();
273 265
274 266 // validate output data types
275 json = this.validate_output(json);
267 if (json.data) {
268 json = this.validate_output(json);
269 }
276 270
277 271 // Clear the output if clear is queued.
278 272 var needs_height_reset = false;
279 273 if (this.clear_queued) {
280 274 this.clear_output(false);
281 275 needs_height_reset = true;
282 276 }
283 277
284 278 var record_output = true;
285 279
286 280 if (json.output_type === 'execute_result') {
287 281 this.append_execute_result(json);
288 282 } else if (json.output_type === 'error') {
289 283 this.append_error(json);
290 284 } else if (json.output_type === 'stream') {
291 285 // append_stream might have merged the output with earlier stream output
292 286 record_output = this.append_stream(json);
293 287 }
294 288
295 289 // We must release the animation fixed height in a callback since Gecko
296 290 // (FireFox) doesn't render the image immediately as the data is
297 291 // available.
298 292 var that = this;
299 293 var handle_appended = function ($el) {
300 294 // Only reset the height to automatic if the height is currently
301 295 // fixed (done by wait=True flag on clear_output).
302 296 if (needs_height_reset) {
303 297 that.element.height('');
304 298 }
305 299 that.element.trigger('resize');
306 300 };
307 301 if (json.output_type === 'display_data') {
308 302 this.append_display_data(json, handle_appended);
309 303 } else {
310 304 handle_appended();
311 305 }
312 306
313 307 if (record_output) {
314 308 this.outputs.push(json);
315 309 }
316 310 };
317 311
318 312
319 313 OutputArea.prototype.create_output_area = function () {
320 314 var oa = $("<div/>").addClass("output_area");
321 315 if (this.prompt_area) {
322 316 oa.append($('<div/>').addClass('prompt'));
323 317 }
324 318 return oa;
325 319 };
326 320
327 321
328 322 function _get_metadata_key(metadata, key, mime) {
329 323 var mime_md = metadata[mime];
330 324 // mime-specific higher priority
331 325 if (mime_md && mime_md[key] !== undefined) {
332 326 return mime_md[key];
333 327 }
334 328 // fallback on global
335 329 return metadata[key];
336 330 }
337 331
338 332 OutputArea.prototype.create_output_subarea = function(md, classes, mime) {
339 333 var subarea = $('<div/>').addClass('output_subarea').addClass(classes);
340 334 if (_get_metadata_key(md, 'isolated', mime)) {
341 335 // Create an iframe to isolate the subarea from the rest of the
342 336 // document
343 337 var iframe = $('<iframe/>').addClass('box-flex1');
344 338 iframe.css({'height':1, 'width':'100%', 'display':'block'});
345 339 iframe.attr('frameborder', 0);
346 340 iframe.attr('scrolling', 'auto');
347 341
348 342 // Once the iframe is loaded, the subarea is dynamically inserted
349 343 iframe.on('load', function() {
350 344 // Workaround needed by Firefox, to properly render svg inside
351 345 // iframes, see http://stackoverflow.com/questions/10177190/
352 346 // svg-dynamically-added-to-iframe-does-not-render-correctly
353 347 this.contentDocument.open();
354 348
355 349 // Insert the subarea into the iframe
356 350 // We must directly write the html. When using Jquery's append
357 351 // method, javascript is evaluated in the parent document and
358 352 // not in the iframe document. At this point, subarea doesn't
359 353 // contain any user content.
360 354 this.contentDocument.write(subarea.html());
361 355
362 356 this.contentDocument.close();
363 357
364 358 var body = this.contentDocument.body;
365 359 // Adjust the iframe height automatically
366 360 iframe.height(body.scrollHeight + 'px');
367 361 });
368 362
369 363 // Elements should be appended to the inner subarea and not to the
370 364 // iframe
371 365 iframe.append = function(that) {
372 366 subarea.append(that);
373 367 };
374 368
375 369 return iframe;
376 370 } else {
377 371 return subarea;
378 372 }
379 }
373 };
380 374
381 375
382 376 OutputArea.prototype._append_javascript_error = function (err, element) {
383 377 // display a message when a javascript error occurs in display output
384 var msg = "Javascript error adding output!"
378 var msg = "Javascript error adding output!";
385 379 if ( element === undefined ) return;
386 380 element
387 381 .append($('<div/>').text(msg).addClass('js-error'))
388 382 .append($('<div/>').text(err.toString()).addClass('js-error'))
389 383 .append($('<div/>').text('See your browser Javascript console for more details.').addClass('js-error'));
390 384 };
391 385
392 386 OutputArea.prototype._safe_append = function (toinsert) {
393 387 // safely append an item to the document
394 388 // this is an object created by user code,
395 389 // and may have errors, which should not be raised
396 390 // under any circumstances.
397 391 try {
398 392 this.element.append(toinsert);
399 393 } catch(err) {
400 394 console.log(err);
401 395 // Create an actual output_area and output_subarea, which creates
402 396 // the prompt area and the proper indentation.
403 397 var toinsert = this.create_output_area();
404 398 var subarea = $('<div/>').addClass('output_subarea');
405 399 toinsert.append(subarea);
406 400 this._append_javascript_error(err, subarea);
407 401 this.element.append(toinsert);
408 402 }
409 403 };
410 404
411 405
412 406 OutputArea.prototype.append_execute_result = function (json) {
413 var n = json.prompt_number || ' ';
407 var n = json.execution_count || ' ';
414 408 var toinsert = this.create_output_area();
415 409 if (this.prompt_area) {
416 410 toinsert.find('div.prompt').addClass('output_prompt').text('Out[' + n + ']:');
417 411 }
418 412 var inserted = this.append_mime_type(json, toinsert);
419 413 if (inserted) {
420 414 inserted.addClass('output_result');
421 415 }
422 416 this._safe_append(toinsert);
423 417 // If we just output latex, typeset it.
424 418 if ((json['text/latex'] !== undefined) ||
425 419 (json['text/html'] !== undefined) ||
426 420 (json['text/markdown'] !== undefined)) {
427 421 this.typeset();
428 422 }
429 423 };
430 424
431 425
432 426 OutputArea.prototype.append_error = function (json) {
433 427 var tb = json.traceback;
434 428 if (tb !== undefined && tb.length > 0) {
435 429 var s = '';
436 430 var len = tb.length;
437 431 for (var i=0; i<len; i++) {
438 432 s = s + tb[i] + '\n';
439 433 }
440 434 s = s + '\n';
441 435 var toinsert = this.create_output_area();
442 436 var append_text = OutputArea.append_map['text/plain'];
443 437 if (append_text) {
444 438 append_text.apply(this, [s, {}, toinsert]).addClass('output_error');
445 439 }
446 440 this._safe_append(toinsert);
447 441 }
448 442 };
449 443
450 444
451 445 OutputArea.prototype.append_stream = function (json) {
452 // temporary fix: if stream undefined (json file written prior to this patch),
453 // default to most likely stdout:
454 if (json.stream === undefined){
455 json.stream = 'stdout';
456 }
457 446 var text = json.text;
458 var subclass = "output_"+json.stream;
447 var subclass = "output_"+json.name;
459 448 if (this.outputs.length > 0){
460 449 // have at least one output to consider
461 450 var last = this.outputs[this.outputs.length-1];
462 if (last.output_type == 'stream' && json.stream == last.stream){
451 if (last.output_type == 'stream' && json.name == last.name){
463 452 // latest output was in the same stream,
464 453 // so append directly into its pre tag
465 454 // escape ANSI & HTML specials:
466 455 last.text = utils.fixCarriageReturn(last.text + json.text);
467 456 var pre = this.element.find('div.'+subclass).last().find('pre');
468 457 var html = utils.fixConsole(last.text);
469 458 // The only user content injected with this HTML call is
470 459 // escaped by the fixConsole() method.
471 460 pre.html(html);
472 461 // return false signals that we merged this output with the previous one,
473 462 // and the new output shouldn't be recorded.
474 463 return false;
475 464 }
476 465 }
477 466
478 467 if (!text.replace("\r", "")) {
479 468 // text is nothing (empty string, \r, etc.)
480 469 // so don't append any elements, which might add undesirable space
481 470 // return true to indicate the output should be recorded.
482 471 return true;
483 472 }
484 473
485 474 // If we got here, attach a new div
486 475 var toinsert = this.create_output_area();
487 476 var append_text = OutputArea.append_map['text/plain'];
488 477 if (append_text) {
489 478 append_text.apply(this, [text, {}, toinsert]).addClass("output_stream " + subclass);
490 479 }
491 480 this._safe_append(toinsert);
492 481 return true;
493 482 };
494 483
495 484
496 485 OutputArea.prototype.append_display_data = function (json, handle_inserted) {
497 486 var toinsert = this.create_output_area();
498 487 if (this.append_mime_type(json, toinsert, handle_inserted)) {
499 488 this._safe_append(toinsert);
500 489 // If we just output latex, typeset it.
501 490 if ((json['text/latex'] !== undefined) ||
502 491 (json['text/html'] !== undefined) ||
503 492 (json['text/markdown'] !== undefined)) {
504 493 this.typeset();
505 494 }
506 495 }
507 496 };
508 497
509 498
510 499 OutputArea.safe_outputs = {
511 500 'text/plain' : true,
512 501 'text/latex' : true,
513 502 'image/png' : true,
514 503 'image/jpeg' : true
515 504 };
516 505
517 506 OutputArea.prototype.append_mime_type = function (json, element, handle_inserted) {
518 507 for (var i=0; i < OutputArea.display_order.length; i++) {
519 508 var type = OutputArea.display_order[i];
520 509 var append = OutputArea.append_map[type];
521 if ((json[type] !== undefined) && append) {
522 var value = json[type];
510 if ((json.data[type] !== undefined) && append) {
511 var value = json.data[type];
523 512 if (!this.trusted && !OutputArea.safe_outputs[type]) {
524 513 // not trusted, sanitize HTML
525 514 if (type==='text/html' || type==='text/svg') {
526 515 value = security.sanitize_html(value);
527 516 } else {
528 517 // don't display if we don't know how to sanitize it
529 518 console.log("Ignoring untrusted " + type + " output.");
530 519 continue;
531 520 }
532 521 }
533 522 var md = json.metadata || {};
534 523 var toinsert = append.apply(this, [value, md, element, handle_inserted]);
535 524 // Since only the png and jpeg mime types call the inserted
536 525 // callback, if the mime type is something other we must call the
537 526 // inserted callback only when the element is actually inserted
538 527 // into the DOM. Use a timeout of 0 to do this.
539 528 if (['image/png', 'image/jpeg'].indexOf(type) < 0 && handle_inserted !== undefined) {
540 529 setTimeout(handle_inserted, 0);
541 530 }
542 531 this.events.trigger('output_appended.OutputArea', [type, value, md, toinsert]);
543 532 return toinsert;
544 533 }
545 534 }
546 535 return null;
547 536 };
548 537
549 538
550 539 var append_html = function (html, md, element) {
551 540 var type = 'text/html';
552 541 var toinsert = this.create_output_subarea(md, "output_html rendered_html", type);
553 542 this.keyboard_manager.register_events(toinsert);
554 543 toinsert.append(html);
555 544 element.append(toinsert);
556 545 return toinsert;
557 546 };
558 547
559 548
560 549 var append_markdown = function(markdown, md, element) {
561 550 var type = 'text/markdown';
562 551 var toinsert = this.create_output_subarea(md, "output_markdown", type);
563 552 var text_and_math = mathjaxutils.remove_math(markdown);
564 553 var text = text_and_math[0];
565 554 var math = text_and_math[1];
566 555 var html = marked.parser(marked.lexer(text));
567 556 html = mathjaxutils.replace_math(html, math);
568 557 toinsert.append(html);
569 558 element.append(toinsert);
570 559 return toinsert;
571 560 };
572 561
573 562
574 563 var append_javascript = function (js, md, element) {
575 564 // We just eval the JS code, element appears in the local scope.
576 565 var type = 'application/javascript';
577 566 var toinsert = this.create_output_subarea(md, "output_javascript", type);
578 567 this.keyboard_manager.register_events(toinsert);
579 568 element.append(toinsert);
580 569
581 570 // Fix for ipython/issues/5293, make sure `element` is the area which
582 571 // output can be inserted into at the time of JS execution.
583 572 element = toinsert;
584 573 try {
585 574 eval(js);
586 575 } catch(err) {
587 576 console.log(err);
588 577 this._append_javascript_error(err, toinsert);
589 578 }
590 579 return toinsert;
591 580 };
592 581
593 582
594 583 var append_text = function (data, md, element) {
595 584 var type = 'text/plain';
596 585 var toinsert = this.create_output_subarea(md, "output_text", type);
597 586 // escape ANSI & HTML specials in plaintext:
598 587 data = utils.fixConsole(data);
599 588 data = utils.fixCarriageReturn(data);
600 589 data = utils.autoLinkUrls(data);
601 590 // The only user content injected with this HTML call is
602 591 // escaped by the fixConsole() method.
603 592 toinsert.append($("<pre/>").html(data));
604 593 element.append(toinsert);
605 594 return toinsert;
606 595 };
607 596
608 597
609 598 var append_svg = function (svg_html, md, element) {
610 599 var type = 'image/svg+xml';
611 600 var toinsert = this.create_output_subarea(md, "output_svg", type);
612 601
613 602 // Get the svg element from within the HTML.
614 603 var svg = $('<div />').html(svg_html).find('svg');
615 604 var svg_area = $('<div />');
616 605 var width = svg.attr('width');
617 606 var height = svg.attr('height');
618 607 svg
619 608 .width('100%')
620 609 .height('100%');
621 610 svg_area
622 611 .width(width)
623 612 .height(height);
624 613
625 614 // The jQuery resize handlers don't seem to work on the svg element.
626 615 // When the svg renders completely, measure it's size and set the parent
627 616 // div to that size. Then set the svg to 100% the size of the parent
628 617 // div and make the parent div resizable.
629 618 this._dblclick_to_reset_size(svg_area, true, false);
630 619
631 620 svg_area.append(svg);
632 621 toinsert.append(svg_area);
633 622 element.append(toinsert);
634 623
635 624 return toinsert;
636 625 };
637 626
638 627 OutputArea.prototype._dblclick_to_reset_size = function (img, immediately, resize_parent) {
639 628 // Add a resize handler to an element
640 629 //
641 630 // img: jQuery element
642 631 // immediately: bool=False
643 632 // Wait for the element to load before creating the handle.
644 633 // resize_parent: bool=True
645 634 // Should the parent of the element be resized when the element is
646 635 // reset (by double click).
647 636 var callback = function (){
648 637 var h0 = img.height();
649 638 var w0 = img.width();
650 639 if (!(h0 && w0)) {
651 640 // zero size, don't make it resizable
652 641 return;
653 642 }
654 643 img.resizable({
655 644 aspectRatio: true,
656 645 autoHide: true
657 646 });
658 647 img.dblclick(function () {
659 648 // resize wrapper & image together for some reason:
660 649 img.height(h0);
661 650 img.width(w0);
662 651 if (resize_parent === undefined || resize_parent) {
663 652 img.parent().height(h0);
664 653 img.parent().width(w0);
665 654 }
666 655 });
667 656 };
668 657
669 658 if (immediately) {
670 659 callback();
671 660 } else {
672 661 img.on("load", callback);
673 662 }
674 663 };
675 664
676 665 var set_width_height = function (img, md, mime) {
677 666 // set width and height of an img element from metadata
678 667 var height = _get_metadata_key(md, 'height', mime);
679 668 if (height !== undefined) img.attr('height', height);
680 669 var width = _get_metadata_key(md, 'width', mime);
681 670 if (width !== undefined) img.attr('width', width);
682 671 };
683 672
684 673 var append_png = function (png, md, element, handle_inserted) {
685 674 var type = 'image/png';
686 675 var toinsert = this.create_output_subarea(md, "output_png", type);
687 676 var img = $("<img/>");
688 677 if (handle_inserted !== undefined) {
689 678 img.on('load', function(){
690 679 handle_inserted(img);
691 680 });
692 681 }
693 682 img[0].src = 'data:image/png;base64,'+ png;
694 683 set_width_height(img, md, 'image/png');
695 684 this._dblclick_to_reset_size(img);
696 685 toinsert.append(img);
697 686 element.append(toinsert);
698 687 return toinsert;
699 688 };
700 689
701 690
702 691 var append_jpeg = function (jpeg, md, element, handle_inserted) {
703 692 var type = 'image/jpeg';
704 693 var toinsert = this.create_output_subarea(md, "output_jpeg", type);
705 694 var img = $("<img/>");
706 695 if (handle_inserted !== undefined) {
707 696 img.on('load', function(){
708 697 handle_inserted(img);
709 698 });
710 699 }
711 700 img[0].src = 'data:image/jpeg;base64,'+ jpeg;
712 701 set_width_height(img, md, 'image/jpeg');
713 702 this._dblclick_to_reset_size(img);
714 703 toinsert.append(img);
715 704 element.append(toinsert);
716 705 return toinsert;
717 706 };
718 707
719 708
720 709 var append_pdf = function (pdf, md, element) {
721 710 var type = 'application/pdf';
722 711 var toinsert = this.create_output_subarea(md, "output_pdf", type);
723 712 var a = $('<a/>').attr('href', 'data:application/pdf;base64,'+pdf);
724 713 a.attr('target', '_blank');
725 a.text('View PDF')
714 a.text('View PDF');
726 715 toinsert.append(a);
727 716 element.append(toinsert);
728 717 return toinsert;
729 }
718 };
730 719
731 720 var append_latex = function (latex, md, element) {
732 721 // This method cannot do the typesetting because the latex first has to
733 722 // be on the page.
734 723 var type = 'text/latex';
735 724 var toinsert = this.create_output_subarea(md, "output_latex", type);
736 725 toinsert.append(latex);
737 726 element.append(toinsert);
738 727 return toinsert;
739 728 };
740 729
741 730
742 731 OutputArea.prototype.append_raw_input = function (msg) {
743 732 var that = this;
744 733 this.expand();
745 734 var content = msg.content;
746 735 var area = this.create_output_area();
747 736
748 737 // disable any other raw_inputs, if they are left around
749 738 $("div.output_subarea.raw_input_container").remove();
750 739
751 740 var input_type = content.password ? 'password' : 'text';
752 741
753 742 area.append(
754 743 $("<div/>")
755 744 .addClass("box-flex1 output_subarea raw_input_container")
756 745 .append(
757 746 $("<span/>")
758 747 .addClass("raw_input_prompt")
759 748 .text(content.prompt)
760 749 )
761 750 .append(
762 751 $("<input/>")
763 752 .addClass("raw_input")
764 753 .attr('type', input_type)
765 754 .attr("size", 47)
766 755 .keydown(function (event, ui) {
767 756 // make sure we submit on enter,
768 757 // and don't re-execute the *cell* on shift-enter
769 758 if (event.which === keyboard.keycodes.enter) {
770 759 that._submit_raw_input();
771 760 return false;
772 761 }
773 762 })
774 763 )
775 764 );
776 765
777 766 this.element.append(area);
778 767 var raw_input = area.find('input.raw_input');
779 768 // Register events that enable/disable the keyboard manager while raw
780 769 // input is focused.
781 770 this.keyboard_manager.register_events(raw_input);
782 771 // Note, the following line used to read raw_input.focus().focus().
783 772 // This seemed to be needed otherwise only the cell would be focused.
784 773 // But with the modal UI, this seems to work fine with one call to focus().
785 774 raw_input.focus();
786 }
775 };
787 776
788 777 OutputArea.prototype._submit_raw_input = function (evt) {
789 778 var container = this.element.find("div.raw_input_container");
790 779 var theprompt = container.find("span.raw_input_prompt");
791 780 var theinput = container.find("input.raw_input");
792 781 var value = theinput.val();
793 782 var echo = value;
794 783 // don't echo if it's a password
795 784 if (theinput.attr('type') == 'password') {
796 785 echo = '········';
797 786 }
798 787 var content = {
799 788 output_type : 'stream',
800 789 stream : 'stdout',
801 790 text : theprompt.text() + echo + '\n'
802 }
791 };
803 792 // remove form container
804 793 container.parent().remove();
805 794 // replace with plaintext version in stdout
806 795 this.append_output(content, false);
807 796 this.events.trigger('send_input_reply.Kernel', value);
808 }
797 };
809 798
810 799
811 800 OutputArea.prototype.handle_clear_output = function (msg) {
812 801 // msg spec v4 had stdout, stderr, display keys
813 802 // v4.1 replaced these with just wait
814 803 // The default behavior is the same (stdout=stderr=display=True, wait=False),
815 804 // so v4 messages will still be properly handled,
816 805 // except for the rarely used clearing less than all output.
817 806 this.clear_output(msg.content.wait || false);
818 807 };
819 808
820 809
821 810 OutputArea.prototype.clear_output = function(wait) {
822 811 if (wait) {
823 812
824 813 // If a clear is queued, clear before adding another to the queue.
825 814 if (this.clear_queued) {
826 815 this.clear_output(false);
827 };
816 }
828 817
829 818 this.clear_queued = true;
830 819 } else {
831 820
832 821 // Fix the output div's height if the clear_output is waiting for
833 822 // new output (it is being used in an animation).
834 823 if (this.clear_queued) {
835 824 var height = this.element.height();
836 825 this.element.height(height);
837 826 this.clear_queued = false;
838 827 }
839 828
840 829 // Clear all
841 830 // Remove load event handlers from img tags because we don't want
842 831 // them to fire if the image is never added to the page.
843 832 this.element.find('img').off('load');
844 833 this.element.html("");
845 834 this.outputs = [];
846 835 this.trusted = true;
847 836 this.unscroll_area();
848 837 return;
849 };
838 }
850 839 };
851 840
852 841
853 842 // JSON serialization
854 843
855 OutputArea.prototype.fromJSON = function (outputs) {
844 OutputArea.prototype.fromJSON = function (outputs, metadata) {
856 845 var len = outputs.length;
857 var data;
846 metadata = metadata || {};
858 847
859 848 for (var i=0; i<len; i++) {
860 data = outputs[i];
861 var msg_type = data.output_type;
862 if (msg_type == "pyout") {
863 // pyout message has been renamed to execute_result,
864 // but the nbformat has not been updated,
865 // so transform back to pyout for json.
866 msg_type = data.output_type = "execute_result";
867 } else if (msg_type == "pyerr") {
868 // pyerr message has been renamed to error,
869 // but the nbformat has not been updated,
870 // so transform back to pyerr for json.
871 msg_type = data.output_type = "error";
849 this.append_output(outputs[i]);
850 }
851
852 if (metadata.collapsed !== undefined) {
853 this.collapsed = metadata.collapsed;
854 if (metadata.collapsed) {
855 this.collapse_output();
872 856 }
873 if (msg_type === "display_data" || msg_type === "execute_result") {
874 // convert short keys to mime keys
875 // TODO: remove mapping of short keys when we update to nbformat 4
876 data = this.rename_keys(data, OutputArea.mime_map_r);
877 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map_r);
878 // msg spec JSON is an object, nbformat v3 JSON is a JSON string
879 if (data["application/json"] !== undefined && typeof data["application/json"] === 'string') {
880 data["application/json"] = JSON.parse(data["application/json"]);
881 }
857 }
858 if (metadata.autoscroll !== undefined) {
859 this.collapsed = metadata.collapsed;
860 if (metadata.collapsed) {
861 this.collapse_output();
862 } else {
863 this.expand_output();
882 864 }
883
884 this.append_output(data);
885 865 }
886 866 };
887 867
888 868
889 869 OutputArea.prototype.toJSON = function () {
890 var outputs = [];
891 var len = this.outputs.length;
892 var data;
893 for (var i=0; i<len; i++) {
894 data = this.outputs[i];
895 var msg_type = data.output_type;
896 if (msg_type === "display_data" || msg_type === "execute_result") {
897 // convert mime keys to short keys
898 data = this.rename_keys(data, OutputArea.mime_map);
899 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map);
900 // msg spec JSON is an object, nbformat v3 JSON is a JSON string
901 if (data.json !== undefined && typeof data.json !== 'string') {
902 data.json = JSON.stringify(data.json);
903 }
904 }
905 if (msg_type == "execute_result") {
906 // pyout message has been renamed to execute_result,
907 // but the nbformat has not been updated,
908 // so transform back to pyout for json.
909 data.output_type = "pyout";
910 } else if (msg_type == "error") {
911 // pyerr message has been renamed to error,
912 // but the nbformat has not been updated,
913 // so transform back to pyerr for json.
914 data.output_type = "pyerr";
915 }
916 outputs[i] = data;
917 }
918 return outputs;
870 return this.outputs;
919 871 };
920 872
921 873 /**
922 874 * Class properties
923 875 **/
924 876
925 877 /**
926 878 * Threshold to trigger autoscroll when the OutputArea is resized,
927 879 * typically when new outputs are added.
928 880 *
929 881 * Behavior is undefined if autoscroll is lower than minimum_scroll_threshold,
930 882 * unless it is < 0, in which case autoscroll will never be triggered
931 883 *
932 884 * @property auto_scroll_threshold
933 885 * @type Number
934 886 * @default 100
935 887 *
936 888 **/
937 889 OutputArea.auto_scroll_threshold = 100;
938 890
939 891 /**
940 892 * Lower limit (in lines) for OutputArea to be made scrollable. OutputAreas
941 893 * shorter than this are never scrolled.
942 894 *
943 895 * @property minimum_scroll_threshold
944 896 * @type Number
945 897 * @default 20
946 898 *
947 899 **/
948 900 OutputArea.minimum_scroll_threshold = 20;
949 901
950 902
951
952 OutputArea.mime_map = {
953 "text/plain" : "text",
954 "text/html" : "html",
955 "image/svg+xml" : "svg",
956 "image/png" : "png",
957 "image/jpeg" : "jpeg",
958 "text/latex" : "latex",
959 "application/json" : "json",
960 "application/javascript" : "javascript",
961 };
962
963 OutputArea.mime_map_r = {
964 "text" : "text/plain",
965 "html" : "text/html",
966 "svg" : "image/svg+xml",
967 "png" : "image/png",
968 "jpeg" : "image/jpeg",
969 "latex" : "text/latex",
970 "json" : "application/json",
971 "javascript" : "application/javascript",
972 };
973
974 903 OutputArea.display_order = [
975 904 'application/javascript',
976 905 'text/html',
977 906 'text/markdown',
978 907 'text/latex',
979 908 'image/svg+xml',
980 909 'image/png',
981 910 'image/jpeg',
982 911 'application/pdf',
983 912 'text/plain'
984 913 ];
985 914
986 915 OutputArea.append_map = {
987 916 "text/plain" : append_text,
988 917 "text/html" : append_html,
989 918 "text/markdown": append_markdown,
990 919 "image/svg+xml" : append_svg,
991 920 "image/png" : append_png,
992 921 "image/jpeg" : append_jpeg,
993 922 "text/latex" : append_latex,
994 923 "application/javascript" : append_javascript,
995 924 "application/pdf" : append_pdf
996 925 };
997 926
998 927 // For backwards compatability.
999 928 IPython.OutputArea = OutputArea;
1000 929
1001 930 return {'OutputArea': OutputArea};
1002 931 });
@@ -1,425 +1,345 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define([
5 5 'base/js/namespace',
6 6 'base/js/utils',
7 7 'jquery',
8 8 'notebook/js/cell',
9 9 'base/js/security',
10 10 'notebook/js/mathjaxutils',
11 11 'notebook/js/celltoolbar',
12 12 'components/marked/lib/marked',
13 13 'codemirror/lib/codemirror',
14 14 'codemirror/mode/gfm/gfm',
15 15 'notebook/js/codemirror-ipythongfm'
16 16 ], function(IPython,utils , $, cell, security, mathjaxutils, celltoolbar, marked, CodeMirror, gfm, ipgfm) {
17 17 "use strict";
18 18 var Cell = cell.Cell;
19 19
20 20 var TextCell = function (options) {
21 21 // Constructor
22 22 //
23 23 // Construct a new TextCell, codemirror mode is by default 'htmlmixed',
24 24 // and cell type is 'text' cell start as not redered.
25 25 //
26 26 // Parameters:
27 27 // options: dictionary
28 28 // Dictionary of keyword arguments.
29 29 // events: $(Events) instance
30 30 // config: dictionary
31 31 // keyboard_manager: KeyboardManager instance
32 32 // notebook: Notebook instance
33 33 options = options || {};
34 34
35 35 // in all TextCell/Cell subclasses
36 36 // do not assign most of members here, just pass it down
37 37 // in the options dict potentially overwriting what you wish.
38 38 // they will be assigned in the base class.
39 39 this.notebook = options.notebook;
40 40 this.events = options.events;
41 41 this.config = options.config;
42 42
43 43 // we cannot put this as a class key as it has handle to "this".
44 44 var cm_overwrite_options = {
45 45 onKeyEvent: $.proxy(this.handle_keyevent,this)
46 46 };
47 47 var config = utils.mergeopt(TextCell, this.config, {cm_config:cm_overwrite_options});
48 48 Cell.apply(this, [{
49 49 config: config,
50 50 keyboard_manager: options.keyboard_manager,
51 51 events: this.events}]);
52 52
53 53 this.cell_type = this.cell_type || 'text';
54 54 mathjaxutils = mathjaxutils;
55 55 this.rendered = false;
56 56 };
57 57
58 58 TextCell.prototype = Object.create(Cell.prototype);
59 59
60 60 TextCell.options_default = {
61 61 cm_config : {
62 62 extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess"},
63 63 mode: 'htmlmixed',
64 64 lineWrapping : true,
65 65 }
66 66 };
67 67
68 68
69 69 /**
70 70 * Create the DOM element of the TextCell
71 71 * @method create_element
72 72 * @private
73 73 */
74 74 TextCell.prototype.create_element = function () {
75 75 Cell.prototype.create_element.apply(this, arguments);
76 76
77 77 var cell = $("<div>").addClass('cell text_cell');
78 78 cell.attr('tabindex','2');
79 79
80 80 var prompt = $('<div/>').addClass('prompt input_prompt');
81 81 cell.append(prompt);
82 82 var inner_cell = $('<div/>').addClass('inner_cell');
83 83 this.celltoolbar = new celltoolbar.CellToolbar({
84 84 cell: this,
85 85 notebook: this.notebook});
86 86 inner_cell.append(this.celltoolbar.element);
87 87 var input_area = $('<div/>').addClass('input_area');
88 88 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
89 89 // The tabindex=-1 makes this div focusable.
90 90 var render_area = $('<div/>').addClass('text_cell_render rendered_html')
91 91 .attr('tabindex','-1');
92 92 inner_cell.append(input_area).append(render_area);
93 93 cell.append(inner_cell);
94 94 this.element = cell;
95 95 };
96 96
97 97
98 98 // Cell level actions
99 99
100 100 TextCell.prototype.select = function () {
101 101 var cont = Cell.prototype.select.apply(this);
102 102 if (cont) {
103 103 if (this.mode === 'edit') {
104 104 this.code_mirror.refresh();
105 105 }
106 106 }
107 107 return cont;
108 108 };
109 109
110 110 TextCell.prototype.unrender = function () {
111 111 if (this.read_only) return;
112 112 var cont = Cell.prototype.unrender.apply(this);
113 113 if (cont) {
114 114 var text_cell = this.element;
115 115 var output = text_cell.find("div.text_cell_render");
116 116 if (this.get_text() === this.placeholder) {
117 117 this.set_text('');
118 118 }
119 119 this.refresh();
120 120 }
121 121 return cont;
122 122 };
123 123
124 124 TextCell.prototype.execute = function () {
125 125 this.render();
126 126 };
127 127
128 128 /**
129 129 * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
130 130 * @method get_text
131 131 * @retrun {string} CodeMirror current text value
132 132 */
133 133 TextCell.prototype.get_text = function() {
134 134 return this.code_mirror.getValue();
135 135 };
136 136
137 137 /**
138 138 * @param {string} text - Codemiror text value
139 139 * @see TextCell#get_text
140 140 * @method set_text
141 141 * */
142 142 TextCell.prototype.set_text = function(text) {
143 143 this.code_mirror.setValue(text);
144 144 this.unrender();
145 145 this.code_mirror.refresh();
146 146 };
147 147
148 148 /**
149 149 * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
150 150 * @method get_rendered
151 151 * */
152 152 TextCell.prototype.get_rendered = function() {
153 153 return this.element.find('div.text_cell_render').html();
154 154 };
155 155
156 156 /**
157 157 * @method set_rendered
158 158 */
159 159 TextCell.prototype.set_rendered = function(text) {
160 160 this.element.find('div.text_cell_render').html(text);
161 161 };
162 162
163 163
164 164 /**
165 165 * Create Text cell from JSON
166 166 * @param {json} data - JSON serialized text-cell
167 167 * @method fromJSON
168 168 */
169 169 TextCell.prototype.fromJSON = function (data) {
170 170 Cell.prototype.fromJSON.apply(this, arguments);
171 171 if (data.cell_type === this.cell_type) {
172 172 if (data.source !== undefined) {
173 173 this.set_text(data.source);
174 174 // make this value the starting point, so that we can only undo
175 175 // to this state, instead of a blank cell
176 176 this.code_mirror.clearHistory();
177 177 // TODO: This HTML needs to be treated as potentially dangerous
178 178 // user input and should be handled before set_rendered.
179 179 this.set_rendered(data.rendered || '');
180 180 this.rendered = false;
181 181 this.render();
182 182 }
183 183 }
184 184 };
185 185
186 186 /** Generate JSON from cell
187 187 * @return {object} cell data serialised to json
188 188 */
189 189 TextCell.prototype.toJSON = function () {
190 190 var data = Cell.prototype.toJSON.apply(this);
191 191 data.source = this.get_text();
192 192 if (data.source == this.placeholder) {
193 193 data.source = "";
194 194 }
195 195 return data;
196 196 };
197 197
198 198
199 199 var MarkdownCell = function (options) {
200 200 // Constructor
201 201 //
202 202 // Parameters:
203 203 // options: dictionary
204 204 // Dictionary of keyword arguments.
205 205 // events: $(Events) instance
206 206 // config: dictionary
207 207 // keyboard_manager: KeyboardManager instance
208 208 // notebook: Notebook instance
209 209 options = options || {};
210 210 var config = utils.mergeopt(MarkdownCell, options.config);
211 211 TextCell.apply(this, [$.extend({}, options, {config: config})]);
212 212
213 213 this.cell_type = 'markdown';
214 214 };
215 215
216 216 MarkdownCell.options_default = {
217 217 cm_config: {
218 218 mode: 'ipythongfm'
219 219 },
220 220 placeholder: "Type *Markdown* and LaTeX: $\\alpha^2$"
221 221 };
222 222
223 223 MarkdownCell.prototype = Object.create(TextCell.prototype);
224 224
225 MarkdownCell.prototype.set_heading_level = function (level) {
226 // make a markdown cell a heading
227 level = level || 1;
228 var source = this.get_text();
229 source = source.replace(/^(#*)\s?/,
230 new Array(level + 1).join('#') + ' ');
231 this.set_text(source);
232 this.refresh();
233 if (this.rendered) {
234 this.render();
235 }
236 };
237
225 238 /**
226 239 * @method render
227 240 */
228 241 MarkdownCell.prototype.render = function () {
229 242 var cont = TextCell.prototype.render.apply(this);
230 243 if (cont) {
231 244 var text = this.get_text();
232 245 var math = null;
233 246 if (text === "") { text = this.placeholder; }
234 247 var text_and_math = mathjaxutils.remove_math(text);
235 248 text = text_and_math[0];
236 249 math = text_and_math[1];
237 250 var html = marked.parser(marked.lexer(text));
238 251 html = mathjaxutils.replace_math(html, math);
239 252 html = security.sanitize_html(html);
240 253 html = $($.parseHTML(html));
254 // add anchors to headings
255 // console.log(html);
256 html.find(":header").addBack(":header").each(function (i, h) {
257 h = $(h);
258 var hash = h.text().replace(/ /g, '-');
259 h.attr('id', hash);
260 h.append(
261 $('<a/>')
262 .addClass('anchor-link')
263 .attr('href', '#' + hash)
264 .text('¶')
265 );
266 })
241 267 // links in markdown cells should open in new tabs
242 268 html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
243 269 this.set_rendered(html);
244 270 this.typeset();
245 271 this.events.trigger("rendered.MarkdownCell", {cell: this})
246 272 }
247 273 return cont;
248 274 };
249 275
250 276
251 277 var RawCell = function (options) {
252 278 // Constructor
253 279 //
254 280 // Parameters:
255 281 // options: dictionary
256 282 // Dictionary of keyword arguments.
257 283 // events: $(Events) instance
258 284 // config: dictionary
259 285 // keyboard_manager: KeyboardManager instance
260 286 // notebook: Notebook instance
261 287 options = options || {};
262 288 var config = utils.mergeopt(RawCell, options.config);
263 289 TextCell.apply(this, [$.extend({}, options, {config: config})]);
264 290
265 291 this.cell_type = 'raw';
266 292 };
267 293
268 294 RawCell.options_default = {
269 295 placeholder : "Write raw LaTeX or other formats here, for use with nbconvert. " +
270 296 "It will not be rendered in the notebook. " +
271 297 "When passing through nbconvert, a Raw Cell's content is added to the output unmodified."
272 298 };
273 299
274 300 RawCell.prototype = Object.create(TextCell.prototype);
275 301
276 302 /** @method bind_events **/
277 303 RawCell.prototype.bind_events = function () {
278 304 TextCell.prototype.bind_events.apply(this);
279 305 var that = this;
280 306 this.element.focusout(function() {
281 307 that.auto_highlight();
282 308 that.render();
283 309 });
284 310
285 311 this.code_mirror.on('focus', function() { that.unrender(); });
286 312 };
287 313
288 314 /**
289 315 * Trigger autodetection of highlight scheme for current cell
290 316 * @method auto_highlight
291 317 */
292 318 RawCell.prototype.auto_highlight = function () {
293 319 this._auto_highlight(this.config.raw_cell_highlight);
294 320 };
295 321
296 322 /** @method render **/
297 323 RawCell.prototype.render = function () {
298 324 var cont = TextCell.prototype.render.apply(this);
299 325 if (cont){
300 326 var text = this.get_text();
301 327 if (text === "") { text = this.placeholder; }
302 328 this.set_text(text);
303 329 this.element.removeClass('rendered');
304 330 }
305 331 return cont;
306 332 };
307 333
308
309 var HeadingCell = function (options) {
310 // Constructor
311 //
312 // Parameters:
313 // options: dictionary
314 // Dictionary of keyword arguments.
315 // events: $(Events) instance
316 // config: dictionary
317 // keyboard_manager: KeyboardManager instance
318 // notebook: Notebook instance
319 options = options || {};
320 var config = utils.mergeopt(HeadingCell, options.config);
321 TextCell.apply(this, [$.extend({}, options, {config: config})]);
322
323 this.level = 1;
324 this.cell_type = 'heading';
325 };
326
327 HeadingCell.options_default = {
328 cm_config: {
329 theme: 'heading-1'
330 },
331 placeholder: "Type Heading Here"
332 };
333
334 HeadingCell.prototype = Object.create(TextCell.prototype);
335
336 /** @method fromJSON */
337 HeadingCell.prototype.fromJSON = function (data) {
338 if (data.level !== undefined){
339 this.level = data.level;
340 }
341 TextCell.prototype.fromJSON.apply(this, arguments);
342 this.code_mirror.setOption("theme", "heading-"+this.level);
343 };
344
345
346 /** @method toJSON */
347 HeadingCell.prototype.toJSON = function () {
348 var data = TextCell.prototype.toJSON.apply(this);
349 data.level = this.get_level();
350 return data;
351 };
352
353 /**
354 * Change heading level of cell, and re-render
355 * @method set_level
356 */
357 HeadingCell.prototype.set_level = function (level) {
358 this.level = level;
359 this.code_mirror.setOption("theme", "heading-"+level);
360
361 if (this.rendered) {
362 this.rendered = false;
363 this.render();
364 }
365 };
366
367 /** The depth of header cell, based on html (h1 to h6)
368 * @method get_level
369 * @return {integer} level - for 1 to 6
370 */
371 HeadingCell.prototype.get_level = function () {
372 return this.level;
373 };
374
375
376 HeadingCell.prototype.get_rendered = function () {
377 var r = this.element.find("div.text_cell_render");
378 return r.children().first().html();
379 };
380
381 HeadingCell.prototype.render = function () {
382 var cont = TextCell.prototype.render.apply(this);
383 if (cont) {
384 var text = this.get_text();
385 var math = null;
386 // Markdown headings must be a single line
387 text = text.replace(/\n/g, ' ');
388 if (text === "") { text = this.placeholder; }
389 text = new Array(this.level + 1).join("#") + " " + text;
390 var text_and_math = mathjaxutils.remove_math(text);
391 text = text_and_math[0];
392 math = text_and_math[1];
393 var html = marked.parser(marked.lexer(text));
394 html = mathjaxutils.replace_math(html, math);
395 html = security.sanitize_html(html);
396 var h = $($.parseHTML(html));
397 // add id and linkback anchor
398 var hash = h.text().trim().replace(/ /g, '-');
399 h.attr('id', hash);
400 h.append(
401 $('<a/>')
402 .addClass('anchor-link')
403 .attr('href', '#' + hash)
404 .text('¶')
405 );
406 this.set_rendered(h);
407 this.typeset();
408 }
409 return cont;
410 };
411
412 334 // Backwards compatability.
413 335 IPython.TextCell = TextCell;
414 336 IPython.MarkdownCell = MarkdownCell;
415 337 IPython.RawCell = RawCell;
416 IPython.HeadingCell = HeadingCell;
417 338
418 339 var textcell = {
419 'TextCell': TextCell,
420 'MarkdownCell': MarkdownCell,
421 'RawCell': RawCell,
422 'HeadingCell': HeadingCell,
340 TextCell: TextCell,
341 MarkdownCell: MarkdownCell,
342 RawCell: RawCell,
423 343 };
424 344 return textcell;
425 345 });
@@ -1,69 +1,68 b''
1 1 div.text_cell {
2 2 padding: 5px 5px 5px 0px;
3 3 .hbox();
4 4 }
5 5 @media (max-width: 480px) {
6 6 // remove prompt indentation on small screens
7 7 div.text_cell > div.prompt {
8 8 display: none;
9 9 }
10 10 }
11 11
12 12 div.text_cell_render {
13 13 /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
14 14 outline: none;
15 15 resize: none;
16 16 width: inherit;
17 17 border-style: none;
18 18 padding: 0.5em 0.5em 0.5em @code_padding;
19 19 color: @text-color;
20 20 .border-box-sizing();
21 21 }
22 22
23 23 a.anchor-link:link {
24 24 text-decoration: none;
25 25 padding: 0px 20px;
26 26 visibility: hidden;
27 27 }
28 28
29 29 h1,h2,h3,h4,h5,h6 {
30 30 &:hover .anchor-link {
31 31 visibility: visible;
32 32 }
33 33 }
34 34
35 35 div.cell.text_cell.rendered {
36 36 padding: 0px;
37 37 }
38 38
39
40 39 .text_cell.rendered .input_area {
41 40 display: none;
42 41 }
43 42
44 43 .text_cell.unrendered .text_cell_render {
45 44 display:none;
46 45 }
47 46
48 .cm-s-heading-1,
49 .cm-s-heading-2,
50 .cm-s-heading-3,
51 .cm-s-heading-4,
52 .cm-s-heading-5,
53 .cm-s-heading-6 {
47 .cm-header-1,
48 .cm-header-2,
49 .cm-header-3,
50 .cm-header-4,
51 .cm-header-5,
52 .cm-header-6 {
54 53 font-weight: bold;
55 54 font-family: @font-family-sans-serif;
56 55 }
57 56
58 .cm-s-heading-1 { font-size:150%; }
59 .cm-s-heading-2 { font-size: 130%; }
60 .cm-s-heading-3 { font-size: 120%; }
61 .cm-s-heading-4 { font-size: 110%; }
62 .cm-s-heading-5 {
63 font-size: 100%;
57 .cm-header-1 { font-size: 185.7%; }
58 .cm-header-2 { font-size: 157.1%; }
59 .cm-header-3 { font-size: 128.6%; }
60 .cm-header-4 { font-size: 110%; }
61 .cm-header-5 {
62 font-size: 100%;
64 63 font-style: italic;
65 64 }
66 .cm-s-heading-6 {
67 font-size: 90%;
65 .cm-header-6 {
66 font-size: 100%;
68 67 font-style: italic;
69 68 }
@@ -1,1535 +1,1535 b''
1 1 /*!
2 2 *
3 3 * IPython base
4 4 *
5 5 */
6 6 .modal.fade .modal-dialog {
7 7 -webkit-transform: translate(0, 0);
8 8 -ms-transform: translate(0, 0);
9 9 transform: translate(0, 0);
10 10 }
11 11 code {
12 12 color: #000000;
13 13 }
14 14 pre {
15 15 font-size: inherit;
16 16 line-height: inherit;
17 17 }
18 18 label {
19 19 font-weight: normal;
20 20 }
21 21 .border-box-sizing {
22 22 box-sizing: border-box;
23 23 -moz-box-sizing: border-box;
24 24 -webkit-box-sizing: border-box;
25 25 }
26 26 .corner-all {
27 27 border-radius: 4px;
28 28 }
29 29 .no-padding {
30 30 padding: 0px;
31 31 }
32 32 /* Flexible box model classes */
33 33 /* Taken from Alex Russell http://infrequently.org/2009/08/css-3-progress/ */
34 34 /* This file is a compatability layer. It allows the usage of flexible box
35 35 model layouts accross multiple browsers, including older browsers. The newest,
36 36 universal implementation of the flexible box model is used when available (see
37 37 `Modern browsers` comments below). Browsers that are known to implement this
38 38 new spec completely include:
39 39
40 40 Firefox 28.0+
41 41 Chrome 29.0+
42 42 Internet Explorer 11+
43 43 Opera 17.0+
44 44
45 45 Browsers not listed, including Safari, are supported via the styling under the
46 46 `Old browsers` comments below.
47 47 */
48 48 .hbox {
49 49 /* Old browsers */
50 50 display: -webkit-box;
51 51 -webkit-box-orient: horizontal;
52 52 -webkit-box-align: stretch;
53 53 display: -moz-box;
54 54 -moz-box-orient: horizontal;
55 55 -moz-box-align: stretch;
56 56 display: box;
57 57 box-orient: horizontal;
58 58 box-align: stretch;
59 59 /* Modern browsers */
60 60 display: flex;
61 61 flex-direction: row;
62 62 align-items: stretch;
63 63 }
64 64 .hbox > * {
65 65 /* Old browsers */
66 66 -webkit-box-flex: 0;
67 67 -moz-box-flex: 0;
68 68 box-flex: 0;
69 69 /* Modern browsers */
70 70 flex: none;
71 71 }
72 72 .vbox {
73 73 /* Old browsers */
74 74 display: -webkit-box;
75 75 -webkit-box-orient: vertical;
76 76 -webkit-box-align: stretch;
77 77 display: -moz-box;
78 78 -moz-box-orient: vertical;
79 79 -moz-box-align: stretch;
80 80 display: box;
81 81 box-orient: vertical;
82 82 box-align: stretch;
83 83 /* Modern browsers */
84 84 display: flex;
85 85 flex-direction: column;
86 86 align-items: stretch;
87 87 }
88 88 .vbox > * {
89 89 /* Old browsers */
90 90 -webkit-box-flex: 0;
91 91 -moz-box-flex: 0;
92 92 box-flex: 0;
93 93 /* Modern browsers */
94 94 flex: none;
95 95 }
96 96 .hbox.reverse,
97 97 .vbox.reverse,
98 98 .reverse {
99 99 /* Old browsers */
100 100 -webkit-box-direction: reverse;
101 101 -moz-box-direction: reverse;
102 102 box-direction: reverse;
103 103 /* Modern browsers */
104 104 flex-direction: row-reverse;
105 105 }
106 106 .hbox.box-flex0,
107 107 .vbox.box-flex0,
108 108 .box-flex0 {
109 109 /* Old browsers */
110 110 -webkit-box-flex: 0;
111 111 -moz-box-flex: 0;
112 112 box-flex: 0;
113 113 /* Modern browsers */
114 114 flex: none;
115 115 width: auto;
116 116 }
117 117 .hbox.box-flex1,
118 118 .vbox.box-flex1,
119 119 .box-flex1 {
120 120 /* Old browsers */
121 121 -webkit-box-flex: 1;
122 122 -moz-box-flex: 1;
123 123 box-flex: 1;
124 124 /* Modern browsers */
125 125 flex: 1;
126 126 }
127 127 .hbox.box-flex,
128 128 .vbox.box-flex,
129 129 .box-flex {
130 130 /* Old browsers */
131 131 /* Old browsers */
132 132 -webkit-box-flex: 1;
133 133 -moz-box-flex: 1;
134 134 box-flex: 1;
135 135 /* Modern browsers */
136 136 flex: 1;
137 137 }
138 138 .hbox.box-flex2,
139 139 .vbox.box-flex2,
140 140 .box-flex2 {
141 141 /* Old browsers */
142 142 -webkit-box-flex: 2;
143 143 -moz-box-flex: 2;
144 144 box-flex: 2;
145 145 /* Modern browsers */
146 146 flex: 2;
147 147 }
148 148 .box-group1 {
149 149 /* Deprecated */
150 150 -webkit-box-flex-group: 1;
151 151 -moz-box-flex-group: 1;
152 152 box-flex-group: 1;
153 153 }
154 154 .box-group2 {
155 155 /* Deprecated */
156 156 -webkit-box-flex-group: 2;
157 157 -moz-box-flex-group: 2;
158 158 box-flex-group: 2;
159 159 }
160 160 .hbox.start,
161 161 .vbox.start,
162 162 .start {
163 163 /* Old browsers */
164 164 -webkit-box-pack: start;
165 165 -moz-box-pack: start;
166 166 box-pack: start;
167 167 /* Modern browsers */
168 168 justify-content: flex-start;
169 169 }
170 170 .hbox.end,
171 171 .vbox.end,
172 172 .end {
173 173 /* Old browsers */
174 174 -webkit-box-pack: end;
175 175 -moz-box-pack: end;
176 176 box-pack: end;
177 177 /* Modern browsers */
178 178 justify-content: flex-end;
179 179 }
180 180 .hbox.center,
181 181 .vbox.center,
182 182 .center {
183 183 /* Old browsers */
184 184 -webkit-box-pack: center;
185 185 -moz-box-pack: center;
186 186 box-pack: center;
187 187 /* Modern browsers */
188 188 justify-content: center;
189 189 }
190 190 .hbox.baseline,
191 191 .vbox.baseline,
192 192 .baseline {
193 193 /* Old browsers */
194 194 -webkit-box-pack: baseline;
195 195 -moz-box-pack: baseline;
196 196 box-pack: baseline;
197 197 /* Modern browsers */
198 198 justify-content: baseline;
199 199 }
200 200 .hbox.stretch,
201 201 .vbox.stretch,
202 202 .stretch {
203 203 /* Old browsers */
204 204 -webkit-box-pack: stretch;
205 205 -moz-box-pack: stretch;
206 206 box-pack: stretch;
207 207 /* Modern browsers */
208 208 justify-content: stretch;
209 209 }
210 210 .hbox.align-start,
211 211 .vbox.align-start,
212 212 .align-start {
213 213 /* Old browsers */
214 214 -webkit-box-align: start;
215 215 -moz-box-align: start;
216 216 box-align: start;
217 217 /* Modern browsers */
218 218 align-items: flex-start;
219 219 }
220 220 .hbox.align-end,
221 221 .vbox.align-end,
222 222 .align-end {
223 223 /* Old browsers */
224 224 -webkit-box-align: end;
225 225 -moz-box-align: end;
226 226 box-align: end;
227 227 /* Modern browsers */
228 228 align-items: flex-end;
229 229 }
230 230 .hbox.align-center,
231 231 .vbox.align-center,
232 232 .align-center {
233 233 /* Old browsers */
234 234 -webkit-box-align: center;
235 235 -moz-box-align: center;
236 236 box-align: center;
237 237 /* Modern browsers */
238 238 align-items: center;
239 239 }
240 240 .hbox.align-baseline,
241 241 .vbox.align-baseline,
242 242 .align-baseline {
243 243 /* Old browsers */
244 244 -webkit-box-align: baseline;
245 245 -moz-box-align: baseline;
246 246 box-align: baseline;
247 247 /* Modern browsers */
248 248 align-items: baseline;
249 249 }
250 250 .hbox.align-stretch,
251 251 .vbox.align-stretch,
252 252 .align-stretch {
253 253 /* Old browsers */
254 254 -webkit-box-align: stretch;
255 255 -moz-box-align: stretch;
256 256 box-align: stretch;
257 257 /* Modern browsers */
258 258 align-items: stretch;
259 259 }
260 260 div.error {
261 261 margin: 2em;
262 262 text-align: center;
263 263 }
264 264 div.error > h1 {
265 265 font-size: 500%;
266 266 line-height: normal;
267 267 }
268 268 div.error > p {
269 269 font-size: 200%;
270 270 line-height: normal;
271 271 }
272 272 div.traceback-wrapper {
273 273 text-align: left;
274 274 max-width: 800px;
275 275 margin: auto;
276 276 }
277 277 /*!
278 278 *
279 279 * IPython notebook
280 280 *
281 281 */
282 282 /* CSS font colors for translated ANSI colors. */
283 283 .ansibold {
284 284 font-weight: bold;
285 285 }
286 286 /* use dark versions for foreground, to improve visibility */
287 287 .ansiblack {
288 288 color: black;
289 289 }
290 290 .ansired {
291 291 color: darkred;
292 292 }
293 293 .ansigreen {
294 294 color: darkgreen;
295 295 }
296 296 .ansiyellow {
297 297 color: #c4a000;
298 298 }
299 299 .ansiblue {
300 300 color: darkblue;
301 301 }
302 302 .ansipurple {
303 303 color: darkviolet;
304 304 }
305 305 .ansicyan {
306 306 color: steelblue;
307 307 }
308 308 .ansigray {
309 309 color: gray;
310 310 }
311 311 /* and light for background, for the same reason */
312 312 .ansibgblack {
313 313 background-color: black;
314 314 }
315 315 .ansibgred {
316 316 background-color: red;
317 317 }
318 318 .ansibggreen {
319 319 background-color: green;
320 320 }
321 321 .ansibgyellow {
322 322 background-color: yellow;
323 323 }
324 324 .ansibgblue {
325 325 background-color: blue;
326 326 }
327 327 .ansibgpurple {
328 328 background-color: magenta;
329 329 }
330 330 .ansibgcyan {
331 331 background-color: cyan;
332 332 }
333 333 .ansibggray {
334 334 background-color: gray;
335 335 }
336 336 div.cell {
337 337 border: 1px solid transparent;
338 338 /* Old browsers */
339 339 display: -webkit-box;
340 340 -webkit-box-orient: vertical;
341 341 -webkit-box-align: stretch;
342 342 display: -moz-box;
343 343 -moz-box-orient: vertical;
344 344 -moz-box-align: stretch;
345 345 display: box;
346 346 box-orient: vertical;
347 347 box-align: stretch;
348 348 /* Modern browsers */
349 349 display: flex;
350 350 flex-direction: column;
351 351 align-items: stretch;
352 352 border-radius: 4px;
353 353 box-sizing: border-box;
354 354 -moz-box-sizing: border-box;
355 355 -webkit-box-sizing: border-box;
356 356 border-width: thin;
357 357 border-style: solid;
358 358 width: 100%;
359 359 padding: 5px 5px 5px 0px;
360 360 /* This acts as a spacer between cells, that is outside the border */
361 361 margin: 0px;
362 362 outline: none;
363 363 }
364 364 div.cell.selected {
365 365 border-color: #ababab;
366 366 }
367 367 div.cell.edit_mode {
368 368 border-color: green;
369 369 }
370 370 div.prompt {
371 371 /* This needs to be wide enough for 3 digit prompt numbers: In[100]: */
372 372 min-width: 15ex;
373 373 /* This padding is tuned to match the padding on the CodeMirror editor. */
374 374 padding: 0.4em;
375 375 margin: 0px;
376 376 font-family: monospace;
377 377 text-align: right;
378 378 /* This has to match that of the the CodeMirror class line-height below */
379 379 line-height: 1.21429em;
380 380 }
381 381 @media (max-width: 480px) {
382 382 div.prompt {
383 383 text-align: left;
384 384 }
385 385 }
386 386 div.inner_cell {
387 387 /* Old browsers */
388 388 display: -webkit-box;
389 389 -webkit-box-orient: vertical;
390 390 -webkit-box-align: stretch;
391 391 display: -moz-box;
392 392 -moz-box-orient: vertical;
393 393 -moz-box-align: stretch;
394 394 display: box;
395 395 box-orient: vertical;
396 396 box-align: stretch;
397 397 /* Modern browsers */
398 398 display: flex;
399 399 flex-direction: column;
400 400 align-items: stretch;
401 401 /* Old browsers */
402 402 -webkit-box-flex: 1;
403 403 -moz-box-flex: 1;
404 404 box-flex: 1;
405 405 /* Modern browsers */
406 406 flex: 1;
407 407 }
408 408 /* input_area and input_prompt must match in top border and margin for alignment */
409 409 div.input_area {
410 410 border: 1px solid #cfcfcf;
411 411 border-radius: 4px;
412 412 background: #f7f7f7;
413 413 line-height: 1.21429em;
414 414 }
415 415 /* This is needed so that empty prompt areas can collapse to zero height when there
416 416 is no content in the output_subarea and the prompt. The main purpose of this is
417 417 to make sure that empty JavaScript output_subareas have no height. */
418 418 div.prompt:empty {
419 419 padding-top: 0;
420 420 padding-bottom: 0;
421 421 }
422 422 /* any special styling for code cells that are currently running goes here */
423 423 div.input {
424 424 page-break-inside: avoid;
425 425 /* Old browsers */
426 426 display: -webkit-box;
427 427 -webkit-box-orient: horizontal;
428 428 -webkit-box-align: stretch;
429 429 display: -moz-box;
430 430 -moz-box-orient: horizontal;
431 431 -moz-box-align: stretch;
432 432 display: box;
433 433 box-orient: horizontal;
434 434 box-align: stretch;
435 435 /* Modern browsers */
436 436 display: flex;
437 437 flex-direction: row;
438 438 align-items: stretch;
439 439 }
440 440 @media (max-width: 480px) {
441 441 div.input {
442 442 /* Old browsers */
443 443 display: -webkit-box;
444 444 -webkit-box-orient: vertical;
445 445 -webkit-box-align: stretch;
446 446 display: -moz-box;
447 447 -moz-box-orient: vertical;
448 448 -moz-box-align: stretch;
449 449 display: box;
450 450 box-orient: vertical;
451 451 box-align: stretch;
452 452 /* Modern browsers */
453 453 display: flex;
454 454 flex-direction: column;
455 455 align-items: stretch;
456 456 }
457 457 }
458 458 /* input_area and input_prompt must match in top border and margin for alignment */
459 459 div.input_prompt {
460 460 color: #000080;
461 461 border-top: 1px solid transparent;
462 462 }
463 463 div.input_area > div.highlight {
464 464 margin: 0.4em;
465 465 border: none;
466 466 padding: 0px;
467 467 background-color: transparent;
468 468 }
469 469 div.input_area > div.highlight > pre {
470 470 margin: 0px;
471 471 border: none;
472 472 padding: 0px;
473 473 background-color: transparent;
474 474 }
475 475 /* The following gets added to the <head> if it is detected that the user has a
476 476 * monospace font with inconsistent normal/bold/italic height. See
477 477 * notebookmain.js. Such fonts will have keywords vertically offset with
478 478 * respect to the rest of the text. The user should select a better font.
479 479 * See: https://github.com/ipython/ipython/issues/1503
480 480 *
481 481 * .CodeMirror span {
482 482 * vertical-align: bottom;
483 483 * }
484 484 */
485 485 .CodeMirror {
486 486 line-height: 1.21429em;
487 487 /* Changed from 1em to our global default */
488 488 height: auto;
489 489 /* Changed to auto to autogrow */
490 490 background: none;
491 491 /* Changed from white to allow our bg to show through */
492 492 }
493 493 .CodeMirror-scroll {
494 494 /* The CodeMirror docs are a bit fuzzy on if overflow-y should be hidden or visible.*/
495 495 /* We have found that if it is visible, vertical scrollbars appear with font size changes.*/
496 496 overflow-y: hidden;
497 497 overflow-x: auto;
498 498 }
499 499 .CodeMirror-lines {
500 500 /* In CM2, this used to be 0.4em, but in CM3 it went to 4px. We need the em value because */
501 501 /* we have set a different line-height and want this to scale with that. */
502 502 padding: 0.4em;
503 503 }
504 504 .CodeMirror-linenumber {
505 505 padding: 0 8px 0 4px;
506 506 }
507 507 .CodeMirror-gutters {
508 508 border-bottom-left-radius: 4px;
509 509 border-top-left-radius: 4px;
510 510 }
511 511 .CodeMirror pre {
512 512 /* In CM3 this went to 4px from 0 in CM2. We need the 0 value because of how we size */
513 513 /* .CodeMirror-lines */
514 514 padding: 0;
515 515 border: 0;
516 516 border-radius: 0;
517 517 }
518 518 .CodeMirror-vscrollbar,
519 519 .CodeMirror-hscrollbar {
520 520 display: none !important;
521 521 }
522 522 /*
523 523
524 524 Original style from softwaremaniacs.org (c) Ivan Sagalaev <Maniac@SoftwareManiacs.Org>
525 525 Adapted from GitHub theme
526 526
527 527 */
528 528 pre code {
529 529 display: block;
530 530 padding: 0.5em;
531 531 }
532 532 .highlight-base,
533 533 pre code,
534 534 pre .subst,
535 535 pre .tag .title,
536 536 pre .lisp .title,
537 537 pre .clojure .built_in,
538 538 pre .nginx .title {
539 539 color: black;
540 540 }
541 541 .highlight-string,
542 542 pre .string,
543 543 pre .constant,
544 544 pre .parent,
545 545 pre .tag .value,
546 546 pre .rules .value,
547 547 pre .rules .value .number,
548 548 pre .preprocessor,
549 549 pre .ruby .symbol,
550 550 pre .ruby .symbol .string,
551 551 pre .aggregate,
552 552 pre .template_tag,
553 553 pre .django .variable,
554 554 pre .smalltalk .class,
555 555 pre .addition,
556 556 pre .flow,
557 557 pre .stream,
558 558 pre .bash .variable,
559 559 pre .apache .tag,
560 560 pre .apache .cbracket,
561 561 pre .tex .command,
562 562 pre .tex .special,
563 563 pre .erlang_repl .function_or_atom,
564 564 pre .markdown .header {
565 565 color: #BA2121;
566 566 }
567 567 .highlight-comment,
568 568 pre .comment,
569 569 pre .annotation,
570 570 pre .template_comment,
571 571 pre .diff .header,
572 572 pre .chunk,
573 573 pre .markdown .blockquote {
574 574 color: #408080;
575 575 font-style: italic;
576 576 }
577 577 .highlight-number,
578 578 pre .number,
579 579 pre .date,
580 580 pre .regexp,
581 581 pre .literal,
582 582 pre .smalltalk .symbol,
583 583 pre .smalltalk .char,
584 584 pre .go .constant,
585 585 pre .change,
586 586 pre .markdown .bullet,
587 587 pre .markdown .link_url {
588 588 color: #080;
589 589 }
590 590 pre .label,
591 591 pre .javadoc,
592 592 pre .ruby .string,
593 593 pre .decorator,
594 594 pre .filter .argument,
595 595 pre .localvars,
596 596 pre .array,
597 597 pre .attr_selector,
598 598 pre .important,
599 599 pre .pseudo,
600 600 pre .pi,
601 601 pre .doctype,
602 602 pre .deletion,
603 603 pre .envvar,
604 604 pre .shebang,
605 605 pre .apache .sqbracket,
606 606 pre .nginx .built_in,
607 607 pre .tex .formula,
608 608 pre .erlang_repl .reserved,
609 609 pre .prompt,
610 610 pre .markdown .link_label,
611 611 pre .vhdl .attribute,
612 612 pre .clojure .attribute,
613 613 pre .coffeescript .property {
614 614 color: #8888ff;
615 615 }
616 616 .highlight-keyword,
617 617 pre .keyword,
618 618 pre .id,
619 619 pre .phpdoc,
620 620 pre .aggregate,
621 621 pre .css .tag,
622 622 pre .javadoctag,
623 623 pre .phpdoc,
624 624 pre .yardoctag,
625 625 pre .smalltalk .class,
626 626 pre .winutils,
627 627 pre .bash .variable,
628 628 pre .apache .tag,
629 629 pre .go .typename,
630 630 pre .tex .command,
631 631 pre .markdown .strong,
632 632 pre .request,
633 633 pre .status {
634 634 color: #008000;
635 635 font-weight: bold;
636 636 }
637 637 .highlight-builtin,
638 638 pre .built_in {
639 639 color: #008000;
640 640 }
641 641 pre .markdown .emphasis {
642 642 font-style: italic;
643 643 }
644 644 pre .nginx .built_in {
645 645 font-weight: normal;
646 646 }
647 647 pre .coffeescript .javascript,
648 648 pre .javascript .xml,
649 649 pre .tex .formula,
650 650 pre .xml .javascript,
651 651 pre .xml .vbscript,
652 652 pre .xml .css,
653 653 pre .xml .cdata {
654 654 opacity: 0.5;
655 655 }
656 656 /* apply the same style to codemirror */
657 657 .cm-s-ipython span.cm-variable {
658 658 color: black;
659 659 }
660 660 .cm-s-ipython span.cm-keyword {
661 661 color: #008000;
662 662 font-weight: bold;
663 663 }
664 664 .cm-s-ipython span.cm-number {
665 665 color: #080;
666 666 }
667 667 .cm-s-ipython span.cm-comment {
668 668 color: #408080;
669 669 font-style: italic;
670 670 }
671 671 .cm-s-ipython span.cm-string {
672 672 color: #BA2121;
673 673 }
674 674 .cm-s-ipython span.cm-builtin {
675 675 color: #008000;
676 676 }
677 677 .cm-s-ipython span.cm-error {
678 678 color: #f00;
679 679 }
680 680 .cm-s-ipython span.cm-operator {
681 681 color: #AA22FF;
682 682 font-weight: bold;
683 683 }
684 684 .cm-s-ipython span.cm-meta {
685 685 color: #AA22FF;
686 686 }
687 687 .cm-s-ipython span.cm-tab {
688 688 background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
689 689 background-position: right;
690 690 background-repeat: no-repeat;
691 691 }
692 692 div.output_wrapper {
693 693 /* this position must be relative to enable descendents to be absolute within it */
694 694 position: relative;
695 695 /* Old browsers */
696 696 display: -webkit-box;
697 697 -webkit-box-orient: vertical;
698 698 -webkit-box-align: stretch;
699 699 display: -moz-box;
700 700 -moz-box-orient: vertical;
701 701 -moz-box-align: stretch;
702 702 display: box;
703 703 box-orient: vertical;
704 704 box-align: stretch;
705 705 /* Modern browsers */
706 706 display: flex;
707 707 flex-direction: column;
708 708 align-items: stretch;
709 709 }
710 710 /* class for the output area when it should be height-limited */
711 711 div.output_scroll {
712 712 /* ideally, this would be max-height, but FF barfs all over that */
713 713 height: 24em;
714 714 /* FF needs this *and the wrapper* to specify full width, or it will shrinkwrap */
715 715 width: 100%;
716 716 overflow: auto;
717 717 border-radius: 4px;
718 718 -webkit-box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
719 719 box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
720 720 display: block;
721 721 }
722 722 /* output div while it is collapsed */
723 723 div.output_collapsed {
724 724 margin: 0px;
725 725 padding: 0px;
726 726 /* Old browsers */
727 727 display: -webkit-box;
728 728 -webkit-box-orient: vertical;
729 729 -webkit-box-align: stretch;
730 730 display: -moz-box;
731 731 -moz-box-orient: vertical;
732 732 -moz-box-align: stretch;
733 733 display: box;
734 734 box-orient: vertical;
735 735 box-align: stretch;
736 736 /* Modern browsers */
737 737 display: flex;
738 738 flex-direction: column;
739 739 align-items: stretch;
740 740 }
741 741 div.out_prompt_overlay {
742 742 height: 100%;
743 743 padding: 0px 0.4em;
744 744 position: absolute;
745 745 border-radius: 4px;
746 746 }
747 747 div.out_prompt_overlay:hover {
748 748 /* use inner shadow to get border that is computed the same on WebKit/FF */
749 749 -webkit-box-shadow: inset 0 0 1px #000000;
750 750 box-shadow: inset 0 0 1px #000000;
751 751 background: rgba(240, 240, 240, 0.5);
752 752 }
753 753 div.output_prompt {
754 754 color: #8b0000;
755 755 }
756 756 /* This class is the outer container of all output sections. */
757 757 div.output_area {
758 758 padding: 0px;
759 759 page-break-inside: avoid;
760 760 /* Old browsers */
761 761 display: -webkit-box;
762 762 -webkit-box-orient: horizontal;
763 763 -webkit-box-align: stretch;
764 764 display: -moz-box;
765 765 -moz-box-orient: horizontal;
766 766 -moz-box-align: stretch;
767 767 display: box;
768 768 box-orient: horizontal;
769 769 box-align: stretch;
770 770 /* Modern browsers */
771 771 display: flex;
772 772 flex-direction: row;
773 773 align-items: stretch;
774 774 }
775 775 div.output_area .MathJax_Display {
776 776 text-align: left !important;
777 777 }
778 778 div.output_area .rendered_html table {
779 779 margin-left: 0;
780 780 margin-right: 0;
781 781 }
782 782 div.output_area .rendered_html img {
783 783 margin-left: 0;
784 784 margin-right: 0;
785 785 }
786 786 /* This is needed to protect the pre formating from global settings such
787 787 as that of bootstrap */
788 788 .output {
789 789 /* Old browsers */
790 790 display: -webkit-box;
791 791 -webkit-box-orient: vertical;
792 792 -webkit-box-align: stretch;
793 793 display: -moz-box;
794 794 -moz-box-orient: vertical;
795 795 -moz-box-align: stretch;
796 796 display: box;
797 797 box-orient: vertical;
798 798 box-align: stretch;
799 799 /* Modern browsers */
800 800 display: flex;
801 801 flex-direction: column;
802 802 align-items: stretch;
803 803 }
804 804 @media (max-width: 480px) {
805 805 div.output_area {
806 806 /* Old browsers */
807 807 display: -webkit-box;
808 808 -webkit-box-orient: vertical;
809 809 -webkit-box-align: stretch;
810 810 display: -moz-box;
811 811 -moz-box-orient: vertical;
812 812 -moz-box-align: stretch;
813 813 display: box;
814 814 box-orient: vertical;
815 815 box-align: stretch;
816 816 /* Modern browsers */
817 817 display: flex;
818 818 flex-direction: column;
819 819 align-items: stretch;
820 820 }
821 821 }
822 822 div.output_area pre {
823 823 margin: 0;
824 824 padding: 0;
825 825 border: 0;
826 826 vertical-align: baseline;
827 827 color: #000000;
828 828 background-color: transparent;
829 829 border-radius: 0;
830 830 }
831 831 /* This class is for the output subarea inside the output_area and after
832 832 the prompt div. */
833 833 div.output_subarea {
834 834 padding: 0.4em 0.4em 0em 0.4em;
835 835 /* Old browsers */
836 836 -webkit-box-flex: 1;
837 837 -moz-box-flex: 1;
838 838 box-flex: 1;
839 839 /* Modern browsers */
840 840 flex: 1;
841 841 }
842 842 /* The rest of the output_* classes are for special styling of the different
843 843 output types */
844 844 /* all text output has this class: */
845 845 div.output_text {
846 846 text-align: left;
847 847 color: #000000;
848 848 /* This has to match that of the the CodeMirror class line-height below */
849 849 line-height: 1.21429em;
850 850 }
851 851 /* stdout/stderr are 'text' as well as 'stream', but execute_result/error are *not* streams */
852 852 div.output_stderr {
853 853 background: #fdd;
854 854 /* very light red background for stderr */
855 855 }
856 856 div.output_latex {
857 857 text-align: left;
858 858 }
859 859 /* Empty output_javascript divs should have no height */
860 860 div.output_javascript:empty {
861 861 padding: 0;
862 862 }
863 863 .js-error {
864 864 color: darkred;
865 865 }
866 866 /* raw_input styles */
867 867 div.raw_input_container {
868 868 font-family: monospace;
869 869 padding-top: 5px;
870 870 }
871 871 span.raw_input_prompt {
872 872 /* nothing needed here */
873 873 }
874 874 input.raw_input {
875 875 font-family: inherit;
876 876 font-size: inherit;
877 877 color: inherit;
878 878 width: auto;
879 879 /* make sure input baseline aligns with prompt */
880 880 vertical-align: baseline;
881 881 /* padding + margin = 0.5em between prompt and cursor */
882 882 padding: 0em 0.25em;
883 883 margin: 0em 0.25em;
884 884 }
885 885 input.raw_input:focus {
886 886 box-shadow: none;
887 887 }
888 888 p.p-space {
889 889 margin-bottom: 10px;
890 890 }
891 891 .rendered_html {
892 892 color: #000000;
893 893 /* any extras will just be numbers: */
894 894 }
895 895 .rendered_html em {
896 896 font-style: italic;
897 897 }
898 898 .rendered_html strong {
899 899 font-weight: bold;
900 900 }
901 901 .rendered_html u {
902 902 text-decoration: underline;
903 903 }
904 904 .rendered_html :link {
905 905 text-decoration: underline;
906 906 }
907 907 .rendered_html :visited {
908 908 text-decoration: underline;
909 909 }
910 910 .rendered_html h1 {
911 911 font-size: 185.7%;
912 912 margin: 1.08em 0 0 0;
913 913 font-weight: bold;
914 914 line-height: 1.0;
915 915 }
916 916 .rendered_html h2 {
917 917 font-size: 157.1%;
918 918 margin: 1.27em 0 0 0;
919 919 font-weight: bold;
920 920 line-height: 1.0;
921 921 }
922 922 .rendered_html h3 {
923 923 font-size: 128.6%;
924 924 margin: 1.55em 0 0 0;
925 925 font-weight: bold;
926 926 line-height: 1.0;
927 927 }
928 928 .rendered_html h4 {
929 929 font-size: 100%;
930 930 margin: 2em 0 0 0;
931 931 font-weight: bold;
932 932 line-height: 1.0;
933 933 }
934 934 .rendered_html h5 {
935 935 font-size: 100%;
936 936 margin: 2em 0 0 0;
937 937 font-weight: bold;
938 938 line-height: 1.0;
939 939 font-style: italic;
940 940 }
941 941 .rendered_html h6 {
942 942 font-size: 100%;
943 943 margin: 2em 0 0 0;
944 944 font-weight: bold;
945 945 line-height: 1.0;
946 946 font-style: italic;
947 947 }
948 948 .rendered_html h1:first-child {
949 949 margin-top: 0.538em;
950 950 }
951 951 .rendered_html h2:first-child {
952 952 margin-top: 0.636em;
953 953 }
954 954 .rendered_html h3:first-child {
955 955 margin-top: 0.777em;
956 956 }
957 957 .rendered_html h4:first-child {
958 958 margin-top: 1em;
959 959 }
960 960 .rendered_html h5:first-child {
961 961 margin-top: 1em;
962 962 }
963 963 .rendered_html h6:first-child {
964 964 margin-top: 1em;
965 965 }
966 966 .rendered_html ul {
967 967 list-style: disc;
968 968 margin: 0em 2em;
969 969 padding-left: 0px;
970 970 }
971 971 .rendered_html ul ul {
972 972 list-style: square;
973 973 margin: 0em 2em;
974 974 }
975 975 .rendered_html ul ul ul {
976 976 list-style: circle;
977 977 margin: 0em 2em;
978 978 }
979 979 .rendered_html ol {
980 980 list-style: decimal;
981 981 margin: 0em 2em;
982 982 padding-left: 0px;
983 983 }
984 984 .rendered_html ol ol {
985 985 list-style: upper-alpha;
986 986 margin: 0em 2em;
987 987 }
988 988 .rendered_html ol ol ol {
989 989 list-style: lower-alpha;
990 990 margin: 0em 2em;
991 991 }
992 992 .rendered_html ol ol ol ol {
993 993 list-style: lower-roman;
994 994 margin: 0em 2em;
995 995 }
996 996 .rendered_html ol ol ol ol ol {
997 997 list-style: decimal;
998 998 margin: 0em 2em;
999 999 }
1000 1000 .rendered_html * + ul {
1001 1001 margin-top: 1em;
1002 1002 }
1003 1003 .rendered_html * + ol {
1004 1004 margin-top: 1em;
1005 1005 }
1006 1006 .rendered_html hr {
1007 1007 color: #000000;
1008 1008 background-color: #000000;
1009 1009 }
1010 1010 .rendered_html pre {
1011 1011 margin: 1em 2em;
1012 1012 }
1013 1013 .rendered_html pre,
1014 1014 .rendered_html code {
1015 1015 border: 0;
1016 1016 background-color: #ffffff;
1017 1017 color: #000000;
1018 1018 font-size: 100%;
1019 1019 padding: 0px;
1020 1020 }
1021 1021 .rendered_html blockquote {
1022 1022 margin: 1em 2em;
1023 1023 }
1024 1024 .rendered_html table {
1025 1025 margin-left: auto;
1026 1026 margin-right: auto;
1027 1027 border: 1px solid #000000;
1028 1028 border-collapse: collapse;
1029 1029 }
1030 1030 .rendered_html tr,
1031 1031 .rendered_html th,
1032 1032 .rendered_html td {
1033 1033 border: 1px solid #000000;
1034 1034 border-collapse: collapse;
1035 1035 margin: 1em 2em;
1036 1036 }
1037 1037 .rendered_html td,
1038 1038 .rendered_html th {
1039 1039 text-align: left;
1040 1040 vertical-align: middle;
1041 1041 padding: 4px;
1042 1042 }
1043 1043 .rendered_html th {
1044 1044 font-weight: bold;
1045 1045 }
1046 1046 .rendered_html * + table {
1047 1047 margin-top: 1em;
1048 1048 }
1049 1049 .rendered_html p {
1050 1050 text-align: justify;
1051 1051 }
1052 1052 .rendered_html * + p {
1053 1053 margin-top: 1em;
1054 1054 }
1055 1055 .rendered_html img {
1056 1056 display: block;
1057 1057 margin-left: auto;
1058 1058 margin-right: auto;
1059 1059 }
1060 1060 .rendered_html * + img {
1061 1061 margin-top: 1em;
1062 1062 }
1063 1063 div.text_cell {
1064 1064 padding: 5px 5px 5px 0px;
1065 1065 /* Old browsers */
1066 1066 display: -webkit-box;
1067 1067 -webkit-box-orient: horizontal;
1068 1068 -webkit-box-align: stretch;
1069 1069 display: -moz-box;
1070 1070 -moz-box-orient: horizontal;
1071 1071 -moz-box-align: stretch;
1072 1072 display: box;
1073 1073 box-orient: horizontal;
1074 1074 box-align: stretch;
1075 1075 /* Modern browsers */
1076 1076 display: flex;
1077 1077 flex-direction: row;
1078 1078 align-items: stretch;
1079 1079 }
1080 1080 @media (max-width: 480px) {
1081 1081 div.text_cell > div.prompt {
1082 1082 display: none;
1083 1083 }
1084 1084 }
1085 1085 div.text_cell_render {
1086 1086 /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
1087 1087 outline: none;
1088 1088 resize: none;
1089 1089 width: inherit;
1090 1090 border-style: none;
1091 1091 padding: 0.5em 0.5em 0.5em 0.4em;
1092 1092 color: #000000;
1093 1093 box-sizing: border-box;
1094 1094 -moz-box-sizing: border-box;
1095 1095 -webkit-box-sizing: border-box;
1096 1096 }
1097 1097 a.anchor-link:link {
1098 1098 text-decoration: none;
1099 1099 padding: 0px 20px;
1100 1100 visibility: hidden;
1101 1101 }
1102 1102 h1:hover .anchor-link,
1103 1103 h2:hover .anchor-link,
1104 1104 h3:hover .anchor-link,
1105 1105 h4:hover .anchor-link,
1106 1106 h5:hover .anchor-link,
1107 1107 h6:hover .anchor-link {
1108 1108 visibility: visible;
1109 1109 }
1110 1110 div.cell.text_cell.rendered {
1111 1111 padding: 0px;
1112 1112 }
1113 1113 .text_cell.rendered .input_area {
1114 1114 display: none;
1115 1115 }
1116 1116 .text_cell.unrendered .text_cell_render {
1117 1117 display: none;
1118 1118 }
1119 .cm-s-heading-1,
1120 .cm-s-heading-2,
1121 .cm-s-heading-3,
1122 .cm-s-heading-4,
1123 .cm-s-heading-5,
1124 .cm-s-heading-6 {
1119 .cm-header-1,
1120 .cm-header-2,
1121 .cm-header-3,
1122 .cm-header-4,
1123 .cm-header-5,
1124 .cm-header-6 {
1125 1125 font-weight: bold;
1126 1126 font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
1127 1127 }
1128 .cm-s-heading-1 {
1129 font-size: 150%;
1128 .cm-header-1 {
1129 font-size: 185.7%;
1130 1130 }
1131 .cm-s-heading-2 {
1132 font-size: 130%;
1131 .cm-header-2 {
1132 font-size: 157.1%;
1133 1133 }
1134 .cm-s-heading-3 {
1135 font-size: 120%;
1134 .cm-header-3 {
1135 font-size: 128.6%;
1136 1136 }
1137 .cm-s-heading-4 {
1137 .cm-header-4 {
1138 1138 font-size: 110%;
1139 1139 }
1140 .cm-s-heading-5 {
1140 .cm-header-5 {
1141 1141 font-size: 100%;
1142 1142 font-style: italic;
1143 1143 }
1144 .cm-s-heading-6 {
1145 font-size: 90%;
1144 .cm-header-6 {
1145 font-size: 100%;
1146 1146 font-style: italic;
1147 1147 }
1148 1148 .widget-area {
1149 1149 /*
1150 1150 LESS file that styles IPython notebook widgets and the area they sit in.
1151 1151
1152 1152 The widget area typically looks something like this:
1153 1153 +------------------------------------------+
1154 1154 | widget-area |
1155 1155 | +--------+---------------------------+ |
1156 1156 | | prompt | widget-subarea | |
1157 1157 | | | +--------+ +--------+ | |
1158 1158 | | | | widget | | widget | | |
1159 1159 | | | +--------+ +--------+ | |
1160 1160 | +--------+---------------------------+ |
1161 1161 +------------------------------------------+
1162 1162 */
1163 1163 page-break-inside: avoid;
1164 1164 /* Old browsers */
1165 1165 display: -webkit-box;
1166 1166 -webkit-box-orient: horizontal;
1167 1167 -webkit-box-align: stretch;
1168 1168 display: -moz-box;
1169 1169 -moz-box-orient: horizontal;
1170 1170 -moz-box-align: stretch;
1171 1171 display: box;
1172 1172 box-orient: horizontal;
1173 1173 box-align: stretch;
1174 1174 /* Modern browsers */
1175 1175 display: flex;
1176 1176 flex-direction: row;
1177 1177 align-items: stretch;
1178 1178 }
1179 1179 .widget-area .widget-subarea {
1180 1180 padding: 0.44em 0.4em 0.4em 1px;
1181 1181 margin-left: 6px;
1182 1182 box-sizing: border-box;
1183 1183 -moz-box-sizing: border-box;
1184 1184 -webkit-box-sizing: border-box;
1185 1185 /* Old browsers */
1186 1186 display: -webkit-box;
1187 1187 -webkit-box-orient: vertical;
1188 1188 -webkit-box-align: stretch;
1189 1189 display: -moz-box;
1190 1190 -moz-box-orient: vertical;
1191 1191 -moz-box-align: stretch;
1192 1192 display: box;
1193 1193 box-orient: vertical;
1194 1194 box-align: stretch;
1195 1195 /* Modern browsers */
1196 1196 display: flex;
1197 1197 flex-direction: column;
1198 1198 align-items: stretch;
1199 1199 /* Old browsers */
1200 1200 -webkit-box-flex: 2;
1201 1201 -moz-box-flex: 2;
1202 1202 box-flex: 2;
1203 1203 /* Modern browsers */
1204 1204 flex: 2;
1205 1205 /* Old browsers */
1206 1206 -webkit-box-align: start;
1207 1207 -moz-box-align: start;
1208 1208 box-align: start;
1209 1209 /* Modern browsers */
1210 1210 align-items: flex-start;
1211 1211 }
1212 1212 /* THE CLASSES BELOW CAN APPEAR ANYWHERE IN THE DOM (POSSIBLEY OUTSIDE OF
1213 1213 THE WIDGET AREA). */
1214 1214 .slide-track {
1215 1215 /* Slider Track */
1216 1216 border: 1px solid #CCCCCC;
1217 1217 background: #FFFFFF;
1218 1218 border-radius: 4px;
1219 1219 /* Round the corners of the slide track */
1220 1220 }
1221 1221 .widget-hslider {
1222 1222 /* Horizontal jQuery Slider
1223 1223
1224 1224 Both the horizontal and vertical versions of the slider are characterized
1225 1225 by a styled div that contains an invisible jQuery slide div which
1226 1226 contains a visible slider handle div. This is requred so we can control
1227 1227 how the slider is drawn and 'fix' the issue where the slide handle
1228 1228 doesn't stop at the end of the slide.
1229 1229
1230 1230 Both horizontal and vertical sliders have this div nesting:
1231 1231 +------------------------------------------+
1232 1232 | widget-(h/v)slider |
1233 1233 | +--------+---------------------------+ |
1234 1234 | | ui-slider | |
1235 1235 | | +------------------+ | |
1236 1236 | | | ui-slider-handle | | |
1237 1237 | | +------------------+ | |
1238 1238 | +--------+---------------------------+ |
1239 1239 +------------------------------------------+
1240 1240 */
1241 1241 /* Fix the padding of the slide track so the ui-slider is sized
1242 1242 correctly. */
1243 1243 padding-left: 8px;
1244 1244 padding-right: 5px;
1245 1245 overflow: visible;
1246 1246 /* Default size of the slider */
1247 1247 width: 350px;
1248 1248 height: 5px;
1249 1249 max-height: 5px;
1250 1250 margin-top: 13px;
1251 1251 margin-bottom: 10px;
1252 1252 /* Style the slider track */
1253 1253 /* Slider Track */
1254 1254 border: 1px solid #CCCCCC;
1255 1255 background: #FFFFFF;
1256 1256 border-radius: 4px;
1257 1257 /* Round the corners of the slide track */
1258 1258 /* Make the div a flex box (makes FF behave correctly). */
1259 1259 /* Old browsers */
1260 1260 display: -webkit-box;
1261 1261 -webkit-box-orient: horizontal;
1262 1262 -webkit-box-align: stretch;
1263 1263 display: -moz-box;
1264 1264 -moz-box-orient: horizontal;
1265 1265 -moz-box-align: stretch;
1266 1266 display: box;
1267 1267 box-orient: horizontal;
1268 1268 box-align: stretch;
1269 1269 /* Modern browsers */
1270 1270 display: flex;
1271 1271 flex-direction: row;
1272 1272 align-items: stretch;
1273 1273 }
1274 1274 .widget-hslider .ui-slider {
1275 1275 /* Inner, invisible slide div */
1276 1276 border: 0px !important;
1277 1277 background: none !important;
1278 1278 /* Old browsers */
1279 1279 display: -webkit-box;
1280 1280 -webkit-box-orient: horizontal;
1281 1281 -webkit-box-align: stretch;
1282 1282 display: -moz-box;
1283 1283 -moz-box-orient: horizontal;
1284 1284 -moz-box-align: stretch;
1285 1285 display: box;
1286 1286 box-orient: horizontal;
1287 1287 box-align: stretch;
1288 1288 /* Modern browsers */
1289 1289 display: flex;
1290 1290 flex-direction: row;
1291 1291 align-items: stretch;
1292 1292 /* Old browsers */
1293 1293 -webkit-box-flex: 1;
1294 1294 -moz-box-flex: 1;
1295 1295 box-flex: 1;
1296 1296 /* Modern browsers */
1297 1297 flex: 1;
1298 1298 }
1299 1299 .widget-hslider .ui-slider .ui-slider-handle {
1300 1300 width: 14px !important;
1301 1301 height: 28px !important;
1302 1302 margin-top: -8px !important;
1303 1303 }
1304 1304 .widget-hslider .ui-slider .ui-slider-range {
1305 1305 height: 12px !important;
1306 1306 margin-top: -4px !important;
1307 1307 }
1308 1308 .widget-vslider {
1309 1309 /* Vertical jQuery Slider */
1310 1310 /* Fix the padding of the slide track so the ui-slider is sized
1311 1311 correctly. */
1312 1312 padding-bottom: 8px;
1313 1313 overflow: visible;
1314 1314 /* Default size of the slider */
1315 1315 width: 5px;
1316 1316 max-width: 5px;
1317 1317 height: 250px;
1318 1318 margin-left: 12px;
1319 1319 /* Style the slider track */
1320 1320 /* Slider Track */
1321 1321 border: 1px solid #CCCCCC;
1322 1322 background: #FFFFFF;
1323 1323 border-radius: 4px;
1324 1324 /* Round the corners of the slide track */
1325 1325 /* Make the div a flex box (makes FF behave correctly). */
1326 1326 /* Old browsers */
1327 1327 display: -webkit-box;
1328 1328 -webkit-box-orient: vertical;
1329 1329 -webkit-box-align: stretch;
1330 1330 display: -moz-box;
1331 1331 -moz-box-orient: vertical;
1332 1332 -moz-box-align: stretch;
1333 1333 display: box;
1334 1334 box-orient: vertical;
1335 1335 box-align: stretch;
1336 1336 /* Modern browsers */
1337 1337 display: flex;
1338 1338 flex-direction: column;
1339 1339 align-items: stretch;
1340 1340 }
1341 1341 .widget-vslider .ui-slider {
1342 1342 /* Inner, invisible slide div */
1343 1343 border: 0px !important;
1344 1344 background: none !important;
1345 1345 margin-left: -4px;
1346 1346 margin-top: 5px;
1347 1347 /* Old browsers */
1348 1348 display: -webkit-box;
1349 1349 -webkit-box-orient: vertical;
1350 1350 -webkit-box-align: stretch;
1351 1351 display: -moz-box;
1352 1352 -moz-box-orient: vertical;
1353 1353 -moz-box-align: stretch;
1354 1354 display: box;
1355 1355 box-orient: vertical;
1356 1356 box-align: stretch;
1357 1357 /* Modern browsers */
1358 1358 display: flex;
1359 1359 flex-direction: column;
1360 1360 align-items: stretch;
1361 1361 /* Old browsers */
1362 1362 -webkit-box-flex: 1;
1363 1363 -moz-box-flex: 1;
1364 1364 box-flex: 1;
1365 1365 /* Modern browsers */
1366 1366 flex: 1;
1367 1367 }
1368 1368 .widget-vslider .ui-slider .ui-slider-handle {
1369 1369 width: 28px !important;
1370 1370 height: 14px !important;
1371 1371 margin-left: -9px;
1372 1372 }
1373 1373 .widget-vslider .ui-slider .ui-slider-range {
1374 1374 width: 12px !important;
1375 1375 margin-left: -1px !important;
1376 1376 }
1377 1377 .widget-text {
1378 1378 /* String Textbox - used for TextBoxView and TextAreaView */
1379 1379 width: 350px;
1380 1380 margin: 0px !important;
1381 1381 }
1382 1382 .widget-listbox {
1383 1383 /* Listbox */
1384 1384 width: 350px;
1385 1385 margin-bottom: 0px;
1386 1386 }
1387 1387 .widget-numeric-text {
1388 1388 /* Single Line Textbox - used for IntTextView and FloatTextView */
1389 1389 width: 150px;
1390 1390 margin: 0px !important;
1391 1391 }
1392 1392 .widget-progress {
1393 1393 /* Progress Bar */
1394 1394 margin-top: 6px;
1395 1395 width: 350px;
1396 1396 }
1397 1397 .widget-progress .progress-bar {
1398 1398 /* Disable progress bar animation */
1399 1399 -webkit-transition: none;
1400 1400 -moz-transition: none;
1401 1401 -ms-transition: none;
1402 1402 -o-transition: none;
1403 1403 transition: none;
1404 1404 }
1405 1405 .widget-combo-btn {
1406 1406 /* ComboBox Main Button */
1407 1407 min-width: 125px;
1408 1408 }
1409 1409 .widget_item .dropdown-menu li a {
1410 1410 color: inherit;
1411 1411 }
1412 1412 .widget-hbox {
1413 1413 /* Horizontal widgets */
1414 1414 /* Old browsers */
1415 1415 display: -webkit-box;
1416 1416 -webkit-box-orient: horizontal;
1417 1417 -webkit-box-align: stretch;
1418 1418 display: -moz-box;
1419 1419 -moz-box-orient: horizontal;
1420 1420 -moz-box-align: stretch;
1421 1421 display: box;
1422 1422 box-orient: horizontal;
1423 1423 box-align: stretch;
1424 1424 /* Modern browsers */
1425 1425 display: flex;
1426 1426 flex-direction: row;
1427 1427 align-items: stretch;
1428 1428 margin-top: 0px !important;
1429 1429 margin-bottom: 0px !important;
1430 1430 margin-right: 5px;
1431 1431 margin-left: 5px;
1432 1432 }
1433 1433 .widget-hbox input[type="checkbox"] {
1434 1434 margin-top: 9px;
1435 1435 }
1436 1436 .widget-hbox .widget-label {
1437 1437 /* Horizontal Label */
1438 1438 min-width: 10ex;
1439 1439 padding-right: 8px;
1440 1440 padding-top: 5px;
1441 1441 text-align: right;
1442 1442 vertical-align: text-top;
1443 1443 }
1444 1444 .widget-hbox .widget-readout {
1445 1445 padding-left: 8px;
1446 1446 padding-top: 5px;
1447 1447 text-align: left;
1448 1448 vertical-align: text-top;
1449 1449 }
1450 1450 .widget-vbox {
1451 1451 /* Vertical widgets */
1452 1452 /* Old browsers */
1453 1453 display: -webkit-box;
1454 1454 -webkit-box-orient: vertical;
1455 1455 -webkit-box-align: stretch;
1456 1456 display: -moz-box;
1457 1457 -moz-box-orient: vertical;
1458 1458 -moz-box-align: stretch;
1459 1459 display: box;
1460 1460 box-orient: vertical;
1461 1461 box-align: stretch;
1462 1462 /* Modern browsers */
1463 1463 display: flex;
1464 1464 flex-direction: column;
1465 1465 align-items: stretch;
1466 1466 }
1467 1467 .widget-vbox .widget-label {
1468 1468 /* Vertical Label */
1469 1469 padding-bottom: 5px;
1470 1470 text-align: center;
1471 1471 vertical-align: text-bottom;
1472 1472 }
1473 1473 .widget-vbox .widget-readout {
1474 1474 /* Vertical Label */
1475 1475 padding-top: 5px;
1476 1476 text-align: center;
1477 1477 vertical-align: text-top;
1478 1478 }
1479 1479 .widget-modal {
1480 1480 /* Box - ModalView */
1481 1481 overflow: hidden;
1482 1482 position: absolute !important;
1483 1483 top: 0px;
1484 1484 left: 0px;
1485 1485 margin-left: 0px !important;
1486 1486 }
1487 1487 .widget-modal-body {
1488 1488 /* Box - ModalView Body */
1489 1489 max-height: none !important;
1490 1490 }
1491 1491 .widget-box {
1492 1492 /* Box */
1493 1493 box-sizing: border-box;
1494 1494 -moz-box-sizing: border-box;
1495 1495 -webkit-box-sizing: border-box;
1496 1496 /* Old browsers */
1497 1497 -webkit-box-align: start;
1498 1498 -moz-box-align: start;
1499 1499 box-align: start;
1500 1500 /* Modern browsers */
1501 1501 align-items: flex-start;
1502 1502 }
1503 1503 .widget-radio-box {
1504 1504 /* Contains RadioButtonsWidget */
1505 1505 /* Old browsers */
1506 1506 display: -webkit-box;
1507 1507 -webkit-box-orient: vertical;
1508 1508 -webkit-box-align: stretch;
1509 1509 display: -moz-box;
1510 1510 -moz-box-orient: vertical;
1511 1511 -moz-box-align: stretch;
1512 1512 display: box;
1513 1513 box-orient: vertical;
1514 1514 box-align: stretch;
1515 1515 /* Modern browsers */
1516 1516 display: flex;
1517 1517 flex-direction: column;
1518 1518 align-items: stretch;
1519 1519 box-sizing: border-box;
1520 1520 -moz-box-sizing: border-box;
1521 1521 -webkit-box-sizing: border-box;
1522 1522 padding-top: 4px;
1523 1523 }
1524 1524 .widget-radio-box label {
1525 1525 margin-top: 0px;
1526 1526 }
1527 1527 .docked-widget-modal {
1528 1528 /* Horizontal Label */
1529 1529 overflow: hidden;
1530 1530 position: relative !important;
1531 1531 top: 0px !important;
1532 1532 left: 0px !important;
1533 1533 margin-left: 0px !important;
1534 1534 }
1535 1535 /*# sourceMappingURL=../style/ipython.min.css.map */ No newline at end of file
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/nbformat/convert.py to IPython/nbformat/converter.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/nbformat/tests/test_current.py to IPython/nbformat/tests/test_api.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now