##// 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 from __future__ import absolute_import, print_function
13 from __future__ import absolute_import, print_function
14
14
15 import __future__
15 import __future__
16 import abc
16 import abc
17 import ast
17 import ast
18 import atexit
18 import atexit
19 import functools
19 import functools
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import types
25 import types
26 import subprocess
26 import subprocess
27 from io import open as io_open
27 from io import open as io_open
28
28
29 from IPython.config.configurable import SingletonConfigurable
29 from IPython.config.configurable import SingletonConfigurable
30 from IPython.core import debugger, oinspect
30 from IPython.core import debugger, oinspect
31 from IPython.core import magic
31 from IPython.core import magic
32 from IPython.core import page
32 from IPython.core import page
33 from IPython.core import prefilter
33 from IPython.core import prefilter
34 from IPython.core import shadowns
34 from IPython.core import shadowns
35 from IPython.core import ultratb
35 from IPython.core import ultratb
36 from IPython.core.alias import AliasManager, AliasError
36 from IPython.core.alias import AliasManager, AliasError
37 from IPython.core.autocall import ExitAutocall
37 from IPython.core.autocall import ExitAutocall
38 from IPython.core.builtin_trap import BuiltinTrap
38 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.core.events import EventManager, available_events
39 from IPython.core.events import EventManager, available_events
40 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
40 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.displayhook import DisplayHook
42 from IPython.core.displayhook import DisplayHook
43 from IPython.core.displaypub import DisplayPublisher
43 from IPython.core.displaypub import DisplayPublisher
44 from IPython.core.error import InputRejected, UsageError
44 from IPython.core.error import InputRejected, UsageError
45 from IPython.core.extensions import ExtensionManager
45 from IPython.core.extensions import ExtensionManager
46 from IPython.core.formatters import DisplayFormatter
46 from IPython.core.formatters import DisplayFormatter
47 from IPython.core.history import HistoryManager
47 from IPython.core.history import HistoryManager
48 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
48 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
49 from IPython.core.logger import Logger
49 from IPython.core.logger import Logger
50 from IPython.core.macro import Macro
50 from IPython.core.macro import Macro
51 from IPython.core.payload import PayloadManager
51 from IPython.core.payload import PayloadManager
52 from IPython.core.prefilter import PrefilterManager
52 from IPython.core.prefilter import PrefilterManager
53 from IPython.core.profiledir import ProfileDir
53 from IPython.core.profiledir import ProfileDir
54 from IPython.core.prompts import PromptManager
54 from IPython.core.prompts import PromptManager
55 from IPython.core.usage import default_banner
55 from IPython.core.usage import default_banner
56 from IPython.lib.latextools import LaTeXTool
56 from IPython.lib.latextools import LaTeXTool
57 from IPython.testing.skipdoctest import skip_doctest
57 from IPython.testing.skipdoctest import skip_doctest
58 from IPython.utils import PyColorize
58 from IPython.utils import PyColorize
59 from IPython.utils import io
59 from IPython.utils import io
60 from IPython.utils import py3compat
60 from IPython.utils import py3compat
61 from IPython.utils import openpy
61 from IPython.utils import openpy
62 from IPython.utils.decorators import undoc
62 from IPython.utils.decorators import undoc
63 from IPython.utils.io import ask_yes_no
63 from IPython.utils.io import ask_yes_no
64 from IPython.utils.ipstruct import Struct
64 from IPython.utils.ipstruct import Struct
65 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
65 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
66 from IPython.utils.pickleshare import PickleShareDB
66 from IPython.utils.pickleshare import PickleShareDB
67 from IPython.utils.process import system, getoutput
67 from IPython.utils.process import system, getoutput
68 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
68 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
69 with_metaclass, iteritems)
69 with_metaclass, iteritems)
70 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.text import (format_screen, LSString, SList,
72 from IPython.utils.text import (format_screen, LSString, SList,
73 DollarFormatter)
73 DollarFormatter)
74 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
74 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
75 List, Unicode, Instance, Type)
75 List, Unicode, Instance, Type)
76 from IPython.utils.warn import warn, error
76 from IPython.utils.warn import warn, error
77 import IPython.core.hooks
77 import IPython.core.hooks
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Globals
80 # Globals
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 # compiled regexps for autoindent management
83 # compiled regexps for autoindent management
84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85
85
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87 # Utilities
87 # Utilities
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89
89
90 @undoc
90 @undoc
91 def softspace(file, newvalue):
91 def softspace(file, newvalue):
92 """Copied from code.py, to remove the dependency"""
92 """Copied from code.py, to remove the dependency"""
93
93
94 oldvalue = 0
94 oldvalue = 0
95 try:
95 try:
96 oldvalue = file.softspace
96 oldvalue = file.softspace
97 except AttributeError:
97 except AttributeError:
98 pass
98 pass
99 try:
99 try:
100 file.softspace = newvalue
100 file.softspace = newvalue
101 except (AttributeError, TypeError):
101 except (AttributeError, TypeError):
102 # "attribute-less object" or "read-only attributes"
102 # "attribute-less object" or "read-only attributes"
103 pass
103 pass
104 return oldvalue
104 return oldvalue
105
105
106 @undoc
106 @undoc
107 def no_op(*a, **kw): pass
107 def no_op(*a, **kw): pass
108
108
109 @undoc
109 @undoc
110 class NoOpContext(object):
110 class NoOpContext(object):
111 def __enter__(self): pass
111 def __enter__(self): pass
112 def __exit__(self, type, value, traceback): pass
112 def __exit__(self, type, value, traceback): pass
113 no_op_context = NoOpContext()
113 no_op_context = NoOpContext()
114
114
115 class SpaceInInput(Exception): pass
115 class SpaceInInput(Exception): pass
116
116
117 @undoc
117 @undoc
118 class Bunch: pass
118 class Bunch: pass
119
119
120
120
121 def get_default_colors():
121 def get_default_colors():
122 if sys.platform=='darwin':
122 if sys.platform=='darwin':
123 return "LightBG"
123 return "LightBG"
124 elif os.name=='nt':
124 elif os.name=='nt':
125 return 'Linux'
125 return 'Linux'
126 else:
126 else:
127 return 'Linux'
127 return 'Linux'
128
128
129
129
130 class SeparateUnicode(Unicode):
130 class SeparateUnicode(Unicode):
131 r"""A Unicode subclass to validate separate_in, separate_out, etc.
131 r"""A Unicode subclass to validate separate_in, separate_out, etc.
132
132
133 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
133 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
134 """
134 """
135
135
136 def validate(self, obj, value):
136 def validate(self, obj, value):
137 if value == '0': value = ''
137 if value == '0': value = ''
138 value = value.replace('\\n','\n')
138 value = value.replace('\\n','\n')
139 return super(SeparateUnicode, self).validate(obj, value)
139 return super(SeparateUnicode, self).validate(obj, value)
140
140
141
141
142 class ReadlineNoRecord(object):
142 class ReadlineNoRecord(object):
143 """Context manager to execute some code, then reload readline history
143 """Context manager to execute some code, then reload readline history
144 so that interactive input to the code doesn't appear when pressing up."""
144 so that interactive input to the code doesn't appear when pressing up."""
145 def __init__(self, shell):
145 def __init__(self, shell):
146 self.shell = shell
146 self.shell = shell
147 self._nested_level = 0
147 self._nested_level = 0
148
148
149 def __enter__(self):
149 def __enter__(self):
150 if self._nested_level == 0:
150 if self._nested_level == 0:
151 try:
151 try:
152 self.orig_length = self.current_length()
152 self.orig_length = self.current_length()
153 self.readline_tail = self.get_readline_tail()
153 self.readline_tail = self.get_readline_tail()
154 except (AttributeError, IndexError): # Can fail with pyreadline
154 except (AttributeError, IndexError): # Can fail with pyreadline
155 self.orig_length, self.readline_tail = 999999, []
155 self.orig_length, self.readline_tail = 999999, []
156 self._nested_level += 1
156 self._nested_level += 1
157
157
158 def __exit__(self, type, value, traceback):
158 def __exit__(self, type, value, traceback):
159 self._nested_level -= 1
159 self._nested_level -= 1
160 if self._nested_level == 0:
160 if self._nested_level == 0:
161 # Try clipping the end if it's got longer
161 # Try clipping the end if it's got longer
162 try:
162 try:
163 e = self.current_length() - self.orig_length
163 e = self.current_length() - self.orig_length
164 if e > 0:
164 if e > 0:
165 for _ in range(e):
165 for _ in range(e):
166 self.shell.readline.remove_history_item(self.orig_length)
166 self.shell.readline.remove_history_item(self.orig_length)
167
167
168 # If it still doesn't match, just reload readline history.
168 # If it still doesn't match, just reload readline history.
169 if self.current_length() != self.orig_length \
169 if self.current_length() != self.orig_length \
170 or self.get_readline_tail() != self.readline_tail:
170 or self.get_readline_tail() != self.readline_tail:
171 self.shell.refill_readline_hist()
171 self.shell.refill_readline_hist()
172 except (AttributeError, IndexError):
172 except (AttributeError, IndexError):
173 pass
173 pass
174 # Returning False will cause exceptions to propagate
174 # Returning False will cause exceptions to propagate
175 return False
175 return False
176
176
177 def current_length(self):
177 def current_length(self):
178 return self.shell.readline.get_current_history_length()
178 return self.shell.readline.get_current_history_length()
179
179
180 def get_readline_tail(self, n=10):
180 def get_readline_tail(self, n=10):
181 """Get the last n items in readline history."""
181 """Get the last n items in readline history."""
182 end = self.shell.readline.get_current_history_length() + 1
182 end = self.shell.readline.get_current_history_length() + 1
183 start = max(end-n, 1)
183 start = max(end-n, 1)
184 ghi = self.shell.readline.get_history_item
184 ghi = self.shell.readline.get_history_item
185 return [ghi(x) for x in range(start, end)]
185 return [ghi(x) for x in range(start, end)]
186
186
187
187
188 @undoc
188 @undoc
189 class DummyMod(object):
189 class DummyMod(object):
190 """A dummy module used for IPython's interactive module when
190 """A dummy module used for IPython's interactive module when
191 a namespace must be assigned to the module's __dict__."""
191 a namespace must be assigned to the module's __dict__."""
192 pass
192 pass
193
193
194 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
195 # Main IPython class
195 # Main IPython class
196 #-----------------------------------------------------------------------------
196 #-----------------------------------------------------------------------------
197
197
198 class InteractiveShell(SingletonConfigurable):
198 class InteractiveShell(SingletonConfigurable):
199 """An enhanced, interactive shell for Python."""
199 """An enhanced, interactive shell for Python."""
200
200
201 _instance = None
201 _instance = None
202
202
203 ast_transformers = List([], config=True, help=
203 ast_transformers = List([], config=True, help=
204 """
204 """
205 A list of ast.NodeTransformer subclass instances, which will be applied
205 A list of ast.NodeTransformer subclass instances, which will be applied
206 to user input before code is run.
206 to user input before code is run.
207 """
207 """
208 )
208 )
209
209
210 autocall = Enum((0,1,2), default_value=0, config=True, help=
210 autocall = Enum((0,1,2), default_value=0, config=True, help=
211 """
211 """
212 Make IPython automatically call any callable object even if you didn't
212 Make IPython automatically call any callable object even if you didn't
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 automatically. The value can be '0' to disable the feature, '1' for
214 automatically. The value can be '0' to disable the feature, '1' for
215 'smart' autocall, where it is not applied if there are no more
215 'smart' autocall, where it is not applied if there are no more
216 arguments on the line, and '2' for 'full' autocall, where all callable
216 arguments on the line, and '2' for 'full' autocall, where all callable
217 objects are automatically called (even if no arguments are present).
217 objects are automatically called (even if no arguments are present).
218 """
218 """
219 )
219 )
220 # TODO: remove all autoindent logic and put into frontends.
220 # TODO: remove all autoindent logic and put into frontends.
221 # We can't do this yet because even runlines uses the autoindent.
221 # We can't do this yet because even runlines uses the autoindent.
222 autoindent = CBool(True, config=True, help=
222 autoindent = CBool(True, config=True, help=
223 """
223 """
224 Autoindent IPython code entered interactively.
224 Autoindent IPython code entered interactively.
225 """
225 """
226 )
226 )
227 automagic = CBool(True, config=True, help=
227 automagic = CBool(True, config=True, help=
228 """
228 """
229 Enable magic commands to be called without the leading %.
229 Enable magic commands to be called without the leading %.
230 """
230 """
231 )
231 )
232
232
233 banner = Unicode('')
233 banner = Unicode('')
234
234
235 banner1 = Unicode(default_banner, config=True,
235 banner1 = Unicode(default_banner, config=True,
236 help="""The part of the banner to be printed before the profile"""
236 help="""The part of the banner to be printed before the profile"""
237 )
237 )
238 banner2 = Unicode('', config=True,
238 banner2 = Unicode('', config=True,
239 help="""The part of the banner to be printed after the profile"""
239 help="""The part of the banner to be printed after the profile"""
240 )
240 )
241
241
242 cache_size = Integer(1000, config=True, help=
242 cache_size = Integer(1000, config=True, help=
243 """
243 """
244 Set the size of the output cache. The default is 1000, you can
244 Set the size of the output cache. The default is 1000, you can
245 change it permanently in your config file. Setting it to 0 completely
245 change it permanently in your config file. Setting it to 0 completely
246 disables the caching system, and the minimum value accepted is 20 (if
246 disables the caching system, and the minimum value accepted is 20 (if
247 you provide a value less than 20, it is reset to 0 and a warning is
247 you provide a value less than 20, it is reset to 0 and a warning is
248 issued). This limit is defined because otherwise you'll spend more
248 issued). This limit is defined because otherwise you'll spend more
249 time re-flushing a too small cache than working
249 time re-flushing a too small cache than working
250 """
250 """
251 )
251 )
252 color_info = CBool(True, config=True, help=
252 color_info = CBool(True, config=True, help=
253 """
253 """
254 Use colors for displaying information about objects. Because this
254 Use colors for displaying information about objects. Because this
255 information is passed through a pager (like 'less'), and some pagers
255 information is passed through a pager (like 'less'), and some pagers
256 get confused with color codes, this capability can be turned off.
256 get confused with color codes, this capability can be turned off.
257 """
257 """
258 )
258 )
259 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
259 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
260 default_value=get_default_colors(), config=True,
260 default_value=get_default_colors(), config=True,
261 help="Set the color scheme (NoColor, Linux, or LightBG)."
261 help="Set the color scheme (NoColor, Linux, or LightBG)."
262 )
262 )
263 colors_force = CBool(False, help=
263 colors_force = CBool(False, help=
264 """
264 """
265 Force use of ANSI color codes, regardless of OS and readline
265 Force use of ANSI color codes, regardless of OS and readline
266 availability.
266 availability.
267 """
267 """
268 # FIXME: This is essentially a hack to allow ZMQShell to show colors
268 # FIXME: This is essentially a hack to allow ZMQShell to show colors
269 # without readline on Win32. When the ZMQ formatting system is
269 # without readline on Win32. When the ZMQ formatting system is
270 # refactored, this should be removed.
270 # refactored, this should be removed.
271 )
271 )
272 debug = CBool(False, config=True)
272 debug = CBool(False, config=True)
273 deep_reload = CBool(False, config=True, help=
273 deep_reload = CBool(False, config=True, help=
274 """
274 """
275 Enable deep (recursive) reloading by default. IPython can use the
275 Enable deep (recursive) reloading by default. IPython can use the
276 deep_reload module which reloads changes in modules recursively (it
276 deep_reload module which reloads changes in modules recursively (it
277 replaces the reload() function, so you don't need to change anything to
277 replaces the reload() function, so you don't need to change anything to
278 use it). deep_reload() forces a full reload of modules whose code may
278 use it). deep_reload() forces a full reload of modules whose code may
279 have changed, which the default reload() function does not. When
279 have changed, which the default reload() function does not. When
280 deep_reload is off, IPython will use the normal reload(), but
280 deep_reload is off, IPython will use the normal reload(), but
281 deep_reload will still be available as dreload().
281 deep_reload will still be available as dreload().
282 """
282 """
283 )
283 )
284 disable_failing_post_execute = CBool(False, config=True,
284 disable_failing_post_execute = CBool(False, config=True,
285 help="Don't call post-execute functions that have failed in the past."
285 help="Don't call post-execute functions that have failed in the past."
286 )
286 )
287 display_formatter = Instance(DisplayFormatter)
287 display_formatter = Instance(DisplayFormatter)
288 displayhook_class = Type(DisplayHook)
288 displayhook_class = Type(DisplayHook)
289 display_pub_class = Type(DisplayPublisher)
289 display_pub_class = Type(DisplayPublisher)
290 data_pub_class = None
290 data_pub_class = None
291
291
292 exit_now = CBool(False)
292 exit_now = CBool(False)
293 exiter = Instance(ExitAutocall)
293 exiter = Instance(ExitAutocall)
294 def _exiter_default(self):
294 def _exiter_default(self):
295 return ExitAutocall(self)
295 return ExitAutocall(self)
296 # Monotonically increasing execution counter
296 # Monotonically increasing execution counter
297 execution_count = Integer(1)
297 execution_count = Integer(1)
298 filename = Unicode("<ipython console>")
298 filename = Unicode("<ipython console>")
299 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
299 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
300
300
301 # Input splitter, to transform input line by line and detect when a block
301 # Input splitter, to transform input line by line and detect when a block
302 # is ready to be executed.
302 # is ready to be executed.
303 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
303 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
304 (), {'line_input_checker': True})
304 (), {'line_input_checker': True})
305
305
306 # This InputSplitter instance is used to transform completed cells before
306 # This InputSplitter instance is used to transform completed cells before
307 # running them. It allows cell magics to contain blank lines.
307 # running them. It allows cell magics to contain blank lines.
308 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
308 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
309 (), {'line_input_checker': False})
309 (), {'line_input_checker': False})
310
310
311 logstart = CBool(False, config=True, help=
311 logstart = CBool(False, config=True, help=
312 """
312 """
313 Start logging to the default log file.
313 Start logging to the default log file.
314 """
314 """
315 )
315 )
316 logfile = Unicode('', config=True, help=
316 logfile = Unicode('', config=True, help=
317 """
317 """
318 The name of the logfile to use.
318 The name of the logfile to use.
319 """
319 """
320 )
320 )
321 logappend = Unicode('', config=True, help=
321 logappend = Unicode('', config=True, help=
322 """
322 """
323 Start logging to the given file in append mode.
323 Start logging to the given file in append mode.
324 """
324 """
325 )
325 )
326 object_info_string_level = Enum((0,1,2), default_value=0,
326 object_info_string_level = Enum((0,1,2), default_value=0,
327 config=True)
327 config=True)
328 pdb = CBool(False, config=True, help=
328 pdb = CBool(False, config=True, help=
329 """
329 """
330 Automatically call the pdb debugger after every exception.
330 Automatically call the pdb debugger after every exception.
331 """
331 """
332 )
332 )
333 multiline_history = CBool(sys.platform != 'win32', config=True,
333 multiline_history = CBool(sys.platform != 'win32', config=True,
334 help="Save multi-line entries as one entry in readline history"
334 help="Save multi-line entries as one entry in readline history"
335 )
335 )
336
336
337 # deprecated prompt traits:
337 # deprecated prompt traits:
338
338
339 prompt_in1 = Unicode('In [\\#]: ', config=True,
339 prompt_in1 = Unicode('In [\\#]: ', config=True,
340 help="Deprecated, use PromptManager.in_template")
340 help="Deprecated, use PromptManager.in_template")
341 prompt_in2 = Unicode(' .\\D.: ', config=True,
341 prompt_in2 = Unicode(' .\\D.: ', config=True,
342 help="Deprecated, use PromptManager.in2_template")
342 help="Deprecated, use PromptManager.in2_template")
343 prompt_out = Unicode('Out[\\#]: ', config=True,
343 prompt_out = Unicode('Out[\\#]: ', config=True,
344 help="Deprecated, use PromptManager.out_template")
344 help="Deprecated, use PromptManager.out_template")
345 prompts_pad_left = CBool(True, config=True,
345 prompts_pad_left = CBool(True, config=True,
346 help="Deprecated, use PromptManager.justify")
346 help="Deprecated, use PromptManager.justify")
347
347
348 def _prompt_trait_changed(self, name, old, new):
348 def _prompt_trait_changed(self, name, old, new):
349 table = {
349 table = {
350 'prompt_in1' : 'in_template',
350 'prompt_in1' : 'in_template',
351 'prompt_in2' : 'in2_template',
351 'prompt_in2' : 'in2_template',
352 'prompt_out' : 'out_template',
352 'prompt_out' : 'out_template',
353 'prompts_pad_left' : 'justify',
353 'prompts_pad_left' : 'justify',
354 }
354 }
355 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
355 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
356 name=name, newname=table[name])
356 name=name, newname=table[name])
357 )
357 )
358 # protect against weird cases where self.config may not exist:
358 # protect against weird cases where self.config may not exist:
359 if self.config is not None:
359 if self.config is not None:
360 # propagate to corresponding PromptManager trait
360 # propagate to corresponding PromptManager trait
361 setattr(self.config.PromptManager, table[name], new)
361 setattr(self.config.PromptManager, table[name], new)
362
362
363 _prompt_in1_changed = _prompt_trait_changed
363 _prompt_in1_changed = _prompt_trait_changed
364 _prompt_in2_changed = _prompt_trait_changed
364 _prompt_in2_changed = _prompt_trait_changed
365 _prompt_out_changed = _prompt_trait_changed
365 _prompt_out_changed = _prompt_trait_changed
366 _prompt_pad_left_changed = _prompt_trait_changed
366 _prompt_pad_left_changed = _prompt_trait_changed
367
367
368 show_rewritten_input = CBool(True, config=True,
368 show_rewritten_input = CBool(True, config=True,
369 help="Show rewritten input, e.g. for autocall."
369 help="Show rewritten input, e.g. for autocall."
370 )
370 )
371
371
372 quiet = CBool(False, config=True)
372 quiet = CBool(False, config=True)
373
373
374 history_length = Integer(10000, config=True)
374 history_length = Integer(10000, config=True)
375
375
376 # The readline stuff will eventually be moved to the terminal subclass
376 # The readline stuff will eventually be moved to the terminal subclass
377 # but for now, we can't do that as readline is welded in everywhere.
377 # but for now, we can't do that as readline is welded in everywhere.
378 readline_use = CBool(True, config=True)
378 readline_use = CBool(True, config=True)
379 readline_remove_delims = Unicode('-/~', config=True)
379 readline_remove_delims = Unicode('-/~', config=True)
380 readline_delims = Unicode() # set by init_readline()
380 readline_delims = Unicode() # set by init_readline()
381 # don't use \M- bindings by default, because they
381 # don't use \M- bindings by default, because they
382 # conflict with 8-bit encodings. See gh-58,gh-88
382 # conflict with 8-bit encodings. See gh-58,gh-88
383 readline_parse_and_bind = List([
383 readline_parse_and_bind = List([
384 'tab: complete',
384 'tab: complete',
385 '"\C-l": clear-screen',
385 '"\C-l": clear-screen',
386 'set show-all-if-ambiguous on',
386 'set show-all-if-ambiguous on',
387 '"\C-o": tab-insert',
387 '"\C-o": tab-insert',
388 '"\C-r": reverse-search-history',
388 '"\C-r": reverse-search-history',
389 '"\C-s": forward-search-history',
389 '"\C-s": forward-search-history',
390 '"\C-p": history-search-backward',
390 '"\C-p": history-search-backward',
391 '"\C-n": history-search-forward',
391 '"\C-n": history-search-forward',
392 '"\e[A": history-search-backward',
392 '"\e[A": history-search-backward',
393 '"\e[B": history-search-forward',
393 '"\e[B": history-search-forward',
394 '"\C-k": kill-line',
394 '"\C-k": kill-line',
395 '"\C-u": unix-line-discard',
395 '"\C-u": unix-line-discard',
396 ], config=True)
396 ], config=True)
397
397
398 _custom_readline_config = False
398 _custom_readline_config = False
399
399
400 def _readline_parse_and_bind_changed(self, name, old, new):
400 def _readline_parse_and_bind_changed(self, name, old, new):
401 # notice that readline config is customized
401 # notice that readline config is customized
402 # indicates that it should have higher priority than inputrc
402 # indicates that it should have higher priority than inputrc
403 self._custom_readline_config = True
403 self._custom_readline_config = True
404
404
405 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
405 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
406 default_value='last_expr', config=True,
406 default_value='last_expr', config=True,
407 help="""
407 help="""
408 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
408 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
409 run interactively (displaying output from expressions).""")
409 run interactively (displaying output from expressions).""")
410
410
411 # TODO: this part of prompt management should be moved to the frontends.
411 # TODO: this part of prompt management should be moved to the frontends.
412 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
412 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
413 separate_in = SeparateUnicode('\n', config=True)
413 separate_in = SeparateUnicode('\n', config=True)
414 separate_out = SeparateUnicode('', config=True)
414 separate_out = SeparateUnicode('', config=True)
415 separate_out2 = SeparateUnicode('', config=True)
415 separate_out2 = SeparateUnicode('', config=True)
416 wildcards_case_sensitive = CBool(True, config=True)
416 wildcards_case_sensitive = CBool(True, config=True)
417 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
417 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
418 default_value='Context', config=True)
418 default_value='Context', config=True)
419
419
420 # Subcomponents of InteractiveShell
420 # Subcomponents of InteractiveShell
421 alias_manager = Instance('IPython.core.alias.AliasManager')
421 alias_manager = Instance('IPython.core.alias.AliasManager')
422 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
422 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
423 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
423 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
424 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
424 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
425 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
425 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
426 payload_manager = Instance('IPython.core.payload.PayloadManager')
426 payload_manager = Instance('IPython.core.payload.PayloadManager')
427 history_manager = Instance('IPython.core.history.HistoryManager')
427 history_manager = Instance('IPython.core.history.HistoryManager')
428 magics_manager = Instance('IPython.core.magic.MagicsManager')
428 magics_manager = Instance('IPython.core.magic.MagicsManager')
429
429
430 profile_dir = Instance('IPython.core.application.ProfileDir')
430 profile_dir = Instance('IPython.core.application.ProfileDir')
431 @property
431 @property
432 def profile(self):
432 def profile(self):
433 if self.profile_dir is not None:
433 if self.profile_dir is not None:
434 name = os.path.basename(self.profile_dir.location)
434 name = os.path.basename(self.profile_dir.location)
435 return name.replace('profile_','')
435 return name.replace('profile_','')
436
436
437
437
438 # Private interface
438 # Private interface
439 _post_execute = Instance(dict)
439 _post_execute = Instance(dict)
440
440
441 # Tracks any GUI loop loaded for pylab
441 # Tracks any GUI loop loaded for pylab
442 pylab_gui_select = None
442 pylab_gui_select = None
443
443
444 def __init__(self, ipython_dir=None, profile_dir=None,
444 def __init__(self, ipython_dir=None, profile_dir=None,
445 user_module=None, user_ns=None,
445 user_module=None, user_ns=None,
446 custom_exceptions=((), None), **kwargs):
446 custom_exceptions=((), None), **kwargs):
447
447
448 # This is where traits with a config_key argument are updated
448 # This is where traits with a config_key argument are updated
449 # from the values on config.
449 # from the values on config.
450 super(InteractiveShell, self).__init__(**kwargs)
450 super(InteractiveShell, self).__init__(**kwargs)
451 self.configurables = [self]
451 self.configurables = [self]
452
452
453 # These are relatively independent and stateless
453 # These are relatively independent and stateless
454 self.init_ipython_dir(ipython_dir)
454 self.init_ipython_dir(ipython_dir)
455 self.init_profile_dir(profile_dir)
455 self.init_profile_dir(profile_dir)
456 self.init_instance_attrs()
456 self.init_instance_attrs()
457 self.init_environment()
457 self.init_environment()
458
458
459 # Check if we're in a virtualenv, and set up sys.path.
459 # Check if we're in a virtualenv, and set up sys.path.
460 self.init_virtualenv()
460 self.init_virtualenv()
461
461
462 # Create namespaces (user_ns, user_global_ns, etc.)
462 # Create namespaces (user_ns, user_global_ns, etc.)
463 self.init_create_namespaces(user_module, user_ns)
463 self.init_create_namespaces(user_module, user_ns)
464 # This has to be done after init_create_namespaces because it uses
464 # This has to be done after init_create_namespaces because it uses
465 # something in self.user_ns, but before init_sys_modules, which
465 # something in self.user_ns, but before init_sys_modules, which
466 # is the first thing to modify sys.
466 # is the first thing to modify sys.
467 # TODO: When we override sys.stdout and sys.stderr before this class
467 # TODO: When we override sys.stdout and sys.stderr before this class
468 # is created, we are saving the overridden ones here. Not sure if this
468 # is created, we are saving the overridden ones here. Not sure if this
469 # is what we want to do.
469 # is what we want to do.
470 self.save_sys_module_state()
470 self.save_sys_module_state()
471 self.init_sys_modules()
471 self.init_sys_modules()
472
472
473 # While we're trying to have each part of the code directly access what
473 # While we're trying to have each part of the code directly access what
474 # it needs without keeping redundant references to objects, we have too
474 # it needs without keeping redundant references to objects, we have too
475 # much legacy code that expects ip.db to exist.
475 # much legacy code that expects ip.db to exist.
476 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
476 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
477
477
478 self.init_history()
478 self.init_history()
479 self.init_encoding()
479 self.init_encoding()
480 self.init_prefilter()
480 self.init_prefilter()
481
481
482 self.init_syntax_highlighting()
482 self.init_syntax_highlighting()
483 self.init_hooks()
483 self.init_hooks()
484 self.init_events()
484 self.init_events()
485 self.init_pushd_popd_magic()
485 self.init_pushd_popd_magic()
486 # self.init_traceback_handlers use to be here, but we moved it below
486 # self.init_traceback_handlers use to be here, but we moved it below
487 # because it and init_io have to come after init_readline.
487 # because it and init_io have to come after init_readline.
488 self.init_user_ns()
488 self.init_user_ns()
489 self.init_logger()
489 self.init_logger()
490 self.init_builtins()
490 self.init_builtins()
491
491
492 # The following was in post_config_initialization
492 # The following was in post_config_initialization
493 self.init_inspector()
493 self.init_inspector()
494 # init_readline() must come before init_io(), because init_io uses
494 # init_readline() must come before init_io(), because init_io uses
495 # readline related things.
495 # readline related things.
496 self.init_readline()
496 self.init_readline()
497 # We save this here in case user code replaces raw_input, but it needs
497 # We save this here in case user code replaces raw_input, but it needs
498 # to be after init_readline(), because PyPy's readline works by replacing
498 # to be after init_readline(), because PyPy's readline works by replacing
499 # raw_input.
499 # raw_input.
500 if py3compat.PY3:
500 if py3compat.PY3:
501 self.raw_input_original = input
501 self.raw_input_original = input
502 else:
502 else:
503 self.raw_input_original = raw_input
503 self.raw_input_original = raw_input
504 # init_completer must come after init_readline, because it needs to
504 # init_completer must come after init_readline, because it needs to
505 # know whether readline is present or not system-wide to configure the
505 # know whether readline is present or not system-wide to configure the
506 # completers, since the completion machinery can now operate
506 # completers, since the completion machinery can now operate
507 # independently of readline (e.g. over the network)
507 # independently of readline (e.g. over the network)
508 self.init_completer()
508 self.init_completer()
509 # TODO: init_io() needs to happen before init_traceback handlers
509 # TODO: init_io() needs to happen before init_traceback handlers
510 # because the traceback handlers hardcode the stdout/stderr streams.
510 # because the traceback handlers hardcode the stdout/stderr streams.
511 # This logic in in debugger.Pdb and should eventually be changed.
511 # This logic in in debugger.Pdb and should eventually be changed.
512 self.init_io()
512 self.init_io()
513 self.init_traceback_handlers(custom_exceptions)
513 self.init_traceback_handlers(custom_exceptions)
514 self.init_prompts()
514 self.init_prompts()
515 self.init_display_formatter()
515 self.init_display_formatter()
516 self.init_display_pub()
516 self.init_display_pub()
517 self.init_data_pub()
517 self.init_data_pub()
518 self.init_displayhook()
518 self.init_displayhook()
519 self.init_latextool()
519 self.init_latextool()
520 self.init_magics()
520 self.init_magics()
521 self.init_alias()
521 self.init_alias()
522 self.init_logstart()
522 self.init_logstart()
523 self.init_pdb()
523 self.init_pdb()
524 self.init_extension_manager()
524 self.init_extension_manager()
525 self.init_payload()
525 self.init_payload()
526 self.hooks.late_startup_hook()
526 self.hooks.late_startup_hook()
527 self.events.trigger('shell_initialized', self)
527 self.events.trigger('shell_initialized', self)
528 atexit.register(self.atexit_operations)
528 atexit.register(self.atexit_operations)
529
529
530 def get_ipython(self):
530 def get_ipython(self):
531 """Return the currently running IPython instance."""
531 """Return the currently running IPython instance."""
532 return self
532 return self
533
533
534 #-------------------------------------------------------------------------
534 #-------------------------------------------------------------------------
535 # Trait changed handlers
535 # Trait changed handlers
536 #-------------------------------------------------------------------------
536 #-------------------------------------------------------------------------
537
537
538 def _ipython_dir_changed(self, name, new):
538 def _ipython_dir_changed(self, name, new):
539 ensure_dir_exists(new)
539 ensure_dir_exists(new)
540
540
541 def set_autoindent(self,value=None):
541 def set_autoindent(self,value=None):
542 """Set the autoindent flag, checking for readline support.
542 """Set the autoindent flag, checking for readline support.
543
543
544 If called with no arguments, it acts as a toggle."""
544 If called with no arguments, it acts as a toggle."""
545
545
546 if value != 0 and not self.has_readline:
546 if value != 0 and not self.has_readline:
547 if os.name == 'posix':
547 if os.name == 'posix':
548 warn("The auto-indent feature requires the readline library")
548 warn("The auto-indent feature requires the readline library")
549 self.autoindent = 0
549 self.autoindent = 0
550 return
550 return
551 if value is None:
551 if value is None:
552 self.autoindent = not self.autoindent
552 self.autoindent = not self.autoindent
553 else:
553 else:
554 self.autoindent = value
554 self.autoindent = value
555
555
556 #-------------------------------------------------------------------------
556 #-------------------------------------------------------------------------
557 # init_* methods called by __init__
557 # init_* methods called by __init__
558 #-------------------------------------------------------------------------
558 #-------------------------------------------------------------------------
559
559
560 def init_ipython_dir(self, ipython_dir):
560 def init_ipython_dir(self, ipython_dir):
561 if ipython_dir is not None:
561 if ipython_dir is not None:
562 self.ipython_dir = ipython_dir
562 self.ipython_dir = ipython_dir
563 return
563 return
564
564
565 self.ipython_dir = get_ipython_dir()
565 self.ipython_dir = get_ipython_dir()
566
566
567 def init_profile_dir(self, profile_dir):
567 def init_profile_dir(self, profile_dir):
568 if profile_dir is not None:
568 if profile_dir is not None:
569 self.profile_dir = profile_dir
569 self.profile_dir = profile_dir
570 return
570 return
571 self.profile_dir =\
571 self.profile_dir =\
572 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
572 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
573
573
574 def init_instance_attrs(self):
574 def init_instance_attrs(self):
575 self.more = False
575 self.more = False
576
576
577 # command compiler
577 # command compiler
578 self.compile = CachingCompiler()
578 self.compile = CachingCompiler()
579
579
580 # Make an empty namespace, which extension writers can rely on both
580 # Make an empty namespace, which extension writers can rely on both
581 # existing and NEVER being used by ipython itself. This gives them a
581 # existing and NEVER being used by ipython itself. This gives them a
582 # convenient location for storing additional information and state
582 # convenient location for storing additional information and state
583 # their extensions may require, without fear of collisions with other
583 # their extensions may require, without fear of collisions with other
584 # ipython names that may develop later.
584 # ipython names that may develop later.
585 self.meta = Struct()
585 self.meta = Struct()
586
586
587 # Temporary files used for various purposes. Deleted at exit.
587 # Temporary files used for various purposes. Deleted at exit.
588 self.tempfiles = []
588 self.tempfiles = []
589 self.tempdirs = []
589 self.tempdirs = []
590
590
591 # Keep track of readline usage (later set by init_readline)
591 # Keep track of readline usage (later set by init_readline)
592 self.has_readline = False
592 self.has_readline = False
593
593
594 # keep track of where we started running (mainly for crash post-mortem)
594 # keep track of where we started running (mainly for crash post-mortem)
595 # This is not being used anywhere currently.
595 # This is not being used anywhere currently.
596 self.starting_dir = py3compat.getcwd()
596 self.starting_dir = py3compat.getcwd()
597
597
598 # Indentation management
598 # Indentation management
599 self.indent_current_nsp = 0
599 self.indent_current_nsp = 0
600
600
601 # Dict to track post-execution functions that have been registered
601 # Dict to track post-execution functions that have been registered
602 self._post_execute = {}
602 self._post_execute = {}
603
603
604 def init_environment(self):
604 def init_environment(self):
605 """Any changes we need to make to the user's environment."""
605 """Any changes we need to make to the user's environment."""
606 pass
606 pass
607
607
608 def init_encoding(self):
608 def init_encoding(self):
609 # Get system encoding at startup time. Certain terminals (like Emacs
609 # Get system encoding at startup time. Certain terminals (like Emacs
610 # under Win32 have it set to None, and we need to have a known valid
610 # under Win32 have it set to None, and we need to have a known valid
611 # encoding to use in the raw_input() method
611 # encoding to use in the raw_input() method
612 try:
612 try:
613 self.stdin_encoding = sys.stdin.encoding or 'ascii'
613 self.stdin_encoding = sys.stdin.encoding or 'ascii'
614 except AttributeError:
614 except AttributeError:
615 self.stdin_encoding = 'ascii'
615 self.stdin_encoding = 'ascii'
616
616
617 def init_syntax_highlighting(self):
617 def init_syntax_highlighting(self):
618 # Python source parser/formatter for syntax highlighting
618 # Python source parser/formatter for syntax highlighting
619 pyformat = PyColorize.Parser().format
619 pyformat = PyColorize.Parser().format
620 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
620 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
621
621
622 def init_pushd_popd_magic(self):
622 def init_pushd_popd_magic(self):
623 # for pushd/popd management
623 # for pushd/popd management
624 self.home_dir = get_home_dir()
624 self.home_dir = get_home_dir()
625
625
626 self.dir_stack = []
626 self.dir_stack = []
627
627
628 def init_logger(self):
628 def init_logger(self):
629 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
629 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
630 logmode='rotate')
630 logmode='rotate')
631
631
632 def init_logstart(self):
632 def init_logstart(self):
633 """Initialize logging in case it was requested at the command line.
633 """Initialize logging in case it was requested at the command line.
634 """
634 """
635 if self.logappend:
635 if self.logappend:
636 self.magic('logstart %s append' % self.logappend)
636 self.magic('logstart %s append' % self.logappend)
637 elif self.logfile:
637 elif self.logfile:
638 self.magic('logstart %s' % self.logfile)
638 self.magic('logstart %s' % self.logfile)
639 elif self.logstart:
639 elif self.logstart:
640 self.magic('logstart')
640 self.magic('logstart')
641
641
642 def init_builtins(self):
642 def init_builtins(self):
643 # A single, static flag that we set to True. Its presence indicates
643 # A single, static flag that we set to True. Its presence indicates
644 # that an IPython shell has been created, and we make no attempts at
644 # that an IPython shell has been created, and we make no attempts at
645 # removing on exit or representing the existence of more than one
645 # removing on exit or representing the existence of more than one
646 # IPython at a time.
646 # IPython at a time.
647 builtin_mod.__dict__['__IPYTHON__'] = True
647 builtin_mod.__dict__['__IPYTHON__'] = True
648
648
649 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
649 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
650 # manage on enter/exit, but with all our shells it's virtually
650 # manage on enter/exit, but with all our shells it's virtually
651 # impossible to get all the cases right. We're leaving the name in for
651 # impossible to get all the cases right. We're leaving the name in for
652 # those who adapted their codes to check for this flag, but will
652 # those who adapted their codes to check for this flag, but will
653 # eventually remove it after a few more releases.
653 # eventually remove it after a few more releases.
654 builtin_mod.__dict__['__IPYTHON__active'] = \
654 builtin_mod.__dict__['__IPYTHON__active'] = \
655 'Deprecated, check for __IPYTHON__'
655 'Deprecated, check for __IPYTHON__'
656
656
657 self.builtin_trap = BuiltinTrap(shell=self)
657 self.builtin_trap = BuiltinTrap(shell=self)
658
658
659 def init_inspector(self):
659 def init_inspector(self):
660 # Object inspector
660 # Object inspector
661 self.inspector = oinspect.Inspector(oinspect.InspectColors,
661 self.inspector = oinspect.Inspector(oinspect.InspectColors,
662 PyColorize.ANSICodeColors,
662 PyColorize.ANSICodeColors,
663 'NoColor',
663 'NoColor',
664 self.object_info_string_level)
664 self.object_info_string_level)
665
665
666 def init_io(self):
666 def init_io(self):
667 # This will just use sys.stdout and sys.stderr. If you want to
667 # This will just use sys.stdout and sys.stderr. If you want to
668 # override sys.stdout and sys.stderr themselves, you need to do that
668 # override sys.stdout and sys.stderr themselves, you need to do that
669 # *before* instantiating this class, because io holds onto
669 # *before* instantiating this class, because io holds onto
670 # references to the underlying streams.
670 # references to the underlying streams.
671 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
671 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
672 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
672 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
673 else:
673 else:
674 io.stdout = io.IOStream(sys.stdout)
674 io.stdout = io.IOStream(sys.stdout)
675 io.stderr = io.IOStream(sys.stderr)
675 io.stderr = io.IOStream(sys.stderr)
676
676
677 def init_prompts(self):
677 def init_prompts(self):
678 self.prompt_manager = PromptManager(shell=self, parent=self)
678 self.prompt_manager = PromptManager(shell=self, parent=self)
679 self.configurables.append(self.prompt_manager)
679 self.configurables.append(self.prompt_manager)
680 # Set system prompts, so that scripts can decide if they are running
680 # Set system prompts, so that scripts can decide if they are running
681 # interactively.
681 # interactively.
682 sys.ps1 = 'In : '
682 sys.ps1 = 'In : '
683 sys.ps2 = '...: '
683 sys.ps2 = '...: '
684 sys.ps3 = 'Out: '
684 sys.ps3 = 'Out: '
685
685
686 def init_display_formatter(self):
686 def init_display_formatter(self):
687 self.display_formatter = DisplayFormatter(parent=self)
687 self.display_formatter = DisplayFormatter(parent=self)
688 self.configurables.append(self.display_formatter)
688 self.configurables.append(self.display_formatter)
689
689
690 def init_display_pub(self):
690 def init_display_pub(self):
691 self.display_pub = self.display_pub_class(parent=self)
691 self.display_pub = self.display_pub_class(parent=self)
692 self.configurables.append(self.display_pub)
692 self.configurables.append(self.display_pub)
693
693
694 def init_data_pub(self):
694 def init_data_pub(self):
695 if not self.data_pub_class:
695 if not self.data_pub_class:
696 self.data_pub = None
696 self.data_pub = None
697 return
697 return
698 self.data_pub = self.data_pub_class(parent=self)
698 self.data_pub = self.data_pub_class(parent=self)
699 self.configurables.append(self.data_pub)
699 self.configurables.append(self.data_pub)
700
700
701 def init_displayhook(self):
701 def init_displayhook(self):
702 # Initialize displayhook, set in/out prompts and printing system
702 # Initialize displayhook, set in/out prompts and printing system
703 self.displayhook = self.displayhook_class(
703 self.displayhook = self.displayhook_class(
704 parent=self,
704 parent=self,
705 shell=self,
705 shell=self,
706 cache_size=self.cache_size,
706 cache_size=self.cache_size,
707 )
707 )
708 self.configurables.append(self.displayhook)
708 self.configurables.append(self.displayhook)
709 # This is a context manager that installs/revmoes the displayhook at
709 # This is a context manager that installs/revmoes the displayhook at
710 # the appropriate time.
710 # the appropriate time.
711 self.display_trap = DisplayTrap(hook=self.displayhook)
711 self.display_trap = DisplayTrap(hook=self.displayhook)
712
712
713 def init_latextool(self):
713 def init_latextool(self):
714 """Configure LaTeXTool."""
714 """Configure LaTeXTool."""
715 cfg = LaTeXTool.instance(parent=self)
715 cfg = LaTeXTool.instance(parent=self)
716 if cfg not in self.configurables:
716 if cfg not in self.configurables:
717 self.configurables.append(cfg)
717 self.configurables.append(cfg)
718
718
719 def init_virtualenv(self):
719 def init_virtualenv(self):
720 """Add a virtualenv to sys.path so the user can import modules from it.
720 """Add a virtualenv to sys.path so the user can import modules from it.
721 This isn't perfect: it doesn't use the Python interpreter with which the
721 This isn't perfect: it doesn't use the Python interpreter with which the
722 virtualenv was built, and it ignores the --no-site-packages option. A
722 virtualenv was built, and it ignores the --no-site-packages option. A
723 warning will appear suggesting the user installs IPython in the
723 warning will appear suggesting the user installs IPython in the
724 virtualenv, but for many cases, it probably works well enough.
724 virtualenv, but for many cases, it probably works well enough.
725
725
726 Adapted from code snippets online.
726 Adapted from code snippets online.
727
727
728 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
728 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
729 """
729 """
730 if 'VIRTUAL_ENV' not in os.environ:
730 if 'VIRTUAL_ENV' not in os.environ:
731 # Not in a virtualenv
731 # Not in a virtualenv
732 return
732 return
733
733
734 # venv detection:
734 # venv detection:
735 # stdlib venv may symlink sys.executable, so we can't use realpath.
735 # stdlib venv may symlink sys.executable, so we can't use realpath.
736 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
736 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
737 # So we just check every item in the symlink tree (generally <= 3)
737 # So we just check every item in the symlink tree (generally <= 3)
738 p = os.path.normcase(sys.executable)
738 p = os.path.normcase(sys.executable)
739 paths = [p]
739 paths = [p]
740 while os.path.islink(p):
740 while os.path.islink(p):
741 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
741 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
742 paths.append(p)
742 paths.append(p)
743 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
743 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
744 if any(p.startswith(p_venv) for p in paths):
744 if any(p.startswith(p_venv) for p in paths):
745 # Running properly in the virtualenv, don't need to do anything
745 # Running properly in the virtualenv, don't need to do anything
746 return
746 return
747
747
748 warn("Attempting to work in a virtualenv. If you encounter problems, please "
748 warn("Attempting to work in a virtualenv. If you encounter problems, please "
749 "install IPython inside the virtualenv.")
749 "install IPython inside the virtualenv.")
750 if sys.platform == "win32":
750 if sys.platform == "win32":
751 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
751 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
752 else:
752 else:
753 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
753 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
754 'python%d.%d' % sys.version_info[:2], 'site-packages')
754 'python%d.%d' % sys.version_info[:2], 'site-packages')
755
755
756 import site
756 import site
757 sys.path.insert(0, virtual_env)
757 sys.path.insert(0, virtual_env)
758 site.addsitedir(virtual_env)
758 site.addsitedir(virtual_env)
759
759
760 #-------------------------------------------------------------------------
760 #-------------------------------------------------------------------------
761 # Things related to injections into the sys module
761 # Things related to injections into the sys module
762 #-------------------------------------------------------------------------
762 #-------------------------------------------------------------------------
763
763
764 def save_sys_module_state(self):
764 def save_sys_module_state(self):
765 """Save the state of hooks in the sys module.
765 """Save the state of hooks in the sys module.
766
766
767 This has to be called after self.user_module is created.
767 This has to be called after self.user_module is created.
768 """
768 """
769 self._orig_sys_module_state = {}
769 self._orig_sys_module_state = {}
770 self._orig_sys_module_state['stdin'] = sys.stdin
770 self._orig_sys_module_state['stdin'] = sys.stdin
771 self._orig_sys_module_state['stdout'] = sys.stdout
771 self._orig_sys_module_state['stdout'] = sys.stdout
772 self._orig_sys_module_state['stderr'] = sys.stderr
772 self._orig_sys_module_state['stderr'] = sys.stderr
773 self._orig_sys_module_state['excepthook'] = sys.excepthook
773 self._orig_sys_module_state['excepthook'] = sys.excepthook
774 self._orig_sys_modules_main_name = self.user_module.__name__
774 self._orig_sys_modules_main_name = self.user_module.__name__
775 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
775 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
776
776
777 def restore_sys_module_state(self):
777 def restore_sys_module_state(self):
778 """Restore the state of the sys module."""
778 """Restore the state of the sys module."""
779 try:
779 try:
780 for k, v in iteritems(self._orig_sys_module_state):
780 for k, v in iteritems(self._orig_sys_module_state):
781 setattr(sys, k, v)
781 setattr(sys, k, v)
782 except AttributeError:
782 except AttributeError:
783 pass
783 pass
784 # Reset what what done in self.init_sys_modules
784 # Reset what what done in self.init_sys_modules
785 if self._orig_sys_modules_main_mod is not None:
785 if self._orig_sys_modules_main_mod is not None:
786 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
786 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
787
787
788 #-------------------------------------------------------------------------
788 #-------------------------------------------------------------------------
789 # Things related to the banner
789 # Things related to the banner
790 #-------------------------------------------------------------------------
790 #-------------------------------------------------------------------------
791
791
792 @property
792 @property
793 def banner(self):
793 def banner(self):
794 banner = self.banner1
794 banner = self.banner1
795 if self.profile and self.profile != 'default':
795 if self.profile and self.profile != 'default':
796 banner += '\nIPython profile: %s\n' % self.profile
796 banner += '\nIPython profile: %s\n' % self.profile
797 if self.banner2:
797 if self.banner2:
798 banner += '\n' + self.banner2
798 banner += '\n' + self.banner2
799 return banner
799 return banner
800
800
801 def show_banner(self, banner=None):
801 def show_banner(self, banner=None):
802 if banner is None:
802 if banner is None:
803 banner = self.banner
803 banner = self.banner
804 self.write(banner)
804 self.write(banner)
805
805
806 #-------------------------------------------------------------------------
806 #-------------------------------------------------------------------------
807 # Things related to hooks
807 # Things related to hooks
808 #-------------------------------------------------------------------------
808 #-------------------------------------------------------------------------
809
809
810 def init_hooks(self):
810 def init_hooks(self):
811 # hooks holds pointers used for user-side customizations
811 # hooks holds pointers used for user-side customizations
812 self.hooks = Struct()
812 self.hooks = Struct()
813
813
814 self.strdispatchers = {}
814 self.strdispatchers = {}
815
815
816 # Set all default hooks, defined in the IPython.hooks module.
816 # Set all default hooks, defined in the IPython.hooks module.
817 hooks = IPython.core.hooks
817 hooks = IPython.core.hooks
818 for hook_name in hooks.__all__:
818 for hook_name in hooks.__all__:
819 # default hooks have priority 100, i.e. low; user hooks should have
819 # default hooks have priority 100, i.e. low; user hooks should have
820 # 0-100 priority
820 # 0-100 priority
821 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
821 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
822
822
823 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
823 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
824 _warn_deprecated=True):
824 _warn_deprecated=True):
825 """set_hook(name,hook) -> sets an internal IPython hook.
825 """set_hook(name,hook) -> sets an internal IPython hook.
826
826
827 IPython exposes some of its internal API as user-modifiable hooks. By
827 IPython exposes some of its internal API as user-modifiable hooks. By
828 adding your function to one of these hooks, you can modify IPython's
828 adding your function to one of these hooks, you can modify IPython's
829 behavior to call at runtime your own routines."""
829 behavior to call at runtime your own routines."""
830
830
831 # At some point in the future, this should validate the hook before it
831 # At some point in the future, this should validate the hook before it
832 # accepts it. Probably at least check that the hook takes the number
832 # accepts it. Probably at least check that the hook takes the number
833 # of args it's supposed to.
833 # of args it's supposed to.
834
834
835 f = types.MethodType(hook,self)
835 f = types.MethodType(hook,self)
836
836
837 # check if the hook is for strdispatcher first
837 # check if the hook is for strdispatcher first
838 if str_key is not None:
838 if str_key is not None:
839 sdp = self.strdispatchers.get(name, StrDispatch())
839 sdp = self.strdispatchers.get(name, StrDispatch())
840 sdp.add_s(str_key, f, priority )
840 sdp.add_s(str_key, f, priority )
841 self.strdispatchers[name] = sdp
841 self.strdispatchers[name] = sdp
842 return
842 return
843 if re_key is not None:
843 if re_key is not None:
844 sdp = self.strdispatchers.get(name, StrDispatch())
844 sdp = self.strdispatchers.get(name, StrDispatch())
845 sdp.add_re(re.compile(re_key), f, priority )
845 sdp.add_re(re.compile(re_key), f, priority )
846 self.strdispatchers[name] = sdp
846 self.strdispatchers[name] = sdp
847 return
847 return
848
848
849 dp = getattr(self.hooks, name, None)
849 dp = getattr(self.hooks, name, None)
850 if name not in IPython.core.hooks.__all__:
850 if name not in IPython.core.hooks.__all__:
851 print("Warning! Hook '%s' is not one of %s" % \
851 print("Warning! Hook '%s' is not one of %s" % \
852 (name, IPython.core.hooks.__all__ ))
852 (name, IPython.core.hooks.__all__ ))
853
853
854 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
854 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
855 alternative = IPython.core.hooks.deprecated[name]
855 alternative = IPython.core.hooks.deprecated[name]
856 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
856 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
857
857
858 if not dp:
858 if not dp:
859 dp = IPython.core.hooks.CommandChainDispatcher()
859 dp = IPython.core.hooks.CommandChainDispatcher()
860
860
861 try:
861 try:
862 dp.add(f,priority)
862 dp.add(f,priority)
863 except AttributeError:
863 except AttributeError:
864 # it was not commandchain, plain old func - replace
864 # it was not commandchain, plain old func - replace
865 dp = f
865 dp = f
866
866
867 setattr(self.hooks,name, dp)
867 setattr(self.hooks,name, dp)
868
868
869 #-------------------------------------------------------------------------
869 #-------------------------------------------------------------------------
870 # Things related to events
870 # Things related to events
871 #-------------------------------------------------------------------------
871 #-------------------------------------------------------------------------
872
872
873 def init_events(self):
873 def init_events(self):
874 self.events = EventManager(self, available_events)
874 self.events = EventManager(self, available_events)
875
875
876 self.events.register("pre_execute", self._clear_warning_registry)
876 self.events.register("pre_execute", self._clear_warning_registry)
877
877
878 def register_post_execute(self, func):
878 def register_post_execute(self, func):
879 """DEPRECATED: Use ip.events.register('post_run_cell', func)
879 """DEPRECATED: Use ip.events.register('post_run_cell', func)
880
880
881 Register a function for calling after code execution.
881 Register a function for calling after code execution.
882 """
882 """
883 warn("ip.register_post_execute is deprecated, use "
883 warn("ip.register_post_execute is deprecated, use "
884 "ip.events.register('post_run_cell', func) instead.")
884 "ip.events.register('post_run_cell', func) instead.")
885 self.events.register('post_run_cell', func)
885 self.events.register('post_run_cell', func)
886
886
887 def _clear_warning_registry(self):
887 def _clear_warning_registry(self):
888 # clear the warning registry, so that different code blocks with
888 # clear the warning registry, so that different code blocks with
889 # overlapping line number ranges don't cause spurious suppression of
889 # overlapping line number ranges don't cause spurious suppression of
890 # warnings (see gh-6611 for details)
890 # warnings (see gh-6611 for details)
891 if "__warningregistry__" in self.user_global_ns:
891 if "__warningregistry__" in self.user_global_ns:
892 del self.user_global_ns["__warningregistry__"]
892 del self.user_global_ns["__warningregistry__"]
893
893
894 #-------------------------------------------------------------------------
894 #-------------------------------------------------------------------------
895 # Things related to the "main" module
895 # Things related to the "main" module
896 #-------------------------------------------------------------------------
896 #-------------------------------------------------------------------------
897
897
898 def new_main_mod(self, filename, modname):
898 def new_main_mod(self, filename, modname):
899 """Return a new 'main' module object for user code execution.
899 """Return a new 'main' module object for user code execution.
900
900
901 ``filename`` should be the path of the script which will be run in the
901 ``filename`` should be the path of the script which will be run in the
902 module. Requests with the same filename will get the same module, with
902 module. Requests with the same filename will get the same module, with
903 its namespace cleared.
903 its namespace cleared.
904
904
905 ``modname`` should be the module name - normally either '__main__' or
905 ``modname`` should be the module name - normally either '__main__' or
906 the basename of the file without the extension.
906 the basename of the file without the extension.
907
907
908 When scripts are executed via %run, we must keep a reference to their
908 When scripts are executed via %run, we must keep a reference to their
909 __main__ module around so that Python doesn't
909 __main__ module around so that Python doesn't
910 clear it, rendering references to module globals useless.
910 clear it, rendering references to module globals useless.
911
911
912 This method keeps said reference in a private dict, keyed by the
912 This method keeps said reference in a private dict, keyed by the
913 absolute path of the script. This way, for multiple executions of the
913 absolute path of the script. This way, for multiple executions of the
914 same script we only keep one copy of the namespace (the last one),
914 same script we only keep one copy of the namespace (the last one),
915 thus preventing memory leaks from old references while allowing the
915 thus preventing memory leaks from old references while allowing the
916 objects from the last execution to be accessible.
916 objects from the last execution to be accessible.
917 """
917 """
918 filename = os.path.abspath(filename)
918 filename = os.path.abspath(filename)
919 try:
919 try:
920 main_mod = self._main_mod_cache[filename]
920 main_mod = self._main_mod_cache[filename]
921 except KeyError:
921 except KeyError:
922 main_mod = self._main_mod_cache[filename] = types.ModuleType(
922 main_mod = self._main_mod_cache[filename] = types.ModuleType(
923 py3compat.cast_bytes_py2(modname),
923 py3compat.cast_bytes_py2(modname),
924 doc="Module created for script run in IPython")
924 doc="Module created for script run in IPython")
925 else:
925 else:
926 main_mod.__dict__.clear()
926 main_mod.__dict__.clear()
927 main_mod.__name__ = modname
927 main_mod.__name__ = modname
928
928
929 main_mod.__file__ = filename
929 main_mod.__file__ = filename
930 # It seems pydoc (and perhaps others) needs any module instance to
930 # It seems pydoc (and perhaps others) needs any module instance to
931 # implement a __nonzero__ method
931 # implement a __nonzero__ method
932 main_mod.__nonzero__ = lambda : True
932 main_mod.__nonzero__ = lambda : True
933
933
934 return main_mod
934 return main_mod
935
935
936 def clear_main_mod_cache(self):
936 def clear_main_mod_cache(self):
937 """Clear the cache of main modules.
937 """Clear the cache of main modules.
938
938
939 Mainly for use by utilities like %reset.
939 Mainly for use by utilities like %reset.
940
940
941 Examples
941 Examples
942 --------
942 --------
943
943
944 In [15]: import IPython
944 In [15]: import IPython
945
945
946 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
946 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
947
947
948 In [17]: len(_ip._main_mod_cache) > 0
948 In [17]: len(_ip._main_mod_cache) > 0
949 Out[17]: True
949 Out[17]: True
950
950
951 In [18]: _ip.clear_main_mod_cache()
951 In [18]: _ip.clear_main_mod_cache()
952
952
953 In [19]: len(_ip._main_mod_cache) == 0
953 In [19]: len(_ip._main_mod_cache) == 0
954 Out[19]: True
954 Out[19]: True
955 """
955 """
956 self._main_mod_cache.clear()
956 self._main_mod_cache.clear()
957
957
958 #-------------------------------------------------------------------------
958 #-------------------------------------------------------------------------
959 # Things related to debugging
959 # Things related to debugging
960 #-------------------------------------------------------------------------
960 #-------------------------------------------------------------------------
961
961
962 def init_pdb(self):
962 def init_pdb(self):
963 # Set calling of pdb on exceptions
963 # Set calling of pdb on exceptions
964 # self.call_pdb is a property
964 # self.call_pdb is a property
965 self.call_pdb = self.pdb
965 self.call_pdb = self.pdb
966
966
967 def _get_call_pdb(self):
967 def _get_call_pdb(self):
968 return self._call_pdb
968 return self._call_pdb
969
969
970 def _set_call_pdb(self,val):
970 def _set_call_pdb(self,val):
971
971
972 if val not in (0,1,False,True):
972 if val not in (0,1,False,True):
973 raise ValueError('new call_pdb value must be boolean')
973 raise ValueError('new call_pdb value must be boolean')
974
974
975 # store value in instance
975 # store value in instance
976 self._call_pdb = val
976 self._call_pdb = val
977
977
978 # notify the actual exception handlers
978 # notify the actual exception handlers
979 self.InteractiveTB.call_pdb = val
979 self.InteractiveTB.call_pdb = val
980
980
981 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
981 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
982 'Control auto-activation of pdb at exceptions')
982 'Control auto-activation of pdb at exceptions')
983
983
984 def debugger(self,force=False):
984 def debugger(self,force=False):
985 """Call the pydb/pdb debugger.
985 """Call the pydb/pdb debugger.
986
986
987 Keywords:
987 Keywords:
988
988
989 - force(False): by default, this routine checks the instance call_pdb
989 - force(False): by default, this routine checks the instance call_pdb
990 flag and does not actually invoke the debugger if the flag is false.
990 flag and does not actually invoke the debugger if the flag is false.
991 The 'force' option forces the debugger to activate even if the flag
991 The 'force' option forces the debugger to activate even if the flag
992 is false.
992 is false.
993 """
993 """
994
994
995 if not (force or self.call_pdb):
995 if not (force or self.call_pdb):
996 return
996 return
997
997
998 if not hasattr(sys,'last_traceback'):
998 if not hasattr(sys,'last_traceback'):
999 error('No traceback has been produced, nothing to debug.')
999 error('No traceback has been produced, nothing to debug.')
1000 return
1000 return
1001
1001
1002 # use pydb if available
1002 # use pydb if available
1003 if debugger.has_pydb:
1003 if debugger.has_pydb:
1004 from pydb import pm
1004 from pydb import pm
1005 else:
1005 else:
1006 # fallback to our internal debugger
1006 # fallback to our internal debugger
1007 pm = lambda : self.InteractiveTB.debugger(force=True)
1007 pm = lambda : self.InteractiveTB.debugger(force=True)
1008
1008
1009 with self.readline_no_record:
1009 with self.readline_no_record:
1010 pm()
1010 pm()
1011
1011
1012 #-------------------------------------------------------------------------
1012 #-------------------------------------------------------------------------
1013 # Things related to IPython's various namespaces
1013 # Things related to IPython's various namespaces
1014 #-------------------------------------------------------------------------
1014 #-------------------------------------------------------------------------
1015 default_user_namespaces = True
1015 default_user_namespaces = True
1016
1016
1017 def init_create_namespaces(self, user_module=None, user_ns=None):
1017 def init_create_namespaces(self, user_module=None, user_ns=None):
1018 # Create the namespace where the user will operate. user_ns is
1018 # Create the namespace where the user will operate. user_ns is
1019 # normally the only one used, and it is passed to the exec calls as
1019 # normally the only one used, and it is passed to the exec calls as
1020 # the locals argument. But we do carry a user_global_ns namespace
1020 # the locals argument. But we do carry a user_global_ns namespace
1021 # given as the exec 'globals' argument, This is useful in embedding
1021 # given as the exec 'globals' argument, This is useful in embedding
1022 # situations where the ipython shell opens in a context where the
1022 # situations where the ipython shell opens in a context where the
1023 # distinction between locals and globals is meaningful. For
1023 # distinction between locals and globals is meaningful. For
1024 # non-embedded contexts, it is just the same object as the user_ns dict.
1024 # non-embedded contexts, it is just the same object as the user_ns dict.
1025
1025
1026 # FIXME. For some strange reason, __builtins__ is showing up at user
1026 # FIXME. For some strange reason, __builtins__ is showing up at user
1027 # level as a dict instead of a module. This is a manual fix, but I
1027 # level as a dict instead of a module. This is a manual fix, but I
1028 # should really track down where the problem is coming from. Alex
1028 # should really track down where the problem is coming from. Alex
1029 # Schmolck reported this problem first.
1029 # Schmolck reported this problem first.
1030
1030
1031 # A useful post by Alex Martelli on this topic:
1031 # A useful post by Alex Martelli on this topic:
1032 # Re: inconsistent value from __builtins__
1032 # Re: inconsistent value from __builtins__
1033 # Von: Alex Martelli <aleaxit@yahoo.com>
1033 # Von: Alex Martelli <aleaxit@yahoo.com>
1034 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1034 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1035 # Gruppen: comp.lang.python
1035 # Gruppen: comp.lang.python
1036
1036
1037 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1037 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1038 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1038 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1039 # > <type 'dict'>
1039 # > <type 'dict'>
1040 # > >>> print type(__builtins__)
1040 # > >>> print type(__builtins__)
1041 # > <type 'module'>
1041 # > <type 'module'>
1042 # > Is this difference in return value intentional?
1042 # > Is this difference in return value intentional?
1043
1043
1044 # Well, it's documented that '__builtins__' can be either a dictionary
1044 # Well, it's documented that '__builtins__' can be either a dictionary
1045 # or a module, and it's been that way for a long time. Whether it's
1045 # or a module, and it's been that way for a long time. Whether it's
1046 # intentional (or sensible), I don't know. In any case, the idea is
1046 # intentional (or sensible), I don't know. In any case, the idea is
1047 # that if you need to access the built-in namespace directly, you
1047 # that if you need to access the built-in namespace directly, you
1048 # should start with "import __builtin__" (note, no 's') which will
1048 # should start with "import __builtin__" (note, no 's') which will
1049 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1049 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1050
1050
1051 # These routines return a properly built module and dict as needed by
1051 # These routines return a properly built module and dict as needed by
1052 # the rest of the code, and can also be used by extension writers to
1052 # the rest of the code, and can also be used by extension writers to
1053 # generate properly initialized namespaces.
1053 # generate properly initialized namespaces.
1054 if (user_ns is not None) or (user_module is not None):
1054 if (user_ns is not None) or (user_module is not None):
1055 self.default_user_namespaces = False
1055 self.default_user_namespaces = False
1056 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1056 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1057
1057
1058 # A record of hidden variables we have added to the user namespace, so
1058 # A record of hidden variables we have added to the user namespace, so
1059 # we can list later only variables defined in actual interactive use.
1059 # we can list later only variables defined in actual interactive use.
1060 self.user_ns_hidden = {}
1060 self.user_ns_hidden = {}
1061
1061
1062 # Now that FakeModule produces a real module, we've run into a nasty
1062 # Now that FakeModule produces a real module, we've run into a nasty
1063 # problem: after script execution (via %run), the module where the user
1063 # problem: after script execution (via %run), the module where the user
1064 # code ran is deleted. Now that this object is a true module (needed
1064 # code ran is deleted. Now that this object is a true module (needed
1065 # so docetst and other tools work correctly), the Python module
1065 # so docetst and other tools work correctly), the Python module
1066 # teardown mechanism runs over it, and sets to None every variable
1066 # teardown mechanism runs over it, and sets to None every variable
1067 # present in that module. Top-level references to objects from the
1067 # present in that module. Top-level references to objects from the
1068 # script survive, because the user_ns is updated with them. However,
1068 # script survive, because the user_ns is updated with them. However,
1069 # calling functions defined in the script that use other things from
1069 # calling functions defined in the script that use other things from
1070 # the script will fail, because the function's closure had references
1070 # the script will fail, because the function's closure had references
1071 # to the original objects, which are now all None. So we must protect
1071 # to the original objects, which are now all None. So we must protect
1072 # these modules from deletion by keeping a cache.
1072 # these modules from deletion by keeping a cache.
1073 #
1073 #
1074 # To avoid keeping stale modules around (we only need the one from the
1074 # To avoid keeping stale modules around (we only need the one from the
1075 # last run), we use a dict keyed with the full path to the script, so
1075 # last run), we use a dict keyed with the full path to the script, so
1076 # only the last version of the module is held in the cache. Note,
1076 # only the last version of the module is held in the cache. Note,
1077 # however, that we must cache the module *namespace contents* (their
1077 # however, that we must cache the module *namespace contents* (their
1078 # __dict__). Because if we try to cache the actual modules, old ones
1078 # __dict__). Because if we try to cache the actual modules, old ones
1079 # (uncached) could be destroyed while still holding references (such as
1079 # (uncached) could be destroyed while still holding references (such as
1080 # those held by GUI objects that tend to be long-lived)>
1080 # those held by GUI objects that tend to be long-lived)>
1081 #
1081 #
1082 # The %reset command will flush this cache. See the cache_main_mod()
1082 # The %reset command will flush this cache. See the cache_main_mod()
1083 # and clear_main_mod_cache() methods for details on use.
1083 # and clear_main_mod_cache() methods for details on use.
1084
1084
1085 # This is the cache used for 'main' namespaces
1085 # This is the cache used for 'main' namespaces
1086 self._main_mod_cache = {}
1086 self._main_mod_cache = {}
1087
1087
1088 # A table holding all the namespaces IPython deals with, so that
1088 # A table holding all the namespaces IPython deals with, so that
1089 # introspection facilities can search easily.
1089 # introspection facilities can search easily.
1090 self.ns_table = {'user_global':self.user_module.__dict__,
1090 self.ns_table = {'user_global':self.user_module.__dict__,
1091 'user_local':self.user_ns,
1091 'user_local':self.user_ns,
1092 'builtin':builtin_mod.__dict__
1092 'builtin':builtin_mod.__dict__
1093 }
1093 }
1094
1094
1095 @property
1095 @property
1096 def user_global_ns(self):
1096 def user_global_ns(self):
1097 return self.user_module.__dict__
1097 return self.user_module.__dict__
1098
1098
1099 def prepare_user_module(self, user_module=None, user_ns=None):
1099 def prepare_user_module(self, user_module=None, user_ns=None):
1100 """Prepare the module and namespace in which user code will be run.
1100 """Prepare the module and namespace in which user code will be run.
1101
1101
1102 When IPython is started normally, both parameters are None: a new module
1102 When IPython is started normally, both parameters are None: a new module
1103 is created automatically, and its __dict__ used as the namespace.
1103 is created automatically, and its __dict__ used as the namespace.
1104
1104
1105 If only user_module is provided, its __dict__ is used as the namespace.
1105 If only user_module is provided, its __dict__ is used as the namespace.
1106 If only user_ns is provided, a dummy module is created, and user_ns
1106 If only user_ns is provided, a dummy module is created, and user_ns
1107 becomes the global namespace. If both are provided (as they may be
1107 becomes the global namespace. If both are provided (as they may be
1108 when embedding), user_ns is the local namespace, and user_module
1108 when embedding), user_ns is the local namespace, and user_module
1109 provides the global namespace.
1109 provides the global namespace.
1110
1110
1111 Parameters
1111 Parameters
1112 ----------
1112 ----------
1113 user_module : module, optional
1113 user_module : module, optional
1114 The current user module in which IPython is being run. If None,
1114 The current user module in which IPython is being run. If None,
1115 a clean module will be created.
1115 a clean module will be created.
1116 user_ns : dict, optional
1116 user_ns : dict, optional
1117 A namespace in which to run interactive commands.
1117 A namespace in which to run interactive commands.
1118
1118
1119 Returns
1119 Returns
1120 -------
1120 -------
1121 A tuple of user_module and user_ns, each properly initialised.
1121 A tuple of user_module and user_ns, each properly initialised.
1122 """
1122 """
1123 if user_module is None and user_ns is not None:
1123 if user_module is None and user_ns is not None:
1124 user_ns.setdefault("__name__", "__main__")
1124 user_ns.setdefault("__name__", "__main__")
1125 user_module = DummyMod()
1125 user_module = DummyMod()
1126 user_module.__dict__ = user_ns
1126 user_module.__dict__ = user_ns
1127
1127
1128 if user_module is None:
1128 if user_module is None:
1129 user_module = types.ModuleType("__main__",
1129 user_module = types.ModuleType("__main__",
1130 doc="Automatically created module for IPython interactive environment")
1130 doc="Automatically created module for IPython interactive environment")
1131
1131
1132 # We must ensure that __builtin__ (without the final 's') is always
1132 # We must ensure that __builtin__ (without the final 's') is always
1133 # available and pointing to the __builtin__ *module*. For more details:
1133 # available and pointing to the __builtin__ *module*. For more details:
1134 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1134 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1135 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1135 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1136 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1136 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1137
1137
1138 if user_ns is None:
1138 if user_ns is None:
1139 user_ns = user_module.__dict__
1139 user_ns = user_module.__dict__
1140
1140
1141 return user_module, user_ns
1141 return user_module, user_ns
1142
1142
1143 def init_sys_modules(self):
1143 def init_sys_modules(self):
1144 # We need to insert into sys.modules something that looks like a
1144 # We need to insert into sys.modules something that looks like a
1145 # module but which accesses the IPython namespace, for shelve and
1145 # module but which accesses the IPython namespace, for shelve and
1146 # pickle to work interactively. Normally they rely on getting
1146 # pickle to work interactively. Normally they rely on getting
1147 # everything out of __main__, but for embedding purposes each IPython
1147 # everything out of __main__, but for embedding purposes each IPython
1148 # instance has its own private namespace, so we can't go shoving
1148 # instance has its own private namespace, so we can't go shoving
1149 # everything into __main__.
1149 # everything into __main__.
1150
1150
1151 # note, however, that we should only do this for non-embedded
1151 # note, however, that we should only do this for non-embedded
1152 # ipythons, which really mimic the __main__.__dict__ with their own
1152 # ipythons, which really mimic the __main__.__dict__ with their own
1153 # namespace. Embedded instances, on the other hand, should not do
1153 # namespace. Embedded instances, on the other hand, should not do
1154 # this because they need to manage the user local/global namespaces
1154 # this because they need to manage the user local/global namespaces
1155 # only, but they live within a 'normal' __main__ (meaning, they
1155 # only, but they live within a 'normal' __main__ (meaning, they
1156 # shouldn't overtake the execution environment of the script they're
1156 # shouldn't overtake the execution environment of the script they're
1157 # embedded in).
1157 # embedded in).
1158
1158
1159 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1159 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1160 main_name = self.user_module.__name__
1160 main_name = self.user_module.__name__
1161 sys.modules[main_name] = self.user_module
1161 sys.modules[main_name] = self.user_module
1162
1162
1163 def init_user_ns(self):
1163 def init_user_ns(self):
1164 """Initialize all user-visible namespaces to their minimum defaults.
1164 """Initialize all user-visible namespaces to their minimum defaults.
1165
1165
1166 Certain history lists are also initialized here, as they effectively
1166 Certain history lists are also initialized here, as they effectively
1167 act as user namespaces.
1167 act as user namespaces.
1168
1168
1169 Notes
1169 Notes
1170 -----
1170 -----
1171 All data structures here are only filled in, they are NOT reset by this
1171 All data structures here are only filled in, they are NOT reset by this
1172 method. If they were not empty before, data will simply be added to
1172 method. If they were not empty before, data will simply be added to
1173 therm.
1173 therm.
1174 """
1174 """
1175 # This function works in two parts: first we put a few things in
1175 # This function works in two parts: first we put a few things in
1176 # user_ns, and we sync that contents into user_ns_hidden so that these
1176 # user_ns, and we sync that contents into user_ns_hidden so that these
1177 # initial variables aren't shown by %who. After the sync, we add the
1177 # initial variables aren't shown by %who. After the sync, we add the
1178 # rest of what we *do* want the user to see with %who even on a new
1178 # rest of what we *do* want the user to see with %who even on a new
1179 # session (probably nothing, so theye really only see their own stuff)
1179 # session (probably nothing, so theye really only see their own stuff)
1180
1180
1181 # The user dict must *always* have a __builtin__ reference to the
1181 # The user dict must *always* have a __builtin__ reference to the
1182 # Python standard __builtin__ namespace, which must be imported.
1182 # Python standard __builtin__ namespace, which must be imported.
1183 # This is so that certain operations in prompt evaluation can be
1183 # This is so that certain operations in prompt evaluation can be
1184 # reliably executed with builtins. Note that we can NOT use
1184 # reliably executed with builtins. Note that we can NOT use
1185 # __builtins__ (note the 's'), because that can either be a dict or a
1185 # __builtins__ (note the 's'), because that can either be a dict or a
1186 # module, and can even mutate at runtime, depending on the context
1186 # module, and can even mutate at runtime, depending on the context
1187 # (Python makes no guarantees on it). In contrast, __builtin__ is
1187 # (Python makes no guarantees on it). In contrast, __builtin__ is
1188 # always a module object, though it must be explicitly imported.
1188 # always a module object, though it must be explicitly imported.
1189
1189
1190 # For more details:
1190 # For more details:
1191 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1191 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1192 ns = dict()
1192 ns = dict()
1193
1193
1194 # make global variables for user access to the histories
1194 # make global variables for user access to the histories
1195 ns['_ih'] = self.history_manager.input_hist_parsed
1195 ns['_ih'] = self.history_manager.input_hist_parsed
1196 ns['_oh'] = self.history_manager.output_hist
1196 ns['_oh'] = self.history_manager.output_hist
1197 ns['_dh'] = self.history_manager.dir_hist
1197 ns['_dh'] = self.history_manager.dir_hist
1198
1198
1199 ns['_sh'] = shadowns
1199 ns['_sh'] = shadowns
1200
1200
1201 # user aliases to input and output histories. These shouldn't show up
1201 # user aliases to input and output histories. These shouldn't show up
1202 # in %who, as they can have very large reprs.
1202 # in %who, as they can have very large reprs.
1203 ns['In'] = self.history_manager.input_hist_parsed
1203 ns['In'] = self.history_manager.input_hist_parsed
1204 ns['Out'] = self.history_manager.output_hist
1204 ns['Out'] = self.history_manager.output_hist
1205
1205
1206 # Store myself as the public api!!!
1206 # Store myself as the public api!!!
1207 ns['get_ipython'] = self.get_ipython
1207 ns['get_ipython'] = self.get_ipython
1208
1208
1209 ns['exit'] = self.exiter
1209 ns['exit'] = self.exiter
1210 ns['quit'] = self.exiter
1210 ns['quit'] = self.exiter
1211
1211
1212 # Sync what we've added so far to user_ns_hidden so these aren't seen
1212 # Sync what we've added so far to user_ns_hidden so these aren't seen
1213 # by %who
1213 # by %who
1214 self.user_ns_hidden.update(ns)
1214 self.user_ns_hidden.update(ns)
1215
1215
1216 # Anything put into ns now would show up in %who. Think twice before
1216 # Anything put into ns now would show up in %who. Think twice before
1217 # putting anything here, as we really want %who to show the user their
1217 # putting anything here, as we really want %who to show the user their
1218 # stuff, not our variables.
1218 # stuff, not our variables.
1219
1219
1220 # Finally, update the real user's namespace
1220 # Finally, update the real user's namespace
1221 self.user_ns.update(ns)
1221 self.user_ns.update(ns)
1222
1222
1223 @property
1223 @property
1224 def all_ns_refs(self):
1224 def all_ns_refs(self):
1225 """Get a list of references to all the namespace dictionaries in which
1225 """Get a list of references to all the namespace dictionaries in which
1226 IPython might store a user-created object.
1226 IPython might store a user-created object.
1227
1227
1228 Note that this does not include the displayhook, which also caches
1228 Note that this does not include the displayhook, which also caches
1229 objects from the output."""
1229 objects from the output."""
1230 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1230 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1231 [m.__dict__ for m in self._main_mod_cache.values()]
1231 [m.__dict__ for m in self._main_mod_cache.values()]
1232
1232
1233 def reset(self, new_session=True):
1233 def reset(self, new_session=True):
1234 """Clear all internal namespaces, and attempt to release references to
1234 """Clear all internal namespaces, and attempt to release references to
1235 user objects.
1235 user objects.
1236
1236
1237 If new_session is True, a new history session will be opened.
1237 If new_session is True, a new history session will be opened.
1238 """
1238 """
1239 # Clear histories
1239 # Clear histories
1240 self.history_manager.reset(new_session)
1240 self.history_manager.reset(new_session)
1241 # Reset counter used to index all histories
1241 # Reset counter used to index all histories
1242 if new_session:
1242 if new_session:
1243 self.execution_count = 1
1243 self.execution_count = 1
1244
1244
1245 # Flush cached output items
1245 # Flush cached output items
1246 if self.displayhook.do_full_cache:
1246 if self.displayhook.do_full_cache:
1247 self.displayhook.flush()
1247 self.displayhook.flush()
1248
1248
1249 # The main execution namespaces must be cleared very carefully,
1249 # The main execution namespaces must be cleared very carefully,
1250 # skipping the deletion of the builtin-related keys, because doing so
1250 # skipping the deletion of the builtin-related keys, because doing so
1251 # would cause errors in many object's __del__ methods.
1251 # would cause errors in many object's __del__ methods.
1252 if self.user_ns is not self.user_global_ns:
1252 if self.user_ns is not self.user_global_ns:
1253 self.user_ns.clear()
1253 self.user_ns.clear()
1254 ns = self.user_global_ns
1254 ns = self.user_global_ns
1255 drop_keys = set(ns.keys())
1255 drop_keys = set(ns.keys())
1256 drop_keys.discard('__builtin__')
1256 drop_keys.discard('__builtin__')
1257 drop_keys.discard('__builtins__')
1257 drop_keys.discard('__builtins__')
1258 drop_keys.discard('__name__')
1258 drop_keys.discard('__name__')
1259 for k in drop_keys:
1259 for k in drop_keys:
1260 del ns[k]
1260 del ns[k]
1261
1261
1262 self.user_ns_hidden.clear()
1262 self.user_ns_hidden.clear()
1263
1263
1264 # Restore the user namespaces to minimal usability
1264 # Restore the user namespaces to minimal usability
1265 self.init_user_ns()
1265 self.init_user_ns()
1266
1266
1267 # Restore the default and user aliases
1267 # Restore the default and user aliases
1268 self.alias_manager.clear_aliases()
1268 self.alias_manager.clear_aliases()
1269 self.alias_manager.init_aliases()
1269 self.alias_manager.init_aliases()
1270
1270
1271 # Flush the private list of module references kept for script
1271 # Flush the private list of module references kept for script
1272 # execution protection
1272 # execution protection
1273 self.clear_main_mod_cache()
1273 self.clear_main_mod_cache()
1274
1274
1275 def del_var(self, varname, by_name=False):
1275 def del_var(self, varname, by_name=False):
1276 """Delete a variable from the various namespaces, so that, as
1276 """Delete a variable from the various namespaces, so that, as
1277 far as possible, we're not keeping any hidden references to it.
1277 far as possible, we're not keeping any hidden references to it.
1278
1278
1279 Parameters
1279 Parameters
1280 ----------
1280 ----------
1281 varname : str
1281 varname : str
1282 The name of the variable to delete.
1282 The name of the variable to delete.
1283 by_name : bool
1283 by_name : bool
1284 If True, delete variables with the given name in each
1284 If True, delete variables with the given name in each
1285 namespace. If False (default), find the variable in the user
1285 namespace. If False (default), find the variable in the user
1286 namespace, and delete references to it.
1286 namespace, and delete references to it.
1287 """
1287 """
1288 if varname in ('__builtin__', '__builtins__'):
1288 if varname in ('__builtin__', '__builtins__'):
1289 raise ValueError("Refusing to delete %s" % varname)
1289 raise ValueError("Refusing to delete %s" % varname)
1290
1290
1291 ns_refs = self.all_ns_refs
1291 ns_refs = self.all_ns_refs
1292
1292
1293 if by_name: # Delete by name
1293 if by_name: # Delete by name
1294 for ns in ns_refs:
1294 for ns in ns_refs:
1295 try:
1295 try:
1296 del ns[varname]
1296 del ns[varname]
1297 except KeyError:
1297 except KeyError:
1298 pass
1298 pass
1299 else: # Delete by object
1299 else: # Delete by object
1300 try:
1300 try:
1301 obj = self.user_ns[varname]
1301 obj = self.user_ns[varname]
1302 except KeyError:
1302 except KeyError:
1303 raise NameError("name '%s' is not defined" % varname)
1303 raise NameError("name '%s' is not defined" % varname)
1304 # Also check in output history
1304 # Also check in output history
1305 ns_refs.append(self.history_manager.output_hist)
1305 ns_refs.append(self.history_manager.output_hist)
1306 for ns in ns_refs:
1306 for ns in ns_refs:
1307 to_delete = [n for n, o in iteritems(ns) if o is obj]
1307 to_delete = [n for n, o in iteritems(ns) if o is obj]
1308 for name in to_delete:
1308 for name in to_delete:
1309 del ns[name]
1309 del ns[name]
1310
1310
1311 # displayhook keeps extra references, but not in a dictionary
1311 # displayhook keeps extra references, but not in a dictionary
1312 for name in ('_', '__', '___'):
1312 for name in ('_', '__', '___'):
1313 if getattr(self.displayhook, name) is obj:
1313 if getattr(self.displayhook, name) is obj:
1314 setattr(self.displayhook, name, None)
1314 setattr(self.displayhook, name, None)
1315
1315
1316 def reset_selective(self, regex=None):
1316 def reset_selective(self, regex=None):
1317 """Clear selective variables from internal namespaces based on a
1317 """Clear selective variables from internal namespaces based on a
1318 specified regular expression.
1318 specified regular expression.
1319
1319
1320 Parameters
1320 Parameters
1321 ----------
1321 ----------
1322 regex : string or compiled pattern, optional
1322 regex : string or compiled pattern, optional
1323 A regular expression pattern that will be used in searching
1323 A regular expression pattern that will be used in searching
1324 variable names in the users namespaces.
1324 variable names in the users namespaces.
1325 """
1325 """
1326 if regex is not None:
1326 if regex is not None:
1327 try:
1327 try:
1328 m = re.compile(regex)
1328 m = re.compile(regex)
1329 except TypeError:
1329 except TypeError:
1330 raise TypeError('regex must be a string or compiled pattern')
1330 raise TypeError('regex must be a string or compiled pattern')
1331 # Search for keys in each namespace that match the given regex
1331 # Search for keys in each namespace that match the given regex
1332 # If a match is found, delete the key/value pair.
1332 # If a match is found, delete the key/value pair.
1333 for ns in self.all_ns_refs:
1333 for ns in self.all_ns_refs:
1334 for var in ns:
1334 for var in ns:
1335 if m.search(var):
1335 if m.search(var):
1336 del ns[var]
1336 del ns[var]
1337
1337
1338 def push(self, variables, interactive=True):
1338 def push(self, variables, interactive=True):
1339 """Inject a group of variables into the IPython user namespace.
1339 """Inject a group of variables into the IPython user namespace.
1340
1340
1341 Parameters
1341 Parameters
1342 ----------
1342 ----------
1343 variables : dict, str or list/tuple of str
1343 variables : dict, str or list/tuple of str
1344 The variables to inject into the user's namespace. If a dict, a
1344 The variables to inject into the user's namespace. If a dict, a
1345 simple update is done. If a str, the string is assumed to have
1345 simple update is done. If a str, the string is assumed to have
1346 variable names separated by spaces. A list/tuple of str can also
1346 variable names separated by spaces. A list/tuple of str can also
1347 be used to give the variable names. If just the variable names are
1347 be used to give the variable names. If just the variable names are
1348 give (list/tuple/str) then the variable values looked up in the
1348 give (list/tuple/str) then the variable values looked up in the
1349 callers frame.
1349 callers frame.
1350 interactive : bool
1350 interactive : bool
1351 If True (default), the variables will be listed with the ``who``
1351 If True (default), the variables will be listed with the ``who``
1352 magic.
1352 magic.
1353 """
1353 """
1354 vdict = None
1354 vdict = None
1355
1355
1356 # We need a dict of name/value pairs to do namespace updates.
1356 # We need a dict of name/value pairs to do namespace updates.
1357 if isinstance(variables, dict):
1357 if isinstance(variables, dict):
1358 vdict = variables
1358 vdict = variables
1359 elif isinstance(variables, string_types+(list, tuple)):
1359 elif isinstance(variables, string_types+(list, tuple)):
1360 if isinstance(variables, string_types):
1360 if isinstance(variables, string_types):
1361 vlist = variables.split()
1361 vlist = variables.split()
1362 else:
1362 else:
1363 vlist = variables
1363 vlist = variables
1364 vdict = {}
1364 vdict = {}
1365 cf = sys._getframe(1)
1365 cf = sys._getframe(1)
1366 for name in vlist:
1366 for name in vlist:
1367 try:
1367 try:
1368 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1368 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1369 except:
1369 except:
1370 print('Could not get variable %s from %s' %
1370 print('Could not get variable %s from %s' %
1371 (name,cf.f_code.co_name))
1371 (name,cf.f_code.co_name))
1372 else:
1372 else:
1373 raise ValueError('variables must be a dict/str/list/tuple')
1373 raise ValueError('variables must be a dict/str/list/tuple')
1374
1374
1375 # Propagate variables to user namespace
1375 # Propagate variables to user namespace
1376 self.user_ns.update(vdict)
1376 self.user_ns.update(vdict)
1377
1377
1378 # And configure interactive visibility
1378 # And configure interactive visibility
1379 user_ns_hidden = self.user_ns_hidden
1379 user_ns_hidden = self.user_ns_hidden
1380 if interactive:
1380 if interactive:
1381 for name in vdict:
1381 for name in vdict:
1382 user_ns_hidden.pop(name, None)
1382 user_ns_hidden.pop(name, None)
1383 else:
1383 else:
1384 user_ns_hidden.update(vdict)
1384 user_ns_hidden.update(vdict)
1385
1385
1386 def drop_by_id(self, variables):
1386 def drop_by_id(self, variables):
1387 """Remove a dict of variables from the user namespace, if they are the
1387 """Remove a dict of variables from the user namespace, if they are the
1388 same as the values in the dictionary.
1388 same as the values in the dictionary.
1389
1389
1390 This is intended for use by extensions: variables that they've added can
1390 This is intended for use by extensions: variables that they've added can
1391 be taken back out if they are unloaded, without removing any that the
1391 be taken back out if they are unloaded, without removing any that the
1392 user has overwritten.
1392 user has overwritten.
1393
1393
1394 Parameters
1394 Parameters
1395 ----------
1395 ----------
1396 variables : dict
1396 variables : dict
1397 A dictionary mapping object names (as strings) to the objects.
1397 A dictionary mapping object names (as strings) to the objects.
1398 """
1398 """
1399 for name, obj in iteritems(variables):
1399 for name, obj in iteritems(variables):
1400 if name in self.user_ns and self.user_ns[name] is obj:
1400 if name in self.user_ns and self.user_ns[name] is obj:
1401 del self.user_ns[name]
1401 del self.user_ns[name]
1402 self.user_ns_hidden.pop(name, None)
1402 self.user_ns_hidden.pop(name, None)
1403
1403
1404 #-------------------------------------------------------------------------
1404 #-------------------------------------------------------------------------
1405 # Things related to object introspection
1405 # Things related to object introspection
1406 #-------------------------------------------------------------------------
1406 #-------------------------------------------------------------------------
1407
1407
1408 def _ofind(self, oname, namespaces=None):
1408 def _ofind(self, oname, namespaces=None):
1409 """Find an object in the available namespaces.
1409 """Find an object in the available namespaces.
1410
1410
1411 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1411 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1412
1412
1413 Has special code to detect magic functions.
1413 Has special code to detect magic functions.
1414 """
1414 """
1415 oname = oname.strip()
1415 oname = oname.strip()
1416 #print '1- oname: <%r>' % oname # dbg
1416 #print '1- oname: <%r>' % oname # dbg
1417 if not oname.startswith(ESC_MAGIC) and \
1417 if not oname.startswith(ESC_MAGIC) and \
1418 not oname.startswith(ESC_MAGIC2) and \
1418 not oname.startswith(ESC_MAGIC2) and \
1419 not py3compat.isidentifier(oname, dotted=True):
1419 not py3compat.isidentifier(oname, dotted=True):
1420 return dict(found=False)
1420 return dict(found=False)
1421
1421
1422 alias_ns = None
1422 alias_ns = None
1423 if namespaces is None:
1423 if namespaces is None:
1424 # Namespaces to search in:
1424 # Namespaces to search in:
1425 # Put them in a list. The order is important so that we
1425 # Put them in a list. The order is important so that we
1426 # find things in the same order that Python finds them.
1426 # find things in the same order that Python finds them.
1427 namespaces = [ ('Interactive', self.user_ns),
1427 namespaces = [ ('Interactive', self.user_ns),
1428 ('Interactive (global)', self.user_global_ns),
1428 ('Interactive (global)', self.user_global_ns),
1429 ('Python builtin', builtin_mod.__dict__),
1429 ('Python builtin', builtin_mod.__dict__),
1430 ]
1430 ]
1431
1431
1432 # initialize results to 'null'
1432 # initialize results to 'null'
1433 found = False; obj = None; ospace = None; ds = None;
1433 found = False; obj = None; ospace = None; ds = None;
1434 ismagic = False; isalias = False; parent = None
1434 ismagic = False; isalias = False; parent = None
1435
1435
1436 # We need to special-case 'print', which as of python2.6 registers as a
1436 # We need to special-case 'print', which as of python2.6 registers as a
1437 # function but should only be treated as one if print_function was
1437 # function but should only be treated as one if print_function was
1438 # loaded with a future import. In this case, just bail.
1438 # loaded with a future import. In this case, just bail.
1439 if (oname == 'print' and not py3compat.PY3 and not \
1439 if (oname == 'print' and not py3compat.PY3 and not \
1440 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1440 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1441 return {'found':found, 'obj':obj, 'namespace':ospace,
1441 return {'found':found, 'obj':obj, 'namespace':ospace,
1442 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1442 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1443
1443
1444 # Look for the given name by splitting it in parts. If the head is
1444 # Look for the given name by splitting it in parts. If the head is
1445 # found, then we look for all the remaining parts as members, and only
1445 # found, then we look for all the remaining parts as members, and only
1446 # declare success if we can find them all.
1446 # declare success if we can find them all.
1447 oname_parts = oname.split('.')
1447 oname_parts = oname.split('.')
1448 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1448 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1449 for nsname,ns in namespaces:
1449 for nsname,ns in namespaces:
1450 try:
1450 try:
1451 obj = ns[oname_head]
1451 obj = ns[oname_head]
1452 except KeyError:
1452 except KeyError:
1453 continue
1453 continue
1454 else:
1454 else:
1455 #print 'oname_rest:', oname_rest # dbg
1455 #print 'oname_rest:', oname_rest # dbg
1456 for idx, part in enumerate(oname_rest):
1456 for idx, part in enumerate(oname_rest):
1457 try:
1457 try:
1458 parent = obj
1458 parent = obj
1459 # The last part is looked up in a special way to avoid
1459 # The last part is looked up in a special way to avoid
1460 # descriptor invocation as it may raise or have side
1460 # descriptor invocation as it may raise or have side
1461 # effects.
1461 # effects.
1462 if idx == len(oname_rest) - 1:
1462 if idx == len(oname_rest) - 1:
1463 obj = self._getattr_property(obj, part)
1463 obj = self._getattr_property(obj, part)
1464 else:
1464 else:
1465 obj = getattr(obj, part)
1465 obj = getattr(obj, part)
1466 except:
1466 except:
1467 # Blanket except b/c some badly implemented objects
1467 # Blanket except b/c some badly implemented objects
1468 # allow __getattr__ to raise exceptions other than
1468 # allow __getattr__ to raise exceptions other than
1469 # AttributeError, which then crashes IPython.
1469 # AttributeError, which then crashes IPython.
1470 break
1470 break
1471 else:
1471 else:
1472 # If we finish the for loop (no break), we got all members
1472 # If we finish the for loop (no break), we got all members
1473 found = True
1473 found = True
1474 ospace = nsname
1474 ospace = nsname
1475 break # namespace loop
1475 break # namespace loop
1476
1476
1477 # Try to see if it's magic
1477 # Try to see if it's magic
1478 if not found:
1478 if not found:
1479 obj = None
1479 obj = None
1480 if oname.startswith(ESC_MAGIC2):
1480 if oname.startswith(ESC_MAGIC2):
1481 oname = oname.lstrip(ESC_MAGIC2)
1481 oname = oname.lstrip(ESC_MAGIC2)
1482 obj = self.find_cell_magic(oname)
1482 obj = self.find_cell_magic(oname)
1483 elif oname.startswith(ESC_MAGIC):
1483 elif oname.startswith(ESC_MAGIC):
1484 oname = oname.lstrip(ESC_MAGIC)
1484 oname = oname.lstrip(ESC_MAGIC)
1485 obj = self.find_line_magic(oname)
1485 obj = self.find_line_magic(oname)
1486 else:
1486 else:
1487 # search without prefix, so run? will find %run?
1487 # search without prefix, so run? will find %run?
1488 obj = self.find_line_magic(oname)
1488 obj = self.find_line_magic(oname)
1489 if obj is None:
1489 if obj is None:
1490 obj = self.find_cell_magic(oname)
1490 obj = self.find_cell_magic(oname)
1491 if obj is not None:
1491 if obj is not None:
1492 found = True
1492 found = True
1493 ospace = 'IPython internal'
1493 ospace = 'IPython internal'
1494 ismagic = True
1494 ismagic = True
1495
1495
1496 # Last try: special-case some literals like '', [], {}, etc:
1496 # Last try: special-case some literals like '', [], {}, etc:
1497 if not found and oname_head in ["''",'""','[]','{}','()']:
1497 if not found and oname_head in ["''",'""','[]','{}','()']:
1498 obj = eval(oname_head)
1498 obj = eval(oname_head)
1499 found = True
1499 found = True
1500 ospace = 'Interactive'
1500 ospace = 'Interactive'
1501
1501
1502 return {'found':found, 'obj':obj, 'namespace':ospace,
1502 return {'found':found, 'obj':obj, 'namespace':ospace,
1503 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1503 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1504
1504
1505 @staticmethod
1505 @staticmethod
1506 def _getattr_property(obj, attrname):
1506 def _getattr_property(obj, attrname):
1507 """Property-aware getattr to use in object finding.
1507 """Property-aware getattr to use in object finding.
1508
1508
1509 If attrname represents a property, return it unevaluated (in case it has
1509 If attrname represents a property, return it unevaluated (in case it has
1510 side effects or raises an error.
1510 side effects or raises an error.
1511
1511
1512 """
1512 """
1513 if not isinstance(obj, type):
1513 if not isinstance(obj, type):
1514 try:
1514 try:
1515 # `getattr(type(obj), attrname)` is not guaranteed to return
1515 # `getattr(type(obj), attrname)` is not guaranteed to return
1516 # `obj`, but does so for property:
1516 # `obj`, but does so for property:
1517 #
1517 #
1518 # property.__get__(self, None, cls) -> self
1518 # property.__get__(self, None, cls) -> self
1519 #
1519 #
1520 # The universal alternative is to traverse the mro manually
1520 # The universal alternative is to traverse the mro manually
1521 # searching for attrname in class dicts.
1521 # searching for attrname in class dicts.
1522 attr = getattr(type(obj), attrname)
1522 attr = getattr(type(obj), attrname)
1523 except AttributeError:
1523 except AttributeError:
1524 pass
1524 pass
1525 else:
1525 else:
1526 # This relies on the fact that data descriptors (with both
1526 # This relies on the fact that data descriptors (with both
1527 # __get__ & __set__ magic methods) take precedence over
1527 # __get__ & __set__ magic methods) take precedence over
1528 # instance-level attributes:
1528 # instance-level attributes:
1529 #
1529 #
1530 # class A(object):
1530 # class A(object):
1531 # @property
1531 # @property
1532 # def foobar(self): return 123
1532 # def foobar(self): return 123
1533 # a = A()
1533 # a = A()
1534 # a.__dict__['foobar'] = 345
1534 # a.__dict__['foobar'] = 345
1535 # a.foobar # == 123
1535 # a.foobar # == 123
1536 #
1536 #
1537 # So, a property may be returned right away.
1537 # So, a property may be returned right away.
1538 if isinstance(attr, property):
1538 if isinstance(attr, property):
1539 return attr
1539 return attr
1540
1540
1541 # Nothing helped, fall back.
1541 # Nothing helped, fall back.
1542 return getattr(obj, attrname)
1542 return getattr(obj, attrname)
1543
1543
1544 def _object_find(self, oname, namespaces=None):
1544 def _object_find(self, oname, namespaces=None):
1545 """Find an object and return a struct with info about it."""
1545 """Find an object and return a struct with info about it."""
1546 return Struct(self._ofind(oname, namespaces))
1546 return Struct(self._ofind(oname, namespaces))
1547
1547
1548 def _inspect(self, meth, oname, namespaces=None, **kw):
1548 def _inspect(self, meth, oname, namespaces=None, **kw):
1549 """Generic interface to the inspector system.
1549 """Generic interface to the inspector system.
1550
1550
1551 This function is meant to be called by pdef, pdoc & friends."""
1551 This function is meant to be called by pdef, pdoc & friends."""
1552 info = self._object_find(oname, namespaces)
1552 info = self._object_find(oname, namespaces)
1553 if info.found:
1553 if info.found:
1554 pmethod = getattr(self.inspector, meth)
1554 pmethod = getattr(self.inspector, meth)
1555 formatter = format_screen if info.ismagic else None
1555 formatter = format_screen if info.ismagic else None
1556 if meth == 'pdoc':
1556 if meth == 'pdoc':
1557 pmethod(info.obj, oname, formatter)
1557 pmethod(info.obj, oname, formatter)
1558 elif meth == 'pinfo':
1558 elif meth == 'pinfo':
1559 pmethod(info.obj, oname, formatter, info, **kw)
1559 pmethod(info.obj, oname, formatter, info, **kw)
1560 else:
1560 else:
1561 pmethod(info.obj, oname)
1561 pmethod(info.obj, oname)
1562 else:
1562 else:
1563 print('Object `%s` not found.' % oname)
1563 print('Object `%s` not found.' % oname)
1564 return 'not found' # so callers can take other action
1564 return 'not found' # so callers can take other action
1565
1565
1566 def object_inspect(self, oname, detail_level=0):
1566 def object_inspect(self, oname, detail_level=0):
1567 """Get object info about oname"""
1567 """Get object info about oname"""
1568 with self.builtin_trap:
1568 with self.builtin_trap:
1569 info = self._object_find(oname)
1569 info = self._object_find(oname)
1570 if info.found:
1570 if info.found:
1571 return self.inspector.info(info.obj, oname, info=info,
1571 return self.inspector.info(info.obj, oname, info=info,
1572 detail_level=detail_level
1572 detail_level=detail_level
1573 )
1573 )
1574 else:
1574 else:
1575 return oinspect.object_info(name=oname, found=False)
1575 return oinspect.object_info(name=oname, found=False)
1576
1576
1577 def object_inspect_text(self, oname, detail_level=0):
1577 def object_inspect_text(self, oname, detail_level=0):
1578 """Get object info as formatted text"""
1578 """Get object info as formatted text"""
1579 with self.builtin_trap:
1579 with self.builtin_trap:
1580 info = self._object_find(oname)
1580 info = self._object_find(oname)
1581 if info.found:
1581 if info.found:
1582 return self.inspector._format_info(info.obj, oname, info=info,
1582 return self.inspector._format_info(info.obj, oname, info=info,
1583 detail_level=detail_level
1583 detail_level=detail_level
1584 )
1584 )
1585 else:
1585 else:
1586 raise KeyError(oname)
1586 raise KeyError(oname)
1587
1587
1588 #-------------------------------------------------------------------------
1588 #-------------------------------------------------------------------------
1589 # Things related to history management
1589 # Things related to history management
1590 #-------------------------------------------------------------------------
1590 #-------------------------------------------------------------------------
1591
1591
1592 def init_history(self):
1592 def init_history(self):
1593 """Sets up the command history, and starts regular autosaves."""
1593 """Sets up the command history, and starts regular autosaves."""
1594 self.history_manager = HistoryManager(shell=self, parent=self)
1594 self.history_manager = HistoryManager(shell=self, parent=self)
1595 self.configurables.append(self.history_manager)
1595 self.configurables.append(self.history_manager)
1596
1596
1597 #-------------------------------------------------------------------------
1597 #-------------------------------------------------------------------------
1598 # Things related to exception handling and tracebacks (not debugging)
1598 # Things related to exception handling and tracebacks (not debugging)
1599 #-------------------------------------------------------------------------
1599 #-------------------------------------------------------------------------
1600
1600
1601 def init_traceback_handlers(self, custom_exceptions):
1601 def init_traceback_handlers(self, custom_exceptions):
1602 # Syntax error handler.
1602 # Syntax error handler.
1603 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1603 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1604
1604
1605 # The interactive one is initialized with an offset, meaning we always
1605 # The interactive one is initialized with an offset, meaning we always
1606 # want to remove the topmost item in the traceback, which is our own
1606 # want to remove the topmost item in the traceback, which is our own
1607 # internal code. Valid modes: ['Plain','Context','Verbose']
1607 # internal code. Valid modes: ['Plain','Context','Verbose']
1608 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1608 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1609 color_scheme='NoColor',
1609 color_scheme='NoColor',
1610 tb_offset = 1,
1610 tb_offset = 1,
1611 check_cache=check_linecache_ipython)
1611 check_cache=check_linecache_ipython)
1612
1612
1613 # The instance will store a pointer to the system-wide exception hook,
1613 # The instance will store a pointer to the system-wide exception hook,
1614 # so that runtime code (such as magics) can access it. This is because
1614 # so that runtime code (such as magics) can access it. This is because
1615 # during the read-eval loop, it may get temporarily overwritten.
1615 # during the read-eval loop, it may get temporarily overwritten.
1616 self.sys_excepthook = sys.excepthook
1616 self.sys_excepthook = sys.excepthook
1617
1617
1618 # and add any custom exception handlers the user may have specified
1618 # and add any custom exception handlers the user may have specified
1619 self.set_custom_exc(*custom_exceptions)
1619 self.set_custom_exc(*custom_exceptions)
1620
1620
1621 # Set the exception mode
1621 # Set the exception mode
1622 self.InteractiveTB.set_mode(mode=self.xmode)
1622 self.InteractiveTB.set_mode(mode=self.xmode)
1623
1623
1624 def set_custom_exc(self, exc_tuple, handler):
1624 def set_custom_exc(self, exc_tuple, handler):
1625 """set_custom_exc(exc_tuple,handler)
1625 """set_custom_exc(exc_tuple,handler)
1626
1626
1627 Set a custom exception handler, which will be called if any of the
1627 Set a custom exception handler, which will be called if any of the
1628 exceptions in exc_tuple occur in the mainloop (specifically, in the
1628 exceptions in exc_tuple occur in the mainloop (specifically, in the
1629 run_code() method).
1629 run_code() method).
1630
1630
1631 Parameters
1631 Parameters
1632 ----------
1632 ----------
1633
1633
1634 exc_tuple : tuple of exception classes
1634 exc_tuple : tuple of exception classes
1635 A *tuple* of exception classes, for which to call the defined
1635 A *tuple* of exception classes, for which to call the defined
1636 handler. It is very important that you use a tuple, and NOT A
1636 handler. It is very important that you use a tuple, and NOT A
1637 LIST here, because of the way Python's except statement works. If
1637 LIST here, because of the way Python's except statement works. If
1638 you only want to trap a single exception, use a singleton tuple::
1638 you only want to trap a single exception, use a singleton tuple::
1639
1639
1640 exc_tuple == (MyCustomException,)
1640 exc_tuple == (MyCustomException,)
1641
1641
1642 handler : callable
1642 handler : callable
1643 handler must have the following signature::
1643 handler must have the following signature::
1644
1644
1645 def my_handler(self, etype, value, tb, tb_offset=None):
1645 def my_handler(self, etype, value, tb, tb_offset=None):
1646 ...
1646 ...
1647 return structured_traceback
1647 return structured_traceback
1648
1648
1649 Your handler must return a structured traceback (a list of strings),
1649 Your handler must return a structured traceback (a list of strings),
1650 or None.
1650 or None.
1651
1651
1652 This will be made into an instance method (via types.MethodType)
1652 This will be made into an instance method (via types.MethodType)
1653 of IPython itself, and it will be called if any of the exceptions
1653 of IPython itself, and it will be called if any of the exceptions
1654 listed in the exc_tuple are caught. If the handler is None, an
1654 listed in the exc_tuple are caught. If the handler is None, an
1655 internal basic one is used, which just prints basic info.
1655 internal basic one is used, which just prints basic info.
1656
1656
1657 To protect IPython from crashes, if your handler ever raises an
1657 To protect IPython from crashes, if your handler ever raises an
1658 exception or returns an invalid result, it will be immediately
1658 exception or returns an invalid result, it will be immediately
1659 disabled.
1659 disabled.
1660
1660
1661 WARNING: by putting in your own exception handler into IPython's main
1661 WARNING: by putting in your own exception handler into IPython's main
1662 execution loop, you run a very good chance of nasty crashes. This
1662 execution loop, you run a very good chance of nasty crashes. This
1663 facility should only be used if you really know what you are doing."""
1663 facility should only be used if you really know what you are doing."""
1664
1664
1665 assert type(exc_tuple)==type(()) , \
1665 assert type(exc_tuple)==type(()) , \
1666 "The custom exceptions must be given AS A TUPLE."
1666 "The custom exceptions must be given AS A TUPLE."
1667
1667
1668 def dummy_handler(self,etype,value,tb,tb_offset=None):
1668 def dummy_handler(self,etype,value,tb,tb_offset=None):
1669 print('*** Simple custom exception handler ***')
1669 print('*** Simple custom exception handler ***')
1670 print('Exception type :',etype)
1670 print('Exception type :',etype)
1671 print('Exception value:',value)
1671 print('Exception value:',value)
1672 print('Traceback :',tb)
1672 print('Traceback :',tb)
1673 #print 'Source code :','\n'.join(self.buffer)
1673 #print 'Source code :','\n'.join(self.buffer)
1674
1674
1675 def validate_stb(stb):
1675 def validate_stb(stb):
1676 """validate structured traceback return type
1676 """validate structured traceback return type
1677
1677
1678 return type of CustomTB *should* be a list of strings, but allow
1678 return type of CustomTB *should* be a list of strings, but allow
1679 single strings or None, which are harmless.
1679 single strings or None, which are harmless.
1680
1680
1681 This function will *always* return a list of strings,
1681 This function will *always* return a list of strings,
1682 and will raise a TypeError if stb is inappropriate.
1682 and will raise a TypeError if stb is inappropriate.
1683 """
1683 """
1684 msg = "CustomTB must return list of strings, not %r" % stb
1684 msg = "CustomTB must return list of strings, not %r" % stb
1685 if stb is None:
1685 if stb is None:
1686 return []
1686 return []
1687 elif isinstance(stb, string_types):
1687 elif isinstance(stb, string_types):
1688 return [stb]
1688 return [stb]
1689 elif not isinstance(stb, list):
1689 elif not isinstance(stb, list):
1690 raise TypeError(msg)
1690 raise TypeError(msg)
1691 # it's a list
1691 # it's a list
1692 for line in stb:
1692 for line in stb:
1693 # check every element
1693 # check every element
1694 if not isinstance(line, string_types):
1694 if not isinstance(line, string_types):
1695 raise TypeError(msg)
1695 raise TypeError(msg)
1696 return stb
1696 return stb
1697
1697
1698 if handler is None:
1698 if handler is None:
1699 wrapped = dummy_handler
1699 wrapped = dummy_handler
1700 else:
1700 else:
1701 def wrapped(self,etype,value,tb,tb_offset=None):
1701 def wrapped(self,etype,value,tb,tb_offset=None):
1702 """wrap CustomTB handler, to protect IPython from user code
1702 """wrap CustomTB handler, to protect IPython from user code
1703
1703
1704 This makes it harder (but not impossible) for custom exception
1704 This makes it harder (but not impossible) for custom exception
1705 handlers to crash IPython.
1705 handlers to crash IPython.
1706 """
1706 """
1707 try:
1707 try:
1708 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1708 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1709 return validate_stb(stb)
1709 return validate_stb(stb)
1710 except:
1710 except:
1711 # clear custom handler immediately
1711 # clear custom handler immediately
1712 self.set_custom_exc((), None)
1712 self.set_custom_exc((), None)
1713 print("Custom TB Handler failed, unregistering", file=io.stderr)
1713 print("Custom TB Handler failed, unregistering", file=io.stderr)
1714 # show the exception in handler first
1714 # show the exception in handler first
1715 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1715 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1716 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1716 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1717 print("The original exception:", file=io.stdout)
1717 print("The original exception:", file=io.stdout)
1718 stb = self.InteractiveTB.structured_traceback(
1718 stb = self.InteractiveTB.structured_traceback(
1719 (etype,value,tb), tb_offset=tb_offset
1719 (etype,value,tb), tb_offset=tb_offset
1720 )
1720 )
1721 return stb
1721 return stb
1722
1722
1723 self.CustomTB = types.MethodType(wrapped,self)
1723 self.CustomTB = types.MethodType(wrapped,self)
1724 self.custom_exceptions = exc_tuple
1724 self.custom_exceptions = exc_tuple
1725
1725
1726 def excepthook(self, etype, value, tb):
1726 def excepthook(self, etype, value, tb):
1727 """One more defense for GUI apps that call sys.excepthook.
1727 """One more defense for GUI apps that call sys.excepthook.
1728
1728
1729 GUI frameworks like wxPython trap exceptions and call
1729 GUI frameworks like wxPython trap exceptions and call
1730 sys.excepthook themselves. I guess this is a feature that
1730 sys.excepthook themselves. I guess this is a feature that
1731 enables them to keep running after exceptions that would
1731 enables them to keep running after exceptions that would
1732 otherwise kill their mainloop. This is a bother for IPython
1732 otherwise kill their mainloop. This is a bother for IPython
1733 which excepts to catch all of the program exceptions with a try:
1733 which excepts to catch all of the program exceptions with a try:
1734 except: statement.
1734 except: statement.
1735
1735
1736 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1736 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1737 any app directly invokes sys.excepthook, it will look to the user like
1737 any app directly invokes sys.excepthook, it will look to the user like
1738 IPython crashed. In order to work around this, we can disable the
1738 IPython crashed. In order to work around this, we can disable the
1739 CrashHandler and replace it with this excepthook instead, which prints a
1739 CrashHandler and replace it with this excepthook instead, which prints a
1740 regular traceback using our InteractiveTB. In this fashion, apps which
1740 regular traceback using our InteractiveTB. In this fashion, apps which
1741 call sys.excepthook will generate a regular-looking exception from
1741 call sys.excepthook will generate a regular-looking exception from
1742 IPython, and the CrashHandler will only be triggered by real IPython
1742 IPython, and the CrashHandler will only be triggered by real IPython
1743 crashes.
1743 crashes.
1744
1744
1745 This hook should be used sparingly, only in places which are not likely
1745 This hook should be used sparingly, only in places which are not likely
1746 to be true IPython errors.
1746 to be true IPython errors.
1747 """
1747 """
1748 self.showtraceback((etype, value, tb), tb_offset=0)
1748 self.showtraceback((etype, value, tb), tb_offset=0)
1749
1749
1750 def _get_exc_info(self, exc_tuple=None):
1750 def _get_exc_info(self, exc_tuple=None):
1751 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1751 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1752
1752
1753 Ensures sys.last_type,value,traceback hold the exc_info we found,
1753 Ensures sys.last_type,value,traceback hold the exc_info we found,
1754 from whichever source.
1754 from whichever source.
1755
1755
1756 raises ValueError if none of these contain any information
1756 raises ValueError if none of these contain any information
1757 """
1757 """
1758 if exc_tuple is None:
1758 if exc_tuple is None:
1759 etype, value, tb = sys.exc_info()
1759 etype, value, tb = sys.exc_info()
1760 else:
1760 else:
1761 etype, value, tb = exc_tuple
1761 etype, value, tb = exc_tuple
1762
1762
1763 if etype is None:
1763 if etype is None:
1764 if hasattr(sys, 'last_type'):
1764 if hasattr(sys, 'last_type'):
1765 etype, value, tb = sys.last_type, sys.last_value, \
1765 etype, value, tb = sys.last_type, sys.last_value, \
1766 sys.last_traceback
1766 sys.last_traceback
1767
1767
1768 if etype is None:
1768 if etype is None:
1769 raise ValueError("No exception to find")
1769 raise ValueError("No exception to find")
1770
1770
1771 # Now store the exception info in sys.last_type etc.
1771 # Now store the exception info in sys.last_type etc.
1772 # WARNING: these variables are somewhat deprecated and not
1772 # WARNING: these variables are somewhat deprecated and not
1773 # necessarily safe to use in a threaded environment, but tools
1773 # necessarily safe to use in a threaded environment, but tools
1774 # like pdb depend on their existence, so let's set them. If we
1774 # like pdb depend on their existence, so let's set them. If we
1775 # find problems in the field, we'll need to revisit their use.
1775 # find problems in the field, we'll need to revisit their use.
1776 sys.last_type = etype
1776 sys.last_type = etype
1777 sys.last_value = value
1777 sys.last_value = value
1778 sys.last_traceback = tb
1778 sys.last_traceback = tb
1779
1779
1780 return etype, value, tb
1780 return etype, value, tb
1781
1781
1782 def show_usage_error(self, exc):
1782 def show_usage_error(self, exc):
1783 """Show a short message for UsageErrors
1783 """Show a short message for UsageErrors
1784
1784
1785 These are special exceptions that shouldn't show a traceback.
1785 These are special exceptions that shouldn't show a traceback.
1786 """
1786 """
1787 self.write_err("UsageError: %s" % exc)
1787 self.write_err("UsageError: %s" % exc)
1788
1788
1789 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1789 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1790 exception_only=False):
1790 exception_only=False):
1791 """Display the exception that just occurred.
1791 """Display the exception that just occurred.
1792
1792
1793 If nothing is known about the exception, this is the method which
1793 If nothing is known about the exception, this is the method which
1794 should be used throughout the code for presenting user tracebacks,
1794 should be used throughout the code for presenting user tracebacks,
1795 rather than directly invoking the InteractiveTB object.
1795 rather than directly invoking the InteractiveTB object.
1796
1796
1797 A specific showsyntaxerror() also exists, but this method can take
1797 A specific showsyntaxerror() also exists, but this method can take
1798 care of calling it if needed, so unless you are explicitly catching a
1798 care of calling it if needed, so unless you are explicitly catching a
1799 SyntaxError exception, don't try to analyze the stack manually and
1799 SyntaxError exception, don't try to analyze the stack manually and
1800 simply call this method."""
1800 simply call this method."""
1801
1801
1802 try:
1802 try:
1803 try:
1803 try:
1804 etype, value, tb = self._get_exc_info(exc_tuple)
1804 etype, value, tb = self._get_exc_info(exc_tuple)
1805 except ValueError:
1805 except ValueError:
1806 self.write_err('No traceback available to show.\n')
1806 self.write_err('No traceback available to show.\n')
1807 return
1807 return
1808
1808
1809 if issubclass(etype, SyntaxError):
1809 if issubclass(etype, SyntaxError):
1810 # Though this won't be called by syntax errors in the input
1810 # Though this won't be called by syntax errors in the input
1811 # line, there may be SyntaxError cases with imported code.
1811 # line, there may be SyntaxError cases with imported code.
1812 self.showsyntaxerror(filename)
1812 self.showsyntaxerror(filename)
1813 elif etype is UsageError:
1813 elif etype is UsageError:
1814 self.show_usage_error(value)
1814 self.show_usage_error(value)
1815 else:
1815 else:
1816 if exception_only:
1816 if exception_only:
1817 stb = ['An exception has occurred, use %tb to see '
1817 stb = ['An exception has occurred, use %tb to see '
1818 'the full traceback.\n']
1818 'the full traceback.\n']
1819 stb.extend(self.InteractiveTB.get_exception_only(etype,
1819 stb.extend(self.InteractiveTB.get_exception_only(etype,
1820 value))
1820 value))
1821 else:
1821 else:
1822 try:
1822 try:
1823 # Exception classes can customise their traceback - we
1823 # Exception classes can customise their traceback - we
1824 # use this in IPython.parallel for exceptions occurring
1824 # use this in IPython.parallel for exceptions occurring
1825 # in the engines. This should return a list of strings.
1825 # in the engines. This should return a list of strings.
1826 stb = value._render_traceback_()
1826 stb = value._render_traceback_()
1827 except Exception:
1827 except Exception:
1828 stb = self.InteractiveTB.structured_traceback(etype,
1828 stb = self.InteractiveTB.structured_traceback(etype,
1829 value, tb, tb_offset=tb_offset)
1829 value, tb, tb_offset=tb_offset)
1830
1830
1831 self._showtraceback(etype, value, stb)
1831 self._showtraceback(etype, value, stb)
1832 if self.call_pdb:
1832 if self.call_pdb:
1833 # drop into debugger
1833 # drop into debugger
1834 self.debugger(force=True)
1834 self.debugger(force=True)
1835 return
1835 return
1836
1836
1837 # Actually show the traceback
1837 # Actually show the traceback
1838 self._showtraceback(etype, value, stb)
1838 self._showtraceback(etype, value, stb)
1839
1839
1840 except KeyboardInterrupt:
1840 except KeyboardInterrupt:
1841 self.write_err("\nKeyboardInterrupt\n")
1841 self.write_err("\nKeyboardInterrupt\n")
1842
1842
1843 def _showtraceback(self, etype, evalue, stb):
1843 def _showtraceback(self, etype, evalue, stb):
1844 """Actually show a traceback.
1844 """Actually show a traceback.
1845
1845
1846 Subclasses may override this method to put the traceback on a different
1846 Subclasses may override this method to put the traceback on a different
1847 place, like a side channel.
1847 place, like a side channel.
1848 """
1848 """
1849 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1849 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1850
1850
1851 def showsyntaxerror(self, filename=None):
1851 def showsyntaxerror(self, filename=None):
1852 """Display the syntax error that just occurred.
1852 """Display the syntax error that just occurred.
1853
1853
1854 This doesn't display a stack trace because there isn't one.
1854 This doesn't display a stack trace because there isn't one.
1855
1855
1856 If a filename is given, it is stuffed in the exception instead
1856 If a filename is given, it is stuffed in the exception instead
1857 of what was there before (because Python's parser always uses
1857 of what was there before (because Python's parser always uses
1858 "<string>" when reading from a string).
1858 "<string>" when reading from a string).
1859 """
1859 """
1860 etype, value, last_traceback = self._get_exc_info()
1860 etype, value, last_traceback = self._get_exc_info()
1861
1861
1862 if filename and issubclass(etype, SyntaxError):
1862 if filename and issubclass(etype, SyntaxError):
1863 try:
1863 try:
1864 value.filename = filename
1864 value.filename = filename
1865 except:
1865 except:
1866 # Not the format we expect; leave it alone
1866 # Not the format we expect; leave it alone
1867 pass
1867 pass
1868
1868
1869 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1869 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1870 self._showtraceback(etype, value, stb)
1870 self._showtraceback(etype, value, stb)
1871
1871
1872 # This is overridden in TerminalInteractiveShell to show a message about
1872 # This is overridden in TerminalInteractiveShell to show a message about
1873 # the %paste magic.
1873 # the %paste magic.
1874 def showindentationerror(self):
1874 def showindentationerror(self):
1875 """Called by run_cell when there's an IndentationError in code entered
1875 """Called by run_cell when there's an IndentationError in code entered
1876 at the prompt.
1876 at the prompt.
1877
1877
1878 This is overridden in TerminalInteractiveShell to show a message about
1878 This is overridden in TerminalInteractiveShell to show a message about
1879 the %paste magic."""
1879 the %paste magic."""
1880 self.showsyntaxerror()
1880 self.showsyntaxerror()
1881
1881
1882 #-------------------------------------------------------------------------
1882 #-------------------------------------------------------------------------
1883 # Things related to readline
1883 # Things related to readline
1884 #-------------------------------------------------------------------------
1884 #-------------------------------------------------------------------------
1885
1885
1886 def init_readline(self):
1886 def init_readline(self):
1887 """Command history completion/saving/reloading."""
1887 """Command history completion/saving/reloading."""
1888
1888
1889 if self.readline_use:
1889 if self.readline_use:
1890 import IPython.utils.rlineimpl as readline
1890 import IPython.utils.rlineimpl as readline
1891
1891
1892 self.rl_next_input = None
1892 self.rl_next_input = None
1893 self.rl_do_indent = False
1893 self.rl_do_indent = False
1894
1894
1895 if not self.readline_use or not readline.have_readline:
1895 if not self.readline_use or not readline.have_readline:
1896 self.has_readline = False
1896 self.has_readline = False
1897 self.readline = None
1897 self.readline = None
1898 # Set a number of methods that depend on readline to be no-op
1898 # Set a number of methods that depend on readline to be no-op
1899 self.readline_no_record = no_op_context
1899 self.readline_no_record = no_op_context
1900 self.set_readline_completer = no_op
1900 self.set_readline_completer = no_op
1901 self.set_custom_completer = no_op
1901 self.set_custom_completer = no_op
1902 if self.readline_use:
1902 if self.readline_use:
1903 warn('Readline services not available or not loaded.')
1903 warn('Readline services not available or not loaded.')
1904 else:
1904 else:
1905 self.has_readline = True
1905 self.has_readline = True
1906 self.readline = readline
1906 self.readline = readline
1907 sys.modules['readline'] = readline
1907 sys.modules['readline'] = readline
1908
1908
1909 # Platform-specific configuration
1909 # Platform-specific configuration
1910 if os.name == 'nt':
1910 if os.name == 'nt':
1911 # FIXME - check with Frederick to see if we can harmonize
1911 # FIXME - check with Frederick to see if we can harmonize
1912 # naming conventions with pyreadline to avoid this
1912 # naming conventions with pyreadline to avoid this
1913 # platform-dependent check
1913 # platform-dependent check
1914 self.readline_startup_hook = readline.set_pre_input_hook
1914 self.readline_startup_hook = readline.set_pre_input_hook
1915 else:
1915 else:
1916 self.readline_startup_hook = readline.set_startup_hook
1916 self.readline_startup_hook = readline.set_startup_hook
1917
1917
1918 # Readline config order:
1918 # Readline config order:
1919 # - IPython config (default value)
1919 # - IPython config (default value)
1920 # - custom inputrc
1920 # - custom inputrc
1921 # - IPython config (user customized)
1921 # - IPython config (user customized)
1922
1922
1923 # load IPython config before inputrc if default
1923 # load IPython config before inputrc if default
1924 # skip if libedit because parse_and_bind syntax is different
1924 # skip if libedit because parse_and_bind syntax is different
1925 if not self._custom_readline_config and not readline.uses_libedit:
1925 if not self._custom_readline_config and not readline.uses_libedit:
1926 for rlcommand in self.readline_parse_and_bind:
1926 for rlcommand in self.readline_parse_and_bind:
1927 readline.parse_and_bind(rlcommand)
1927 readline.parse_and_bind(rlcommand)
1928
1928
1929 # Load user's initrc file (readline config)
1929 # Load user's initrc file (readline config)
1930 # Or if libedit is used, load editrc.
1930 # Or if libedit is used, load editrc.
1931 inputrc_name = os.environ.get('INPUTRC')
1931 inputrc_name = os.environ.get('INPUTRC')
1932 if inputrc_name is None:
1932 if inputrc_name is None:
1933 inputrc_name = '.inputrc'
1933 inputrc_name = '.inputrc'
1934 if readline.uses_libedit:
1934 if readline.uses_libedit:
1935 inputrc_name = '.editrc'
1935 inputrc_name = '.editrc'
1936 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1936 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1937 if os.path.isfile(inputrc_name):
1937 if os.path.isfile(inputrc_name):
1938 try:
1938 try:
1939 readline.read_init_file(inputrc_name)
1939 readline.read_init_file(inputrc_name)
1940 except:
1940 except:
1941 warn('Problems reading readline initialization file <%s>'
1941 warn('Problems reading readline initialization file <%s>'
1942 % inputrc_name)
1942 % inputrc_name)
1943
1943
1944 # load IPython config after inputrc if user has customized
1944 # load IPython config after inputrc if user has customized
1945 if self._custom_readline_config:
1945 if self._custom_readline_config:
1946 for rlcommand in self.readline_parse_and_bind:
1946 for rlcommand in self.readline_parse_and_bind:
1947 readline.parse_and_bind(rlcommand)
1947 readline.parse_and_bind(rlcommand)
1948
1948
1949 # Remove some chars from the delimiters list. If we encounter
1949 # Remove some chars from the delimiters list. If we encounter
1950 # unicode chars, discard them.
1950 # unicode chars, discard them.
1951 delims = readline.get_completer_delims()
1951 delims = readline.get_completer_delims()
1952 if not py3compat.PY3:
1952 if not py3compat.PY3:
1953 delims = delims.encode("ascii", "ignore")
1953 delims = delims.encode("ascii", "ignore")
1954 for d in self.readline_remove_delims:
1954 for d in self.readline_remove_delims:
1955 delims = delims.replace(d, "")
1955 delims = delims.replace(d, "")
1956 delims = delims.replace(ESC_MAGIC, '')
1956 delims = delims.replace(ESC_MAGIC, '')
1957 readline.set_completer_delims(delims)
1957 readline.set_completer_delims(delims)
1958 # Store these so we can restore them if something like rpy2 modifies
1958 # Store these so we can restore them if something like rpy2 modifies
1959 # them.
1959 # them.
1960 self.readline_delims = delims
1960 self.readline_delims = delims
1961 # otherwise we end up with a monster history after a while:
1961 # otherwise we end up with a monster history after a while:
1962 readline.set_history_length(self.history_length)
1962 readline.set_history_length(self.history_length)
1963
1963
1964 self.refill_readline_hist()
1964 self.refill_readline_hist()
1965 self.readline_no_record = ReadlineNoRecord(self)
1965 self.readline_no_record = ReadlineNoRecord(self)
1966
1966
1967 # Configure auto-indent for all platforms
1967 # Configure auto-indent for all platforms
1968 self.set_autoindent(self.autoindent)
1968 self.set_autoindent(self.autoindent)
1969
1969
1970 def refill_readline_hist(self):
1970 def refill_readline_hist(self):
1971 # Load the last 1000 lines from history
1971 # Load the last 1000 lines from history
1972 self.readline.clear_history()
1972 self.readline.clear_history()
1973 stdin_encoding = sys.stdin.encoding or "utf-8"
1973 stdin_encoding = sys.stdin.encoding or "utf-8"
1974 last_cell = u""
1974 last_cell = u""
1975 for _, _, cell in self.history_manager.get_tail(1000,
1975 for _, _, cell in self.history_manager.get_tail(1000,
1976 include_latest=True):
1976 include_latest=True):
1977 # Ignore blank lines and consecutive duplicates
1977 # Ignore blank lines and consecutive duplicates
1978 cell = cell.rstrip()
1978 cell = cell.rstrip()
1979 if cell and (cell != last_cell):
1979 if cell and (cell != last_cell):
1980 try:
1980 try:
1981 if self.multiline_history:
1981 if self.multiline_history:
1982 self.readline.add_history(py3compat.unicode_to_str(cell,
1982 self.readline.add_history(py3compat.unicode_to_str(cell,
1983 stdin_encoding))
1983 stdin_encoding))
1984 else:
1984 else:
1985 for line in cell.splitlines():
1985 for line in cell.splitlines():
1986 self.readline.add_history(py3compat.unicode_to_str(line,
1986 self.readline.add_history(py3compat.unicode_to_str(line,
1987 stdin_encoding))
1987 stdin_encoding))
1988 last_cell = cell
1988 last_cell = cell
1989
1989
1990 except TypeError:
1990 except TypeError:
1991 # The history DB can get corrupted so it returns strings
1991 # The history DB can get corrupted so it returns strings
1992 # containing null bytes, which readline objects to.
1992 # containing null bytes, which readline objects to.
1993 continue
1993 continue
1994
1994
1995 @skip_doctest
1995 @skip_doctest
1996 def set_next_input(self, s):
1996 def set_next_input(self, s):
1997 """ Sets the 'default' input string for the next command line.
1997 """ Sets the 'default' input string for the next command line.
1998
1998
1999 Requires readline.
1999 Requires readline.
2000
2000
2001 Example::
2001 Example::
2002
2002
2003 In [1]: _ip.set_next_input("Hello Word")
2003 In [1]: _ip.set_next_input("Hello Word")
2004 In [2]: Hello Word_ # cursor is here
2004 In [2]: Hello Word_ # cursor is here
2005 """
2005 """
2006 self.rl_next_input = py3compat.cast_bytes_py2(s)
2006 self.rl_next_input = py3compat.cast_bytes_py2(s)
2007
2007
2008 # Maybe move this to the terminal subclass?
2008 # Maybe move this to the terminal subclass?
2009 def pre_readline(self):
2009 def pre_readline(self):
2010 """readline hook to be used at the start of each line.
2010 """readline hook to be used at the start of each line.
2011
2011
2012 Currently it handles auto-indent only."""
2012 Currently it handles auto-indent only."""
2013
2013
2014 if self.rl_do_indent:
2014 if self.rl_do_indent:
2015 self.readline.insert_text(self._indent_current_str())
2015 self.readline.insert_text(self._indent_current_str())
2016 if self.rl_next_input is not None:
2016 if self.rl_next_input is not None:
2017 self.readline.insert_text(self.rl_next_input)
2017 self.readline.insert_text(self.rl_next_input)
2018 self.rl_next_input = None
2018 self.rl_next_input = None
2019
2019
2020 def _indent_current_str(self):
2020 def _indent_current_str(self):
2021 """return the current level of indentation as a string"""
2021 """return the current level of indentation as a string"""
2022 return self.input_splitter.indent_spaces * ' '
2022 return self.input_splitter.indent_spaces * ' '
2023
2023
2024 #-------------------------------------------------------------------------
2024 #-------------------------------------------------------------------------
2025 # Things related to text completion
2025 # Things related to text completion
2026 #-------------------------------------------------------------------------
2026 #-------------------------------------------------------------------------
2027
2027
2028 def init_completer(self):
2028 def init_completer(self):
2029 """Initialize the completion machinery.
2029 """Initialize the completion machinery.
2030
2030
2031 This creates completion machinery that can be used by client code,
2031 This creates completion machinery that can be used by client code,
2032 either interactively in-process (typically triggered by the readline
2032 either interactively in-process (typically triggered by the readline
2033 library), programatically (such as in test suites) or out-of-prcess
2033 library), programatically (such as in test suites) or out-of-prcess
2034 (typically over the network by remote frontends).
2034 (typically over the network by remote frontends).
2035 """
2035 """
2036 from IPython.core.completer import IPCompleter
2036 from IPython.core.completer import IPCompleter
2037 from IPython.core.completerlib import (module_completer,
2037 from IPython.core.completerlib import (module_completer,
2038 magic_run_completer, cd_completer, reset_completer)
2038 magic_run_completer, cd_completer, reset_completer)
2039
2039
2040 self.Completer = IPCompleter(shell=self,
2040 self.Completer = IPCompleter(shell=self,
2041 namespace=self.user_ns,
2041 namespace=self.user_ns,
2042 global_namespace=self.user_global_ns,
2042 global_namespace=self.user_global_ns,
2043 use_readline=self.has_readline,
2043 use_readline=self.has_readline,
2044 parent=self,
2044 parent=self,
2045 )
2045 )
2046 self.configurables.append(self.Completer)
2046 self.configurables.append(self.Completer)
2047
2047
2048 # Add custom completers to the basic ones built into IPCompleter
2048 # Add custom completers to the basic ones built into IPCompleter
2049 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2049 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2050 self.strdispatchers['complete_command'] = sdisp
2050 self.strdispatchers['complete_command'] = sdisp
2051 self.Completer.custom_completers = sdisp
2051 self.Completer.custom_completers = sdisp
2052
2052
2053 self.set_hook('complete_command', module_completer, str_key = 'import')
2053 self.set_hook('complete_command', module_completer, str_key = 'import')
2054 self.set_hook('complete_command', module_completer, str_key = 'from')
2054 self.set_hook('complete_command', module_completer, str_key = 'from')
2055 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2055 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2056 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2056 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2057 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2057 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2058
2058
2059 # Only configure readline if we truly are using readline. IPython can
2059 # Only configure readline if we truly are using readline. IPython can
2060 # do tab-completion over the network, in GUIs, etc, where readline
2060 # do tab-completion over the network, in GUIs, etc, where readline
2061 # itself may be absent
2061 # itself may be absent
2062 if self.has_readline:
2062 if self.has_readline:
2063 self.set_readline_completer()
2063 self.set_readline_completer()
2064
2064
2065 def complete(self, text, line=None, cursor_pos=None):
2065 def complete(self, text, line=None, cursor_pos=None):
2066 """Return the completed text and a list of completions.
2066 """Return the completed text and a list of completions.
2067
2067
2068 Parameters
2068 Parameters
2069 ----------
2069 ----------
2070
2070
2071 text : string
2071 text : string
2072 A string of text to be completed on. It can be given as empty and
2072 A string of text to be completed on. It can be given as empty and
2073 instead a line/position pair are given. In this case, the
2073 instead a line/position pair are given. In this case, the
2074 completer itself will split the line like readline does.
2074 completer itself will split the line like readline does.
2075
2075
2076 line : string, optional
2076 line : string, optional
2077 The complete line that text is part of.
2077 The complete line that text is part of.
2078
2078
2079 cursor_pos : int, optional
2079 cursor_pos : int, optional
2080 The position of the cursor on the input line.
2080 The position of the cursor on the input line.
2081
2081
2082 Returns
2082 Returns
2083 -------
2083 -------
2084 text : string
2084 text : string
2085 The actual text that was completed.
2085 The actual text that was completed.
2086
2086
2087 matches : list
2087 matches : list
2088 A sorted list with all possible completions.
2088 A sorted list with all possible completions.
2089
2089
2090 The optional arguments allow the completion to take more context into
2090 The optional arguments allow the completion to take more context into
2091 account, and are part of the low-level completion API.
2091 account, and are part of the low-level completion API.
2092
2092
2093 This is a wrapper around the completion mechanism, similar to what
2093 This is a wrapper around the completion mechanism, similar to what
2094 readline does at the command line when the TAB key is hit. By
2094 readline does at the command line when the TAB key is hit. By
2095 exposing it as a method, it can be used by other non-readline
2095 exposing it as a method, it can be used by other non-readline
2096 environments (such as GUIs) for text completion.
2096 environments (such as GUIs) for text completion.
2097
2097
2098 Simple usage example:
2098 Simple usage example:
2099
2099
2100 In [1]: x = 'hello'
2100 In [1]: x = 'hello'
2101
2101
2102 In [2]: _ip.complete('x.l')
2102 In [2]: _ip.complete('x.l')
2103 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2103 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2104 """
2104 """
2105
2105
2106 # Inject names into __builtin__ so we can complete on the added names.
2106 # Inject names into __builtin__ so we can complete on the added names.
2107 with self.builtin_trap:
2107 with self.builtin_trap:
2108 return self.Completer.complete(text, line, cursor_pos)
2108 return self.Completer.complete(text, line, cursor_pos)
2109
2109
2110 def set_custom_completer(self, completer, pos=0):
2110 def set_custom_completer(self, completer, pos=0):
2111 """Adds a new custom completer function.
2111 """Adds a new custom completer function.
2112
2112
2113 The position argument (defaults to 0) is the index in the completers
2113 The position argument (defaults to 0) is the index in the completers
2114 list where you want the completer to be inserted."""
2114 list where you want the completer to be inserted."""
2115
2115
2116 newcomp = types.MethodType(completer,self.Completer)
2116 newcomp = types.MethodType(completer,self.Completer)
2117 self.Completer.matchers.insert(pos,newcomp)
2117 self.Completer.matchers.insert(pos,newcomp)
2118
2118
2119 def set_readline_completer(self):
2119 def set_readline_completer(self):
2120 """Reset readline's completer to be our own."""
2120 """Reset readline's completer to be our own."""
2121 self.readline.set_completer(self.Completer.rlcomplete)
2121 self.readline.set_completer(self.Completer.rlcomplete)
2122
2122
2123 def set_completer_frame(self, frame=None):
2123 def set_completer_frame(self, frame=None):
2124 """Set the frame of the completer."""
2124 """Set the frame of the completer."""
2125 if frame:
2125 if frame:
2126 self.Completer.namespace = frame.f_locals
2126 self.Completer.namespace = frame.f_locals
2127 self.Completer.global_namespace = frame.f_globals
2127 self.Completer.global_namespace = frame.f_globals
2128 else:
2128 else:
2129 self.Completer.namespace = self.user_ns
2129 self.Completer.namespace = self.user_ns
2130 self.Completer.global_namespace = self.user_global_ns
2130 self.Completer.global_namespace = self.user_global_ns
2131
2131
2132 #-------------------------------------------------------------------------
2132 #-------------------------------------------------------------------------
2133 # Things related to magics
2133 # Things related to magics
2134 #-------------------------------------------------------------------------
2134 #-------------------------------------------------------------------------
2135
2135
2136 def init_magics(self):
2136 def init_magics(self):
2137 from IPython.core import magics as m
2137 from IPython.core import magics as m
2138 self.magics_manager = magic.MagicsManager(shell=self,
2138 self.magics_manager = magic.MagicsManager(shell=self,
2139 parent=self,
2139 parent=self,
2140 user_magics=m.UserMagics(self))
2140 user_magics=m.UserMagics(self))
2141 self.configurables.append(self.magics_manager)
2141 self.configurables.append(self.magics_manager)
2142
2142
2143 # Expose as public API from the magics manager
2143 # Expose as public API from the magics manager
2144 self.register_magics = self.magics_manager.register
2144 self.register_magics = self.magics_manager.register
2145 self.define_magic = self.magics_manager.define_magic
2145 self.define_magic = self.magics_manager.define_magic
2146
2146
2147 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2147 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2148 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2148 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2149 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2149 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2150 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2150 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2151 )
2151 )
2152
2152
2153 # Register Magic Aliases
2153 # Register Magic Aliases
2154 mman = self.magics_manager
2154 mman = self.magics_manager
2155 # FIXME: magic aliases should be defined by the Magics classes
2155 # FIXME: magic aliases should be defined by the Magics classes
2156 # or in MagicsManager, not here
2156 # or in MagicsManager, not here
2157 mman.register_alias('ed', 'edit')
2157 mman.register_alias('ed', 'edit')
2158 mman.register_alias('hist', 'history')
2158 mman.register_alias('hist', 'history')
2159 mman.register_alias('rep', 'recall')
2159 mman.register_alias('rep', 'recall')
2160 mman.register_alias('SVG', 'svg', 'cell')
2160 mman.register_alias('SVG', 'svg', 'cell')
2161 mman.register_alias('HTML', 'html', 'cell')
2161 mman.register_alias('HTML', 'html', 'cell')
2162 mman.register_alias('file', 'writefile', 'cell')
2162 mman.register_alias('file', 'writefile', 'cell')
2163
2163
2164 # FIXME: Move the color initialization to the DisplayHook, which
2164 # FIXME: Move the color initialization to the DisplayHook, which
2165 # should be split into a prompt manager and displayhook. We probably
2165 # should be split into a prompt manager and displayhook. We probably
2166 # even need a centralize colors management object.
2166 # even need a centralize colors management object.
2167 self.magic('colors %s' % self.colors)
2167 self.magic('colors %s' % self.colors)
2168
2168
2169 # Defined here so that it's included in the documentation
2169 # Defined here so that it's included in the documentation
2170 @functools.wraps(magic.MagicsManager.register_function)
2170 @functools.wraps(magic.MagicsManager.register_function)
2171 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2171 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2172 self.magics_manager.register_function(func,
2172 self.magics_manager.register_function(func,
2173 magic_kind=magic_kind, magic_name=magic_name)
2173 magic_kind=magic_kind, magic_name=magic_name)
2174
2174
2175 def run_line_magic(self, magic_name, line):
2175 def run_line_magic(self, magic_name, line):
2176 """Execute the given line magic.
2176 """Execute the given line magic.
2177
2177
2178 Parameters
2178 Parameters
2179 ----------
2179 ----------
2180 magic_name : str
2180 magic_name : str
2181 Name of the desired magic function, without '%' prefix.
2181 Name of the desired magic function, without '%' prefix.
2182
2182
2183 line : str
2183 line : str
2184 The rest of the input line as a single string.
2184 The rest of the input line as a single string.
2185 """
2185 """
2186 fn = self.find_line_magic(magic_name)
2186 fn = self.find_line_magic(magic_name)
2187 if fn is None:
2187 if fn is None:
2188 cm = self.find_cell_magic(magic_name)
2188 cm = self.find_cell_magic(magic_name)
2189 etpl = "Line magic function `%%%s` not found%s."
2189 etpl = "Line magic function `%%%s` not found%s."
2190 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2190 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2191 'did you mean that instead?)' % magic_name )
2191 'did you mean that instead?)' % magic_name )
2192 error(etpl % (magic_name, extra))
2192 error(etpl % (magic_name, extra))
2193 else:
2193 else:
2194 # Note: this is the distance in the stack to the user's frame.
2194 # Note: this is the distance in the stack to the user's frame.
2195 # This will need to be updated if the internal calling logic gets
2195 # This will need to be updated if the internal calling logic gets
2196 # refactored, or else we'll be expanding the wrong variables.
2196 # refactored, or else we'll be expanding the wrong variables.
2197 stack_depth = 2
2197 stack_depth = 2
2198 magic_arg_s = self.var_expand(line, stack_depth)
2198 magic_arg_s = self.var_expand(line, stack_depth)
2199 # Put magic args in a list so we can call with f(*a) syntax
2199 # Put magic args in a list so we can call with f(*a) syntax
2200 args = [magic_arg_s]
2200 args = [magic_arg_s]
2201 kwargs = {}
2201 kwargs = {}
2202 # Grab local namespace if we need it:
2202 # Grab local namespace if we need it:
2203 if getattr(fn, "needs_local_scope", False):
2203 if getattr(fn, "needs_local_scope", False):
2204 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2204 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2205 with self.builtin_trap:
2205 with self.builtin_trap:
2206 result = fn(*args,**kwargs)
2206 result = fn(*args,**kwargs)
2207 return result
2207 return result
2208
2208
2209 def run_cell_magic(self, magic_name, line, cell):
2209 def run_cell_magic(self, magic_name, line, cell):
2210 """Execute the given cell magic.
2210 """Execute the given cell magic.
2211
2211
2212 Parameters
2212 Parameters
2213 ----------
2213 ----------
2214 magic_name : str
2214 magic_name : str
2215 Name of the desired magic function, without '%' prefix.
2215 Name of the desired magic function, without '%' prefix.
2216
2216
2217 line : str
2217 line : str
2218 The rest of the first input line as a single string.
2218 The rest of the first input line as a single string.
2219
2219
2220 cell : str
2220 cell : str
2221 The body of the cell as a (possibly multiline) string.
2221 The body of the cell as a (possibly multiline) string.
2222 """
2222 """
2223 fn = self.find_cell_magic(magic_name)
2223 fn = self.find_cell_magic(magic_name)
2224 if fn is None:
2224 if fn is None:
2225 lm = self.find_line_magic(magic_name)
2225 lm = self.find_line_magic(magic_name)
2226 etpl = "Cell magic `%%{0}` not found{1}."
2226 etpl = "Cell magic `%%{0}` not found{1}."
2227 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2227 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2228 'did you mean that instead?)'.format(magic_name))
2228 'did you mean that instead?)'.format(magic_name))
2229 error(etpl.format(magic_name, extra))
2229 error(etpl.format(magic_name, extra))
2230 elif cell == '':
2230 elif cell == '':
2231 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2231 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2232 if self.find_line_magic(magic_name) is not None:
2232 if self.find_line_magic(magic_name) is not None:
2233 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2233 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2234 raise UsageError(message)
2234 raise UsageError(message)
2235 else:
2235 else:
2236 # Note: this is the distance in the stack to the user's frame.
2236 # Note: this is the distance in the stack to the user's frame.
2237 # This will need to be updated if the internal calling logic gets
2237 # This will need to be updated if the internal calling logic gets
2238 # refactored, or else we'll be expanding the wrong variables.
2238 # refactored, or else we'll be expanding the wrong variables.
2239 stack_depth = 2
2239 stack_depth = 2
2240 magic_arg_s = self.var_expand(line, stack_depth)
2240 magic_arg_s = self.var_expand(line, stack_depth)
2241 with self.builtin_trap:
2241 with self.builtin_trap:
2242 result = fn(magic_arg_s, cell)
2242 result = fn(magic_arg_s, cell)
2243 return result
2243 return result
2244
2244
2245 def find_line_magic(self, magic_name):
2245 def find_line_magic(self, magic_name):
2246 """Find and return a line magic by name.
2246 """Find and return a line magic by name.
2247
2247
2248 Returns None if the magic isn't found."""
2248 Returns None if the magic isn't found."""
2249 return self.magics_manager.magics['line'].get(magic_name)
2249 return self.magics_manager.magics['line'].get(magic_name)
2250
2250
2251 def find_cell_magic(self, magic_name):
2251 def find_cell_magic(self, magic_name):
2252 """Find and return a cell magic by name.
2252 """Find and return a cell magic by name.
2253
2253
2254 Returns None if the magic isn't found."""
2254 Returns None if the magic isn't found."""
2255 return self.magics_manager.magics['cell'].get(magic_name)
2255 return self.magics_manager.magics['cell'].get(magic_name)
2256
2256
2257 def find_magic(self, magic_name, magic_kind='line'):
2257 def find_magic(self, magic_name, magic_kind='line'):
2258 """Find and return a magic of the given type by name.
2258 """Find and return a magic of the given type by name.
2259
2259
2260 Returns None if the magic isn't found."""
2260 Returns None if the magic isn't found."""
2261 return self.magics_manager.magics[magic_kind].get(magic_name)
2261 return self.magics_manager.magics[magic_kind].get(magic_name)
2262
2262
2263 def magic(self, arg_s):
2263 def magic(self, arg_s):
2264 """DEPRECATED. Use run_line_magic() instead.
2264 """DEPRECATED. Use run_line_magic() instead.
2265
2265
2266 Call a magic function by name.
2266 Call a magic function by name.
2267
2267
2268 Input: a string containing the name of the magic function to call and
2268 Input: a string containing the name of the magic function to call and
2269 any additional arguments to be passed to the magic.
2269 any additional arguments to be passed to the magic.
2270
2270
2271 magic('name -opt foo bar') is equivalent to typing at the ipython
2271 magic('name -opt foo bar') is equivalent to typing at the ipython
2272 prompt:
2272 prompt:
2273
2273
2274 In[1]: %name -opt foo bar
2274 In[1]: %name -opt foo bar
2275
2275
2276 To call a magic without arguments, simply use magic('name').
2276 To call a magic without arguments, simply use magic('name').
2277
2277
2278 This provides a proper Python function to call IPython's magics in any
2278 This provides a proper Python function to call IPython's magics in any
2279 valid Python code you can type at the interpreter, including loops and
2279 valid Python code you can type at the interpreter, including loops and
2280 compound statements.
2280 compound statements.
2281 """
2281 """
2282 # TODO: should we issue a loud deprecation warning here?
2282 # TODO: should we issue a loud deprecation warning here?
2283 magic_name, _, magic_arg_s = arg_s.partition(' ')
2283 magic_name, _, magic_arg_s = arg_s.partition(' ')
2284 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2284 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2285 return self.run_line_magic(magic_name, magic_arg_s)
2285 return self.run_line_magic(magic_name, magic_arg_s)
2286
2286
2287 #-------------------------------------------------------------------------
2287 #-------------------------------------------------------------------------
2288 # Things related to macros
2288 # Things related to macros
2289 #-------------------------------------------------------------------------
2289 #-------------------------------------------------------------------------
2290
2290
2291 def define_macro(self, name, themacro):
2291 def define_macro(self, name, themacro):
2292 """Define a new macro
2292 """Define a new macro
2293
2293
2294 Parameters
2294 Parameters
2295 ----------
2295 ----------
2296 name : str
2296 name : str
2297 The name of the macro.
2297 The name of the macro.
2298 themacro : str or Macro
2298 themacro : str or Macro
2299 The action to do upon invoking the macro. If a string, a new
2299 The action to do upon invoking the macro. If a string, a new
2300 Macro object is created by passing the string to it.
2300 Macro object is created by passing the string to it.
2301 """
2301 """
2302
2302
2303 from IPython.core import macro
2303 from IPython.core import macro
2304
2304
2305 if isinstance(themacro, string_types):
2305 if isinstance(themacro, string_types):
2306 themacro = macro.Macro(themacro)
2306 themacro = macro.Macro(themacro)
2307 if not isinstance(themacro, macro.Macro):
2307 if not isinstance(themacro, macro.Macro):
2308 raise ValueError('A macro must be a string or a Macro instance.')
2308 raise ValueError('A macro must be a string or a Macro instance.')
2309 self.user_ns[name] = themacro
2309 self.user_ns[name] = themacro
2310
2310
2311 #-------------------------------------------------------------------------
2311 #-------------------------------------------------------------------------
2312 # Things related to the running of system commands
2312 # Things related to the running of system commands
2313 #-------------------------------------------------------------------------
2313 #-------------------------------------------------------------------------
2314
2314
2315 def system_piped(self, cmd):
2315 def system_piped(self, cmd):
2316 """Call the given cmd in a subprocess, piping stdout/err
2316 """Call the given cmd in a subprocess, piping stdout/err
2317
2317
2318 Parameters
2318 Parameters
2319 ----------
2319 ----------
2320 cmd : str
2320 cmd : str
2321 Command to execute (can not end in '&', as background processes are
2321 Command to execute (can not end in '&', as background processes are
2322 not supported. Should not be a command that expects input
2322 not supported. Should not be a command that expects input
2323 other than simple text.
2323 other than simple text.
2324 """
2324 """
2325 if cmd.rstrip().endswith('&'):
2325 if cmd.rstrip().endswith('&'):
2326 # this is *far* from a rigorous test
2326 # this is *far* from a rigorous test
2327 # We do not support backgrounding processes because we either use
2327 # We do not support backgrounding processes because we either use
2328 # pexpect or pipes to read from. Users can always just call
2328 # pexpect or pipes to read from. Users can always just call
2329 # os.system() or use ip.system=ip.system_raw
2329 # os.system() or use ip.system=ip.system_raw
2330 # if they really want a background process.
2330 # if they really want a background process.
2331 raise OSError("Background processes not supported.")
2331 raise OSError("Background processes not supported.")
2332
2332
2333 # we explicitly do NOT return the subprocess status code, because
2333 # we explicitly do NOT return the subprocess status code, because
2334 # a non-None value would trigger :func:`sys.displayhook` calls.
2334 # a non-None value would trigger :func:`sys.displayhook` calls.
2335 # Instead, we store the exit_code in user_ns.
2335 # Instead, we store the exit_code in user_ns.
2336 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2336 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2337
2337
2338 def system_raw(self, cmd):
2338 def system_raw(self, cmd):
2339 """Call the given cmd in a subprocess using os.system on Windows or
2339 """Call the given cmd in a subprocess using os.system on Windows or
2340 subprocess.call using the system shell on other platforms.
2340 subprocess.call using the system shell on other platforms.
2341
2341
2342 Parameters
2342 Parameters
2343 ----------
2343 ----------
2344 cmd : str
2344 cmd : str
2345 Command to execute.
2345 Command to execute.
2346 """
2346 """
2347 cmd = self.var_expand(cmd, depth=1)
2347 cmd = self.var_expand(cmd, depth=1)
2348 # protect os.system from UNC paths on Windows, which it can't handle:
2348 # protect os.system from UNC paths on Windows, which it can't handle:
2349 if sys.platform == 'win32':
2349 if sys.platform == 'win32':
2350 from IPython.utils._process_win32 import AvoidUNCPath
2350 from IPython.utils._process_win32 import AvoidUNCPath
2351 with AvoidUNCPath() as path:
2351 with AvoidUNCPath() as path:
2352 if path is not None:
2352 if path is not None:
2353 cmd = '"pushd %s &&"%s' % (path, cmd)
2353 cmd = '"pushd %s &&"%s' % (path, cmd)
2354 cmd = py3compat.unicode_to_str(cmd)
2354 cmd = py3compat.unicode_to_str(cmd)
2355 ec = os.system(cmd)
2355 ec = os.system(cmd)
2356 else:
2356 else:
2357 cmd = py3compat.unicode_to_str(cmd)
2357 cmd = py3compat.unicode_to_str(cmd)
2358 # Call the cmd using the OS shell, instead of the default /bin/sh, if set.
2358 # Call the cmd using the OS shell, instead of the default /bin/sh, if set.
2359 ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None))
2359 ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None))
2360 # exit code is positive for program failure, or negative for
2360 # exit code is positive for program failure, or negative for
2361 # terminating signal number.
2361 # terminating signal number.
2362
2362
2363 # Interpret ec > 128 as signal
2363 # Interpret ec > 128 as signal
2364 # Some shells (csh, fish) don't follow sh/bash conventions for exit codes
2364 # Some shells (csh, fish) don't follow sh/bash conventions for exit codes
2365 if ec > 128:
2365 if ec > 128:
2366 ec = -(ec - 128)
2366 ec = -(ec - 128)
2367
2367
2368 # We explicitly do NOT return the subprocess status code, because
2368 # We explicitly do NOT return the subprocess status code, because
2369 # a non-None value would trigger :func:`sys.displayhook` calls.
2369 # a non-None value would trigger :func:`sys.displayhook` calls.
2370 # Instead, we store the exit_code in user_ns.
2370 # Instead, we store the exit_code in user_ns.
2371 self.user_ns['_exit_code'] = ec
2371 self.user_ns['_exit_code'] = ec
2372
2372
2373 # use piped system by default, because it is better behaved
2373 # use piped system by default, because it is better behaved
2374 system = system_piped
2374 system = system_piped
2375
2375
2376 def getoutput(self, cmd, split=True, depth=0):
2376 def getoutput(self, cmd, split=True, depth=0):
2377 """Get output (possibly including stderr) from a subprocess.
2377 """Get output (possibly including stderr) from a subprocess.
2378
2378
2379 Parameters
2379 Parameters
2380 ----------
2380 ----------
2381 cmd : str
2381 cmd : str
2382 Command to execute (can not end in '&', as background processes are
2382 Command to execute (can not end in '&', as background processes are
2383 not supported.
2383 not supported.
2384 split : bool, optional
2384 split : bool, optional
2385 If True, split the output into an IPython SList. Otherwise, an
2385 If True, split the output into an IPython SList. Otherwise, an
2386 IPython LSString is returned. These are objects similar to normal
2386 IPython LSString is returned. These are objects similar to normal
2387 lists and strings, with a few convenience attributes for easier
2387 lists and strings, with a few convenience attributes for easier
2388 manipulation of line-based output. You can use '?' on them for
2388 manipulation of line-based output. You can use '?' on them for
2389 details.
2389 details.
2390 depth : int, optional
2390 depth : int, optional
2391 How many frames above the caller are the local variables which should
2391 How many frames above the caller are the local variables which should
2392 be expanded in the command string? The default (0) assumes that the
2392 be expanded in the command string? The default (0) assumes that the
2393 expansion variables are in the stack frame calling this function.
2393 expansion variables are in the stack frame calling this function.
2394 """
2394 """
2395 if cmd.rstrip().endswith('&'):
2395 if cmd.rstrip().endswith('&'):
2396 # this is *far* from a rigorous test
2396 # this is *far* from a rigorous test
2397 raise OSError("Background processes not supported.")
2397 raise OSError("Background processes not supported.")
2398 out = getoutput(self.var_expand(cmd, depth=depth+1))
2398 out = getoutput(self.var_expand(cmd, depth=depth+1))
2399 if split:
2399 if split:
2400 out = SList(out.splitlines())
2400 out = SList(out.splitlines())
2401 else:
2401 else:
2402 out = LSString(out)
2402 out = LSString(out)
2403 return out
2403 return out
2404
2404
2405 #-------------------------------------------------------------------------
2405 #-------------------------------------------------------------------------
2406 # Things related to aliases
2406 # Things related to aliases
2407 #-------------------------------------------------------------------------
2407 #-------------------------------------------------------------------------
2408
2408
2409 def init_alias(self):
2409 def init_alias(self):
2410 self.alias_manager = AliasManager(shell=self, parent=self)
2410 self.alias_manager = AliasManager(shell=self, parent=self)
2411 self.configurables.append(self.alias_manager)
2411 self.configurables.append(self.alias_manager)
2412
2412
2413 #-------------------------------------------------------------------------
2413 #-------------------------------------------------------------------------
2414 # Things related to extensions
2414 # Things related to extensions
2415 #-------------------------------------------------------------------------
2415 #-------------------------------------------------------------------------
2416
2416
2417 def init_extension_manager(self):
2417 def init_extension_manager(self):
2418 self.extension_manager = ExtensionManager(shell=self, parent=self)
2418 self.extension_manager = ExtensionManager(shell=self, parent=self)
2419 self.configurables.append(self.extension_manager)
2419 self.configurables.append(self.extension_manager)
2420
2420
2421 #-------------------------------------------------------------------------
2421 #-------------------------------------------------------------------------
2422 # Things related to payloads
2422 # Things related to payloads
2423 #-------------------------------------------------------------------------
2423 #-------------------------------------------------------------------------
2424
2424
2425 def init_payload(self):
2425 def init_payload(self):
2426 self.payload_manager = PayloadManager(parent=self)
2426 self.payload_manager = PayloadManager(parent=self)
2427 self.configurables.append(self.payload_manager)
2427 self.configurables.append(self.payload_manager)
2428
2428
2429 #-------------------------------------------------------------------------
2429 #-------------------------------------------------------------------------
2430 # Things related to the prefilter
2430 # Things related to the prefilter
2431 #-------------------------------------------------------------------------
2431 #-------------------------------------------------------------------------
2432
2432
2433 def init_prefilter(self):
2433 def init_prefilter(self):
2434 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2434 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2435 self.configurables.append(self.prefilter_manager)
2435 self.configurables.append(self.prefilter_manager)
2436 # Ultimately this will be refactored in the new interpreter code, but
2436 # Ultimately this will be refactored in the new interpreter code, but
2437 # for now, we should expose the main prefilter method (there's legacy
2437 # for now, we should expose the main prefilter method (there's legacy
2438 # code out there that may rely on this).
2438 # code out there that may rely on this).
2439 self.prefilter = self.prefilter_manager.prefilter_lines
2439 self.prefilter = self.prefilter_manager.prefilter_lines
2440
2440
2441 def auto_rewrite_input(self, cmd):
2441 def auto_rewrite_input(self, cmd):
2442 """Print to the screen the rewritten form of the user's command.
2442 """Print to the screen the rewritten form of the user's command.
2443
2443
2444 This shows visual feedback by rewriting input lines that cause
2444 This shows visual feedback by rewriting input lines that cause
2445 automatic calling to kick in, like::
2445 automatic calling to kick in, like::
2446
2446
2447 /f x
2447 /f x
2448
2448
2449 into::
2449 into::
2450
2450
2451 ------> f(x)
2451 ------> f(x)
2452
2452
2453 after the user's input prompt. This helps the user understand that the
2453 after the user's input prompt. This helps the user understand that the
2454 input line was transformed automatically by IPython.
2454 input line was transformed automatically by IPython.
2455 """
2455 """
2456 if not self.show_rewritten_input:
2456 if not self.show_rewritten_input:
2457 return
2457 return
2458
2458
2459 rw = self.prompt_manager.render('rewrite') + cmd
2459 rw = self.prompt_manager.render('rewrite') + cmd
2460
2460
2461 try:
2461 try:
2462 # plain ascii works better w/ pyreadline, on some machines, so
2462 # plain ascii works better w/ pyreadline, on some machines, so
2463 # we use it and only print uncolored rewrite if we have unicode
2463 # we use it and only print uncolored rewrite if we have unicode
2464 rw = str(rw)
2464 rw = str(rw)
2465 print(rw, file=io.stdout)
2465 print(rw, file=io.stdout)
2466 except UnicodeEncodeError:
2466 except UnicodeEncodeError:
2467 print("------> " + cmd)
2467 print("------> " + cmd)
2468
2468
2469 #-------------------------------------------------------------------------
2469 #-------------------------------------------------------------------------
2470 # Things related to extracting values/expressions from kernel and user_ns
2470 # Things related to extracting values/expressions from kernel and user_ns
2471 #-------------------------------------------------------------------------
2471 #-------------------------------------------------------------------------
2472
2472
2473 def _user_obj_error(self):
2473 def _user_obj_error(self):
2474 """return simple exception dict
2474 """return simple exception dict
2475
2475
2476 for use in user_expressions
2476 for use in user_expressions
2477 """
2477 """
2478
2478
2479 etype, evalue, tb = self._get_exc_info()
2479 etype, evalue, tb = self._get_exc_info()
2480 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2480 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2481
2481
2482 exc_info = {
2482 exc_info = {
2483 u'status' : 'error',
2483 u'status' : 'error',
2484 u'traceback' : stb,
2484 u'traceback' : stb,
2485 u'ename' : unicode_type(etype.__name__),
2485 u'ename' : unicode_type(etype.__name__),
2486 u'evalue' : py3compat.safe_unicode(evalue),
2486 u'evalue' : py3compat.safe_unicode(evalue),
2487 }
2487 }
2488
2488
2489 return exc_info
2489 return exc_info
2490
2490
2491 def _format_user_obj(self, obj):
2491 def _format_user_obj(self, obj):
2492 """format a user object to display dict
2492 """format a user object to display dict
2493
2493
2494 for use in user_expressions
2494 for use in user_expressions
2495 """
2495 """
2496
2496
2497 data, md = self.display_formatter.format(obj)
2497 data, md = self.display_formatter.format(obj)
2498 value = {
2498 value = {
2499 'status' : 'ok',
2499 'status' : 'ok',
2500 'data' : data,
2500 'data' : data,
2501 'metadata' : md,
2501 'metadata' : md,
2502 }
2502 }
2503 return value
2503 return value
2504
2504
2505 def user_expressions(self, expressions):
2505 def user_expressions(self, expressions):
2506 """Evaluate a dict of expressions in the user's namespace.
2506 """Evaluate a dict of expressions in the user's namespace.
2507
2507
2508 Parameters
2508 Parameters
2509 ----------
2509 ----------
2510 expressions : dict
2510 expressions : dict
2511 A dict with string keys and string values. The expression values
2511 A dict with string keys and string values. The expression values
2512 should be valid Python expressions, each of which will be evaluated
2512 should be valid Python expressions, each of which will be evaluated
2513 in the user namespace.
2513 in the user namespace.
2514
2514
2515 Returns
2515 Returns
2516 -------
2516 -------
2517 A dict, keyed like the input expressions dict, with the rich mime-typed
2517 A dict, keyed like the input expressions dict, with the rich mime-typed
2518 display_data of each value.
2518 display_data of each value.
2519 """
2519 """
2520 out = {}
2520 out = {}
2521 user_ns = self.user_ns
2521 user_ns = self.user_ns
2522 global_ns = self.user_global_ns
2522 global_ns = self.user_global_ns
2523
2523
2524 for key, expr in iteritems(expressions):
2524 for key, expr in iteritems(expressions):
2525 try:
2525 try:
2526 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2526 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2527 except:
2527 except:
2528 value = self._user_obj_error()
2528 value = self._user_obj_error()
2529 out[key] = value
2529 out[key] = value
2530 return out
2530 return out
2531
2531
2532 #-------------------------------------------------------------------------
2532 #-------------------------------------------------------------------------
2533 # Things related to the running of code
2533 # Things related to the running of code
2534 #-------------------------------------------------------------------------
2534 #-------------------------------------------------------------------------
2535
2535
2536 def ex(self, cmd):
2536 def ex(self, cmd):
2537 """Execute a normal python statement in user namespace."""
2537 """Execute a normal python statement in user namespace."""
2538 with self.builtin_trap:
2538 with self.builtin_trap:
2539 exec(cmd, self.user_global_ns, self.user_ns)
2539 exec(cmd, self.user_global_ns, self.user_ns)
2540
2540
2541 def ev(self, expr):
2541 def ev(self, expr):
2542 """Evaluate python expression expr in user namespace.
2542 """Evaluate python expression expr in user namespace.
2543
2543
2544 Returns the result of evaluation
2544 Returns the result of evaluation
2545 """
2545 """
2546 with self.builtin_trap:
2546 with self.builtin_trap:
2547 return eval(expr, self.user_global_ns, self.user_ns)
2547 return eval(expr, self.user_global_ns, self.user_ns)
2548
2548
2549 def safe_execfile(self, fname, *where, **kw):
2549 def safe_execfile(self, fname, *where, **kw):
2550 """A safe version of the builtin execfile().
2550 """A safe version of the builtin execfile().
2551
2551
2552 This version will never throw an exception, but instead print
2552 This version will never throw an exception, but instead print
2553 helpful error messages to the screen. This only works on pure
2553 helpful error messages to the screen. This only works on pure
2554 Python files with the .py extension.
2554 Python files with the .py extension.
2555
2555
2556 Parameters
2556 Parameters
2557 ----------
2557 ----------
2558 fname : string
2558 fname : string
2559 The name of the file to be executed.
2559 The name of the file to be executed.
2560 where : tuple
2560 where : tuple
2561 One or two namespaces, passed to execfile() as (globals,locals).
2561 One or two namespaces, passed to execfile() as (globals,locals).
2562 If only one is given, it is passed as both.
2562 If only one is given, it is passed as both.
2563 exit_ignore : bool (False)
2563 exit_ignore : bool (False)
2564 If True, then silence SystemExit for non-zero status (it is always
2564 If True, then silence SystemExit for non-zero status (it is always
2565 silenced for zero status, as it is so common).
2565 silenced for zero status, as it is so common).
2566 raise_exceptions : bool (False)
2566 raise_exceptions : bool (False)
2567 If True raise exceptions everywhere. Meant for testing.
2567 If True raise exceptions everywhere. Meant for testing.
2568 shell_futures : bool (False)
2568 shell_futures : bool (False)
2569 If True, the code will share future statements with the interactive
2569 If True, the code will share future statements with the interactive
2570 shell. It will both be affected by previous __future__ imports, and
2570 shell. It will both be affected by previous __future__ imports, and
2571 any __future__ imports in the code will affect the shell. If False,
2571 any __future__ imports in the code will affect the shell. If False,
2572 __future__ imports are not shared in either direction.
2572 __future__ imports are not shared in either direction.
2573
2573
2574 """
2574 """
2575 kw.setdefault('exit_ignore', False)
2575 kw.setdefault('exit_ignore', False)
2576 kw.setdefault('raise_exceptions', False)
2576 kw.setdefault('raise_exceptions', False)
2577 kw.setdefault('shell_futures', False)
2577 kw.setdefault('shell_futures', False)
2578
2578
2579 fname = os.path.abspath(os.path.expanduser(fname))
2579 fname = os.path.abspath(os.path.expanduser(fname))
2580
2580
2581 # Make sure we can open the file
2581 # Make sure we can open the file
2582 try:
2582 try:
2583 with open(fname) as thefile:
2583 with open(fname) as thefile:
2584 pass
2584 pass
2585 except:
2585 except:
2586 warn('Could not open file <%s> for safe execution.' % fname)
2586 warn('Could not open file <%s> for safe execution.' % fname)
2587 return
2587 return
2588
2588
2589 # Find things also in current directory. This is needed to mimic the
2589 # Find things also in current directory. This is needed to mimic the
2590 # behavior of running a script from the system command line, where
2590 # behavior of running a script from the system command line, where
2591 # Python inserts the script's directory into sys.path
2591 # Python inserts the script's directory into sys.path
2592 dname = os.path.dirname(fname)
2592 dname = os.path.dirname(fname)
2593
2593
2594 with prepended_to_syspath(dname):
2594 with prepended_to_syspath(dname):
2595 try:
2595 try:
2596 glob, loc = (where + (None, ))[:2]
2596 glob, loc = (where + (None, ))[:2]
2597 py3compat.execfile(
2597 py3compat.execfile(
2598 fname, glob, loc,
2598 fname, glob, loc,
2599 self.compile if kw['shell_futures'] else None)
2599 self.compile if kw['shell_futures'] else None)
2600 except SystemExit as status:
2600 except SystemExit as status:
2601 # If the call was made with 0 or None exit status (sys.exit(0)
2601 # If the call was made with 0 or None exit status (sys.exit(0)
2602 # or sys.exit() ), don't bother showing a traceback, as both of
2602 # or sys.exit() ), don't bother showing a traceback, as both of
2603 # these are considered normal by the OS:
2603 # these are considered normal by the OS:
2604 # > python -c'import sys;sys.exit(0)'; echo $?
2604 # > python -c'import sys;sys.exit(0)'; echo $?
2605 # 0
2605 # 0
2606 # > python -c'import sys;sys.exit()'; echo $?
2606 # > python -c'import sys;sys.exit()'; echo $?
2607 # 0
2607 # 0
2608 # For other exit status, we show the exception unless
2608 # For other exit status, we show the exception unless
2609 # explicitly silenced, but only in short form.
2609 # explicitly silenced, but only in short form.
2610 if kw['raise_exceptions']:
2610 if kw['raise_exceptions']:
2611 raise
2611 raise
2612 if status.code and not kw['exit_ignore']:
2612 if status.code and not kw['exit_ignore']:
2613 self.showtraceback(exception_only=True)
2613 self.showtraceback(exception_only=True)
2614 except:
2614 except:
2615 if kw['raise_exceptions']:
2615 if kw['raise_exceptions']:
2616 raise
2616 raise
2617 # tb offset is 2 because we wrap execfile
2617 # tb offset is 2 because we wrap execfile
2618 self.showtraceback(tb_offset=2)
2618 self.showtraceback(tb_offset=2)
2619
2619
2620 def safe_execfile_ipy(self, fname, shell_futures=False):
2620 def safe_execfile_ipy(self, fname, shell_futures=False):
2621 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2621 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2622
2622
2623 Parameters
2623 Parameters
2624 ----------
2624 ----------
2625 fname : str
2625 fname : str
2626 The name of the file to execute. The filename must have a
2626 The name of the file to execute. The filename must have a
2627 .ipy or .ipynb extension.
2627 .ipy or .ipynb extension.
2628 shell_futures : bool (False)
2628 shell_futures : bool (False)
2629 If True, the code will share future statements with the interactive
2629 If True, the code will share future statements with the interactive
2630 shell. It will both be affected by previous __future__ imports, and
2630 shell. It will both be affected by previous __future__ imports, and
2631 any __future__ imports in the code will affect the shell. If False,
2631 any __future__ imports in the code will affect the shell. If False,
2632 __future__ imports are not shared in either direction.
2632 __future__ imports are not shared in either direction.
2633 """
2633 """
2634 fname = os.path.abspath(os.path.expanduser(fname))
2634 fname = os.path.abspath(os.path.expanduser(fname))
2635
2635
2636 # Make sure we can open the file
2636 # Make sure we can open the file
2637 try:
2637 try:
2638 with open(fname) as thefile:
2638 with open(fname) as thefile:
2639 pass
2639 pass
2640 except:
2640 except:
2641 warn('Could not open file <%s> for safe execution.' % fname)
2641 warn('Could not open file <%s> for safe execution.' % fname)
2642 return
2642 return
2643
2643
2644 # Find things also in current directory. This is needed to mimic the
2644 # Find things also in current directory. This is needed to mimic the
2645 # behavior of running a script from the system command line, where
2645 # behavior of running a script from the system command line, where
2646 # Python inserts the script's directory into sys.path
2646 # Python inserts the script's directory into sys.path
2647 dname = os.path.dirname(fname)
2647 dname = os.path.dirname(fname)
2648
2648
2649 def get_cells():
2649 def get_cells():
2650 """generator for sequence of code blocks to run"""
2650 """generator for sequence of code blocks to run"""
2651 if fname.endswith('.ipynb'):
2651 if fname.endswith('.ipynb'):
2652 from IPython.nbformat import current
2652 from IPython.nbformat import read
2653 with open(fname) as f:
2653 with io_open(fname) as f:
2654 nb = current.read(f, 'json')
2654 nb = read(f, as_version=4)
2655 if not nb.worksheets:
2655 if not nb.cells:
2656 return
2656 return
2657 for cell in nb.worksheets[0].cells:
2657 for cell in nb.cells:
2658 if cell.cell_type == 'code':
2658 if cell.cell_type == 'code':
2659 yield cell.input
2659 yield cell.source
2660 else:
2660 else:
2661 with open(fname) as f:
2661 with open(fname) as f:
2662 yield f.read()
2662 yield f.read()
2663
2663
2664 with prepended_to_syspath(dname):
2664 with prepended_to_syspath(dname):
2665 try:
2665 try:
2666 for cell in get_cells():
2666 for cell in get_cells():
2667 # self.run_cell currently captures all exceptions
2667 # self.run_cell currently captures all exceptions
2668 # raised in user code. It would be nice if there were
2668 # raised in user code. It would be nice if there were
2669 # versions of run_cell that did raise, so
2669 # versions of run_cell that did raise, so
2670 # we could catch the errors.
2670 # we could catch the errors.
2671 self.run_cell(cell, silent=True, shell_futures=shell_futures)
2671 self.run_cell(cell, silent=True, shell_futures=shell_futures)
2672 except:
2672 except:
2673 self.showtraceback()
2673 self.showtraceback()
2674 warn('Unknown failure executing file: <%s>' % fname)
2674 warn('Unknown failure executing file: <%s>' % fname)
2675
2675
2676 def safe_run_module(self, mod_name, where):
2676 def safe_run_module(self, mod_name, where):
2677 """A safe version of runpy.run_module().
2677 """A safe version of runpy.run_module().
2678
2678
2679 This version will never throw an exception, but instead print
2679 This version will never throw an exception, but instead print
2680 helpful error messages to the screen.
2680 helpful error messages to the screen.
2681
2681
2682 `SystemExit` exceptions with status code 0 or None are ignored.
2682 `SystemExit` exceptions with status code 0 or None are ignored.
2683
2683
2684 Parameters
2684 Parameters
2685 ----------
2685 ----------
2686 mod_name : string
2686 mod_name : string
2687 The name of the module to be executed.
2687 The name of the module to be executed.
2688 where : dict
2688 where : dict
2689 The globals namespace.
2689 The globals namespace.
2690 """
2690 """
2691 try:
2691 try:
2692 try:
2692 try:
2693 where.update(
2693 where.update(
2694 runpy.run_module(str(mod_name), run_name="__main__",
2694 runpy.run_module(str(mod_name), run_name="__main__",
2695 alter_sys=True)
2695 alter_sys=True)
2696 )
2696 )
2697 except SystemExit as status:
2697 except SystemExit as status:
2698 if status.code:
2698 if status.code:
2699 raise
2699 raise
2700 except:
2700 except:
2701 self.showtraceback()
2701 self.showtraceback()
2702 warn('Unknown failure executing module: <%s>' % mod_name)
2702 warn('Unknown failure executing module: <%s>' % mod_name)
2703
2703
2704 def _run_cached_cell_magic(self, magic_name, line):
2704 def _run_cached_cell_magic(self, magic_name, line):
2705 """Special method to call a cell magic with the data stored in self.
2705 """Special method to call a cell magic with the data stored in self.
2706 """
2706 """
2707 cell = self._current_cell_magic_body
2707 cell = self._current_cell_magic_body
2708 self._current_cell_magic_body = None
2708 self._current_cell_magic_body = None
2709 return self.run_cell_magic(magic_name, line, cell)
2709 return self.run_cell_magic(magic_name, line, cell)
2710
2710
2711 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2711 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2712 """Run a complete IPython cell.
2712 """Run a complete IPython cell.
2713
2713
2714 Parameters
2714 Parameters
2715 ----------
2715 ----------
2716 raw_cell : str
2716 raw_cell : str
2717 The code (including IPython code such as %magic functions) to run.
2717 The code (including IPython code such as %magic functions) to run.
2718 store_history : bool
2718 store_history : bool
2719 If True, the raw and translated cell will be stored in IPython's
2719 If True, the raw and translated cell will be stored in IPython's
2720 history. For user code calling back into IPython's machinery, this
2720 history. For user code calling back into IPython's machinery, this
2721 should be set to False.
2721 should be set to False.
2722 silent : bool
2722 silent : bool
2723 If True, avoid side-effects, such as implicit displayhooks and
2723 If True, avoid side-effects, such as implicit displayhooks and
2724 and logging. silent=True forces store_history=False.
2724 and logging. silent=True forces store_history=False.
2725 shell_futures : bool
2725 shell_futures : bool
2726 If True, the code will share future statements with the interactive
2726 If True, the code will share future statements with the interactive
2727 shell. It will both be affected by previous __future__ imports, and
2727 shell. It will both be affected by previous __future__ imports, and
2728 any __future__ imports in the code will affect the shell. If False,
2728 any __future__ imports in the code will affect the shell. If False,
2729 __future__ imports are not shared in either direction.
2729 __future__ imports are not shared in either direction.
2730 """
2730 """
2731 if (not raw_cell) or raw_cell.isspace():
2731 if (not raw_cell) or raw_cell.isspace():
2732 return
2732 return
2733
2733
2734 if silent:
2734 if silent:
2735 store_history = False
2735 store_history = False
2736
2736
2737 self.events.trigger('pre_execute')
2737 self.events.trigger('pre_execute')
2738 if not silent:
2738 if not silent:
2739 self.events.trigger('pre_run_cell')
2739 self.events.trigger('pre_run_cell')
2740
2740
2741 # If any of our input transformation (input_transformer_manager or
2741 # If any of our input transformation (input_transformer_manager or
2742 # prefilter_manager) raises an exception, we store it in this variable
2742 # prefilter_manager) raises an exception, we store it in this variable
2743 # so that we can display the error after logging the input and storing
2743 # so that we can display the error after logging the input and storing
2744 # it in the history.
2744 # it in the history.
2745 preprocessing_exc_tuple = None
2745 preprocessing_exc_tuple = None
2746 try:
2746 try:
2747 # Static input transformations
2747 # Static input transformations
2748 cell = self.input_transformer_manager.transform_cell(raw_cell)
2748 cell = self.input_transformer_manager.transform_cell(raw_cell)
2749 except SyntaxError:
2749 except SyntaxError:
2750 preprocessing_exc_tuple = sys.exc_info()
2750 preprocessing_exc_tuple = sys.exc_info()
2751 cell = raw_cell # cell has to exist so it can be stored/logged
2751 cell = raw_cell # cell has to exist so it can be stored/logged
2752 else:
2752 else:
2753 if len(cell.splitlines()) == 1:
2753 if len(cell.splitlines()) == 1:
2754 # Dynamic transformations - only applied for single line commands
2754 # Dynamic transformations - only applied for single line commands
2755 with self.builtin_trap:
2755 with self.builtin_trap:
2756 try:
2756 try:
2757 # use prefilter_lines to handle trailing newlines
2757 # use prefilter_lines to handle trailing newlines
2758 # restore trailing newline for ast.parse
2758 # restore trailing newline for ast.parse
2759 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2759 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2760 except Exception:
2760 except Exception:
2761 # don't allow prefilter errors to crash IPython
2761 # don't allow prefilter errors to crash IPython
2762 preprocessing_exc_tuple = sys.exc_info()
2762 preprocessing_exc_tuple = sys.exc_info()
2763
2763
2764 # Store raw and processed history
2764 # Store raw and processed history
2765 if store_history:
2765 if store_history:
2766 self.history_manager.store_inputs(self.execution_count,
2766 self.history_manager.store_inputs(self.execution_count,
2767 cell, raw_cell)
2767 cell, raw_cell)
2768 if not silent:
2768 if not silent:
2769 self.logger.log(cell, raw_cell)
2769 self.logger.log(cell, raw_cell)
2770
2770
2771 # Display the exception if input processing failed.
2771 # Display the exception if input processing failed.
2772 if preprocessing_exc_tuple is not None:
2772 if preprocessing_exc_tuple is not None:
2773 self.showtraceback(preprocessing_exc_tuple)
2773 self.showtraceback(preprocessing_exc_tuple)
2774 if store_history:
2774 if store_history:
2775 self.execution_count += 1
2775 self.execution_count += 1
2776 return
2776 return
2777
2777
2778 # Our own compiler remembers the __future__ environment. If we want to
2778 # Our own compiler remembers the __future__ environment. If we want to
2779 # run code with a separate __future__ environment, use the default
2779 # run code with a separate __future__ environment, use the default
2780 # compiler
2780 # compiler
2781 compiler = self.compile if shell_futures else CachingCompiler()
2781 compiler = self.compile if shell_futures else CachingCompiler()
2782
2782
2783 with self.builtin_trap:
2783 with self.builtin_trap:
2784 cell_name = self.compile.cache(cell, self.execution_count)
2784 cell_name = self.compile.cache(cell, self.execution_count)
2785
2785
2786 with self.display_trap:
2786 with self.display_trap:
2787 # Compile to bytecode
2787 # Compile to bytecode
2788 try:
2788 try:
2789 code_ast = compiler.ast_parse(cell, filename=cell_name)
2789 code_ast = compiler.ast_parse(cell, filename=cell_name)
2790 except IndentationError:
2790 except IndentationError:
2791 self.showindentationerror()
2791 self.showindentationerror()
2792 if store_history:
2792 if store_history:
2793 self.execution_count += 1
2793 self.execution_count += 1
2794 return None
2794 return None
2795 except (OverflowError, SyntaxError, ValueError, TypeError,
2795 except (OverflowError, SyntaxError, ValueError, TypeError,
2796 MemoryError):
2796 MemoryError):
2797 self.showsyntaxerror()
2797 self.showsyntaxerror()
2798 if store_history:
2798 if store_history:
2799 self.execution_count += 1
2799 self.execution_count += 1
2800 return None
2800 return None
2801
2801
2802 # Apply AST transformations
2802 # Apply AST transformations
2803 try:
2803 try:
2804 code_ast = self.transform_ast(code_ast)
2804 code_ast = self.transform_ast(code_ast)
2805 except InputRejected:
2805 except InputRejected:
2806 self.showtraceback()
2806 self.showtraceback()
2807 if store_history:
2807 if store_history:
2808 self.execution_count += 1
2808 self.execution_count += 1
2809 return None
2809 return None
2810
2810
2811 # Execute the user code
2811 # Execute the user code
2812 interactivity = "none" if silent else self.ast_node_interactivity
2812 interactivity = "none" if silent else self.ast_node_interactivity
2813 self.run_ast_nodes(code_ast.body, cell_name,
2813 self.run_ast_nodes(code_ast.body, cell_name,
2814 interactivity=interactivity, compiler=compiler)
2814 interactivity=interactivity, compiler=compiler)
2815
2815
2816 self.events.trigger('post_execute')
2816 self.events.trigger('post_execute')
2817 if not silent:
2817 if not silent:
2818 self.events.trigger('post_run_cell')
2818 self.events.trigger('post_run_cell')
2819
2819
2820 if store_history:
2820 if store_history:
2821 # Write output to the database. Does nothing unless
2821 # Write output to the database. Does nothing unless
2822 # history output logging is enabled.
2822 # history output logging is enabled.
2823 self.history_manager.store_output(self.execution_count)
2823 self.history_manager.store_output(self.execution_count)
2824 # Each cell is a *single* input, regardless of how many lines it has
2824 # Each cell is a *single* input, regardless of how many lines it has
2825 self.execution_count += 1
2825 self.execution_count += 1
2826
2826
2827 def transform_ast(self, node):
2827 def transform_ast(self, node):
2828 """Apply the AST transformations from self.ast_transformers
2828 """Apply the AST transformations from self.ast_transformers
2829
2829
2830 Parameters
2830 Parameters
2831 ----------
2831 ----------
2832 node : ast.Node
2832 node : ast.Node
2833 The root node to be transformed. Typically called with the ast.Module
2833 The root node to be transformed. Typically called with the ast.Module
2834 produced by parsing user input.
2834 produced by parsing user input.
2835
2835
2836 Returns
2836 Returns
2837 -------
2837 -------
2838 An ast.Node corresponding to the node it was called with. Note that it
2838 An ast.Node corresponding to the node it was called with. Note that it
2839 may also modify the passed object, so don't rely on references to the
2839 may also modify the passed object, so don't rely on references to the
2840 original AST.
2840 original AST.
2841 """
2841 """
2842 for transformer in self.ast_transformers:
2842 for transformer in self.ast_transformers:
2843 try:
2843 try:
2844 node = transformer.visit(node)
2844 node = transformer.visit(node)
2845 except InputRejected:
2845 except InputRejected:
2846 # User-supplied AST transformers can reject an input by raising
2846 # User-supplied AST transformers can reject an input by raising
2847 # an InputRejected. Short-circuit in this case so that we
2847 # an InputRejected. Short-circuit in this case so that we
2848 # don't unregister the transform.
2848 # don't unregister the transform.
2849 raise
2849 raise
2850 except Exception:
2850 except Exception:
2851 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2851 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2852 self.ast_transformers.remove(transformer)
2852 self.ast_transformers.remove(transformer)
2853
2853
2854 if self.ast_transformers:
2854 if self.ast_transformers:
2855 ast.fix_missing_locations(node)
2855 ast.fix_missing_locations(node)
2856 return node
2856 return node
2857
2857
2858
2858
2859 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2859 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2860 compiler=compile):
2860 compiler=compile):
2861 """Run a sequence of AST nodes. The execution mode depends on the
2861 """Run a sequence of AST nodes. The execution mode depends on the
2862 interactivity parameter.
2862 interactivity parameter.
2863
2863
2864 Parameters
2864 Parameters
2865 ----------
2865 ----------
2866 nodelist : list
2866 nodelist : list
2867 A sequence of AST nodes to run.
2867 A sequence of AST nodes to run.
2868 cell_name : str
2868 cell_name : str
2869 Will be passed to the compiler as the filename of the cell. Typically
2869 Will be passed to the compiler as the filename of the cell. Typically
2870 the value returned by ip.compile.cache(cell).
2870 the value returned by ip.compile.cache(cell).
2871 interactivity : str
2871 interactivity : str
2872 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2872 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2873 run interactively (displaying output from expressions). 'last_expr'
2873 run interactively (displaying output from expressions). 'last_expr'
2874 will run the last node interactively only if it is an expression (i.e.
2874 will run the last node interactively only if it is an expression (i.e.
2875 expressions in loops or other blocks are not displayed. Other values
2875 expressions in loops or other blocks are not displayed. Other values
2876 for this parameter will raise a ValueError.
2876 for this parameter will raise a ValueError.
2877 compiler : callable
2877 compiler : callable
2878 A function with the same interface as the built-in compile(), to turn
2878 A function with the same interface as the built-in compile(), to turn
2879 the AST nodes into code objects. Default is the built-in compile().
2879 the AST nodes into code objects. Default is the built-in compile().
2880 """
2880 """
2881 if not nodelist:
2881 if not nodelist:
2882 return
2882 return
2883
2883
2884 if interactivity == 'last_expr':
2884 if interactivity == 'last_expr':
2885 if isinstance(nodelist[-1], ast.Expr):
2885 if isinstance(nodelist[-1], ast.Expr):
2886 interactivity = "last"
2886 interactivity = "last"
2887 else:
2887 else:
2888 interactivity = "none"
2888 interactivity = "none"
2889
2889
2890 if interactivity == 'none':
2890 if interactivity == 'none':
2891 to_run_exec, to_run_interactive = nodelist, []
2891 to_run_exec, to_run_interactive = nodelist, []
2892 elif interactivity == 'last':
2892 elif interactivity == 'last':
2893 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2893 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2894 elif interactivity == 'all':
2894 elif interactivity == 'all':
2895 to_run_exec, to_run_interactive = [], nodelist
2895 to_run_exec, to_run_interactive = [], nodelist
2896 else:
2896 else:
2897 raise ValueError("Interactivity was %r" % interactivity)
2897 raise ValueError("Interactivity was %r" % interactivity)
2898
2898
2899 exec_count = self.execution_count
2899 exec_count = self.execution_count
2900
2900
2901 try:
2901 try:
2902 for i, node in enumerate(to_run_exec):
2902 for i, node in enumerate(to_run_exec):
2903 mod = ast.Module([node])
2903 mod = ast.Module([node])
2904 code = compiler(mod, cell_name, "exec")
2904 code = compiler(mod, cell_name, "exec")
2905 if self.run_code(code):
2905 if self.run_code(code):
2906 return True
2906 return True
2907
2907
2908 for i, node in enumerate(to_run_interactive):
2908 for i, node in enumerate(to_run_interactive):
2909 mod = ast.Interactive([node])
2909 mod = ast.Interactive([node])
2910 code = compiler(mod, cell_name, "single")
2910 code = compiler(mod, cell_name, "single")
2911 if self.run_code(code):
2911 if self.run_code(code):
2912 return True
2912 return True
2913
2913
2914 # Flush softspace
2914 # Flush softspace
2915 if softspace(sys.stdout, 0):
2915 if softspace(sys.stdout, 0):
2916 print()
2916 print()
2917
2917
2918 except:
2918 except:
2919 # It's possible to have exceptions raised here, typically by
2919 # It's possible to have exceptions raised here, typically by
2920 # compilation of odd code (such as a naked 'return' outside a
2920 # compilation of odd code (such as a naked 'return' outside a
2921 # function) that did parse but isn't valid. Typically the exception
2921 # function) that did parse but isn't valid. Typically the exception
2922 # is a SyntaxError, but it's safest just to catch anything and show
2922 # is a SyntaxError, but it's safest just to catch anything and show
2923 # the user a traceback.
2923 # the user a traceback.
2924
2924
2925 # We do only one try/except outside the loop to minimize the impact
2925 # We do only one try/except outside the loop to minimize the impact
2926 # on runtime, and also because if any node in the node list is
2926 # on runtime, and also because if any node in the node list is
2927 # broken, we should stop execution completely.
2927 # broken, we should stop execution completely.
2928 self.showtraceback()
2928 self.showtraceback()
2929
2929
2930 return False
2930 return False
2931
2931
2932 def run_code(self, code_obj):
2932 def run_code(self, code_obj):
2933 """Execute a code object.
2933 """Execute a code object.
2934
2934
2935 When an exception occurs, self.showtraceback() is called to display a
2935 When an exception occurs, self.showtraceback() is called to display a
2936 traceback.
2936 traceback.
2937
2937
2938 Parameters
2938 Parameters
2939 ----------
2939 ----------
2940 code_obj : code object
2940 code_obj : code object
2941 A compiled code object, to be executed
2941 A compiled code object, to be executed
2942
2942
2943 Returns
2943 Returns
2944 -------
2944 -------
2945 False : successful execution.
2945 False : successful execution.
2946 True : an error occurred.
2946 True : an error occurred.
2947 """
2947 """
2948 # Set our own excepthook in case the user code tries to call it
2948 # Set our own excepthook in case the user code tries to call it
2949 # directly, so that the IPython crash handler doesn't get triggered
2949 # directly, so that the IPython crash handler doesn't get triggered
2950 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2950 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2951
2951
2952 # we save the original sys.excepthook in the instance, in case config
2952 # we save the original sys.excepthook in the instance, in case config
2953 # code (such as magics) needs access to it.
2953 # code (such as magics) needs access to it.
2954 self.sys_excepthook = old_excepthook
2954 self.sys_excepthook = old_excepthook
2955 outflag = 1 # happens in more places, so it's easier as default
2955 outflag = 1 # happens in more places, so it's easier as default
2956 try:
2956 try:
2957 try:
2957 try:
2958 self.hooks.pre_run_code_hook()
2958 self.hooks.pre_run_code_hook()
2959 #rprint('Running code', repr(code_obj)) # dbg
2959 #rprint('Running code', repr(code_obj)) # dbg
2960 exec(code_obj, self.user_global_ns, self.user_ns)
2960 exec(code_obj, self.user_global_ns, self.user_ns)
2961 finally:
2961 finally:
2962 # Reset our crash handler in place
2962 # Reset our crash handler in place
2963 sys.excepthook = old_excepthook
2963 sys.excepthook = old_excepthook
2964 except SystemExit:
2964 except SystemExit:
2965 self.showtraceback(exception_only=True)
2965 self.showtraceback(exception_only=True)
2966 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2966 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2967 except self.custom_exceptions:
2967 except self.custom_exceptions:
2968 etype, value, tb = sys.exc_info()
2968 etype, value, tb = sys.exc_info()
2969 self.CustomTB(etype, value, tb)
2969 self.CustomTB(etype, value, tb)
2970 except:
2970 except:
2971 self.showtraceback()
2971 self.showtraceback()
2972 else:
2972 else:
2973 outflag = 0
2973 outflag = 0
2974 return outflag
2974 return outflag
2975
2975
2976 # For backwards compatibility
2976 # For backwards compatibility
2977 runcode = run_code
2977 runcode = run_code
2978
2978
2979 #-------------------------------------------------------------------------
2979 #-------------------------------------------------------------------------
2980 # Things related to GUI support and pylab
2980 # Things related to GUI support and pylab
2981 #-------------------------------------------------------------------------
2981 #-------------------------------------------------------------------------
2982
2982
2983 def enable_gui(self, gui=None):
2983 def enable_gui(self, gui=None):
2984 raise NotImplementedError('Implement enable_gui in a subclass')
2984 raise NotImplementedError('Implement enable_gui in a subclass')
2985
2985
2986 def enable_matplotlib(self, gui=None):
2986 def enable_matplotlib(self, gui=None):
2987 """Enable interactive matplotlib and inline figure support.
2987 """Enable interactive matplotlib and inline figure support.
2988
2988
2989 This takes the following steps:
2989 This takes the following steps:
2990
2990
2991 1. select the appropriate eventloop and matplotlib backend
2991 1. select the appropriate eventloop and matplotlib backend
2992 2. set up matplotlib for interactive use with that backend
2992 2. set up matplotlib for interactive use with that backend
2993 3. configure formatters for inline figure display
2993 3. configure formatters for inline figure display
2994 4. enable the selected gui eventloop
2994 4. enable the selected gui eventloop
2995
2995
2996 Parameters
2996 Parameters
2997 ----------
2997 ----------
2998 gui : optional, string
2998 gui : optional, string
2999 If given, dictates the choice of matplotlib GUI backend to use
2999 If given, dictates the choice of matplotlib GUI backend to use
3000 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3000 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3001 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3001 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3002 matplotlib (as dictated by the matplotlib build-time options plus the
3002 matplotlib (as dictated by the matplotlib build-time options plus the
3003 user's matplotlibrc configuration file). Note that not all backends
3003 user's matplotlibrc configuration file). Note that not all backends
3004 make sense in all contexts, for example a terminal ipython can't
3004 make sense in all contexts, for example a terminal ipython can't
3005 display figures inline.
3005 display figures inline.
3006 """
3006 """
3007 from IPython.core import pylabtools as pt
3007 from IPython.core import pylabtools as pt
3008 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3008 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3009
3009
3010 if gui != 'inline':
3010 if gui != 'inline':
3011 # If we have our first gui selection, store it
3011 # If we have our first gui selection, store it
3012 if self.pylab_gui_select is None:
3012 if self.pylab_gui_select is None:
3013 self.pylab_gui_select = gui
3013 self.pylab_gui_select = gui
3014 # Otherwise if they are different
3014 # Otherwise if they are different
3015 elif gui != self.pylab_gui_select:
3015 elif gui != self.pylab_gui_select:
3016 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3016 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3017 ' Using %s instead.' % (gui, self.pylab_gui_select))
3017 ' Using %s instead.' % (gui, self.pylab_gui_select))
3018 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3018 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3019
3019
3020 pt.activate_matplotlib(backend)
3020 pt.activate_matplotlib(backend)
3021 pt.configure_inline_support(self, backend)
3021 pt.configure_inline_support(self, backend)
3022
3022
3023 # Now we must activate the gui pylab wants to use, and fix %run to take
3023 # Now we must activate the gui pylab wants to use, and fix %run to take
3024 # plot updates into account
3024 # plot updates into account
3025 self.enable_gui(gui)
3025 self.enable_gui(gui)
3026 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3026 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3027 pt.mpl_runner(self.safe_execfile)
3027 pt.mpl_runner(self.safe_execfile)
3028
3028
3029 return gui, backend
3029 return gui, backend
3030
3030
3031 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3031 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3032 """Activate pylab support at runtime.
3032 """Activate pylab support at runtime.
3033
3033
3034 This turns on support for matplotlib, preloads into the interactive
3034 This turns on support for matplotlib, preloads into the interactive
3035 namespace all of numpy and pylab, and configures IPython to correctly
3035 namespace all of numpy and pylab, and configures IPython to correctly
3036 interact with the GUI event loop. The GUI backend to be used can be
3036 interact with the GUI event loop. The GUI backend to be used can be
3037 optionally selected with the optional ``gui`` argument.
3037 optionally selected with the optional ``gui`` argument.
3038
3038
3039 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3039 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3040
3040
3041 Parameters
3041 Parameters
3042 ----------
3042 ----------
3043 gui : optional, string
3043 gui : optional, string
3044 If given, dictates the choice of matplotlib GUI backend to use
3044 If given, dictates the choice of matplotlib GUI backend to use
3045 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3045 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3046 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3046 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3047 matplotlib (as dictated by the matplotlib build-time options plus the
3047 matplotlib (as dictated by the matplotlib build-time options plus the
3048 user's matplotlibrc configuration file). Note that not all backends
3048 user's matplotlibrc configuration file). Note that not all backends
3049 make sense in all contexts, for example a terminal ipython can't
3049 make sense in all contexts, for example a terminal ipython can't
3050 display figures inline.
3050 display figures inline.
3051 import_all : optional, bool, default: True
3051 import_all : optional, bool, default: True
3052 Whether to do `from numpy import *` and `from pylab import *`
3052 Whether to do `from numpy import *` and `from pylab import *`
3053 in addition to module imports.
3053 in addition to module imports.
3054 welcome_message : deprecated
3054 welcome_message : deprecated
3055 This argument is ignored, no welcome message will be displayed.
3055 This argument is ignored, no welcome message will be displayed.
3056 """
3056 """
3057 from IPython.core.pylabtools import import_pylab
3057 from IPython.core.pylabtools import import_pylab
3058
3058
3059 gui, backend = self.enable_matplotlib(gui)
3059 gui, backend = self.enable_matplotlib(gui)
3060
3060
3061 # We want to prevent the loading of pylab to pollute the user's
3061 # We want to prevent the loading of pylab to pollute the user's
3062 # namespace as shown by the %who* magics, so we execute the activation
3062 # namespace as shown by the %who* magics, so we execute the activation
3063 # code in an empty namespace, and we update *both* user_ns and
3063 # code in an empty namespace, and we update *both* user_ns and
3064 # user_ns_hidden with this information.
3064 # user_ns_hidden with this information.
3065 ns = {}
3065 ns = {}
3066 import_pylab(ns, import_all)
3066 import_pylab(ns, import_all)
3067 # warn about clobbered names
3067 # warn about clobbered names
3068 ignored = set(["__builtins__"])
3068 ignored = set(["__builtins__"])
3069 both = set(ns).intersection(self.user_ns).difference(ignored)
3069 both = set(ns).intersection(self.user_ns).difference(ignored)
3070 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3070 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3071 self.user_ns.update(ns)
3071 self.user_ns.update(ns)
3072 self.user_ns_hidden.update(ns)
3072 self.user_ns_hidden.update(ns)
3073 return gui, backend, clobbered
3073 return gui, backend, clobbered
3074
3074
3075 #-------------------------------------------------------------------------
3075 #-------------------------------------------------------------------------
3076 # Utilities
3076 # Utilities
3077 #-------------------------------------------------------------------------
3077 #-------------------------------------------------------------------------
3078
3078
3079 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3079 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3080 """Expand python variables in a string.
3080 """Expand python variables in a string.
3081
3081
3082 The depth argument indicates how many frames above the caller should
3082 The depth argument indicates how many frames above the caller should
3083 be walked to look for the local namespace where to expand variables.
3083 be walked to look for the local namespace where to expand variables.
3084
3084
3085 The global namespace for expansion is always the user's interactive
3085 The global namespace for expansion is always the user's interactive
3086 namespace.
3086 namespace.
3087 """
3087 """
3088 ns = self.user_ns.copy()
3088 ns = self.user_ns.copy()
3089 ns.update(sys._getframe(depth+1).f_locals)
3089 ns.update(sys._getframe(depth+1).f_locals)
3090 try:
3090 try:
3091 # We have to use .vformat() here, because 'self' is a valid and common
3091 # We have to use .vformat() here, because 'self' is a valid and common
3092 # name, and expanding **ns for .format() would make it collide with
3092 # name, and expanding **ns for .format() would make it collide with
3093 # the 'self' argument of the method.
3093 # the 'self' argument of the method.
3094 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3094 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3095 except Exception:
3095 except Exception:
3096 # if formatter couldn't format, just let it go untransformed
3096 # if formatter couldn't format, just let it go untransformed
3097 pass
3097 pass
3098 return cmd
3098 return cmd
3099
3099
3100 def mktempfile(self, data=None, prefix='ipython_edit_'):
3100 def mktempfile(self, data=None, prefix='ipython_edit_'):
3101 """Make a new tempfile and return its filename.
3101 """Make a new tempfile and return its filename.
3102
3102
3103 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3103 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3104 but it registers the created filename internally so ipython cleans it up
3104 but it registers the created filename internally so ipython cleans it up
3105 at exit time.
3105 at exit time.
3106
3106
3107 Optional inputs:
3107 Optional inputs:
3108
3108
3109 - data(None): if data is given, it gets written out to the temp file
3109 - data(None): if data is given, it gets written out to the temp file
3110 immediately, and the file is closed again."""
3110 immediately, and the file is closed again."""
3111
3111
3112 dirname = tempfile.mkdtemp(prefix=prefix)
3112 dirname = tempfile.mkdtemp(prefix=prefix)
3113 self.tempdirs.append(dirname)
3113 self.tempdirs.append(dirname)
3114
3114
3115 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3115 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3116 os.close(handle) # On Windows, there can only be one open handle on a file
3116 os.close(handle) # On Windows, there can only be one open handle on a file
3117 self.tempfiles.append(filename)
3117 self.tempfiles.append(filename)
3118
3118
3119 if data:
3119 if data:
3120 tmp_file = open(filename,'w')
3120 tmp_file = open(filename,'w')
3121 tmp_file.write(data)
3121 tmp_file.write(data)
3122 tmp_file.close()
3122 tmp_file.close()
3123 return filename
3123 return filename
3124
3124
3125 # TODO: This should be removed when Term is refactored.
3125 # TODO: This should be removed when Term is refactored.
3126 def write(self,data):
3126 def write(self,data):
3127 """Write a string to the default output"""
3127 """Write a string to the default output"""
3128 io.stdout.write(data)
3128 io.stdout.write(data)
3129
3129
3130 # TODO: This should be removed when Term is refactored.
3130 # TODO: This should be removed when Term is refactored.
3131 def write_err(self,data):
3131 def write_err(self,data):
3132 """Write a string to the default error output"""
3132 """Write a string to the default error output"""
3133 io.stderr.write(data)
3133 io.stderr.write(data)
3134
3134
3135 def ask_yes_no(self, prompt, default=None):
3135 def ask_yes_no(self, prompt, default=None):
3136 if self.quiet:
3136 if self.quiet:
3137 return True
3137 return True
3138 return ask_yes_no(prompt,default)
3138 return ask_yes_no(prompt,default)
3139
3139
3140 def show_usage(self):
3140 def show_usage(self):
3141 """Show a usage message"""
3141 """Show a usage message"""
3142 page.page(IPython.core.usage.interactive_usage)
3142 page.page(IPython.core.usage.interactive_usage)
3143
3143
3144 def extract_input_lines(self, range_str, raw=False):
3144 def extract_input_lines(self, range_str, raw=False):
3145 """Return as a string a set of input history slices.
3145 """Return as a string a set of input history slices.
3146
3146
3147 Parameters
3147 Parameters
3148 ----------
3148 ----------
3149 range_str : string
3149 range_str : string
3150 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3150 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3151 since this function is for use by magic functions which get their
3151 since this function is for use by magic functions which get their
3152 arguments as strings. The number before the / is the session
3152 arguments as strings. The number before the / is the session
3153 number: ~n goes n back from the current session.
3153 number: ~n goes n back from the current session.
3154
3154
3155 raw : bool, optional
3155 raw : bool, optional
3156 By default, the processed input is used. If this is true, the raw
3156 By default, the processed input is used. If this is true, the raw
3157 input history is used instead.
3157 input history is used instead.
3158
3158
3159 Notes
3159 Notes
3160 -----
3160 -----
3161
3161
3162 Slices can be described with two notations:
3162 Slices can be described with two notations:
3163
3163
3164 * ``N:M`` -> standard python form, means including items N...(M-1).
3164 * ``N:M`` -> standard python form, means including items N...(M-1).
3165 * ``N-M`` -> include items N..M (closed endpoint).
3165 * ``N-M`` -> include items N..M (closed endpoint).
3166 """
3166 """
3167 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3167 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3168 return "\n".join(x for _, _, x in lines)
3168 return "\n".join(x for _, _, x in lines)
3169
3169
3170 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3170 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3171 """Get a code string from history, file, url, or a string or macro.
3171 """Get a code string from history, file, url, or a string or macro.
3172
3172
3173 This is mainly used by magic functions.
3173 This is mainly used by magic functions.
3174
3174
3175 Parameters
3175 Parameters
3176 ----------
3176 ----------
3177
3177
3178 target : str
3178 target : str
3179
3179
3180 A string specifying code to retrieve. This will be tried respectively
3180 A string specifying code to retrieve. This will be tried respectively
3181 as: ranges of input history (see %history for syntax), url,
3181 as: ranges of input history (see %history for syntax), url,
3182 correspnding .py file, filename, or an expression evaluating to a
3182 correspnding .py file, filename, or an expression evaluating to a
3183 string or Macro in the user namespace.
3183 string or Macro in the user namespace.
3184
3184
3185 raw : bool
3185 raw : bool
3186 If true (default), retrieve raw history. Has no effect on the other
3186 If true (default), retrieve raw history. Has no effect on the other
3187 retrieval mechanisms.
3187 retrieval mechanisms.
3188
3188
3189 py_only : bool (default False)
3189 py_only : bool (default False)
3190 Only try to fetch python code, do not try alternative methods to decode file
3190 Only try to fetch python code, do not try alternative methods to decode file
3191 if unicode fails.
3191 if unicode fails.
3192
3192
3193 Returns
3193 Returns
3194 -------
3194 -------
3195 A string of code.
3195 A string of code.
3196
3196
3197 ValueError is raised if nothing is found, and TypeError if it evaluates
3197 ValueError is raised if nothing is found, and TypeError if it evaluates
3198 to an object of another type. In each case, .args[0] is a printable
3198 to an object of another type. In each case, .args[0] is a printable
3199 message.
3199 message.
3200 """
3200 """
3201 code = self.extract_input_lines(target, raw=raw) # Grab history
3201 code = self.extract_input_lines(target, raw=raw) # Grab history
3202 if code:
3202 if code:
3203 return code
3203 return code
3204 utarget = unquote_filename(target)
3204 utarget = unquote_filename(target)
3205 try:
3205 try:
3206 if utarget.startswith(('http://', 'https://')):
3206 if utarget.startswith(('http://', 'https://')):
3207 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3207 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3208 except UnicodeDecodeError:
3208 except UnicodeDecodeError:
3209 if not py_only :
3209 if not py_only :
3210 # Deferred import
3210 # Deferred import
3211 try:
3211 try:
3212 from urllib.request import urlopen # Py3
3212 from urllib.request import urlopen # Py3
3213 except ImportError:
3213 except ImportError:
3214 from urllib import urlopen
3214 from urllib import urlopen
3215 response = urlopen(target)
3215 response = urlopen(target)
3216 return response.read().decode('latin1')
3216 return response.read().decode('latin1')
3217 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3217 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3218
3218
3219 potential_target = [target]
3219 potential_target = [target]
3220 try :
3220 try :
3221 potential_target.insert(0,get_py_filename(target))
3221 potential_target.insert(0,get_py_filename(target))
3222 except IOError:
3222 except IOError:
3223 pass
3223 pass
3224
3224
3225 for tgt in potential_target :
3225 for tgt in potential_target :
3226 if os.path.isfile(tgt): # Read file
3226 if os.path.isfile(tgt): # Read file
3227 try :
3227 try :
3228 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3228 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3229 except UnicodeDecodeError :
3229 except UnicodeDecodeError :
3230 if not py_only :
3230 if not py_only :
3231 with io_open(tgt,'r', encoding='latin1') as f :
3231 with io_open(tgt,'r', encoding='latin1') as f :
3232 return f.read()
3232 return f.read()
3233 raise ValueError(("'%s' seem to be unreadable.") % target)
3233 raise ValueError(("'%s' seem to be unreadable.") % target)
3234 elif os.path.isdir(os.path.expanduser(tgt)):
3234 elif os.path.isdir(os.path.expanduser(tgt)):
3235 raise ValueError("'%s' is a directory, not a regular file." % target)
3235 raise ValueError("'%s' is a directory, not a regular file." % target)
3236
3236
3237 if search_ns:
3237 if search_ns:
3238 # Inspect namespace to load object source
3238 # Inspect namespace to load object source
3239 object_info = self.object_inspect(target, detail_level=1)
3239 object_info = self.object_inspect(target, detail_level=1)
3240 if object_info['found'] and object_info['source']:
3240 if object_info['found'] and object_info['source']:
3241 return object_info['source']
3241 return object_info['source']
3242
3242
3243 try: # User namespace
3243 try: # User namespace
3244 codeobj = eval(target, self.user_ns)
3244 codeobj = eval(target, self.user_ns)
3245 except Exception:
3245 except Exception:
3246 raise ValueError(("'%s' was not found in history, as a file, url, "
3246 raise ValueError(("'%s' was not found in history, as a file, url, "
3247 "nor in the user namespace.") % target)
3247 "nor in the user namespace.") % target)
3248
3248
3249 if isinstance(codeobj, string_types):
3249 if isinstance(codeobj, string_types):
3250 return codeobj
3250 return codeobj
3251 elif isinstance(codeobj, Macro):
3251 elif isinstance(codeobj, Macro):
3252 return codeobj.value
3252 return codeobj.value
3253
3253
3254 raise TypeError("%s is neither a string nor a macro." % target,
3254 raise TypeError("%s is neither a string nor a macro." % target,
3255 codeobj)
3255 codeobj)
3256
3256
3257 #-------------------------------------------------------------------------
3257 #-------------------------------------------------------------------------
3258 # Things related to IPython exiting
3258 # Things related to IPython exiting
3259 #-------------------------------------------------------------------------
3259 #-------------------------------------------------------------------------
3260 def atexit_operations(self):
3260 def atexit_operations(self):
3261 """This will be executed at the time of exit.
3261 """This will be executed at the time of exit.
3262
3262
3263 Cleanup operations and saving of persistent data that is done
3263 Cleanup operations and saving of persistent data that is done
3264 unconditionally by IPython should be performed here.
3264 unconditionally by IPython should be performed here.
3265
3265
3266 For things that may depend on startup flags or platform specifics (such
3266 For things that may depend on startup flags or platform specifics (such
3267 as having readline or not), register a separate atexit function in the
3267 as having readline or not), register a separate atexit function in the
3268 code that has the appropriate information, rather than trying to
3268 code that has the appropriate information, rather than trying to
3269 clutter
3269 clutter
3270 """
3270 """
3271 # Close the history session (this stores the end time and line count)
3271 # Close the history session (this stores the end time and line count)
3272 # this must be *before* the tempfile cleanup, in case of temporary
3272 # this must be *before* the tempfile cleanup, in case of temporary
3273 # history db
3273 # history db
3274 self.history_manager.end_session()
3274 self.history_manager.end_session()
3275
3275
3276 # Cleanup all tempfiles and folders left around
3276 # Cleanup all tempfiles and folders left around
3277 for tfile in self.tempfiles:
3277 for tfile in self.tempfiles:
3278 try:
3278 try:
3279 os.unlink(tfile)
3279 os.unlink(tfile)
3280 except OSError:
3280 except OSError:
3281 pass
3281 pass
3282
3282
3283 for tdir in self.tempdirs:
3283 for tdir in self.tempdirs:
3284 try:
3284 try:
3285 os.rmdir(tdir)
3285 os.rmdir(tdir)
3286 except OSError:
3286 except OSError:
3287 pass
3287 pass
3288
3288
3289 # Clear all user namespaces to release all references cleanly.
3289 # Clear all user namespaces to release all references cleanly.
3290 self.reset(new_session=False)
3290 self.reset(new_session=False)
3291
3291
3292 # Run user hooks
3292 # Run user hooks
3293 self.hooks.shutdown_hook()
3293 self.hooks.shutdown_hook()
3294
3294
3295 def cleanup(self):
3295 def cleanup(self):
3296 self.restore_sys_module_state()
3296 self.restore_sys_module_state()
3297
3297
3298
3298
3299 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3299 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3300 """An abstract base class for InteractiveShell."""
3300 """An abstract base class for InteractiveShell."""
3301
3301
3302 InteractiveShellABC.register(InteractiveShell)
3302 InteractiveShellABC.register(InteractiveShell)
@@ -1,653 +1,611 b''
1 """Implementation of basic magic functions.
1 """Implementation of basic magic functions."""
2 """
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 #-----------------------------------------------------------------------------
14 from __future__ import print_function
3 from __future__ import print_function
15
4
16 # Stdlib
17 import io
5 import io
18 import json
6 import json
19 import sys
7 import sys
20 from pprint import pformat
8 from pprint import pformat
21
9
22 # Our own packages
23 from IPython.core import magic_arguments, page
10 from IPython.core import magic_arguments, page
24 from IPython.core.error import UsageError
11 from IPython.core.error import UsageError
25 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
26 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.utils.text import format_screen, dedent, indent
27 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils.ipstruct import Struct
15 from IPython.utils.ipstruct import Struct
29 from IPython.utils.path import unquote_filename
16 from IPython.utils.path import unquote_filename
30 from IPython.utils.py3compat import unicode_type
17 from IPython.utils.py3compat import unicode_type
31 from IPython.utils.warn import warn, error
18 from IPython.utils.warn import warn, error
32
19
33 #-----------------------------------------------------------------------------
34 # Magics class implementation
35 #-----------------------------------------------------------------------------
36
20
37 class MagicsDisplay(object):
21 class MagicsDisplay(object):
38 def __init__(self, magics_manager):
22 def __init__(self, magics_manager):
39 self.magics_manager = magics_manager
23 self.magics_manager = magics_manager
40
24
41 def _lsmagic(self):
25 def _lsmagic(self):
42 """The main implementation of the %lsmagic"""
26 """The main implementation of the %lsmagic"""
43 mesc = magic_escapes['line']
27 mesc = magic_escapes['line']
44 cesc = magic_escapes['cell']
28 cesc = magic_escapes['cell']
45 mman = self.magics_manager
29 mman = self.magics_manager
46 magics = mman.lsmagic()
30 magics = mman.lsmagic()
47 out = ['Available line magics:',
31 out = ['Available line magics:',
48 mesc + (' '+mesc).join(sorted(magics['line'])),
32 mesc + (' '+mesc).join(sorted(magics['line'])),
49 '',
33 '',
50 'Available cell magics:',
34 'Available cell magics:',
51 cesc + (' '+cesc).join(sorted(magics['cell'])),
35 cesc + (' '+cesc).join(sorted(magics['cell'])),
52 '',
36 '',
53 mman.auto_status()]
37 mman.auto_status()]
54 return '\n'.join(out)
38 return '\n'.join(out)
55
39
56 def _repr_pretty_(self, p, cycle):
40 def _repr_pretty_(self, p, cycle):
57 p.text(self._lsmagic())
41 p.text(self._lsmagic())
58
42
59 def __str__(self):
43 def __str__(self):
60 return self._lsmagic()
44 return self._lsmagic()
61
45
62 def _jsonable(self):
46 def _jsonable(self):
63 """turn magics dict into jsonable dict of the same structure
47 """turn magics dict into jsonable dict of the same structure
64
48
65 replaces object instances with their class names as strings
49 replaces object instances with their class names as strings
66 """
50 """
67 magic_dict = {}
51 magic_dict = {}
68 mman = self.magics_manager
52 mman = self.magics_manager
69 magics = mman.lsmagic()
53 magics = mman.lsmagic()
70 for key, subdict in magics.items():
54 for key, subdict in magics.items():
71 d = {}
55 d = {}
72 magic_dict[key] = d
56 magic_dict[key] = d
73 for name, obj in subdict.items():
57 for name, obj in subdict.items():
74 try:
58 try:
75 classname = obj.__self__.__class__.__name__
59 classname = obj.__self__.__class__.__name__
76 except AttributeError:
60 except AttributeError:
77 classname = 'Other'
61 classname = 'Other'
78
62
79 d[name] = classname
63 d[name] = classname
80 return magic_dict
64 return magic_dict
81
65
82 def _repr_json_(self):
66 def _repr_json_(self):
83 return json.dumps(self._jsonable())
67 return json.dumps(self._jsonable())
84
68
85
69
86 @magics_class
70 @magics_class
87 class BasicMagics(Magics):
71 class BasicMagics(Magics):
88 """Magics that provide central IPython functionality.
72 """Magics that provide central IPython functionality.
89
73
90 These are various magics that don't fit into specific categories but that
74 These are various magics that don't fit into specific categories but that
91 are all part of the base 'IPython experience'."""
75 are all part of the base 'IPython experience'."""
92
76
93 @magic_arguments.magic_arguments()
77 @magic_arguments.magic_arguments()
94 @magic_arguments.argument(
78 @magic_arguments.argument(
95 '-l', '--line', action='store_true',
79 '-l', '--line', action='store_true',
96 help="""Create a line magic alias."""
80 help="""Create a line magic alias."""
97 )
81 )
98 @magic_arguments.argument(
82 @magic_arguments.argument(
99 '-c', '--cell', action='store_true',
83 '-c', '--cell', action='store_true',
100 help="""Create a cell magic alias."""
84 help="""Create a cell magic alias."""
101 )
85 )
102 @magic_arguments.argument(
86 @magic_arguments.argument(
103 'name',
87 'name',
104 help="""Name of the magic to be created."""
88 help="""Name of the magic to be created."""
105 )
89 )
106 @magic_arguments.argument(
90 @magic_arguments.argument(
107 'target',
91 'target',
108 help="""Name of the existing line or cell magic."""
92 help="""Name of the existing line or cell magic."""
109 )
93 )
110 @line_magic
94 @line_magic
111 def alias_magic(self, line=''):
95 def alias_magic(self, line=''):
112 """Create an alias for an existing line or cell magic.
96 """Create an alias for an existing line or cell magic.
113
97
114 Examples
98 Examples
115 --------
99 --------
116 ::
100 ::
117
101
118 In [1]: %alias_magic t timeit
102 In [1]: %alias_magic t timeit
119 Created `%t` as an alias for `%timeit`.
103 Created `%t` as an alias for `%timeit`.
120 Created `%%t` as an alias for `%%timeit`.
104 Created `%%t` as an alias for `%%timeit`.
121
105
122 In [2]: %t -n1 pass
106 In [2]: %t -n1 pass
123 1 loops, best of 3: 954 ns per loop
107 1 loops, best of 3: 954 ns per loop
124
108
125 In [3]: %%t -n1
109 In [3]: %%t -n1
126 ...: pass
110 ...: pass
127 ...:
111 ...:
128 1 loops, best of 3: 954 ns per loop
112 1 loops, best of 3: 954 ns per loop
129
113
130 In [4]: %alias_magic --cell whereami pwd
114 In [4]: %alias_magic --cell whereami pwd
131 UsageError: Cell magic function `%%pwd` not found.
115 UsageError: Cell magic function `%%pwd` not found.
132 In [5]: %alias_magic --line whereami pwd
116 In [5]: %alias_magic --line whereami pwd
133 Created `%whereami` as an alias for `%pwd`.
117 Created `%whereami` as an alias for `%pwd`.
134
118
135 In [6]: %whereami
119 In [6]: %whereami
136 Out[6]: u'/home/testuser'
120 Out[6]: u'/home/testuser'
137 """
121 """
138 args = magic_arguments.parse_argstring(self.alias_magic, line)
122 args = magic_arguments.parse_argstring(self.alias_magic, line)
139 shell = self.shell
123 shell = self.shell
140 mman = self.shell.magics_manager
124 mman = self.shell.magics_manager
141 escs = ''.join(magic_escapes.values())
125 escs = ''.join(magic_escapes.values())
142
126
143 target = args.target.lstrip(escs)
127 target = args.target.lstrip(escs)
144 name = args.name.lstrip(escs)
128 name = args.name.lstrip(escs)
145
129
146 # Find the requested magics.
130 # Find the requested magics.
147 m_line = shell.find_magic(target, 'line')
131 m_line = shell.find_magic(target, 'line')
148 m_cell = shell.find_magic(target, 'cell')
132 m_cell = shell.find_magic(target, 'cell')
149 if args.line and m_line is None:
133 if args.line and m_line is None:
150 raise UsageError('Line magic function `%s%s` not found.' %
134 raise UsageError('Line magic function `%s%s` not found.' %
151 (magic_escapes['line'], target))
135 (magic_escapes['line'], target))
152 if args.cell and m_cell is None:
136 if args.cell and m_cell is None:
153 raise UsageError('Cell magic function `%s%s` not found.' %
137 raise UsageError('Cell magic function `%s%s` not found.' %
154 (magic_escapes['cell'], target))
138 (magic_escapes['cell'], target))
155
139
156 # If --line and --cell are not specified, default to the ones
140 # If --line and --cell are not specified, default to the ones
157 # that are available.
141 # that are available.
158 if not args.line and not args.cell:
142 if not args.line and not args.cell:
159 if not m_line and not m_cell:
143 if not m_line and not m_cell:
160 raise UsageError(
144 raise UsageError(
161 'No line or cell magic with name `%s` found.' % target
145 'No line or cell magic with name `%s` found.' % target
162 )
146 )
163 args.line = bool(m_line)
147 args.line = bool(m_line)
164 args.cell = bool(m_cell)
148 args.cell = bool(m_cell)
165
149
166 if args.line:
150 if args.line:
167 mman.register_alias(name, target, 'line')
151 mman.register_alias(name, target, 'line')
168 print('Created `%s%s` as an alias for `%s%s`.' % (
152 print('Created `%s%s` as an alias for `%s%s`.' % (
169 magic_escapes['line'], name,
153 magic_escapes['line'], name,
170 magic_escapes['line'], target))
154 magic_escapes['line'], target))
171
155
172 if args.cell:
156 if args.cell:
173 mman.register_alias(name, target, 'cell')
157 mman.register_alias(name, target, 'cell')
174 print('Created `%s%s` as an alias for `%s%s`.' % (
158 print('Created `%s%s` as an alias for `%s%s`.' % (
175 magic_escapes['cell'], name,
159 magic_escapes['cell'], name,
176 magic_escapes['cell'], target))
160 magic_escapes['cell'], target))
177
161
178 @line_magic
162 @line_magic
179 def lsmagic(self, parameter_s=''):
163 def lsmagic(self, parameter_s=''):
180 """List currently available magic functions."""
164 """List currently available magic functions."""
181 return MagicsDisplay(self.shell.magics_manager)
165 return MagicsDisplay(self.shell.magics_manager)
182
166
183 def _magic_docs(self, brief=False, rest=False):
167 def _magic_docs(self, brief=False, rest=False):
184 """Return docstrings from magic functions."""
168 """Return docstrings from magic functions."""
185 mman = self.shell.magics_manager
169 mman = self.shell.magics_manager
186 docs = mman.lsmagic_docs(brief, missing='No documentation')
170 docs = mman.lsmagic_docs(brief, missing='No documentation')
187
171
188 if rest:
172 if rest:
189 format_string = '**%s%s**::\n\n%s\n\n'
173 format_string = '**%s%s**::\n\n%s\n\n'
190 else:
174 else:
191 format_string = '%s%s:\n%s\n'
175 format_string = '%s%s:\n%s\n'
192
176
193 return ''.join(
177 return ''.join(
194 [format_string % (magic_escapes['line'], fname,
178 [format_string % (magic_escapes['line'], fname,
195 indent(dedent(fndoc)))
179 indent(dedent(fndoc)))
196 for fname, fndoc in sorted(docs['line'].items())]
180 for fname, fndoc in sorted(docs['line'].items())]
197 +
181 +
198 [format_string % (magic_escapes['cell'], fname,
182 [format_string % (magic_escapes['cell'], fname,
199 indent(dedent(fndoc)))
183 indent(dedent(fndoc)))
200 for fname, fndoc in sorted(docs['cell'].items())]
184 for fname, fndoc in sorted(docs['cell'].items())]
201 )
185 )
202
186
203 @line_magic
187 @line_magic
204 def magic(self, parameter_s=''):
188 def magic(self, parameter_s=''):
205 """Print information about the magic function system.
189 """Print information about the magic function system.
206
190
207 Supported formats: -latex, -brief, -rest
191 Supported formats: -latex, -brief, -rest
208 """
192 """
209
193
210 mode = ''
194 mode = ''
211 try:
195 try:
212 mode = parameter_s.split()[0][1:]
196 mode = parameter_s.split()[0][1:]
213 if mode == 'rest':
197 if mode == 'rest':
214 rest_docs = []
198 rest_docs = []
215 except IndexError:
199 except IndexError:
216 pass
200 pass
217
201
218 brief = (mode == 'brief')
202 brief = (mode == 'brief')
219 rest = (mode == 'rest')
203 rest = (mode == 'rest')
220 magic_docs = self._magic_docs(brief, rest)
204 magic_docs = self._magic_docs(brief, rest)
221
205
222 if mode == 'latex':
206 if mode == 'latex':
223 print(self.format_latex(magic_docs))
207 print(self.format_latex(magic_docs))
224 return
208 return
225 else:
209 else:
226 magic_docs = format_screen(magic_docs)
210 magic_docs = format_screen(magic_docs)
227
211
228 out = ["""
212 out = ["""
229 IPython's 'magic' functions
213 IPython's 'magic' functions
230 ===========================
214 ===========================
231
215
232 The magic function system provides a series of functions which allow you to
216 The magic function system provides a series of functions which allow you to
233 control the behavior of IPython itself, plus a lot of system-type
217 control the behavior of IPython itself, plus a lot of system-type
234 features. There are two kinds of magics, line-oriented and cell-oriented.
218 features. There are two kinds of magics, line-oriented and cell-oriented.
235
219
236 Line magics are prefixed with the % character and work much like OS
220 Line magics are prefixed with the % character and work much like OS
237 command-line calls: they get as an argument the rest of the line, where
221 command-line calls: they get as an argument the rest of the line, where
238 arguments are passed without parentheses or quotes. For example, this will
222 arguments are passed without parentheses or quotes. For example, this will
239 time the given statement::
223 time the given statement::
240
224
241 %timeit range(1000)
225 %timeit range(1000)
242
226
243 Cell magics are prefixed with a double %%, and they are functions that get as
227 Cell magics are prefixed with a double %%, and they are functions that get as
244 an argument not only the rest of the line, but also the lines below it in a
228 an argument not only the rest of the line, but also the lines below it in a
245 separate argument. These magics are called with two arguments: the rest of the
229 separate argument. These magics are called with two arguments: the rest of the
246 call line and the body of the cell, consisting of the lines below the first.
230 call line and the body of the cell, consisting of the lines below the first.
247 For example::
231 For example::
248
232
249 %%timeit x = numpy.random.randn((100, 100))
233 %%timeit x = numpy.random.randn((100, 100))
250 numpy.linalg.svd(x)
234 numpy.linalg.svd(x)
251
235
252 will time the execution of the numpy svd routine, running the assignment of x
236 will time the execution of the numpy svd routine, running the assignment of x
253 as part of the setup phase, which is not timed.
237 as part of the setup phase, which is not timed.
254
238
255 In a line-oriented client (the terminal or Qt console IPython), starting a new
239 In a line-oriented client (the terminal or Qt console IPython), starting a new
256 input with %% will automatically enter cell mode, and IPython will continue
240 input with %% will automatically enter cell mode, and IPython will continue
257 reading input until a blank line is given. In the notebook, simply type the
241 reading input until a blank line is given. In the notebook, simply type the
258 whole cell as one entity, but keep in mind that the %% escape can only be at
242 whole cell as one entity, but keep in mind that the %% escape can only be at
259 the very start of the cell.
243 the very start of the cell.
260
244
261 NOTE: If you have 'automagic' enabled (via the command line option or with the
245 NOTE: If you have 'automagic' enabled (via the command line option or with the
262 %automagic function), you don't need to type in the % explicitly for line
246 %automagic function), you don't need to type in the % explicitly for line
263 magics; cell magics always require an explicit '%%' escape. By default,
247 magics; cell magics always require an explicit '%%' escape. By default,
264 IPython ships with automagic on, so you should only rarely need the % escape.
248 IPython ships with automagic on, so you should only rarely need the % escape.
265
249
266 Example: typing '%cd mydir' (without the quotes) changes you working directory
250 Example: typing '%cd mydir' (without the quotes) changes you working directory
267 to 'mydir', if it exists.
251 to 'mydir', if it exists.
268
252
269 For a list of the available magic functions, use %lsmagic. For a description
253 For a list of the available magic functions, use %lsmagic. For a description
270 of any of them, type %magic_name?, e.g. '%cd?'.
254 of any of them, type %magic_name?, e.g. '%cd?'.
271
255
272 Currently the magic system has the following functions:""",
256 Currently the magic system has the following functions:""",
273 magic_docs,
257 magic_docs,
274 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
258 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
275 str(self.lsmagic()),
259 str(self.lsmagic()),
276 ]
260 ]
277 page.page('\n'.join(out))
261 page.page('\n'.join(out))
278
262
279
263
280 @line_magic
264 @line_magic
281 def page(self, parameter_s=''):
265 def page(self, parameter_s=''):
282 """Pretty print the object and display it through a pager.
266 """Pretty print the object and display it through a pager.
283
267
284 %page [options] OBJECT
268 %page [options] OBJECT
285
269
286 If no object is given, use _ (last output).
270 If no object is given, use _ (last output).
287
271
288 Options:
272 Options:
289
273
290 -r: page str(object), don't pretty-print it."""
274 -r: page str(object), don't pretty-print it."""
291
275
292 # After a function contributed by Olivier Aubert, slightly modified.
276 # After a function contributed by Olivier Aubert, slightly modified.
293
277
294 # Process options/args
278 # Process options/args
295 opts, args = self.parse_options(parameter_s, 'r')
279 opts, args = self.parse_options(parameter_s, 'r')
296 raw = 'r' in opts
280 raw = 'r' in opts
297
281
298 oname = args and args or '_'
282 oname = args and args or '_'
299 info = self.shell._ofind(oname)
283 info = self.shell._ofind(oname)
300 if info['found']:
284 if info['found']:
301 txt = (raw and str or pformat)( info['obj'] )
285 txt = (raw and str or pformat)( info['obj'] )
302 page.page(txt)
286 page.page(txt)
303 else:
287 else:
304 print('Object `%s` not found' % oname)
288 print('Object `%s` not found' % oname)
305
289
306 @line_magic
290 @line_magic
307 def profile(self, parameter_s=''):
291 def profile(self, parameter_s=''):
308 """Print your currently active IPython profile.
292 """Print your currently active IPython profile.
309
293
310 See Also
294 See Also
311 --------
295 --------
312 prun : run code using the Python profiler
296 prun : run code using the Python profiler
313 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
297 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
314 """
298 """
315 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
299 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
316 from IPython.core.application import BaseIPythonApplication
300 from IPython.core.application import BaseIPythonApplication
317 if BaseIPythonApplication.initialized():
301 if BaseIPythonApplication.initialized():
318 print(BaseIPythonApplication.instance().profile)
302 print(BaseIPythonApplication.instance().profile)
319 else:
303 else:
320 error("profile is an application-level value, but you don't appear to be in an IPython application")
304 error("profile is an application-level value, but you don't appear to be in an IPython application")
321
305
322 @line_magic
306 @line_magic
323 def pprint(self, parameter_s=''):
307 def pprint(self, parameter_s=''):
324 """Toggle pretty printing on/off."""
308 """Toggle pretty printing on/off."""
325 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 ptformatter = self.shell.display_formatter.formatters['text/plain']
326 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 ptformatter.pprint = bool(1 - ptformatter.pprint)
327 print('Pretty printing has been turned',
311 print('Pretty printing has been turned',
328 ['OFF','ON'][ptformatter.pprint])
312 ['OFF','ON'][ptformatter.pprint])
329
313
330 @line_magic
314 @line_magic
331 def colors(self, parameter_s=''):
315 def colors(self, parameter_s=''):
332 """Switch color scheme for prompts, info system and exception handlers.
316 """Switch color scheme for prompts, info system and exception handlers.
333
317
334 Currently implemented schemes: NoColor, Linux, LightBG.
318 Currently implemented schemes: NoColor, Linux, LightBG.
335
319
336 Color scheme names are not case-sensitive.
320 Color scheme names are not case-sensitive.
337
321
338 Examples
322 Examples
339 --------
323 --------
340 To get a plain black and white terminal::
324 To get a plain black and white terminal::
341
325
342 %colors nocolor
326 %colors nocolor
343 """
327 """
344 def color_switch_err(name):
328 def color_switch_err(name):
345 warn('Error changing %s color schemes.\n%s' %
329 warn('Error changing %s color schemes.\n%s' %
346 (name, sys.exc_info()[1]))
330 (name, sys.exc_info()[1]))
347
331
348
332
349 new_scheme = parameter_s.strip()
333 new_scheme = parameter_s.strip()
350 if not new_scheme:
334 if not new_scheme:
351 raise UsageError(
335 raise UsageError(
352 "%colors: you must specify a color scheme. See '%colors?'")
336 "%colors: you must specify a color scheme. See '%colors?'")
353 # local shortcut
337 # local shortcut
354 shell = self.shell
338 shell = self.shell
355
339
356 import IPython.utils.rlineimpl as readline
340 import IPython.utils.rlineimpl as readline
357
341
358 if not shell.colors_force and \
342 if not shell.colors_force and \
359 not readline.have_readline and \
343 not readline.have_readline and \
360 (sys.platform == "win32" or sys.platform == "cli"):
344 (sys.platform == "win32" or sys.platform == "cli"):
361 msg = """\
345 msg = """\
362 Proper color support under MS Windows requires the pyreadline library.
346 Proper color support under MS Windows requires the pyreadline library.
363 You can find it at:
347 You can find it at:
364 http://ipython.org/pyreadline.html
348 http://ipython.org/pyreadline.html
365
349
366 Defaulting color scheme to 'NoColor'"""
350 Defaulting color scheme to 'NoColor'"""
367 new_scheme = 'NoColor'
351 new_scheme = 'NoColor'
368 warn(msg)
352 warn(msg)
369
353
370 # readline option is 0
354 # readline option is 0
371 if not shell.colors_force and not shell.has_readline:
355 if not shell.colors_force and not shell.has_readline:
372 new_scheme = 'NoColor'
356 new_scheme = 'NoColor'
373
357
374 # Set prompt colors
358 # Set prompt colors
375 try:
359 try:
376 shell.prompt_manager.color_scheme = new_scheme
360 shell.prompt_manager.color_scheme = new_scheme
377 except:
361 except:
378 color_switch_err('prompt')
362 color_switch_err('prompt')
379 else:
363 else:
380 shell.colors = \
364 shell.colors = \
381 shell.prompt_manager.color_scheme_table.active_scheme_name
365 shell.prompt_manager.color_scheme_table.active_scheme_name
382 # Set exception colors
366 # Set exception colors
383 try:
367 try:
384 shell.InteractiveTB.set_colors(scheme = new_scheme)
368 shell.InteractiveTB.set_colors(scheme = new_scheme)
385 shell.SyntaxTB.set_colors(scheme = new_scheme)
369 shell.SyntaxTB.set_colors(scheme = new_scheme)
386 except:
370 except:
387 color_switch_err('exception')
371 color_switch_err('exception')
388
372
389 # Set info (for 'object?') colors
373 # Set info (for 'object?') colors
390 if shell.color_info:
374 if shell.color_info:
391 try:
375 try:
392 shell.inspector.set_active_scheme(new_scheme)
376 shell.inspector.set_active_scheme(new_scheme)
393 except:
377 except:
394 color_switch_err('object inspector')
378 color_switch_err('object inspector')
395 else:
379 else:
396 shell.inspector.set_active_scheme('NoColor')
380 shell.inspector.set_active_scheme('NoColor')
397
381
398 @line_magic
382 @line_magic
399 def xmode(self, parameter_s=''):
383 def xmode(self, parameter_s=''):
400 """Switch modes for the exception handlers.
384 """Switch modes for the exception handlers.
401
385
402 Valid modes: Plain, Context and Verbose.
386 Valid modes: Plain, Context and Verbose.
403
387
404 If called without arguments, acts as a toggle."""
388 If called without arguments, acts as a toggle."""
405
389
406 def xmode_switch_err(name):
390 def xmode_switch_err(name):
407 warn('Error changing %s exception modes.\n%s' %
391 warn('Error changing %s exception modes.\n%s' %
408 (name,sys.exc_info()[1]))
392 (name,sys.exc_info()[1]))
409
393
410 shell = self.shell
394 shell = self.shell
411 new_mode = parameter_s.strip().capitalize()
395 new_mode = parameter_s.strip().capitalize()
412 try:
396 try:
413 shell.InteractiveTB.set_mode(mode=new_mode)
397 shell.InteractiveTB.set_mode(mode=new_mode)
414 print('Exception reporting mode:',shell.InteractiveTB.mode)
398 print('Exception reporting mode:',shell.InteractiveTB.mode)
415 except:
399 except:
416 xmode_switch_err('user')
400 xmode_switch_err('user')
417
401
418 @line_magic
402 @line_magic
419 def quickref(self,arg):
403 def quickref(self,arg):
420 """ Show a quick reference sheet """
404 """ Show a quick reference sheet """
421 from IPython.core.usage import quick_reference
405 from IPython.core.usage import quick_reference
422 qr = quick_reference + self._magic_docs(brief=True)
406 qr = quick_reference + self._magic_docs(brief=True)
423 page.page(qr)
407 page.page(qr)
424
408
425 @line_magic
409 @line_magic
426 def doctest_mode(self, parameter_s=''):
410 def doctest_mode(self, parameter_s=''):
427 """Toggle doctest mode on and off.
411 """Toggle doctest mode on and off.
428
412
429 This mode is intended to make IPython behave as much as possible like a
413 This mode is intended to make IPython behave as much as possible like a
430 plain Python shell, from the perspective of how its prompts, exceptions
414 plain Python shell, from the perspective of how its prompts, exceptions
431 and output look. This makes it easy to copy and paste parts of a
415 and output look. This makes it easy to copy and paste parts of a
432 session into doctests. It does so by:
416 session into doctests. It does so by:
433
417
434 - Changing the prompts to the classic ``>>>`` ones.
418 - Changing the prompts to the classic ``>>>`` ones.
435 - Changing the exception reporting mode to 'Plain'.
419 - Changing the exception reporting mode to 'Plain'.
436 - Disabling pretty-printing of output.
420 - Disabling pretty-printing of output.
437
421
438 Note that IPython also supports the pasting of code snippets that have
422 Note that IPython also supports the pasting of code snippets that have
439 leading '>>>' and '...' prompts in them. This means that you can paste
423 leading '>>>' and '...' prompts in them. This means that you can paste
440 doctests from files or docstrings (even if they have leading
424 doctests from files or docstrings (even if they have leading
441 whitespace), and the code will execute correctly. You can then use
425 whitespace), and the code will execute correctly. You can then use
442 '%history -t' to see the translated history; this will give you the
426 '%history -t' to see the translated history; this will give you the
443 input after removal of all the leading prompts and whitespace, which
427 input after removal of all the leading prompts and whitespace, which
444 can be pasted back into an editor.
428 can be pasted back into an editor.
445
429
446 With these features, you can switch into this mode easily whenever you
430 With these features, you can switch into this mode easily whenever you
447 need to do testing and changes to doctests, without having to leave
431 need to do testing and changes to doctests, without having to leave
448 your existing IPython session.
432 your existing IPython session.
449 """
433 """
450
434
451 # Shorthands
435 # Shorthands
452 shell = self.shell
436 shell = self.shell
453 pm = shell.prompt_manager
437 pm = shell.prompt_manager
454 meta = shell.meta
438 meta = shell.meta
455 disp_formatter = self.shell.display_formatter
439 disp_formatter = self.shell.display_formatter
456 ptformatter = disp_formatter.formatters['text/plain']
440 ptformatter = disp_formatter.formatters['text/plain']
457 # dstore is a data store kept in the instance metadata bag to track any
441 # dstore is a data store kept in the instance metadata bag to track any
458 # changes we make, so we can undo them later.
442 # changes we make, so we can undo them later.
459 dstore = meta.setdefault('doctest_mode',Struct())
443 dstore = meta.setdefault('doctest_mode',Struct())
460 save_dstore = dstore.setdefault
444 save_dstore = dstore.setdefault
461
445
462 # save a few values we'll need to recover later
446 # save a few values we'll need to recover later
463 mode = save_dstore('mode',False)
447 mode = save_dstore('mode',False)
464 save_dstore('rc_pprint',ptformatter.pprint)
448 save_dstore('rc_pprint',ptformatter.pprint)
465 save_dstore('xmode',shell.InteractiveTB.mode)
449 save_dstore('xmode',shell.InteractiveTB.mode)
466 save_dstore('rc_separate_out',shell.separate_out)
450 save_dstore('rc_separate_out',shell.separate_out)
467 save_dstore('rc_separate_out2',shell.separate_out2)
451 save_dstore('rc_separate_out2',shell.separate_out2)
468 save_dstore('rc_prompts_pad_left',pm.justify)
452 save_dstore('rc_prompts_pad_left',pm.justify)
469 save_dstore('rc_separate_in',shell.separate_in)
453 save_dstore('rc_separate_in',shell.separate_in)
470 save_dstore('rc_active_types',disp_formatter.active_types)
454 save_dstore('rc_active_types',disp_formatter.active_types)
471 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
455 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
472
456
473 if mode == False:
457 if mode == False:
474 # turn on
458 # turn on
475 pm.in_template = '>>> '
459 pm.in_template = '>>> '
476 pm.in2_template = '... '
460 pm.in2_template = '... '
477 pm.out_template = ''
461 pm.out_template = ''
478
462
479 # Prompt separators like plain python
463 # Prompt separators like plain python
480 shell.separate_in = ''
464 shell.separate_in = ''
481 shell.separate_out = ''
465 shell.separate_out = ''
482 shell.separate_out2 = ''
466 shell.separate_out2 = ''
483
467
484 pm.justify = False
468 pm.justify = False
485
469
486 ptformatter.pprint = False
470 ptformatter.pprint = False
487 disp_formatter.active_types = ['text/plain']
471 disp_formatter.active_types = ['text/plain']
488
472
489 shell.magic('xmode Plain')
473 shell.magic('xmode Plain')
490 else:
474 else:
491 # turn off
475 # turn off
492 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
476 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
493
477
494 shell.separate_in = dstore.rc_separate_in
478 shell.separate_in = dstore.rc_separate_in
495
479
496 shell.separate_out = dstore.rc_separate_out
480 shell.separate_out = dstore.rc_separate_out
497 shell.separate_out2 = dstore.rc_separate_out2
481 shell.separate_out2 = dstore.rc_separate_out2
498
482
499 pm.justify = dstore.rc_prompts_pad_left
483 pm.justify = dstore.rc_prompts_pad_left
500
484
501 ptformatter.pprint = dstore.rc_pprint
485 ptformatter.pprint = dstore.rc_pprint
502 disp_formatter.active_types = dstore.rc_active_types
486 disp_formatter.active_types = dstore.rc_active_types
503
487
504 shell.magic('xmode ' + dstore.xmode)
488 shell.magic('xmode ' + dstore.xmode)
505
489
506 # Store new mode and inform
490 # Store new mode and inform
507 dstore.mode = bool(1-int(mode))
491 dstore.mode = bool(1-int(mode))
508 mode_label = ['OFF','ON'][dstore.mode]
492 mode_label = ['OFF','ON'][dstore.mode]
509 print('Doctest mode is:', mode_label)
493 print('Doctest mode is:', mode_label)
510
494
511 @line_magic
495 @line_magic
512 def gui(self, parameter_s=''):
496 def gui(self, parameter_s=''):
513 """Enable or disable IPython GUI event loop integration.
497 """Enable or disable IPython GUI event loop integration.
514
498
515 %gui [GUINAME]
499 %gui [GUINAME]
516
500
517 This magic replaces IPython's threaded shells that were activated
501 This magic replaces IPython's threaded shells that were activated
518 using the (pylab/wthread/etc.) command line flags. GUI toolkits
502 using the (pylab/wthread/etc.) command line flags. GUI toolkits
519 can now be enabled at runtime and keyboard
503 can now be enabled at runtime and keyboard
520 interrupts should work without any problems. The following toolkits
504 interrupts should work without any problems. The following toolkits
521 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
505 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
522
506
523 %gui wx # enable wxPython event loop integration
507 %gui wx # enable wxPython event loop integration
524 %gui qt4|qt # enable PyQt4 event loop integration
508 %gui qt4|qt # enable PyQt4 event loop integration
525 %gui qt5 # enable PyQt5 event loop integration
509 %gui qt5 # enable PyQt5 event loop integration
526 %gui gtk # enable PyGTK event loop integration
510 %gui gtk # enable PyGTK event loop integration
527 %gui gtk3 # enable Gtk3 event loop integration
511 %gui gtk3 # enable Gtk3 event loop integration
528 %gui tk # enable Tk event loop integration
512 %gui tk # enable Tk event loop integration
529 %gui osx # enable Cocoa event loop integration
513 %gui osx # enable Cocoa event loop integration
530 # (requires %matplotlib 1.1)
514 # (requires %matplotlib 1.1)
531 %gui # disable all event loop integration
515 %gui # disable all event loop integration
532
516
533 WARNING: after any of these has been called you can simply create
517 WARNING: after any of these has been called you can simply create
534 an application object, but DO NOT start the event loop yourself, as
518 an application object, but DO NOT start the event loop yourself, as
535 we have already handled that.
519 we have already handled that.
536 """
520 """
537 opts, arg = self.parse_options(parameter_s, '')
521 opts, arg = self.parse_options(parameter_s, '')
538 if arg=='': arg = None
522 if arg=='': arg = None
539 try:
523 try:
540 return self.shell.enable_gui(arg)
524 return self.shell.enable_gui(arg)
541 except Exception as e:
525 except Exception as e:
542 # print simple error message, rather than traceback if we can't
526 # print simple error message, rather than traceback if we can't
543 # hook up the GUI
527 # hook up the GUI
544 error(str(e))
528 error(str(e))
545
529
546 @skip_doctest
530 @skip_doctest
547 @line_magic
531 @line_magic
548 def precision(self, s=''):
532 def precision(self, s=''):
549 """Set floating point precision for pretty printing.
533 """Set floating point precision for pretty printing.
550
534
551 Can set either integer precision or a format string.
535 Can set either integer precision or a format string.
552
536
553 If numpy has been imported and precision is an int,
537 If numpy has been imported and precision is an int,
554 numpy display precision will also be set, via ``numpy.set_printoptions``.
538 numpy display precision will also be set, via ``numpy.set_printoptions``.
555
539
556 If no argument is given, defaults will be restored.
540 If no argument is given, defaults will be restored.
557
541
558 Examples
542 Examples
559 --------
543 --------
560 ::
544 ::
561
545
562 In [1]: from math import pi
546 In [1]: from math import pi
563
547
564 In [2]: %precision 3
548 In [2]: %precision 3
565 Out[2]: u'%.3f'
549 Out[2]: u'%.3f'
566
550
567 In [3]: pi
551 In [3]: pi
568 Out[3]: 3.142
552 Out[3]: 3.142
569
553
570 In [4]: %precision %i
554 In [4]: %precision %i
571 Out[4]: u'%i'
555 Out[4]: u'%i'
572
556
573 In [5]: pi
557 In [5]: pi
574 Out[5]: 3
558 Out[5]: 3
575
559
576 In [6]: %precision %e
560 In [6]: %precision %e
577 Out[6]: u'%e'
561 Out[6]: u'%e'
578
562
579 In [7]: pi**10
563 In [7]: pi**10
580 Out[7]: 9.364805e+04
564 Out[7]: 9.364805e+04
581
565
582 In [8]: %precision
566 In [8]: %precision
583 Out[8]: u'%r'
567 Out[8]: u'%r'
584
568
585 In [9]: pi**10
569 In [9]: pi**10
586 Out[9]: 93648.047476082982
570 Out[9]: 93648.047476082982
587 """
571 """
588 ptformatter = self.shell.display_formatter.formatters['text/plain']
572 ptformatter = self.shell.display_formatter.formatters['text/plain']
589 ptformatter.float_precision = s
573 ptformatter.float_precision = s
590 return ptformatter.float_format
574 return ptformatter.float_format
591
575
592 @magic_arguments.magic_arguments()
576 @magic_arguments.magic_arguments()
593 @magic_arguments.argument(
577 @magic_arguments.argument(
594 '-e', '--export', action='store_true', default=False,
578 '-e', '--export', action='store_true', default=False,
595 help='Export IPython history as a notebook. The filename argument '
579 help='Export IPython history as a notebook. The filename argument '
596 'is used to specify the notebook name and format. For example '
580 'is used to specify the notebook name and format. For example '
597 'a filename of notebook.ipynb will result in a notebook name '
581 'a filename of notebook.ipynb will result in a notebook name '
598 'of "notebook" and a format of "json". Likewise using a ".py" '
582 'of "notebook" and a format of "json". Likewise using a ".py" '
599 'file extension will write the notebook as a Python script'
583 'file extension will write the notebook as a Python script'
600 )
584 )
601 @magic_arguments.argument(
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 'filename', type=unicode_type,
586 'filename', type=unicode_type,
610 help='Notebook name or filename'
587 help='Notebook name or filename'
611 )
588 )
612 @line_magic
589 @line_magic
613 def notebook(self, s):
590 def notebook(self, s):
614 """Export and convert IPython notebooks.
591 """Export and convert IPython notebooks.
615
592
616 This function can export the current IPython history to a notebook file
593 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
594 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
618 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".
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).
622 """
596 """
623 args = magic_arguments.parse_argstring(self.notebook, s)
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 args.filename = unquote_filename(args.filename)
600 args.filename = unquote_filename(args.filename)
627 if args.export:
601 if args.export:
628 fname, name, format = current.parse_filename(args.filename)
629 cells = []
602 cells = []
630 hist = list(self.shell.history_manager.get_range())
603 hist = list(self.shell.history_manager.get_range())
631 for session, prompt_number, input in hist[:-1]:
604 for session, execution_count, input in hist[:-1]:
632 cells.append(current.new_code_cell(prompt_number=prompt_number,
605 cells.append(v4.new_code_cell(
633 input=input))
606 execution_count=execution_count,
634 worksheet = current.new_worksheet(cells=cells)
607 source=source
635 nb = current.new_notebook(name=name,worksheets=[worksheet])
608 ))
636 with io.open(fname, 'w', encoding='utf-8') as f:
609 nb = v4.new_notebook(cells=cells)
637 current.write(nb, f, format);
610 with io.open(args.filename, 'w', encoding='utf-8') as f:
638 elif args.format is not None:
611 write(nb, f, version=4)
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)
@@ -1,991 +1,955 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions.
2 """Tests for various magic functions.
3
3
4 Needs to be run by nose (to make ipython session available).
4 Needs to be run by nose (to make ipython session available).
5 """
5 """
6 from __future__ import absolute_import
6 from __future__ import absolute_import
7
7
8 #-----------------------------------------------------------------------------
9 # Imports
10 #-----------------------------------------------------------------------------
11
12 import io
8 import io
13 import os
9 import os
14 import sys
10 import sys
15 from unittest import TestCase, skipIf
11 from unittest import TestCase, skipIf
16
12
17 try:
13 try:
18 from importlib import invalidate_caches # Required from Python 3.3
14 from importlib import invalidate_caches # Required from Python 3.3
19 except ImportError:
15 except ImportError:
20 def invalidate_caches():
16 def invalidate_caches():
21 pass
17 pass
22
18
23 import nose.tools as nt
19 import nose.tools as nt
24
20
25 from IPython.core import magic
21 from IPython.core import magic
26 from IPython.core.magic import (Magics, magics_class, line_magic,
22 from IPython.core.magic import (Magics, magics_class, line_magic,
27 cell_magic, line_cell_magic,
23 cell_magic, line_cell_magic,
28 register_line_magic, register_cell_magic,
24 register_line_magic, register_cell_magic,
29 register_line_cell_magic)
25 register_line_cell_magic)
30 from IPython.core.magics import execution, script, code
26 from IPython.core.magics import execution, script, code
31 from IPython.testing import decorators as dec
27 from IPython.testing import decorators as dec
32 from IPython.testing import tools as tt
28 from IPython.testing import tools as tt
33 from IPython.utils import py3compat
29 from IPython.utils import py3compat
34 from IPython.utils.io import capture_output
30 from IPython.utils.io import capture_output
35 from IPython.utils.tempdir import TemporaryDirectory
31 from IPython.utils.tempdir import TemporaryDirectory
36 from IPython.utils.process import find_cmd
32 from IPython.utils.process import find_cmd
37
33
38 if py3compat.PY3:
34 if py3compat.PY3:
39 from io import StringIO
35 from io import StringIO
40 else:
36 else:
41 from StringIO import StringIO
37 from StringIO import StringIO
42
38
43 #-----------------------------------------------------------------------------
44 # Test functions begin
45 #-----------------------------------------------------------------------------
46
39
47 @magic.magics_class
40 @magic.magics_class
48 class DummyMagics(magic.Magics): pass
41 class DummyMagics(magic.Magics): pass
49
42
50 def test_extract_code_ranges():
43 def test_extract_code_ranges():
51 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
44 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
52 expected = [(0, 1),
45 expected = [(0, 1),
53 (2, 3),
46 (2, 3),
54 (4, 6),
47 (4, 6),
55 (6, 9),
48 (6, 9),
56 (9, 14),
49 (9, 14),
57 (16, None),
50 (16, None),
58 (None, 9),
51 (None, 9),
59 (9, None),
52 (9, None),
60 (None, 13),
53 (None, 13),
61 (None, None)]
54 (None, None)]
62 actual = list(code.extract_code_ranges(instr))
55 actual = list(code.extract_code_ranges(instr))
63 nt.assert_equal(actual, expected)
56 nt.assert_equal(actual, expected)
64
57
65 def test_extract_symbols():
58 def test_extract_symbols():
66 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
59 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
67 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
60 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
68 expected = [([], ['a']),
61 expected = [([], ['a']),
69 (["def b():\n return 42\n"], []),
62 (["def b():\n return 42\n"], []),
70 (["class A: pass\n"], []),
63 (["class A: pass\n"], []),
71 (["class A: pass\n", "def b():\n return 42\n"], []),
64 (["class A: pass\n", "def b():\n return 42\n"], []),
72 (["class A: pass\n"], ['a']),
65 (["class A: pass\n"], ['a']),
73 ([], ['z'])]
66 ([], ['z'])]
74 for symbols, exp in zip(symbols_args, expected):
67 for symbols, exp in zip(symbols_args, expected):
75 nt.assert_equal(code.extract_symbols(source, symbols), exp)
68 nt.assert_equal(code.extract_symbols(source, symbols), exp)
76
69
77
70
78 def test_extract_symbols_raises_exception_with_non_python_code():
71 def test_extract_symbols_raises_exception_with_non_python_code():
79 source = ("=begin A Ruby program :)=end\n"
72 source = ("=begin A Ruby program :)=end\n"
80 "def hello\n"
73 "def hello\n"
81 "puts 'Hello world'\n"
74 "puts 'Hello world'\n"
82 "end")
75 "end")
83 with nt.assert_raises(SyntaxError):
76 with nt.assert_raises(SyntaxError):
84 code.extract_symbols(source, "hello")
77 code.extract_symbols(source, "hello")
85
78
86 def test_config():
79 def test_config():
87 """ test that config magic does not raise
80 """ test that config magic does not raise
88 can happen if Configurable init is moved too early into
81 can happen if Configurable init is moved too early into
89 Magics.__init__ as then a Config object will be registerd as a
82 Magics.__init__ as then a Config object will be registerd as a
90 magic.
83 magic.
91 """
84 """
92 ## should not raise.
85 ## should not raise.
93 _ip.magic('config')
86 _ip.magic('config')
94
87
95 def test_rehashx():
88 def test_rehashx():
96 # clear up everything
89 # clear up everything
97 _ip = get_ipython()
90 _ip = get_ipython()
98 _ip.alias_manager.clear_aliases()
91 _ip.alias_manager.clear_aliases()
99 del _ip.db['syscmdlist']
92 del _ip.db['syscmdlist']
100
93
101 _ip.magic('rehashx')
94 _ip.magic('rehashx')
102 # Practically ALL ipython development systems will have more than 10 aliases
95 # Practically ALL ipython development systems will have more than 10 aliases
103
96
104 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
97 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
105 for name, cmd in _ip.alias_manager.aliases:
98 for name, cmd in _ip.alias_manager.aliases:
106 # we must strip dots from alias names
99 # we must strip dots from alias names
107 nt.assert_not_in('.', name)
100 nt.assert_not_in('.', name)
108
101
109 # rehashx must fill up syscmdlist
102 # rehashx must fill up syscmdlist
110 scoms = _ip.db['syscmdlist']
103 scoms = _ip.db['syscmdlist']
111 nt.assert_true(len(scoms) > 10)
104 nt.assert_true(len(scoms) > 10)
112
105
113
106
114 def test_magic_parse_options():
107 def test_magic_parse_options():
115 """Test that we don't mangle paths when parsing magic options."""
108 """Test that we don't mangle paths when parsing magic options."""
116 ip = get_ipython()
109 ip = get_ipython()
117 path = 'c:\\x'
110 path = 'c:\\x'
118 m = DummyMagics(ip)
111 m = DummyMagics(ip)
119 opts = m.parse_options('-f %s' % path,'f:')[0]
112 opts = m.parse_options('-f %s' % path,'f:')[0]
120 # argv splitting is os-dependent
113 # argv splitting is os-dependent
121 if os.name == 'posix':
114 if os.name == 'posix':
122 expected = 'c:x'
115 expected = 'c:x'
123 else:
116 else:
124 expected = path
117 expected = path
125 nt.assert_equal(opts['f'], expected)
118 nt.assert_equal(opts['f'], expected)
126
119
127 def test_magic_parse_long_options():
120 def test_magic_parse_long_options():
128 """Magic.parse_options can handle --foo=bar long options"""
121 """Magic.parse_options can handle --foo=bar long options"""
129 ip = get_ipython()
122 ip = get_ipython()
130 m = DummyMagics(ip)
123 m = DummyMagics(ip)
131 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
124 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
132 nt.assert_in('foo', opts)
125 nt.assert_in('foo', opts)
133 nt.assert_in('bar', opts)
126 nt.assert_in('bar', opts)
134 nt.assert_equal(opts['bar'], "bubble")
127 nt.assert_equal(opts['bar'], "bubble")
135
128
136
129
137 @dec.skip_without('sqlite3')
130 @dec.skip_without('sqlite3')
138 def doctest_hist_f():
131 def doctest_hist_f():
139 """Test %hist -f with temporary filename.
132 """Test %hist -f with temporary filename.
140
133
141 In [9]: import tempfile
134 In [9]: import tempfile
142
135
143 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
136 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
144
137
145 In [11]: %hist -nl -f $tfile 3
138 In [11]: %hist -nl -f $tfile 3
146
139
147 In [13]: import os; os.unlink(tfile)
140 In [13]: import os; os.unlink(tfile)
148 """
141 """
149
142
150
143
151 @dec.skip_without('sqlite3')
144 @dec.skip_without('sqlite3')
152 def doctest_hist_r():
145 def doctest_hist_r():
153 """Test %hist -r
146 """Test %hist -r
154
147
155 XXX - This test is not recording the output correctly. For some reason, in
148 XXX - This test is not recording the output correctly. For some reason, in
156 testing mode the raw history isn't getting populated. No idea why.
149 testing mode the raw history isn't getting populated. No idea why.
157 Disabling the output checking for now, though at least we do run it.
150 Disabling the output checking for now, though at least we do run it.
158
151
159 In [1]: 'hist' in _ip.lsmagic()
152 In [1]: 'hist' in _ip.lsmagic()
160 Out[1]: True
153 Out[1]: True
161
154
162 In [2]: x=1
155 In [2]: x=1
163
156
164 In [3]: %hist -rl 2
157 In [3]: %hist -rl 2
165 x=1 # random
158 x=1 # random
166 %hist -r 2
159 %hist -r 2
167 """
160 """
168
161
169
162
170 @dec.skip_without('sqlite3')
163 @dec.skip_without('sqlite3')
171 def doctest_hist_op():
164 def doctest_hist_op():
172 """Test %hist -op
165 """Test %hist -op
173
166
174 In [1]: class b(float):
167 In [1]: class b(float):
175 ...: pass
168 ...: pass
176 ...:
169 ...:
177
170
178 In [2]: class s(object):
171 In [2]: class s(object):
179 ...: def __str__(self):
172 ...: def __str__(self):
180 ...: return 's'
173 ...: return 's'
181 ...:
174 ...:
182
175
183 In [3]:
176 In [3]:
184
177
185 In [4]: class r(b):
178 In [4]: class r(b):
186 ...: def __repr__(self):
179 ...: def __repr__(self):
187 ...: return 'r'
180 ...: return 'r'
188 ...:
181 ...:
189
182
190 In [5]: class sr(s,r): pass
183 In [5]: class sr(s,r): pass
191 ...:
184 ...:
192
185
193 In [6]:
186 In [6]:
194
187
195 In [7]: bb=b()
188 In [7]: bb=b()
196
189
197 In [8]: ss=s()
190 In [8]: ss=s()
198
191
199 In [9]: rr=r()
192 In [9]: rr=r()
200
193
201 In [10]: ssrr=sr()
194 In [10]: ssrr=sr()
202
195
203 In [11]: 4.5
196 In [11]: 4.5
204 Out[11]: 4.5
197 Out[11]: 4.5
205
198
206 In [12]: str(ss)
199 In [12]: str(ss)
207 Out[12]: 's'
200 Out[12]: 's'
208
201
209 In [13]:
202 In [13]:
210
203
211 In [14]: %hist -op
204 In [14]: %hist -op
212 >>> class b:
205 >>> class b:
213 ... pass
206 ... pass
214 ...
207 ...
215 >>> class s(b):
208 >>> class s(b):
216 ... def __str__(self):
209 ... def __str__(self):
217 ... return 's'
210 ... return 's'
218 ...
211 ...
219 >>>
212 >>>
220 >>> class r(b):
213 >>> class r(b):
221 ... def __repr__(self):
214 ... def __repr__(self):
222 ... return 'r'
215 ... return 'r'
223 ...
216 ...
224 >>> class sr(s,r): pass
217 >>> class sr(s,r): pass
225 >>>
218 >>>
226 >>> bb=b()
219 >>> bb=b()
227 >>> ss=s()
220 >>> ss=s()
228 >>> rr=r()
221 >>> rr=r()
229 >>> ssrr=sr()
222 >>> ssrr=sr()
230 >>> 4.5
223 >>> 4.5
231 4.5
224 4.5
232 >>> str(ss)
225 >>> str(ss)
233 's'
226 's'
234 >>>
227 >>>
235 """
228 """
236
229
237 def test_hist_pof():
230 def test_hist_pof():
238 ip = get_ipython()
231 ip = get_ipython()
239 ip.run_cell(u"1+2", store_history=True)
232 ip.run_cell(u"1+2", store_history=True)
240 #raise Exception(ip.history_manager.session_number)
233 #raise Exception(ip.history_manager.session_number)
241 #raise Exception(list(ip.history_manager._get_range_session()))
234 #raise Exception(list(ip.history_manager._get_range_session()))
242 with TemporaryDirectory() as td:
235 with TemporaryDirectory() as td:
243 tf = os.path.join(td, 'hist.py')
236 tf = os.path.join(td, 'hist.py')
244 ip.run_line_magic('history', '-pof %s' % tf)
237 ip.run_line_magic('history', '-pof %s' % tf)
245 assert os.path.isfile(tf)
238 assert os.path.isfile(tf)
246
239
247
240
248 @dec.skip_without('sqlite3')
241 @dec.skip_without('sqlite3')
249 def test_macro():
242 def test_macro():
250 ip = get_ipython()
243 ip = get_ipython()
251 ip.history_manager.reset() # Clear any existing history.
244 ip.history_manager.reset() # Clear any existing history.
252 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
245 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
253 for i, cmd in enumerate(cmds, start=1):
246 for i, cmd in enumerate(cmds, start=1):
254 ip.history_manager.store_inputs(i, cmd)
247 ip.history_manager.store_inputs(i, cmd)
255 ip.magic("macro test 1-3")
248 ip.magic("macro test 1-3")
256 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
249 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
257
250
258 # List macros
251 # List macros
259 nt.assert_in("test", ip.magic("macro"))
252 nt.assert_in("test", ip.magic("macro"))
260
253
261
254
262 @dec.skip_without('sqlite3')
255 @dec.skip_without('sqlite3')
263 def test_macro_run():
256 def test_macro_run():
264 """Test that we can run a multi-line macro successfully."""
257 """Test that we can run a multi-line macro successfully."""
265 ip = get_ipython()
258 ip = get_ipython()
266 ip.history_manager.reset()
259 ip.history_manager.reset()
267 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
260 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
268 "%macro test 2-3"]
261 "%macro test 2-3"]
269 for cmd in cmds:
262 for cmd in cmds:
270 ip.run_cell(cmd, store_history=True)
263 ip.run_cell(cmd, store_history=True)
271 nt.assert_equal(ip.user_ns["test"].value,
264 nt.assert_equal(ip.user_ns["test"].value,
272 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
265 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
273 with tt.AssertPrints("12"):
266 with tt.AssertPrints("12"):
274 ip.run_cell("test")
267 ip.run_cell("test")
275 with tt.AssertPrints("13"):
268 with tt.AssertPrints("13"):
276 ip.run_cell("test")
269 ip.run_cell("test")
277
270
278
271
279 def test_magic_magic():
272 def test_magic_magic():
280 """Test %magic"""
273 """Test %magic"""
281 ip = get_ipython()
274 ip = get_ipython()
282 with capture_output() as captured:
275 with capture_output() as captured:
283 ip.magic("magic")
276 ip.magic("magic")
284
277
285 stdout = captured.stdout
278 stdout = captured.stdout
286 nt.assert_in('%magic', stdout)
279 nt.assert_in('%magic', stdout)
287 nt.assert_in('IPython', stdout)
280 nt.assert_in('IPython', stdout)
288 nt.assert_in('Available', stdout)
281 nt.assert_in('Available', stdout)
289
282
290
283
291 @dec.skipif_not_numpy
284 @dec.skipif_not_numpy
292 def test_numpy_reset_array_undec():
285 def test_numpy_reset_array_undec():
293 "Test '%reset array' functionality"
286 "Test '%reset array' functionality"
294 _ip.ex('import numpy as np')
287 _ip.ex('import numpy as np')
295 _ip.ex('a = np.empty(2)')
288 _ip.ex('a = np.empty(2)')
296 nt.assert_in('a', _ip.user_ns)
289 nt.assert_in('a', _ip.user_ns)
297 _ip.magic('reset -f array')
290 _ip.magic('reset -f array')
298 nt.assert_not_in('a', _ip.user_ns)
291 nt.assert_not_in('a', _ip.user_ns)
299
292
300 def test_reset_out():
293 def test_reset_out():
301 "Test '%reset out' magic"
294 "Test '%reset out' magic"
302 _ip.run_cell("parrot = 'dead'", store_history=True)
295 _ip.run_cell("parrot = 'dead'", store_history=True)
303 # test '%reset -f out', make an Out prompt
296 # test '%reset -f out', make an Out prompt
304 _ip.run_cell("parrot", store_history=True)
297 _ip.run_cell("parrot", store_history=True)
305 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
298 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
306 _ip.magic('reset -f out')
299 _ip.magic('reset -f out')
307 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
300 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
308 nt.assert_equal(len(_ip.user_ns['Out']), 0)
301 nt.assert_equal(len(_ip.user_ns['Out']), 0)
309
302
310 def test_reset_in():
303 def test_reset_in():
311 "Test '%reset in' magic"
304 "Test '%reset in' magic"
312 # test '%reset -f in'
305 # test '%reset -f in'
313 _ip.run_cell("parrot", store_history=True)
306 _ip.run_cell("parrot", store_history=True)
314 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
307 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
315 _ip.magic('%reset -f in')
308 _ip.magic('%reset -f in')
316 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
309 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
317 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
310 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
318
311
319 def test_reset_dhist():
312 def test_reset_dhist():
320 "Test '%reset dhist' magic"
313 "Test '%reset dhist' magic"
321 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
314 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
322 _ip.magic('cd ' + os.path.dirname(nt.__file__))
315 _ip.magic('cd ' + os.path.dirname(nt.__file__))
323 _ip.magic('cd -')
316 _ip.magic('cd -')
324 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
317 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
325 _ip.magic('reset -f dhist')
318 _ip.magic('reset -f dhist')
326 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
319 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
327 _ip.run_cell("_dh = [d for d in tmp]") #restore
320 _ip.run_cell("_dh = [d for d in tmp]") #restore
328
321
329 def test_reset_in_length():
322 def test_reset_in_length():
330 "Test that '%reset in' preserves In[] length"
323 "Test that '%reset in' preserves In[] length"
331 _ip.run_cell("print 'foo'")
324 _ip.run_cell("print 'foo'")
332 _ip.run_cell("reset -f in")
325 _ip.run_cell("reset -f in")
333 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
326 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
334
327
335 def test_tb_syntaxerror():
328 def test_tb_syntaxerror():
336 """test %tb after a SyntaxError"""
329 """test %tb after a SyntaxError"""
337 ip = get_ipython()
330 ip = get_ipython()
338 ip.run_cell("for")
331 ip.run_cell("for")
339
332
340 # trap and validate stdout
333 # trap and validate stdout
341 save_stdout = sys.stdout
334 save_stdout = sys.stdout
342 try:
335 try:
343 sys.stdout = StringIO()
336 sys.stdout = StringIO()
344 ip.run_cell("%tb")
337 ip.run_cell("%tb")
345 out = sys.stdout.getvalue()
338 out = sys.stdout.getvalue()
346 finally:
339 finally:
347 sys.stdout = save_stdout
340 sys.stdout = save_stdout
348 # trim output, and only check the last line
341 # trim output, and only check the last line
349 last_line = out.rstrip().splitlines()[-1].strip()
342 last_line = out.rstrip().splitlines()[-1].strip()
350 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
343 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
351
344
352
345
353 def test_time():
346 def test_time():
354 ip = get_ipython()
347 ip = get_ipython()
355
348
356 with tt.AssertPrints("Wall time: "):
349 with tt.AssertPrints("Wall time: "):
357 ip.run_cell("%time None")
350 ip.run_cell("%time None")
358
351
359 ip.run_cell("def f(kmjy):\n"
352 ip.run_cell("def f(kmjy):\n"
360 " %time print (2*kmjy)")
353 " %time print (2*kmjy)")
361
354
362 with tt.AssertPrints("Wall time: "):
355 with tt.AssertPrints("Wall time: "):
363 with tt.AssertPrints("hihi", suppress=False):
356 with tt.AssertPrints("hihi", suppress=False):
364 ip.run_cell("f('hi')")
357 ip.run_cell("f('hi')")
365
358
366
359
367 @dec.skip_win32
360 @dec.skip_win32
368 def test_time2():
361 def test_time2():
369 ip = get_ipython()
362 ip = get_ipython()
370
363
371 with tt.AssertPrints("CPU times: user "):
364 with tt.AssertPrints("CPU times: user "):
372 ip.run_cell("%time None")
365 ip.run_cell("%time None")
373
366
374 def test_time3():
367 def test_time3():
375 """Erroneous magic function calls, issue gh-3334"""
368 """Erroneous magic function calls, issue gh-3334"""
376 ip = get_ipython()
369 ip = get_ipython()
377 ip.user_ns.pop('run', None)
370 ip.user_ns.pop('run', None)
378
371
379 with tt.AssertNotPrints("not found", channel='stderr'):
372 with tt.AssertNotPrints("not found", channel='stderr'):
380 ip.run_cell("%%time\n"
373 ip.run_cell("%%time\n"
381 "run = 0\n"
374 "run = 0\n"
382 "run += 1")
375 "run += 1")
383
376
384 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
377 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
385 def test_time_futures():
378 def test_time_futures():
386 "Test %time with __future__ environments"
379 "Test %time with __future__ environments"
387 ip = get_ipython()
380 ip = get_ipython()
388 ip.autocall = 0
381 ip.autocall = 0
389 ip.run_cell("from __future__ import division")
382 ip.run_cell("from __future__ import division")
390 with tt.AssertPrints('0.25'):
383 with tt.AssertPrints('0.25'):
391 ip.run_line_magic('time', 'print(1/4)')
384 ip.run_line_magic('time', 'print(1/4)')
392 ip.compile.reset_compiler_flags()
385 ip.compile.reset_compiler_flags()
393 with tt.AssertNotPrints('0.25'):
386 with tt.AssertNotPrints('0.25'):
394 ip.run_line_magic('time', 'print(1/4)')
387 ip.run_line_magic('time', 'print(1/4)')
395
388
396 def test_doctest_mode():
389 def test_doctest_mode():
397 "Toggle doctest_mode twice, it should be a no-op and run without error"
390 "Toggle doctest_mode twice, it should be a no-op and run without error"
398 _ip.magic('doctest_mode')
391 _ip.magic('doctest_mode')
399 _ip.magic('doctest_mode')
392 _ip.magic('doctest_mode')
400
393
401
394
402 def test_parse_options():
395 def test_parse_options():
403 """Tests for basic options parsing in magics."""
396 """Tests for basic options parsing in magics."""
404 # These are only the most minimal of tests, more should be added later. At
397 # These are only the most minimal of tests, more should be added later. At
405 # the very least we check that basic text/unicode calls work OK.
398 # the very least we check that basic text/unicode calls work OK.
406 m = DummyMagics(_ip)
399 m = DummyMagics(_ip)
407 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
400 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
408 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
401 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
409
402
410
403
411 def test_dirops():
404 def test_dirops():
412 """Test various directory handling operations."""
405 """Test various directory handling operations."""
413 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
406 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
414 curpath = py3compat.getcwd
407 curpath = py3compat.getcwd
415 startdir = py3compat.getcwd()
408 startdir = py3compat.getcwd()
416 ipdir = os.path.realpath(_ip.ipython_dir)
409 ipdir = os.path.realpath(_ip.ipython_dir)
417 try:
410 try:
418 _ip.magic('cd "%s"' % ipdir)
411 _ip.magic('cd "%s"' % ipdir)
419 nt.assert_equal(curpath(), ipdir)
412 nt.assert_equal(curpath(), ipdir)
420 _ip.magic('cd -')
413 _ip.magic('cd -')
421 nt.assert_equal(curpath(), startdir)
414 nt.assert_equal(curpath(), startdir)
422 _ip.magic('pushd "%s"' % ipdir)
415 _ip.magic('pushd "%s"' % ipdir)
423 nt.assert_equal(curpath(), ipdir)
416 nt.assert_equal(curpath(), ipdir)
424 _ip.magic('popd')
417 _ip.magic('popd')
425 nt.assert_equal(curpath(), startdir)
418 nt.assert_equal(curpath(), startdir)
426 finally:
419 finally:
427 os.chdir(startdir)
420 os.chdir(startdir)
428
421
429
422
430 def test_xmode():
423 def test_xmode():
431 # Calling xmode three times should be a no-op
424 # Calling xmode three times should be a no-op
432 xmode = _ip.InteractiveTB.mode
425 xmode = _ip.InteractiveTB.mode
433 for i in range(3):
426 for i in range(3):
434 _ip.magic("xmode")
427 _ip.magic("xmode")
435 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
428 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
436
429
437 def test_reset_hard():
430 def test_reset_hard():
438 monitor = []
431 monitor = []
439 class A(object):
432 class A(object):
440 def __del__(self):
433 def __del__(self):
441 monitor.append(1)
434 monitor.append(1)
442 def __repr__(self):
435 def __repr__(self):
443 return "<A instance>"
436 return "<A instance>"
444
437
445 _ip.user_ns["a"] = A()
438 _ip.user_ns["a"] = A()
446 _ip.run_cell("a")
439 _ip.run_cell("a")
447
440
448 nt.assert_equal(monitor, [])
441 nt.assert_equal(monitor, [])
449 _ip.magic("reset -f")
442 _ip.magic("reset -f")
450 nt.assert_equal(monitor, [1])
443 nt.assert_equal(monitor, [1])
451
444
452 class TestXdel(tt.TempFileMixin):
445 class TestXdel(tt.TempFileMixin):
453 def test_xdel(self):
446 def test_xdel(self):
454 """Test that references from %run are cleared by xdel."""
447 """Test that references from %run are cleared by xdel."""
455 src = ("class A(object):\n"
448 src = ("class A(object):\n"
456 " monitor = []\n"
449 " monitor = []\n"
457 " def __del__(self):\n"
450 " def __del__(self):\n"
458 " self.monitor.append(1)\n"
451 " self.monitor.append(1)\n"
459 "a = A()\n")
452 "a = A()\n")
460 self.mktmp(src)
453 self.mktmp(src)
461 # %run creates some hidden references...
454 # %run creates some hidden references...
462 _ip.magic("run %s" % self.fname)
455 _ip.magic("run %s" % self.fname)
463 # ... as does the displayhook.
456 # ... as does the displayhook.
464 _ip.run_cell("a")
457 _ip.run_cell("a")
465
458
466 monitor = _ip.user_ns["A"].monitor
459 monitor = _ip.user_ns["A"].monitor
467 nt.assert_equal(monitor, [])
460 nt.assert_equal(monitor, [])
468
461
469 _ip.magic("xdel a")
462 _ip.magic("xdel a")
470
463
471 # Check that a's __del__ method has been called.
464 # Check that a's __del__ method has been called.
472 nt.assert_equal(monitor, [1])
465 nt.assert_equal(monitor, [1])
473
466
474 def doctest_who():
467 def doctest_who():
475 """doctest for %who
468 """doctest for %who
476
469
477 In [1]: %reset -f
470 In [1]: %reset -f
478
471
479 In [2]: alpha = 123
472 In [2]: alpha = 123
480
473
481 In [3]: beta = 'beta'
474 In [3]: beta = 'beta'
482
475
483 In [4]: %who int
476 In [4]: %who int
484 alpha
477 alpha
485
478
486 In [5]: %who str
479 In [5]: %who str
487 beta
480 beta
488
481
489 In [6]: %whos
482 In [6]: %whos
490 Variable Type Data/Info
483 Variable Type Data/Info
491 ----------------------------
484 ----------------------------
492 alpha int 123
485 alpha int 123
493 beta str beta
486 beta str beta
494
487
495 In [7]: %who_ls
488 In [7]: %who_ls
496 Out[7]: ['alpha', 'beta']
489 Out[7]: ['alpha', 'beta']
497 """
490 """
498
491
499 def test_whos():
492 def test_whos():
500 """Check that whos is protected against objects where repr() fails."""
493 """Check that whos is protected against objects where repr() fails."""
501 class A(object):
494 class A(object):
502 def __repr__(self):
495 def __repr__(self):
503 raise Exception()
496 raise Exception()
504 _ip.user_ns['a'] = A()
497 _ip.user_ns['a'] = A()
505 _ip.magic("whos")
498 _ip.magic("whos")
506
499
507 @py3compat.u_format
500 @py3compat.u_format
508 def doctest_precision():
501 def doctest_precision():
509 """doctest for %precision
502 """doctest for %precision
510
503
511 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
504 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
512
505
513 In [2]: %precision 5
506 In [2]: %precision 5
514 Out[2]: {u}'%.5f'
507 Out[2]: {u}'%.5f'
515
508
516 In [3]: f.float_format
509 In [3]: f.float_format
517 Out[3]: {u}'%.5f'
510 Out[3]: {u}'%.5f'
518
511
519 In [4]: %precision %e
512 In [4]: %precision %e
520 Out[4]: {u}'%e'
513 Out[4]: {u}'%e'
521
514
522 In [5]: f(3.1415927)
515 In [5]: f(3.1415927)
523 Out[5]: {u}'3.141593e+00'
516 Out[5]: {u}'3.141593e+00'
524 """
517 """
525
518
526 def test_psearch():
519 def test_psearch():
527 with tt.AssertPrints("dict.fromkeys"):
520 with tt.AssertPrints("dict.fromkeys"):
528 _ip.run_cell("dict.fr*?")
521 _ip.run_cell("dict.fr*?")
529
522
530 def test_timeit_shlex():
523 def test_timeit_shlex():
531 """test shlex issues with timeit (#1109)"""
524 """test shlex issues with timeit (#1109)"""
532 _ip.ex("def f(*a,**kw): pass")
525 _ip.ex("def f(*a,**kw): pass")
533 _ip.magic('timeit -n1 "this is a bug".count(" ")')
526 _ip.magic('timeit -n1 "this is a bug".count(" ")')
534 _ip.magic('timeit -r1 -n1 f(" ", 1)')
527 _ip.magic('timeit -r1 -n1 f(" ", 1)')
535 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
528 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
536 _ip.magic('timeit -r1 -n1 ("a " + "b")')
529 _ip.magic('timeit -r1 -n1 ("a " + "b")')
537 _ip.magic('timeit -r1 -n1 f("a " + "b")')
530 _ip.magic('timeit -r1 -n1 f("a " + "b")')
538 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
531 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
539
532
540
533
541 def test_timeit_arguments():
534 def test_timeit_arguments():
542 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
535 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
543 _ip.magic("timeit ('#')")
536 _ip.magic("timeit ('#')")
544
537
545
538
546 def test_timeit_special_syntax():
539 def test_timeit_special_syntax():
547 "Test %%timeit with IPython special syntax"
540 "Test %%timeit with IPython special syntax"
548 @register_line_magic
541 @register_line_magic
549 def lmagic(line):
542 def lmagic(line):
550 ip = get_ipython()
543 ip = get_ipython()
551 ip.user_ns['lmagic_out'] = line
544 ip.user_ns['lmagic_out'] = line
552
545
553 # line mode test
546 # line mode test
554 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
547 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
555 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
548 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
556 # cell mode test
549 # cell mode test
557 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
550 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
558 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
551 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
559
552
560 def test_timeit_return():
553 def test_timeit_return():
561 """
554 """
562 test wether timeit -o return object
555 test wether timeit -o return object
563 """
556 """
564
557
565 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
558 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
566 assert(res is not None)
559 assert(res is not None)
567
560
568 def test_timeit_quiet():
561 def test_timeit_quiet():
569 """
562 """
570 test quiet option of timeit magic
563 test quiet option of timeit magic
571 """
564 """
572 with tt.AssertNotPrints("loops"):
565 with tt.AssertNotPrints("loops"):
573 _ip.run_cell("%timeit -n1 -r1 -q 1")
566 _ip.run_cell("%timeit -n1 -r1 -q 1")
574
567
575 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
568 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
576 def test_timeit_futures():
569 def test_timeit_futures():
577 "Test %timeit with __future__ environments"
570 "Test %timeit with __future__ environments"
578 ip = get_ipython()
571 ip = get_ipython()
579 ip.run_cell("from __future__ import division")
572 ip.run_cell("from __future__ import division")
580 with tt.AssertPrints('0.25'):
573 with tt.AssertPrints('0.25'):
581 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
574 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
582 ip.compile.reset_compiler_flags()
575 ip.compile.reset_compiler_flags()
583 with tt.AssertNotPrints('0.25'):
576 with tt.AssertNotPrints('0.25'):
584 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
577 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
585
578
586 @dec.skipif(execution.profile is None)
579 @dec.skipif(execution.profile is None)
587 def test_prun_special_syntax():
580 def test_prun_special_syntax():
588 "Test %%prun with IPython special syntax"
581 "Test %%prun with IPython special syntax"
589 @register_line_magic
582 @register_line_magic
590 def lmagic(line):
583 def lmagic(line):
591 ip = get_ipython()
584 ip = get_ipython()
592 ip.user_ns['lmagic_out'] = line
585 ip.user_ns['lmagic_out'] = line
593
586
594 # line mode test
587 # line mode test
595 _ip.run_line_magic('prun', '-q %lmagic my line')
588 _ip.run_line_magic('prun', '-q %lmagic my line')
596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
589 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
597 # cell mode test
590 # cell mode test
598 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
591 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
599 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
592 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
600
593
601 @dec.skipif(execution.profile is None)
594 @dec.skipif(execution.profile is None)
602 def test_prun_quotes():
595 def test_prun_quotes():
603 "Test that prun does not clobber string escapes (GH #1302)"
596 "Test that prun does not clobber string escapes (GH #1302)"
604 _ip.magic(r"prun -q x = '\t'")
597 _ip.magic(r"prun -q x = '\t'")
605 nt.assert_equal(_ip.user_ns['x'], '\t')
598 nt.assert_equal(_ip.user_ns['x'], '\t')
606
599
607 def test_extension():
600 def test_extension():
608 tmpdir = TemporaryDirectory()
601 tmpdir = TemporaryDirectory()
609 orig_ipython_dir = _ip.ipython_dir
602 orig_ipython_dir = _ip.ipython_dir
610 try:
603 try:
611 _ip.ipython_dir = tmpdir.name
604 _ip.ipython_dir = tmpdir.name
612 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
605 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
613 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
606 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
614 _ip.magic("install_ext %s" % url)
607 _ip.magic("install_ext %s" % url)
615 _ip.user_ns.pop('arq', None)
608 _ip.user_ns.pop('arq', None)
616 invalidate_caches() # Clear import caches
609 invalidate_caches() # Clear import caches
617 _ip.magic("load_ext daft_extension")
610 _ip.magic("load_ext daft_extension")
618 nt.assert_equal(_ip.user_ns['arq'], 185)
611 nt.assert_equal(_ip.user_ns['arq'], 185)
619 _ip.magic("unload_ext daft_extension")
612 _ip.magic("unload_ext daft_extension")
620 assert 'arq' not in _ip.user_ns
613 assert 'arq' not in _ip.user_ns
621 finally:
614 finally:
622 _ip.ipython_dir = orig_ipython_dir
615 _ip.ipython_dir = orig_ipython_dir
623 tmpdir.cleanup()
616 tmpdir.cleanup()
624
617
625
618
626 # The nose skip decorator doesn't work on classes, so this uses unittest's skipIf
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 class NotebookExportMagicTests(TestCase):
621 class NotebookExportMagicTests(TestCase):
629 def test_notebook_export_json(self):
622 def test_notebook_export_json(self):
630 with TemporaryDirectory() as td:
623 with TemporaryDirectory() as td:
631 outfile = os.path.join(td, "nb.ipynb")
624 outfile = os.path.join(td, "nb.ipynb")
632 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
625 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
633 _ip.magic("notebook -e %s" % outfile)
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 def test_env():
629 def test_env():
666 env = _ip.magic("env")
630 env = _ip.magic("env")
667 assert isinstance(env, dict), type(env)
631 assert isinstance(env, dict), type(env)
668
632
669
633
670 class CellMagicTestCase(TestCase):
634 class CellMagicTestCase(TestCase):
671
635
672 def check_ident(self, magic):
636 def check_ident(self, magic):
673 # Manually called, we get the result
637 # Manually called, we get the result
674 out = _ip.run_cell_magic(magic, 'a', 'b')
638 out = _ip.run_cell_magic(magic, 'a', 'b')
675 nt.assert_equal(out, ('a','b'))
639 nt.assert_equal(out, ('a','b'))
676 # Via run_cell, it goes into the user's namespace via displayhook
640 # Via run_cell, it goes into the user's namespace via displayhook
677 _ip.run_cell('%%' + magic +' c\nd')
641 _ip.run_cell('%%' + magic +' c\nd')
678 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
642 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
679
643
680 def test_cell_magic_func_deco(self):
644 def test_cell_magic_func_deco(self):
681 "Cell magic using simple decorator"
645 "Cell magic using simple decorator"
682 @register_cell_magic
646 @register_cell_magic
683 def cellm(line, cell):
647 def cellm(line, cell):
684 return line, cell
648 return line, cell
685
649
686 self.check_ident('cellm')
650 self.check_ident('cellm')
687
651
688 def test_cell_magic_reg(self):
652 def test_cell_magic_reg(self):
689 "Cell magic manually registered"
653 "Cell magic manually registered"
690 def cellm(line, cell):
654 def cellm(line, cell):
691 return line, cell
655 return line, cell
692
656
693 _ip.register_magic_function(cellm, 'cell', 'cellm2')
657 _ip.register_magic_function(cellm, 'cell', 'cellm2')
694 self.check_ident('cellm2')
658 self.check_ident('cellm2')
695
659
696 def test_cell_magic_class(self):
660 def test_cell_magic_class(self):
697 "Cell magics declared via a class"
661 "Cell magics declared via a class"
698 @magics_class
662 @magics_class
699 class MyMagics(Magics):
663 class MyMagics(Magics):
700
664
701 @cell_magic
665 @cell_magic
702 def cellm3(self, line, cell):
666 def cellm3(self, line, cell):
703 return line, cell
667 return line, cell
704
668
705 _ip.register_magics(MyMagics)
669 _ip.register_magics(MyMagics)
706 self.check_ident('cellm3')
670 self.check_ident('cellm3')
707
671
708 def test_cell_magic_class2(self):
672 def test_cell_magic_class2(self):
709 "Cell magics declared via a class, #2"
673 "Cell magics declared via a class, #2"
710 @magics_class
674 @magics_class
711 class MyMagics2(Magics):
675 class MyMagics2(Magics):
712
676
713 @cell_magic('cellm4')
677 @cell_magic('cellm4')
714 def cellm33(self, line, cell):
678 def cellm33(self, line, cell):
715 return line, cell
679 return line, cell
716
680
717 _ip.register_magics(MyMagics2)
681 _ip.register_magics(MyMagics2)
718 self.check_ident('cellm4')
682 self.check_ident('cellm4')
719 # Check that nothing is registered as 'cellm33'
683 # Check that nothing is registered as 'cellm33'
720 c33 = _ip.find_cell_magic('cellm33')
684 c33 = _ip.find_cell_magic('cellm33')
721 nt.assert_equal(c33, None)
685 nt.assert_equal(c33, None)
722
686
723 def test_file():
687 def test_file():
724 """Basic %%file"""
688 """Basic %%file"""
725 ip = get_ipython()
689 ip = get_ipython()
726 with TemporaryDirectory() as td:
690 with TemporaryDirectory() as td:
727 fname = os.path.join(td, 'file1')
691 fname = os.path.join(td, 'file1')
728 ip.run_cell_magic("file", fname, u'\n'.join([
692 ip.run_cell_magic("file", fname, u'\n'.join([
729 'line1',
693 'line1',
730 'line2',
694 'line2',
731 ]))
695 ]))
732 with open(fname) as f:
696 with open(fname) as f:
733 s = f.read()
697 s = f.read()
734 nt.assert_in('line1\n', s)
698 nt.assert_in('line1\n', s)
735 nt.assert_in('line2', s)
699 nt.assert_in('line2', s)
736
700
737 def test_file_var_expand():
701 def test_file_var_expand():
738 """%%file $filename"""
702 """%%file $filename"""
739 ip = get_ipython()
703 ip = get_ipython()
740 with TemporaryDirectory() as td:
704 with TemporaryDirectory() as td:
741 fname = os.path.join(td, 'file1')
705 fname = os.path.join(td, 'file1')
742 ip.user_ns['filename'] = fname
706 ip.user_ns['filename'] = fname
743 ip.run_cell_magic("file", '$filename', u'\n'.join([
707 ip.run_cell_magic("file", '$filename', u'\n'.join([
744 'line1',
708 'line1',
745 'line2',
709 'line2',
746 ]))
710 ]))
747 with open(fname) as f:
711 with open(fname) as f:
748 s = f.read()
712 s = f.read()
749 nt.assert_in('line1\n', s)
713 nt.assert_in('line1\n', s)
750 nt.assert_in('line2', s)
714 nt.assert_in('line2', s)
751
715
752 def test_file_unicode():
716 def test_file_unicode():
753 """%%file with unicode cell"""
717 """%%file with unicode cell"""
754 ip = get_ipython()
718 ip = get_ipython()
755 with TemporaryDirectory() as td:
719 with TemporaryDirectory() as td:
756 fname = os.path.join(td, 'file1')
720 fname = os.path.join(td, 'file1')
757 ip.run_cell_magic("file", fname, u'\n'.join([
721 ip.run_cell_magic("file", fname, u'\n'.join([
758 u'liné1',
722 u'liné1',
759 u'liné2',
723 u'liné2',
760 ]))
724 ]))
761 with io.open(fname, encoding='utf-8') as f:
725 with io.open(fname, encoding='utf-8') as f:
762 s = f.read()
726 s = f.read()
763 nt.assert_in(u'liné1\n', s)
727 nt.assert_in(u'liné1\n', s)
764 nt.assert_in(u'liné2', s)
728 nt.assert_in(u'liné2', s)
765
729
766 def test_file_amend():
730 def test_file_amend():
767 """%%file -a amends files"""
731 """%%file -a amends files"""
768 ip = get_ipython()
732 ip = get_ipython()
769 with TemporaryDirectory() as td:
733 with TemporaryDirectory() as td:
770 fname = os.path.join(td, 'file2')
734 fname = os.path.join(td, 'file2')
771 ip.run_cell_magic("file", fname, u'\n'.join([
735 ip.run_cell_magic("file", fname, u'\n'.join([
772 'line1',
736 'line1',
773 'line2',
737 'line2',
774 ]))
738 ]))
775 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
739 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
776 'line3',
740 'line3',
777 'line4',
741 'line4',
778 ]))
742 ]))
779 with open(fname) as f:
743 with open(fname) as f:
780 s = f.read()
744 s = f.read()
781 nt.assert_in('line1\n', s)
745 nt.assert_in('line1\n', s)
782 nt.assert_in('line3\n', s)
746 nt.assert_in('line3\n', s)
783
747
784
748
785 def test_script_config():
749 def test_script_config():
786 ip = get_ipython()
750 ip = get_ipython()
787 ip.config.ScriptMagics.script_magics = ['whoda']
751 ip.config.ScriptMagics.script_magics = ['whoda']
788 sm = script.ScriptMagics(shell=ip)
752 sm = script.ScriptMagics(shell=ip)
789 nt.assert_in('whoda', sm.magics['cell'])
753 nt.assert_in('whoda', sm.magics['cell'])
790
754
791 @dec.skip_win32
755 @dec.skip_win32
792 def test_script_out():
756 def test_script_out():
793 ip = get_ipython()
757 ip = get_ipython()
794 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
758 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
795 nt.assert_equal(ip.user_ns['output'], 'hi\n')
759 nt.assert_equal(ip.user_ns['output'], 'hi\n')
796
760
797 @dec.skip_win32
761 @dec.skip_win32
798 def test_script_err():
762 def test_script_err():
799 ip = get_ipython()
763 ip = get_ipython()
800 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
764 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
801 nt.assert_equal(ip.user_ns['error'], 'hello\n')
765 nt.assert_equal(ip.user_ns['error'], 'hello\n')
802
766
803 @dec.skip_win32
767 @dec.skip_win32
804 def test_script_out_err():
768 def test_script_out_err():
805 ip = get_ipython()
769 ip = get_ipython()
806 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
770 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
807 nt.assert_equal(ip.user_ns['output'], 'hi\n')
771 nt.assert_equal(ip.user_ns['output'], 'hi\n')
808 nt.assert_equal(ip.user_ns['error'], 'hello\n')
772 nt.assert_equal(ip.user_ns['error'], 'hello\n')
809
773
810 @dec.skip_win32
774 @dec.skip_win32
811 def test_script_bg_out():
775 def test_script_bg_out():
812 ip = get_ipython()
776 ip = get_ipython()
813 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
777 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
814 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
778 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
815
779
816 @dec.skip_win32
780 @dec.skip_win32
817 def test_script_bg_err():
781 def test_script_bg_err():
818 ip = get_ipython()
782 ip = get_ipython()
819 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
783 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
820 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
784 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
821
785
822 @dec.skip_win32
786 @dec.skip_win32
823 def test_script_bg_out_err():
787 def test_script_bg_out_err():
824 ip = get_ipython()
788 ip = get_ipython()
825 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
789 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
826 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
790 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
827 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
791 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
828
792
829 def test_script_defaults():
793 def test_script_defaults():
830 ip = get_ipython()
794 ip = get_ipython()
831 for cmd in ['sh', 'bash', 'perl', 'ruby']:
795 for cmd in ['sh', 'bash', 'perl', 'ruby']:
832 try:
796 try:
833 find_cmd(cmd)
797 find_cmd(cmd)
834 except Exception:
798 except Exception:
835 pass
799 pass
836 else:
800 else:
837 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
801 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
838
802
839
803
840 @magics_class
804 @magics_class
841 class FooFoo(Magics):
805 class FooFoo(Magics):
842 """class with both %foo and %%foo magics"""
806 """class with both %foo and %%foo magics"""
843 @line_magic('foo')
807 @line_magic('foo')
844 def line_foo(self, line):
808 def line_foo(self, line):
845 "I am line foo"
809 "I am line foo"
846 pass
810 pass
847
811
848 @cell_magic("foo")
812 @cell_magic("foo")
849 def cell_foo(self, line, cell):
813 def cell_foo(self, line, cell):
850 "I am cell foo, not line foo"
814 "I am cell foo, not line foo"
851 pass
815 pass
852
816
853 def test_line_cell_info():
817 def test_line_cell_info():
854 """%%foo and %foo magics are distinguishable to inspect"""
818 """%%foo and %foo magics are distinguishable to inspect"""
855 ip = get_ipython()
819 ip = get_ipython()
856 ip.magics_manager.register(FooFoo)
820 ip.magics_manager.register(FooFoo)
857 oinfo = ip.object_inspect('foo')
821 oinfo = ip.object_inspect('foo')
858 nt.assert_true(oinfo['found'])
822 nt.assert_true(oinfo['found'])
859 nt.assert_true(oinfo['ismagic'])
823 nt.assert_true(oinfo['ismagic'])
860
824
861 oinfo = ip.object_inspect('%%foo')
825 oinfo = ip.object_inspect('%%foo')
862 nt.assert_true(oinfo['found'])
826 nt.assert_true(oinfo['found'])
863 nt.assert_true(oinfo['ismagic'])
827 nt.assert_true(oinfo['ismagic'])
864 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
828 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
865
829
866 oinfo = ip.object_inspect('%foo')
830 oinfo = ip.object_inspect('%foo')
867 nt.assert_true(oinfo['found'])
831 nt.assert_true(oinfo['found'])
868 nt.assert_true(oinfo['ismagic'])
832 nt.assert_true(oinfo['ismagic'])
869 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
833 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
870
834
871 def test_multiple_magics():
835 def test_multiple_magics():
872 ip = get_ipython()
836 ip = get_ipython()
873 foo1 = FooFoo(ip)
837 foo1 = FooFoo(ip)
874 foo2 = FooFoo(ip)
838 foo2 = FooFoo(ip)
875 mm = ip.magics_manager
839 mm = ip.magics_manager
876 mm.register(foo1)
840 mm.register(foo1)
877 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
841 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
878 mm.register(foo2)
842 mm.register(foo2)
879 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
843 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
880
844
881 def test_alias_magic():
845 def test_alias_magic():
882 """Test %alias_magic."""
846 """Test %alias_magic."""
883 ip = get_ipython()
847 ip = get_ipython()
884 mm = ip.magics_manager
848 mm = ip.magics_manager
885
849
886 # Basic operation: both cell and line magics are created, if possible.
850 # Basic operation: both cell and line magics are created, if possible.
887 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
851 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
888 nt.assert_in('timeit_alias', mm.magics['line'])
852 nt.assert_in('timeit_alias', mm.magics['line'])
889 nt.assert_in('timeit_alias', mm.magics['cell'])
853 nt.assert_in('timeit_alias', mm.magics['cell'])
890
854
891 # --cell is specified, line magic not created.
855 # --cell is specified, line magic not created.
892 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
856 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
893 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
857 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
894 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
858 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
895
859
896 # Test that line alias is created successfully.
860 # Test that line alias is created successfully.
897 ip.run_line_magic('alias_magic', '--line env_alias env')
861 ip.run_line_magic('alias_magic', '--line env_alias env')
898 nt.assert_equal(ip.run_line_magic('env', ''),
862 nt.assert_equal(ip.run_line_magic('env', ''),
899 ip.run_line_magic('env_alias', ''))
863 ip.run_line_magic('env_alias', ''))
900
864
901 def test_save():
865 def test_save():
902 """Test %save."""
866 """Test %save."""
903 ip = get_ipython()
867 ip = get_ipython()
904 ip.history_manager.reset() # Clear any existing history.
868 ip.history_manager.reset() # Clear any existing history.
905 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
869 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
906 for i, cmd in enumerate(cmds, start=1):
870 for i, cmd in enumerate(cmds, start=1):
907 ip.history_manager.store_inputs(i, cmd)
871 ip.history_manager.store_inputs(i, cmd)
908 with TemporaryDirectory() as tmpdir:
872 with TemporaryDirectory() as tmpdir:
909 file = os.path.join(tmpdir, "testsave.py")
873 file = os.path.join(tmpdir, "testsave.py")
910 ip.run_line_magic("save", "%s 1-10" % file)
874 ip.run_line_magic("save", "%s 1-10" % file)
911 with open(file) as f:
875 with open(file) as f:
912 content = f.read()
876 content = f.read()
913 nt.assert_equal(content.count(cmds[0]), 1)
877 nt.assert_equal(content.count(cmds[0]), 1)
914 nt.assert_in('coding: utf-8', content)
878 nt.assert_in('coding: utf-8', content)
915 ip.run_line_magic("save", "-a %s 1-10" % file)
879 ip.run_line_magic("save", "-a %s 1-10" % file)
916 with open(file) as f:
880 with open(file) as f:
917 content = f.read()
881 content = f.read()
918 nt.assert_equal(content.count(cmds[0]), 2)
882 nt.assert_equal(content.count(cmds[0]), 2)
919 nt.assert_in('coding: utf-8', content)
883 nt.assert_in('coding: utf-8', content)
920
884
921
885
922 def test_store():
886 def test_store():
923 """Test %store."""
887 """Test %store."""
924 ip = get_ipython()
888 ip = get_ipython()
925 ip.run_line_magic('load_ext', 'storemagic')
889 ip.run_line_magic('load_ext', 'storemagic')
926
890
927 # make sure the storage is empty
891 # make sure the storage is empty
928 ip.run_line_magic('store', '-z')
892 ip.run_line_magic('store', '-z')
929 ip.user_ns['var'] = 42
893 ip.user_ns['var'] = 42
930 ip.run_line_magic('store', 'var')
894 ip.run_line_magic('store', 'var')
931 ip.user_ns['var'] = 39
895 ip.user_ns['var'] = 39
932 ip.run_line_magic('store', '-r')
896 ip.run_line_magic('store', '-r')
933 nt.assert_equal(ip.user_ns['var'], 42)
897 nt.assert_equal(ip.user_ns['var'], 42)
934
898
935 ip.run_line_magic('store', '-d var')
899 ip.run_line_magic('store', '-d var')
936 ip.user_ns['var'] = 39
900 ip.user_ns['var'] = 39
937 ip.run_line_magic('store' , '-r')
901 ip.run_line_magic('store' , '-r')
938 nt.assert_equal(ip.user_ns['var'], 39)
902 nt.assert_equal(ip.user_ns['var'], 39)
939
903
940
904
941 def _run_edit_test(arg_s, exp_filename=None,
905 def _run_edit_test(arg_s, exp_filename=None,
942 exp_lineno=-1,
906 exp_lineno=-1,
943 exp_contents=None,
907 exp_contents=None,
944 exp_is_temp=None):
908 exp_is_temp=None):
945 ip = get_ipython()
909 ip = get_ipython()
946 M = code.CodeMagics(ip)
910 M = code.CodeMagics(ip)
947 last_call = ['','']
911 last_call = ['','']
948 opts,args = M.parse_options(arg_s,'prxn:')
912 opts,args = M.parse_options(arg_s,'prxn:')
949 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
913 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
950
914
951 if exp_filename is not None:
915 if exp_filename is not None:
952 nt.assert_equal(exp_filename, filename)
916 nt.assert_equal(exp_filename, filename)
953 if exp_contents is not None:
917 if exp_contents is not None:
954 with io.open(filename, 'r', encoding='utf-8') as f:
918 with io.open(filename, 'r', encoding='utf-8') as f:
955 contents = f.read()
919 contents = f.read()
956 nt.assert_equal(exp_contents, contents)
920 nt.assert_equal(exp_contents, contents)
957 if exp_lineno != -1:
921 if exp_lineno != -1:
958 nt.assert_equal(exp_lineno, lineno)
922 nt.assert_equal(exp_lineno, lineno)
959 if exp_is_temp is not None:
923 if exp_is_temp is not None:
960 nt.assert_equal(exp_is_temp, is_temp)
924 nt.assert_equal(exp_is_temp, is_temp)
961
925
962
926
963 def test_edit_interactive():
927 def test_edit_interactive():
964 """%edit on interactively defined objects"""
928 """%edit on interactively defined objects"""
965 ip = get_ipython()
929 ip = get_ipython()
966 n = ip.execution_count
930 n = ip.execution_count
967 ip.run_cell(u"def foo(): return 1", store_history=True)
931 ip.run_cell(u"def foo(): return 1", store_history=True)
968
932
969 try:
933 try:
970 _run_edit_test("foo")
934 _run_edit_test("foo")
971 except code.InteractivelyDefined as e:
935 except code.InteractivelyDefined as e:
972 nt.assert_equal(e.index, n)
936 nt.assert_equal(e.index, n)
973 else:
937 else:
974 raise AssertionError("Should have raised InteractivelyDefined")
938 raise AssertionError("Should have raised InteractivelyDefined")
975
939
976
940
977 def test_edit_cell():
941 def test_edit_cell():
978 """%edit [cell id]"""
942 """%edit [cell id]"""
979 ip = get_ipython()
943 ip = get_ipython()
980
944
981 ip.run_cell(u"def foo(): return 1", store_history=True)
945 ip.run_cell(u"def foo(): return 1", store_history=True)
982
946
983 # test
947 # test
984 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
948 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
985
949
986 def test_bookmark():
950 def test_bookmark():
987 ip = get_ipython()
951 ip = get_ipython()
988 ip.run_line_magic('bookmark', 'bmname')
952 ip.run_line_magic('bookmark', 'bmname')
989 with tt.AssertPrints('bmname'):
953 with tt.AssertPrints('bmname'):
990 ip.run_line_magic('bookmark', '-l')
954 ip.run_line_magic('bookmark', '-l')
991 ip.run_line_magic('bookmark', '-d bmname')
955 ip.run_line_magic('bookmark', '-d bmname')
@@ -1,516 +1,512 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for code execution (%run and related), which is particularly tricky.
2 """Tests for code execution (%run and related), which is particularly tricky.
3
3
4 Because of how %run manages namespaces, and the fact that we are trying here to
4 Because of how %run manages namespaces, and the fact that we are trying here to
5 verify subtle object deletion and reference counting issues, the %run tests
5 verify subtle object deletion and reference counting issues, the %run tests
6 will be kept in this separate file. This makes it easier to aggregate in one
6 will be kept in this separate file. This makes it easier to aggregate in one
7 place the tricks needed to handle it; most other magics are much easier to test
7 place the tricks needed to handle it; most other magics are much easier to test
8 and we do so in a common test_magic file.
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 from __future__ import absolute_import
14 from __future__ import absolute_import
11
15
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16
16 import functools
17 import functools
17 import os
18 import os
18 from os.path import join as pjoin
19 from os.path import join as pjoin
19 import random
20 import random
20 import sys
21 import sys
21 import tempfile
22 import tempfile
22 import textwrap
23 import textwrap
23 import unittest
24 import unittest
24
25
25 import nose.tools as nt
26 import nose.tools as nt
26 from nose import SkipTest
27 from nose import SkipTest
27
28
28 from IPython.testing import decorators as dec
29 from IPython.testing import decorators as dec
29 from IPython.testing import tools as tt
30 from IPython.testing import tools as tt
30 from IPython.utils import py3compat
31 from IPython.utils import py3compat
31 from IPython.utils.io import capture_output
32 from IPython.utils.io import capture_output
32 from IPython.utils.tempdir import TemporaryDirectory
33 from IPython.utils.tempdir import TemporaryDirectory
33 from IPython.core import debugger
34 from IPython.core import debugger
34
35
35 #-----------------------------------------------------------------------------
36 # Test functions begin
37 #-----------------------------------------------------------------------------
38
36
39 def doctest_refbug():
37 def doctest_refbug():
40 """Very nasty problem with references held by multiple runs of a script.
38 """Very nasty problem with references held by multiple runs of a script.
41 See: https://github.com/ipython/ipython/issues/141
39 See: https://github.com/ipython/ipython/issues/141
42
40
43 In [1]: _ip.clear_main_mod_cache()
41 In [1]: _ip.clear_main_mod_cache()
44 # random
42 # random
45
43
46 In [2]: %run refbug
44 In [2]: %run refbug
47
45
48 In [3]: call_f()
46 In [3]: call_f()
49 lowercased: hello
47 lowercased: hello
50
48
51 In [4]: %run refbug
49 In [4]: %run refbug
52
50
53 In [5]: call_f()
51 In [5]: call_f()
54 lowercased: hello
52 lowercased: hello
55 lowercased: hello
53 lowercased: hello
56 """
54 """
57
55
58
56
59 def doctest_run_builtins():
57 def doctest_run_builtins():
60 r"""Check that %run doesn't damage __builtins__.
58 r"""Check that %run doesn't damage __builtins__.
61
59
62 In [1]: import tempfile
60 In [1]: import tempfile
63
61
64 In [2]: bid1 = id(__builtins__)
62 In [2]: bid1 = id(__builtins__)
65
63
66 In [3]: fname = tempfile.mkstemp('.py')[1]
64 In [3]: fname = tempfile.mkstemp('.py')[1]
67
65
68 In [3]: f = open(fname,'w')
66 In [3]: f = open(fname,'w')
69
67
70 In [4]: dummy= f.write('pass\n')
68 In [4]: dummy= f.write('pass\n')
71
69
72 In [5]: f.flush()
70 In [5]: f.flush()
73
71
74 In [6]: t1 = type(__builtins__)
72 In [6]: t1 = type(__builtins__)
75
73
76 In [7]: %run $fname
74 In [7]: %run $fname
77
75
78 In [7]: f.close()
76 In [7]: f.close()
79
77
80 In [8]: bid2 = id(__builtins__)
78 In [8]: bid2 = id(__builtins__)
81
79
82 In [9]: t2 = type(__builtins__)
80 In [9]: t2 = type(__builtins__)
83
81
84 In [10]: t1 == t2
82 In [10]: t1 == t2
85 Out[10]: True
83 Out[10]: True
86
84
87 In [10]: bid1 == bid2
85 In [10]: bid1 == bid2
88 Out[10]: True
86 Out[10]: True
89
87
90 In [12]: try:
88 In [12]: try:
91 ....: os.unlink(fname)
89 ....: os.unlink(fname)
92 ....: except:
90 ....: except:
93 ....: pass
91 ....: pass
94 ....:
92 ....:
95 """
93 """
96
94
97
95
98 def doctest_run_option_parser():
96 def doctest_run_option_parser():
99 r"""Test option parser in %run.
97 r"""Test option parser in %run.
100
98
101 In [1]: %run print_argv.py
99 In [1]: %run print_argv.py
102 []
100 []
103
101
104 In [2]: %run print_argv.py print*.py
102 In [2]: %run print_argv.py print*.py
105 ['print_argv.py']
103 ['print_argv.py']
106
104
107 In [3]: %run -G print_argv.py print*.py
105 In [3]: %run -G print_argv.py print*.py
108 ['print*.py']
106 ['print*.py']
109
107
110 """
108 """
111
109
112
110
113 @dec.skip_win32
111 @dec.skip_win32
114 def doctest_run_option_parser_for_posix():
112 def doctest_run_option_parser_for_posix():
115 r"""Test option parser in %run (Linux/OSX specific).
113 r"""Test option parser in %run (Linux/OSX specific).
116
114
117 You need double quote to escape glob in POSIX systems:
115 You need double quote to escape glob in POSIX systems:
118
116
119 In [1]: %run print_argv.py print\\*.py
117 In [1]: %run print_argv.py print\\*.py
120 ['print*.py']
118 ['print*.py']
121
119
122 You can't use quote to escape glob in POSIX systems:
120 You can't use quote to escape glob in POSIX systems:
123
121
124 In [2]: %run print_argv.py 'print*.py'
122 In [2]: %run print_argv.py 'print*.py'
125 ['print_argv.py']
123 ['print_argv.py']
126
124
127 """
125 """
128
126
129
127
130 @dec.skip_if_not_win32
128 @dec.skip_if_not_win32
131 def doctest_run_option_parser_for_windows():
129 def doctest_run_option_parser_for_windows():
132 r"""Test option parser in %run (Windows specific).
130 r"""Test option parser in %run (Windows specific).
133
131
134 In Windows, you can't escape ``*` `by backslash:
132 In Windows, you can't escape ``*` `by backslash:
135
133
136 In [1]: %run print_argv.py print\\*.py
134 In [1]: %run print_argv.py print\\*.py
137 ['print\\*.py']
135 ['print\\*.py']
138
136
139 You can use quote to escape glob:
137 You can use quote to escape glob:
140
138
141 In [2]: %run print_argv.py 'print*.py'
139 In [2]: %run print_argv.py 'print*.py'
142 ['print*.py']
140 ['print*.py']
143
141
144 """
142 """
145
143
146
144
147 @py3compat.doctest_refactor_print
145 @py3compat.doctest_refactor_print
148 def doctest_reset_del():
146 def doctest_reset_del():
149 """Test that resetting doesn't cause errors in __del__ methods.
147 """Test that resetting doesn't cause errors in __del__ methods.
150
148
151 In [2]: class A(object):
149 In [2]: class A(object):
152 ...: def __del__(self):
150 ...: def __del__(self):
153 ...: print str("Hi")
151 ...: print str("Hi")
154 ...:
152 ...:
155
153
156 In [3]: a = A()
154 In [3]: a = A()
157
155
158 In [4]: get_ipython().reset()
156 In [4]: get_ipython().reset()
159 Hi
157 Hi
160
158
161 In [5]: 1+1
159 In [5]: 1+1
162 Out[5]: 2
160 Out[5]: 2
163 """
161 """
164
162
165 # For some tests, it will be handy to organize them in a class with a common
163 # For some tests, it will be handy to organize them in a class with a common
166 # setup that makes a temp file
164 # setup that makes a temp file
167
165
168 class TestMagicRunPass(tt.TempFileMixin):
166 class TestMagicRunPass(tt.TempFileMixin):
169
167
170 def setup(self):
168 def setup(self):
171 """Make a valid python temp file."""
169 """Make a valid python temp file."""
172 self.mktmp('pass\n')
170 self.mktmp('pass\n')
173
171
174 def run_tmpfile(self):
172 def run_tmpfile(self):
175 _ip = get_ipython()
173 _ip = get_ipython()
176 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
174 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
177 # See below and ticket https://bugs.launchpad.net/bugs/366353
175 # See below and ticket https://bugs.launchpad.net/bugs/366353
178 _ip.magic('run %s' % self.fname)
176 _ip.magic('run %s' % self.fname)
179
177
180 def run_tmpfile_p(self):
178 def run_tmpfile_p(self):
181 _ip = get_ipython()
179 _ip = get_ipython()
182 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
180 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
183 # See below and ticket https://bugs.launchpad.net/bugs/366353
181 # See below and ticket https://bugs.launchpad.net/bugs/366353
184 _ip.magic('run -p %s' % self.fname)
182 _ip.magic('run -p %s' % self.fname)
185
183
186 def test_builtins_id(self):
184 def test_builtins_id(self):
187 """Check that %run doesn't damage __builtins__ """
185 """Check that %run doesn't damage __builtins__ """
188 _ip = get_ipython()
186 _ip = get_ipython()
189 # Test that the id of __builtins__ is not modified by %run
187 # Test that the id of __builtins__ is not modified by %run
190 bid1 = id(_ip.user_ns['__builtins__'])
188 bid1 = id(_ip.user_ns['__builtins__'])
191 self.run_tmpfile()
189 self.run_tmpfile()
192 bid2 = id(_ip.user_ns['__builtins__'])
190 bid2 = id(_ip.user_ns['__builtins__'])
193 nt.assert_equal(bid1, bid2)
191 nt.assert_equal(bid1, bid2)
194
192
195 def test_builtins_type(self):
193 def test_builtins_type(self):
196 """Check that the type of __builtins__ doesn't change with %run.
194 """Check that the type of __builtins__ doesn't change with %run.
197
195
198 However, the above could pass if __builtins__ was already modified to
196 However, the above could pass if __builtins__ was already modified to
199 be a dict (it should be a module) by a previous use of %run. So we
197 be a dict (it should be a module) by a previous use of %run. So we
200 also check explicitly that it really is a module:
198 also check explicitly that it really is a module:
201 """
199 """
202 _ip = get_ipython()
200 _ip = get_ipython()
203 self.run_tmpfile()
201 self.run_tmpfile()
204 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
202 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
205
203
206 def test_prompts(self):
204 def test_prompts(self):
207 """Test that prompts correctly generate after %run"""
205 """Test that prompts correctly generate after %run"""
208 self.run_tmpfile()
206 self.run_tmpfile()
209 _ip = get_ipython()
207 _ip = get_ipython()
210 p2 = _ip.prompt_manager.render('in2').strip()
208 p2 = _ip.prompt_manager.render('in2').strip()
211 nt.assert_equal(p2[:3], '...')
209 nt.assert_equal(p2[:3], '...')
212
210
213 def test_run_profile( self ):
211 def test_run_profile( self ):
214 """Test that the option -p, which invokes the profiler, do not
212 """Test that the option -p, which invokes the profiler, do not
215 crash by invoking execfile"""
213 crash by invoking execfile"""
216 _ip = get_ipython()
214 _ip = get_ipython()
217 self.run_tmpfile_p()
215 self.run_tmpfile_p()
218
216
219
217
220 class TestMagicRunSimple(tt.TempFileMixin):
218 class TestMagicRunSimple(tt.TempFileMixin):
221
219
222 def test_simpledef(self):
220 def test_simpledef(self):
223 """Test that simple class definitions work."""
221 """Test that simple class definitions work."""
224 src = ("class foo: pass\n"
222 src = ("class foo: pass\n"
225 "def f(): return foo()")
223 "def f(): return foo()")
226 self.mktmp(src)
224 self.mktmp(src)
227 _ip.magic('run %s' % self.fname)
225 _ip.magic('run %s' % self.fname)
228 _ip.run_cell('t = isinstance(f(), foo)')
226 _ip.run_cell('t = isinstance(f(), foo)')
229 nt.assert_true(_ip.user_ns['t'])
227 nt.assert_true(_ip.user_ns['t'])
230
228
231 def test_obj_del(self):
229 def test_obj_del(self):
232 """Test that object's __del__ methods are called on exit."""
230 """Test that object's __del__ methods are called on exit."""
233 if sys.platform == 'win32':
231 if sys.platform == 'win32':
234 try:
232 try:
235 import win32api
233 import win32api
236 except ImportError:
234 except ImportError:
237 raise SkipTest("Test requires pywin32")
235 raise SkipTest("Test requires pywin32")
238 src = ("class A(object):\n"
236 src = ("class A(object):\n"
239 " def __del__(self):\n"
237 " def __del__(self):\n"
240 " print 'object A deleted'\n"
238 " print 'object A deleted'\n"
241 "a = A()\n")
239 "a = A()\n")
242 self.mktmp(py3compat.doctest_refactor_print(src))
240 self.mktmp(py3compat.doctest_refactor_print(src))
243 if dec.module_not_available('sqlite3'):
241 if dec.module_not_available('sqlite3'):
244 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
242 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
245 else:
243 else:
246 err = None
244 err = None
247 tt.ipexec_validate(self.fname, 'object A deleted', err)
245 tt.ipexec_validate(self.fname, 'object A deleted', err)
248
246
249 def test_aggressive_namespace_cleanup(self):
247 def test_aggressive_namespace_cleanup(self):
250 """Test that namespace cleanup is not too aggressive GH-238
248 """Test that namespace cleanup is not too aggressive GH-238
251
249
252 Returning from another run magic deletes the namespace"""
250 Returning from another run magic deletes the namespace"""
253 # see ticket https://github.com/ipython/ipython/issues/238
251 # see ticket https://github.com/ipython/ipython/issues/238
254 class secondtmp(tt.TempFileMixin): pass
252 class secondtmp(tt.TempFileMixin): pass
255 empty = secondtmp()
253 empty = secondtmp()
256 empty.mktmp('')
254 empty.mktmp('')
257 # On Windows, the filename will have \users in it, so we need to use the
255 # On Windows, the filename will have \users in it, so we need to use the
258 # repr so that the \u becomes \\u.
256 # repr so that the \u becomes \\u.
259 src = ("ip = get_ipython()\n"
257 src = ("ip = get_ipython()\n"
260 "for i in range(5):\n"
258 "for i in range(5):\n"
261 " try:\n"
259 " try:\n"
262 " ip.magic(%r)\n"
260 " ip.magic(%r)\n"
263 " except NameError as e:\n"
261 " except NameError as e:\n"
264 " print(i)\n"
262 " print(i)\n"
265 " break\n" % ('run ' + empty.fname))
263 " break\n" % ('run ' + empty.fname))
266 self.mktmp(src)
264 self.mktmp(src)
267 _ip.magic('run %s' % self.fname)
265 _ip.magic('run %s' % self.fname)
268 _ip.run_cell('ip == get_ipython()')
266 _ip.run_cell('ip == get_ipython()')
269 nt.assert_equal(_ip.user_ns['i'], 4)
267 nt.assert_equal(_ip.user_ns['i'], 4)
270
268
271 def test_run_second(self):
269 def test_run_second(self):
272 """Test that running a second file doesn't clobber the first, gh-3547
270 """Test that running a second file doesn't clobber the first, gh-3547
273 """
271 """
274 self.mktmp("avar = 1\n"
272 self.mktmp("avar = 1\n"
275 "def afunc():\n"
273 "def afunc():\n"
276 " return avar\n")
274 " return avar\n")
277
275
278 empty = tt.TempFileMixin()
276 empty = tt.TempFileMixin()
279 empty.mktmp("")
277 empty.mktmp("")
280
278
281 _ip.magic('run %s' % self.fname)
279 _ip.magic('run %s' % self.fname)
282 _ip.magic('run %s' % empty.fname)
280 _ip.magic('run %s' % empty.fname)
283 nt.assert_equal(_ip.user_ns['afunc'](), 1)
281 nt.assert_equal(_ip.user_ns['afunc'](), 1)
284
282
285 @dec.skip_win32
283 @dec.skip_win32
286 def test_tclass(self):
284 def test_tclass(self):
287 mydir = os.path.dirname(__file__)
285 mydir = os.path.dirname(__file__)
288 tc = os.path.join(mydir, 'tclass')
286 tc = os.path.join(mydir, 'tclass')
289 src = ("%%run '%s' C-first\n"
287 src = ("%%run '%s' C-first\n"
290 "%%run '%s' C-second\n"
288 "%%run '%s' C-second\n"
291 "%%run '%s' C-third\n") % (tc, tc, tc)
289 "%%run '%s' C-third\n") % (tc, tc, tc)
292 self.mktmp(src, '.ipy')
290 self.mktmp(src, '.ipy')
293 out = """\
291 out = """\
294 ARGV 1-: ['C-first']
292 ARGV 1-: ['C-first']
295 ARGV 1-: ['C-second']
293 ARGV 1-: ['C-second']
296 tclass.py: deleting object: C-first
294 tclass.py: deleting object: C-first
297 ARGV 1-: ['C-third']
295 ARGV 1-: ['C-third']
298 tclass.py: deleting object: C-second
296 tclass.py: deleting object: C-second
299 tclass.py: deleting object: C-third
297 tclass.py: deleting object: C-third
300 """
298 """
301 if dec.module_not_available('sqlite3'):
299 if dec.module_not_available('sqlite3'):
302 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
300 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
303 else:
301 else:
304 err = None
302 err = None
305 tt.ipexec_validate(self.fname, out, err)
303 tt.ipexec_validate(self.fname, out, err)
306
304
307 def test_run_i_after_reset(self):
305 def test_run_i_after_reset(self):
308 """Check that %run -i still works after %reset (gh-693)"""
306 """Check that %run -i still works after %reset (gh-693)"""
309 src = "yy = zz\n"
307 src = "yy = zz\n"
310 self.mktmp(src)
308 self.mktmp(src)
311 _ip.run_cell("zz = 23")
309 _ip.run_cell("zz = 23")
312 _ip.magic('run -i %s' % self.fname)
310 _ip.magic('run -i %s' % self.fname)
313 nt.assert_equal(_ip.user_ns['yy'], 23)
311 nt.assert_equal(_ip.user_ns['yy'], 23)
314 _ip.magic('reset -f')
312 _ip.magic('reset -f')
315 _ip.run_cell("zz = 23")
313 _ip.run_cell("zz = 23")
316 _ip.magic('run -i %s' % self.fname)
314 _ip.magic('run -i %s' % self.fname)
317 nt.assert_equal(_ip.user_ns['yy'], 23)
315 nt.assert_equal(_ip.user_ns['yy'], 23)
318
316
319 def test_unicode(self):
317 def test_unicode(self):
320 """Check that files in odd encodings are accepted."""
318 """Check that files in odd encodings are accepted."""
321 mydir = os.path.dirname(__file__)
319 mydir = os.path.dirname(__file__)
322 na = os.path.join(mydir, 'nonascii.py')
320 na = os.path.join(mydir, 'nonascii.py')
323 _ip.magic('run "%s"' % na)
321 _ip.magic('run "%s"' % na)
324 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
322 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
325
323
326 def test_run_py_file_attribute(self):
324 def test_run_py_file_attribute(self):
327 """Test handling of `__file__` attribute in `%run <file>.py`."""
325 """Test handling of `__file__` attribute in `%run <file>.py`."""
328 src = "t = __file__\n"
326 src = "t = __file__\n"
329 self.mktmp(src)
327 self.mktmp(src)
330 _missing = object()
328 _missing = object()
331 file1 = _ip.user_ns.get('__file__', _missing)
329 file1 = _ip.user_ns.get('__file__', _missing)
332 _ip.magic('run %s' % self.fname)
330 _ip.magic('run %s' % self.fname)
333 file2 = _ip.user_ns.get('__file__', _missing)
331 file2 = _ip.user_ns.get('__file__', _missing)
334
332
335 # Check that __file__ was equal to the filename in the script's
333 # Check that __file__ was equal to the filename in the script's
336 # namespace.
334 # namespace.
337 nt.assert_equal(_ip.user_ns['t'], self.fname)
335 nt.assert_equal(_ip.user_ns['t'], self.fname)
338
336
339 # Check that __file__ was not leaked back into user_ns.
337 # Check that __file__ was not leaked back into user_ns.
340 nt.assert_equal(file1, file2)
338 nt.assert_equal(file1, file2)
341
339
342 def test_run_ipy_file_attribute(self):
340 def test_run_ipy_file_attribute(self):
343 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
341 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
344 src = "t = __file__\n"
342 src = "t = __file__\n"
345 self.mktmp(src, ext='.ipy')
343 self.mktmp(src, ext='.ipy')
346 _missing = object()
344 _missing = object()
347 file1 = _ip.user_ns.get('__file__', _missing)
345 file1 = _ip.user_ns.get('__file__', _missing)
348 _ip.magic('run %s' % self.fname)
346 _ip.magic('run %s' % self.fname)
349 file2 = _ip.user_ns.get('__file__', _missing)
347 file2 = _ip.user_ns.get('__file__', _missing)
350
348
351 # Check that __file__ was equal to the filename in the script's
349 # Check that __file__ was equal to the filename in the script's
352 # namespace.
350 # namespace.
353 nt.assert_equal(_ip.user_ns['t'], self.fname)
351 nt.assert_equal(_ip.user_ns['t'], self.fname)
354
352
355 # Check that __file__ was not leaked back into user_ns.
353 # Check that __file__ was not leaked back into user_ns.
356 nt.assert_equal(file1, file2)
354 nt.assert_equal(file1, file2)
357
355
358 def test_run_formatting(self):
356 def test_run_formatting(self):
359 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
357 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
360 src = "pass"
358 src = "pass"
361 self.mktmp(src)
359 self.mktmp(src)
362 _ip.magic('run -t -N 1 %s' % self.fname)
360 _ip.magic('run -t -N 1 %s' % self.fname)
363 _ip.magic('run -t -N 10 %s' % self.fname)
361 _ip.magic('run -t -N 10 %s' % self.fname)
364
362
365 def test_ignore_sys_exit(self):
363 def test_ignore_sys_exit(self):
366 """Test the -e option to ignore sys.exit()"""
364 """Test the -e option to ignore sys.exit()"""
367 src = "import sys; sys.exit(1)"
365 src = "import sys; sys.exit(1)"
368 self.mktmp(src)
366 self.mktmp(src)
369 with tt.AssertPrints('SystemExit'):
367 with tt.AssertPrints('SystemExit'):
370 _ip.magic('run %s' % self.fname)
368 _ip.magic('run %s' % self.fname)
371
369
372 with tt.AssertNotPrints('SystemExit'):
370 with tt.AssertNotPrints('SystemExit'):
373 _ip.magic('run -e %s' % self.fname)
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 def test_run_nb(self):
374 def test_run_nb(self):
377 """Test %run notebook.ipynb"""
375 """Test %run notebook.ipynb"""
378 from IPython.nbformat import current
376 from IPython.nbformat import v4, writes
379 nb = current.new_notebook(
377 nb = v4.new_notebook(
380 worksheets=[
378 cells=[
381 current.new_worksheet(cells=[
379 v4.new_markdown_cell("The Ultimate Question of Everything"),
382 current.new_text_cell("The Ultimate Question of Everything"),
380 v4.new_code_cell("answer=42")
383 current.new_code_cell("answer=42")
384 ])
385 ]
381 ]
386 )
382 )
387 src = current.writes(nb, 'json')
383 src = writes(nb, version=4)
388 self.mktmp(src, ext='.ipynb')
384 self.mktmp(src, ext='.ipynb')
389
385
390 _ip.magic("run %s" % self.fname)
386 _ip.magic("run %s" % self.fname)
391
387
392 nt.assert_equal(_ip.user_ns['answer'], 42)
388 nt.assert_equal(_ip.user_ns['answer'], 42)
393
389
394
390
395
391
396 class TestMagicRunWithPackage(unittest.TestCase):
392 class TestMagicRunWithPackage(unittest.TestCase):
397
393
398 def writefile(self, name, content):
394 def writefile(self, name, content):
399 path = os.path.join(self.tempdir.name, name)
395 path = os.path.join(self.tempdir.name, name)
400 d = os.path.dirname(path)
396 d = os.path.dirname(path)
401 if not os.path.isdir(d):
397 if not os.path.isdir(d):
402 os.makedirs(d)
398 os.makedirs(d)
403 with open(path, 'w') as f:
399 with open(path, 'w') as f:
404 f.write(textwrap.dedent(content))
400 f.write(textwrap.dedent(content))
405
401
406 def setUp(self):
402 def setUp(self):
407 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
403 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
408 """Temporary valid python package name."""
404 """Temporary valid python package name."""
409
405
410 self.value = int(random.random() * 10000)
406 self.value = int(random.random() * 10000)
411
407
412 self.tempdir = TemporaryDirectory()
408 self.tempdir = TemporaryDirectory()
413 self.__orig_cwd = py3compat.getcwd()
409 self.__orig_cwd = py3compat.getcwd()
414 sys.path.insert(0, self.tempdir.name)
410 sys.path.insert(0, self.tempdir.name)
415
411
416 self.writefile(os.path.join(package, '__init__.py'), '')
412 self.writefile(os.path.join(package, '__init__.py'), '')
417 self.writefile(os.path.join(package, 'sub.py'), """
413 self.writefile(os.path.join(package, 'sub.py'), """
418 x = {0!r}
414 x = {0!r}
419 """.format(self.value))
415 """.format(self.value))
420 self.writefile(os.path.join(package, 'relative.py'), """
416 self.writefile(os.path.join(package, 'relative.py'), """
421 from .sub import x
417 from .sub import x
422 """)
418 """)
423 self.writefile(os.path.join(package, 'absolute.py'), """
419 self.writefile(os.path.join(package, 'absolute.py'), """
424 from {0}.sub import x
420 from {0}.sub import x
425 """.format(package))
421 """.format(package))
426
422
427 def tearDown(self):
423 def tearDown(self):
428 os.chdir(self.__orig_cwd)
424 os.chdir(self.__orig_cwd)
429 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
425 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
430 self.tempdir.cleanup()
426 self.tempdir.cleanup()
431
427
432 def check_run_submodule(self, submodule, opts=''):
428 def check_run_submodule(self, submodule, opts=''):
433 _ip.user_ns.pop('x', None)
429 _ip.user_ns.pop('x', None)
434 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
430 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
435 self.assertEqual(_ip.user_ns['x'], self.value,
431 self.assertEqual(_ip.user_ns['x'], self.value,
436 'Variable `x` is not loaded from module `{0}`.'
432 'Variable `x` is not loaded from module `{0}`.'
437 .format(submodule))
433 .format(submodule))
438
434
439 def test_run_submodule_with_absolute_import(self):
435 def test_run_submodule_with_absolute_import(self):
440 self.check_run_submodule('absolute')
436 self.check_run_submodule('absolute')
441
437
442 def test_run_submodule_with_relative_import(self):
438 def test_run_submodule_with_relative_import(self):
443 """Run submodule that has a relative import statement (#2727)."""
439 """Run submodule that has a relative import statement (#2727)."""
444 self.check_run_submodule('relative')
440 self.check_run_submodule('relative')
445
441
446 def test_prun_submodule_with_absolute_import(self):
442 def test_prun_submodule_with_absolute_import(self):
447 self.check_run_submodule('absolute', '-p')
443 self.check_run_submodule('absolute', '-p')
448
444
449 def test_prun_submodule_with_relative_import(self):
445 def test_prun_submodule_with_relative_import(self):
450 self.check_run_submodule('relative', '-p')
446 self.check_run_submodule('relative', '-p')
451
447
452 def with_fake_debugger(func):
448 def with_fake_debugger(func):
453 @functools.wraps(func)
449 @functools.wraps(func)
454 def wrapper(*args, **kwds):
450 def wrapper(*args, **kwds):
455 with tt.monkeypatch(debugger.Pdb, 'run', staticmethod(eval)):
451 with tt.monkeypatch(debugger.Pdb, 'run', staticmethod(eval)):
456 return func(*args, **kwds)
452 return func(*args, **kwds)
457 return wrapper
453 return wrapper
458
454
459 @with_fake_debugger
455 @with_fake_debugger
460 def test_debug_run_submodule_with_absolute_import(self):
456 def test_debug_run_submodule_with_absolute_import(self):
461 self.check_run_submodule('absolute', '-d')
457 self.check_run_submodule('absolute', '-d')
462
458
463 @with_fake_debugger
459 @with_fake_debugger
464 def test_debug_run_submodule_with_relative_import(self):
460 def test_debug_run_submodule_with_relative_import(self):
465 self.check_run_submodule('relative', '-d')
461 self.check_run_submodule('relative', '-d')
466
462
467 def test_run__name__():
463 def test_run__name__():
468 with TemporaryDirectory() as td:
464 with TemporaryDirectory() as td:
469 path = pjoin(td, 'foo.py')
465 path = pjoin(td, 'foo.py')
470 with open(path, 'w') as f:
466 with open(path, 'w') as f:
471 f.write("q = __name__")
467 f.write("q = __name__")
472
468
473 _ip.user_ns.pop('q', None)
469 _ip.user_ns.pop('q', None)
474 _ip.magic('run {}'.format(path))
470 _ip.magic('run {}'.format(path))
475 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
471 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
476
472
477 _ip.magic('run -n {}'.format(path))
473 _ip.magic('run -n {}'.format(path))
478 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
474 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
479
475
480 def test_run_tb():
476 def test_run_tb():
481 """Test traceback offset in %run"""
477 """Test traceback offset in %run"""
482 with TemporaryDirectory() as td:
478 with TemporaryDirectory() as td:
483 path = pjoin(td, 'foo.py')
479 path = pjoin(td, 'foo.py')
484 with open(path, 'w') as f:
480 with open(path, 'w') as f:
485 f.write('\n'.join([
481 f.write('\n'.join([
486 "def foo():",
482 "def foo():",
487 " return bar()",
483 " return bar()",
488 "def bar():",
484 "def bar():",
489 " raise RuntimeError('hello!')",
485 " raise RuntimeError('hello!')",
490 "foo()",
486 "foo()",
491 ]))
487 ]))
492 with capture_output() as io:
488 with capture_output() as io:
493 _ip.magic('run {}'.format(path))
489 _ip.magic('run {}'.format(path))
494 out = io.stdout
490 out = io.stdout
495 nt.assert_not_in("execfile", out)
491 nt.assert_not_in("execfile", out)
496 nt.assert_in("RuntimeError", out)
492 nt.assert_in("RuntimeError", out)
497 nt.assert_equal(out.count("---->"), 3)
493 nt.assert_equal(out.count("---->"), 3)
498
494
499 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
495 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
500 def test_script_tb():
496 def test_script_tb():
501 """Test traceback offset in `ipython script.py`"""
497 """Test traceback offset in `ipython script.py`"""
502 with TemporaryDirectory() as td:
498 with TemporaryDirectory() as td:
503 path = pjoin(td, 'foo.py')
499 path = pjoin(td, 'foo.py')
504 with open(path, 'w') as f:
500 with open(path, 'w') as f:
505 f.write('\n'.join([
501 f.write('\n'.join([
506 "def foo():",
502 "def foo():",
507 " return bar()",
503 " return bar()",
508 "def bar():",
504 "def bar():",
509 " raise RuntimeError('hello!')",
505 " raise RuntimeError('hello!')",
510 "foo()",
506 "foo()",
511 ]))
507 ]))
512 out, err = tt.ipexec(path)
508 out, err = tt.ipexec(path)
513 nt.assert_not_in("execfile", out)
509 nt.assert_not_in("execfile", out)
514 nt.assert_in("RuntimeError", out)
510 nt.assert_in("RuntimeError", out)
515 nt.assert_equal(out.count("---->"), 3)
511 nt.assert_equal(out.count("---->"), 3)
516
512
@@ -1,147 +1,148 b''
1 """Tornado handlers for nbconvert."""
1 """Tornado handlers for nbconvert."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 import io
6 import io
7 import os
7 import os
8 import zipfile
8 import zipfile
9
9
10 from tornado import web
10 from tornado import web
11
11
12 from ..base.handlers import (
12 from ..base.handlers import (
13 IPythonHandler, FilesRedirectHandler,
13 IPythonHandler, FilesRedirectHandler,
14 notebook_path_regex, path_regex,
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 from IPython.utils.py3compat import cast_bytes
18 from IPython.utils.py3compat import cast_bytes
19
19
20 def find_resource_files(output_files_dir):
20 def find_resource_files(output_files_dir):
21 files = []
21 files = []
22 for dirpath, dirnames, filenames in os.walk(output_files_dir):
22 for dirpath, dirnames, filenames in os.walk(output_files_dir):
23 files.extend([os.path.join(dirpath, f) for f in filenames])
23 files.extend([os.path.join(dirpath, f) for f in filenames])
24 return files
24 return files
25
25
26 def respond_zip(handler, name, output, resources):
26 def respond_zip(handler, name, output, resources):
27 """Zip up the output and resource files and respond with the zip file.
27 """Zip up the output and resource files and respond with the zip file.
28
28
29 Returns True if it has served a zip file, False if there are no resource
29 Returns True if it has served a zip file, False if there are no resource
30 files, in which case we serve the plain output file.
30 files, in which case we serve the plain output file.
31 """
31 """
32 # Check if we have resource files we need to zip
32 # Check if we have resource files we need to zip
33 output_files = resources.get('outputs', None)
33 output_files = resources.get('outputs', None)
34 if not output_files:
34 if not output_files:
35 return False
35 return False
36
36
37 # Headers
37 # Headers
38 zip_filename = os.path.splitext(name)[0] + '.zip'
38 zip_filename = os.path.splitext(name)[0] + '.zip'
39 handler.set_header('Content-Disposition',
39 handler.set_header('Content-Disposition',
40 'attachment; filename="%s"' % zip_filename)
40 'attachment; filename="%s"' % zip_filename)
41 handler.set_header('Content-Type', 'application/zip')
41 handler.set_header('Content-Type', 'application/zip')
42
42
43 # Prepare the zip file
43 # Prepare the zip file
44 buffer = io.BytesIO()
44 buffer = io.BytesIO()
45 zipf = zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED)
45 zipf = zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED)
46 output_filename = os.path.splitext(name)[0] + '.' + resources['output_extension']
46 output_filename = os.path.splitext(name)[0] + '.' + resources['output_extension']
47 zipf.writestr(output_filename, cast_bytes(output, 'utf-8'))
47 zipf.writestr(output_filename, cast_bytes(output, 'utf-8'))
48 for filename, data in output_files.items():
48 for filename, data in output_files.items():
49 zipf.writestr(os.path.basename(filename), data)
49 zipf.writestr(os.path.basename(filename), data)
50 zipf.close()
50 zipf.close()
51
51
52 handler.finish(buffer.getvalue())
52 handler.finish(buffer.getvalue())
53 return True
53 return True
54
54
55 def get_exporter(format, **kwargs):
55 def get_exporter(format, **kwargs):
56 """get an exporter, raising appropriate errors"""
56 """get an exporter, raising appropriate errors"""
57 # if this fails, will raise 500
57 # if this fails, will raise 500
58 try:
58 try:
59 from IPython.nbconvert.exporters.export import exporter_map
59 from IPython.nbconvert.exporters.export import exporter_map
60 except ImportError as e:
60 except ImportError as e:
61 raise web.HTTPError(500, "Could not import nbconvert: %s" % e)
61 raise web.HTTPError(500, "Could not import nbconvert: %s" % e)
62
62
63 try:
63 try:
64 Exporter = exporter_map[format]
64 Exporter = exporter_map[format]
65 except KeyError:
65 except KeyError:
66 # should this be 400?
66 # should this be 400?
67 raise web.HTTPError(404, u"No exporter for format: %s" % format)
67 raise web.HTTPError(404, u"No exporter for format: %s" % format)
68
68
69 try:
69 try:
70 return Exporter(**kwargs)
70 return Exporter(**kwargs)
71 except Exception as e:
71 except Exception as e:
72 raise web.HTTPError(500, "Could not construct Exporter: %s" % e)
72 raise web.HTTPError(500, "Could not construct Exporter: %s" % e)
73
73
74 class NbconvertFileHandler(IPythonHandler):
74 class NbconvertFileHandler(IPythonHandler):
75
75
76 SUPPORTED_METHODS = ('GET',)
76 SUPPORTED_METHODS = ('GET',)
77
77
78 @web.authenticated
78 @web.authenticated
79 def get(self, format, path='', name=None):
79 def get(self, format, path='', name=None):
80
80
81 exporter = get_exporter(format, config=self.config, log=self.log)
81 exporter = get_exporter(format, config=self.config, log=self.log)
82
82
83 path = path.strip('/')
83 path = path.strip('/')
84 model = self.contents_manager.get_model(name=name, path=path)
84 model = self.contents_manager.get_model(name=name, path=path)
85
85
86 self.set_header('Last-Modified', model['last_modified'])
86 self.set_header('Last-Modified', model['last_modified'])
87
87
88 try:
88 try:
89 output, resources = exporter.from_notebook_node(model['content'])
89 output, resources = exporter.from_notebook_node(model['content'])
90 except Exception as e:
90 except Exception as e:
91 raise web.HTTPError(500, "nbconvert failed: %s" % e)
91 raise web.HTTPError(500, "nbconvert failed: %s" % e)
92
92
93 if respond_zip(self, name, output, resources):
93 if respond_zip(self, name, output, resources):
94 return
94 return
95
95
96 # Force download if requested
96 # Force download if requested
97 if self.get_argument('download', 'false').lower() == 'true':
97 if self.get_argument('download', 'false').lower() == 'true':
98 filename = os.path.splitext(name)[0] + '.' + resources['output_extension']
98 filename = os.path.splitext(name)[0] + '.' + resources['output_extension']
99 self.set_header('Content-Disposition',
99 self.set_header('Content-Disposition',
100 'attachment; filename="%s"' % filename)
100 'attachment; filename="%s"' % filename)
101
101
102 # MIME type
102 # MIME type
103 if exporter.output_mimetype:
103 if exporter.output_mimetype:
104 self.set_header('Content-Type',
104 self.set_header('Content-Type',
105 '%s; charset=utf-8' % exporter.output_mimetype)
105 '%s; charset=utf-8' % exporter.output_mimetype)
106
106
107 self.finish(output)
107 self.finish(output)
108
108
109 class NbconvertPostHandler(IPythonHandler):
109 class NbconvertPostHandler(IPythonHandler):
110 SUPPORTED_METHODS = ('POST',)
110 SUPPORTED_METHODS = ('POST',)
111
111
112 @web.authenticated
112 @web.authenticated
113 def post(self, format):
113 def post(self, format):
114 exporter = get_exporter(format, config=self.config)
114 exporter = get_exporter(format, config=self.config)
115
115
116 model = self.get_json_body()
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 try:
120 try:
120 output, resources = exporter.from_notebook_node(nbnode)
121 output, resources = exporter.from_notebook_node(nbnode)
121 except Exception as e:
122 except Exception as e:
122 raise web.HTTPError(500, "nbconvert failed: %s" % e)
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 return
126 return
126
127
127 # MIME type
128 # MIME type
128 if exporter.output_mimetype:
129 if exporter.output_mimetype:
129 self.set_header('Content-Type',
130 self.set_header('Content-Type',
130 '%s; charset=utf-8' % exporter.output_mimetype)
131 '%s; charset=utf-8' % exporter.output_mimetype)
131
132
132 self.finish(output)
133 self.finish(output)
133
134
134
135
135 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
136 # URL to handler mappings
137 # URL to handler mappings
137 #-----------------------------------------------------------------------------
138 #-----------------------------------------------------------------------------
138
139
139 _format_regex = r"(?P<format>\w+)"
140 _format_regex = r"(?P<format>\w+)"
140
141
141
142
142 default_handlers = [
143 default_handlers = [
143 (r"/nbconvert/%s%s" % (_format_regex, notebook_path_regex),
144 (r"/nbconvert/%s%s" % (_format_regex, notebook_path_regex),
144 NbconvertFileHandler),
145 NbconvertFileHandler),
145 (r"/nbconvert/%s" % _format_regex, NbconvertPostHandler),
146 (r"/nbconvert/%s" % _format_regex, NbconvertPostHandler),
146 (r"/nbconvert/html%s" % path_regex, FilesRedirectHandler),
147 (r"/nbconvert/html%s" % path_regex, FilesRedirectHandler),
147 ]
148 ]
@@ -1,129 +1,132 b''
1 # coding: utf-8
1 # coding: utf-8
2 import base64
2 import base64
3 import io
3 import io
4 import json
4 import json
5 import os
5 import os
6 from os.path import join as pjoin
6 from os.path import join as pjoin
7 import shutil
7 import shutil
8
8
9 import requests
9 import requests
10
10
11 from IPython.html.utils import url_path_join
11 from IPython.html.utils import url_path_join
12 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
12 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
13 from IPython.nbformat.current import (new_notebook, write, new_worksheet,
13 from IPython.nbformat import write
14 new_heading_cell, new_code_cell,
14 from IPython.nbformat.v4 import (
15 new_output)
15 new_notebook, new_markdown_cell, new_code_cell, new_output,
16 )
16
17
17 from IPython.testing.decorators import onlyif_cmds_exist
18 from IPython.testing.decorators import onlyif_cmds_exist
18
19
19
20
20 class NbconvertAPI(object):
21 class NbconvertAPI(object):
21 """Wrapper for nbconvert API calls."""
22 """Wrapper for nbconvert API calls."""
22 def __init__(self, base_url):
23 def __init__(self, base_url):
23 self.base_url = base_url
24 self.base_url = base_url
24
25
25 def _req(self, verb, path, body=None, params=None):
26 def _req(self, verb, path, body=None, params=None):
26 response = requests.request(verb,
27 response = requests.request(verb,
27 url_path_join(self.base_url, 'nbconvert', path),
28 url_path_join(self.base_url, 'nbconvert', path),
28 data=body, params=params,
29 data=body, params=params,
29 )
30 )
30 response.raise_for_status()
31 response.raise_for_status()
31 return response
32 return response
32
33
33 def from_file(self, format, path, name, download=False):
34 def from_file(self, format, path, name, download=False):
34 return self._req('GET', url_path_join(format, path, name),
35 return self._req('GET', url_path_join(format, path, name),
35 params={'download':download})
36 params={'download':download})
36
37
37 def from_post(self, format, nbmodel):
38 def from_post(self, format, nbmodel):
38 body = json.dumps(nbmodel)
39 body = json.dumps(nbmodel)
39 return self._req('POST', format, body)
40 return self._req('POST', format, body)
40
41
41 def list_formats(self):
42 def list_formats(self):
42 return self._req('GET', '')
43 return self._req('GET', '')
43
44
44 png_green_pixel = base64.encodestring(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00'
45 png_green_pixel = base64.encodestring(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00'
45 b'\x00\x00\x01\x00\x00x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDAT'
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 class APITest(NotebookTestBase):
50 class APITest(NotebookTestBase):
49 def setUp(self):
51 def setUp(self):
50 nbdir = self.notebook_dir.name
52 nbdir = self.notebook_dir.name
51
53
52 if not os.path.isdir(pjoin(nbdir, 'foo')):
54 if not os.path.isdir(pjoin(nbdir, 'foo')):
53 os.mkdir(pjoin(nbdir, 'foo'))
55 os.mkdir(pjoin(nbdir, 'foo'))
54
56
55 nb = new_notebook(name='testnb')
57 nb = new_notebook()
56
58
57 ws = new_worksheet()
59 nb.cells.append(new_markdown_cell(u'Created by test ³'))
58 nb.worksheets = [ws]
60 cc1 = new_code_cell(source=u'print(2*6)')
59 ws.cells.append(new_heading_cell(u'Created by test ³'))
61 cc1.outputs.append(new_output(output_type="stream", text=u'12'))
60 cc1 = new_code_cell(input=u'print(2*6)')
62 cc1.outputs.append(new_output(output_type="execute_result",
61 cc1.outputs.append(new_output(output_text=u'12', output_type='stream'))
63 data={'image/png' : png_green_pixel},
62 cc1.outputs.append(new_output(output_png=png_green_pixel, output_type='pyout'))
64 execution_count=1,
63 ws.cells.append(cc1)
65 ))
66 nb.cells.append(cc1)
64
67
65 with io.open(pjoin(nbdir, 'foo', 'testnb.ipynb'), 'w',
68 with io.open(pjoin(nbdir, 'foo', 'testnb.ipynb'), 'w',
66 encoding='utf-8') as f:
69 encoding='utf-8') as f:
67 write(nb, f, format='ipynb')
70 write(nb, f, version=4)
68
71
69 self.nbconvert_api = NbconvertAPI(self.base_url())
72 self.nbconvert_api = NbconvertAPI(self.base_url())
70
73
71 def tearDown(self):
74 def tearDown(self):
72 nbdir = self.notebook_dir.name
75 nbdir = self.notebook_dir.name
73
76
74 for dname in ['foo']:
77 for dname in ['foo']:
75 shutil.rmtree(pjoin(nbdir, dname), ignore_errors=True)
78 shutil.rmtree(pjoin(nbdir, dname), ignore_errors=True)
76
79
77 @onlyif_cmds_exist('pandoc')
80 @onlyif_cmds_exist('pandoc')
78 def test_from_file(self):
81 def test_from_file(self):
79 r = self.nbconvert_api.from_file('html', 'foo', 'testnb.ipynb')
82 r = self.nbconvert_api.from_file('html', 'foo', 'testnb.ipynb')
80 self.assertEqual(r.status_code, 200)
83 self.assertEqual(r.status_code, 200)
81 self.assertIn(u'text/html', r.headers['Content-Type'])
84 self.assertIn(u'text/html', r.headers['Content-Type'])
82 self.assertIn(u'Created by test', r.text)
85 self.assertIn(u'Created by test', r.text)
83 self.assertIn(u'print', r.text)
86 self.assertIn(u'print', r.text)
84
87
85 r = self.nbconvert_api.from_file('python', 'foo', 'testnb.ipynb')
88 r = self.nbconvert_api.from_file('python', 'foo', 'testnb.ipynb')
86 self.assertIn(u'text/x-python', r.headers['Content-Type'])
89 self.assertIn(u'text/x-python', r.headers['Content-Type'])
87 self.assertIn(u'print(2*6)', r.text)
90 self.assertIn(u'print(2*6)', r.text)
88
91
89 @onlyif_cmds_exist('pandoc')
92 @onlyif_cmds_exist('pandoc')
90 def test_from_file_404(self):
93 def test_from_file_404(self):
91 with assert_http_error(404):
94 with assert_http_error(404):
92 self.nbconvert_api.from_file('html', 'foo', 'thisdoesntexist.ipynb')
95 self.nbconvert_api.from_file('html', 'foo', 'thisdoesntexist.ipynb')
93
96
94 @onlyif_cmds_exist('pandoc')
97 @onlyif_cmds_exist('pandoc')
95 def test_from_file_download(self):
98 def test_from_file_download(self):
96 r = self.nbconvert_api.from_file('python', 'foo', 'testnb.ipynb', download=True)
99 r = self.nbconvert_api.from_file('python', 'foo', 'testnb.ipynb', download=True)
97 content_disposition = r.headers['Content-Disposition']
100 content_disposition = r.headers['Content-Disposition']
98 self.assertIn('attachment', content_disposition)
101 self.assertIn('attachment', content_disposition)
99 self.assertIn('testnb.py', content_disposition)
102 self.assertIn('testnb.py', content_disposition)
100
103
101 @onlyif_cmds_exist('pandoc')
104 @onlyif_cmds_exist('pandoc')
102 def test_from_file_zip(self):
105 def test_from_file_zip(self):
103 r = self.nbconvert_api.from_file('latex', 'foo', 'testnb.ipynb', download=True)
106 r = self.nbconvert_api.from_file('latex', 'foo', 'testnb.ipynb', download=True)
104 self.assertIn(u'application/zip', r.headers['Content-Type'])
107 self.assertIn(u'application/zip', r.headers['Content-Type'])
105 self.assertIn(u'.zip', r.headers['Content-Disposition'])
108 self.assertIn(u'.zip', r.headers['Content-Disposition'])
106
109
107 @onlyif_cmds_exist('pandoc')
110 @onlyif_cmds_exist('pandoc')
108 def test_from_post(self):
111 def test_from_post(self):
109 nbmodel_url = url_path_join(self.base_url(), 'api/contents/foo/testnb.ipynb')
112 nbmodel_url = url_path_join(self.base_url(), 'api/contents/foo/testnb.ipynb')
110 nbmodel = requests.get(nbmodel_url).json()
113 nbmodel = requests.get(nbmodel_url).json()
111
114
112 r = self.nbconvert_api.from_post(format='html', nbmodel=nbmodel)
115 r = self.nbconvert_api.from_post(format='html', nbmodel=nbmodel)
113 self.assertEqual(r.status_code, 200)
116 self.assertEqual(r.status_code, 200)
114 self.assertIn(u'text/html', r.headers['Content-Type'])
117 self.assertIn(u'text/html', r.headers['Content-Type'])
115 self.assertIn(u'Created by test', r.text)
118 self.assertIn(u'Created by test', r.text)
116 self.assertIn(u'print', r.text)
119 self.assertIn(u'print', r.text)
117
120
118 r = self.nbconvert_api.from_post(format='python', nbmodel=nbmodel)
121 r = self.nbconvert_api.from_post(format='python', nbmodel=nbmodel)
119 self.assertIn(u'text/x-python', r.headers['Content-Type'])
122 self.assertIn(u'text/x-python', r.headers['Content-Type'])
120 self.assertIn(u'print(2*6)', r.text)
123 self.assertIn(u'print(2*6)', r.text)
121
124
122 @onlyif_cmds_exist('pandoc')
125 @onlyif_cmds_exist('pandoc')
123 def test_from_post_zip(self):
126 def test_from_post_zip(self):
124 nbmodel_url = url_path_join(self.base_url(), 'api/contents/foo/testnb.ipynb')
127 nbmodel_url = url_path_join(self.base_url(), 'api/contents/foo/testnb.ipynb')
125 nbmodel = requests.get(nbmodel_url).json()
128 nbmodel = requests.get(nbmodel_url).json()
126
129
127 r = self.nbconvert_api.from_post(format='latex', nbmodel=nbmodel)
130 r = self.nbconvert_api.from_post(format='latex', nbmodel=nbmodel)
128 self.assertIn(u'application/zip', r.headers['Content-Type'])
131 self.assertIn(u'application/zip', r.headers['Content-Type'])
129 self.assertIn(u'.zip', r.headers['Content-Disposition'])
132 self.assertIn(u'.zip', r.headers['Content-Disposition'])
@@ -1,545 +1,545 b''
1 """A contents manager that uses the local file system for storage."""
1 """A contents manager that uses the local file system for storage."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 import base64
6 import base64
7 import io
7 import io
8 import os
8 import os
9 import glob
9 import glob
10 import shutil
10 import shutil
11
11
12 from tornado import web
12 from tornado import web
13
13
14 from .manager import ContentsManager
14 from .manager import ContentsManager
15 from IPython.nbformat import current
15 from IPython import nbformat
16 from IPython.utils.io import atomic_writing
16 from IPython.utils.io import atomic_writing
17 from IPython.utils.path import ensure_dir_exists
17 from IPython.utils.path import ensure_dir_exists
18 from IPython.utils.traitlets import Unicode, Bool, TraitError
18 from IPython.utils.traitlets import Unicode, Bool, TraitError
19 from IPython.utils.py3compat import getcwd
19 from IPython.utils.py3compat import getcwd
20 from IPython.utils import tz
20 from IPython.utils import tz
21 from IPython.html.utils import is_hidden, to_os_path, url_path_join
21 from IPython.html.utils import is_hidden, to_os_path, url_path_join
22
22
23
23
24 class FileContentsManager(ContentsManager):
24 class FileContentsManager(ContentsManager):
25
25
26 root_dir = Unicode(getcwd(), config=True)
26 root_dir = Unicode(getcwd(), config=True)
27
27
28 save_script = Bool(False, config=True, help='DEPRECATED, IGNORED')
28 save_script = Bool(False, config=True, help='DEPRECATED, IGNORED')
29 def _save_script_changed(self):
29 def _save_script_changed(self):
30 self.log.warn("""
30 self.log.warn("""
31 Automatically saving notebooks as scripts has been removed.
31 Automatically saving notebooks as scripts has been removed.
32 Use `ipython nbconvert --to python [notebook]` instead.
32 Use `ipython nbconvert --to python [notebook]` instead.
33 """)
33 """)
34
34
35 def _root_dir_changed(self, name, old, new):
35 def _root_dir_changed(self, name, old, new):
36 """Do a bit of validation of the root_dir."""
36 """Do a bit of validation of the root_dir."""
37 if not os.path.isabs(new):
37 if not os.path.isabs(new):
38 # If we receive a non-absolute path, make it absolute.
38 # If we receive a non-absolute path, make it absolute.
39 self.root_dir = os.path.abspath(new)
39 self.root_dir = os.path.abspath(new)
40 return
40 return
41 if not os.path.isdir(new):
41 if not os.path.isdir(new):
42 raise TraitError("%r is not a directory" % new)
42 raise TraitError("%r is not a directory" % new)
43
43
44 checkpoint_dir = Unicode('.ipynb_checkpoints', config=True,
44 checkpoint_dir = Unicode('.ipynb_checkpoints', config=True,
45 help="""The directory name in which to keep file checkpoints
45 help="""The directory name in which to keep file checkpoints
46
46
47 This is a path relative to the file's own directory.
47 This is a path relative to the file's own directory.
48
48
49 By default, it is .ipynb_checkpoints
49 By default, it is .ipynb_checkpoints
50 """
50 """
51 )
51 )
52
52
53 def _copy(self, src, dest):
53 def _copy(self, src, dest):
54 """copy src to dest
54 """copy src to dest
55
55
56 like shutil.copy2, but log errors in copystat
56 like shutil.copy2, but log errors in copystat
57 """
57 """
58 shutil.copyfile(src, dest)
58 shutil.copyfile(src, dest)
59 try:
59 try:
60 shutil.copystat(src, dest)
60 shutil.copystat(src, dest)
61 except OSError as e:
61 except OSError as e:
62 self.log.debug("copystat on %s failed", dest, exc_info=True)
62 self.log.debug("copystat on %s failed", dest, exc_info=True)
63
63
64 def _get_os_path(self, name=None, path=''):
64 def _get_os_path(self, name=None, path=''):
65 """Given a filename and API path, return its file system
65 """Given a filename and API path, return its file system
66 path.
66 path.
67
67
68 Parameters
68 Parameters
69 ----------
69 ----------
70 name : string
70 name : string
71 A filename
71 A filename
72 path : string
72 path : string
73 The relative API path to the named file.
73 The relative API path to the named file.
74
74
75 Returns
75 Returns
76 -------
76 -------
77 path : string
77 path : string
78 API path to be evaluated relative to root_dir.
78 API path to be evaluated relative to root_dir.
79 """
79 """
80 if name is not None:
80 if name is not None:
81 path = url_path_join(path, name)
81 path = url_path_join(path, name)
82 return to_os_path(path, self.root_dir)
82 return to_os_path(path, self.root_dir)
83
83
84 def path_exists(self, path):
84 def path_exists(self, path):
85 """Does the API-style path refer to an extant directory?
85 """Does the API-style path refer to an extant directory?
86
86
87 API-style wrapper for os.path.isdir
87 API-style wrapper for os.path.isdir
88
88
89 Parameters
89 Parameters
90 ----------
90 ----------
91 path : string
91 path : string
92 The path to check. This is an API path (`/` separated,
92 The path to check. This is an API path (`/` separated,
93 relative to root_dir).
93 relative to root_dir).
94
94
95 Returns
95 Returns
96 -------
96 -------
97 exists : bool
97 exists : bool
98 Whether the path is indeed a directory.
98 Whether the path is indeed a directory.
99 """
99 """
100 path = path.strip('/')
100 path = path.strip('/')
101 os_path = self._get_os_path(path=path)
101 os_path = self._get_os_path(path=path)
102 return os.path.isdir(os_path)
102 return os.path.isdir(os_path)
103
103
104 def is_hidden(self, path):
104 def is_hidden(self, path):
105 """Does the API style path correspond to a hidden directory or file?
105 """Does the API style path correspond to a hidden directory or file?
106
106
107 Parameters
107 Parameters
108 ----------
108 ----------
109 path : string
109 path : string
110 The path to check. This is an API path (`/` separated,
110 The path to check. This is an API path (`/` separated,
111 relative to root_dir).
111 relative to root_dir).
112
112
113 Returns
113 Returns
114 -------
114 -------
115 exists : bool
115 exists : bool
116 Whether the path is hidden.
116 Whether the path is hidden.
117
117
118 """
118 """
119 path = path.strip('/')
119 path = path.strip('/')
120 os_path = self._get_os_path(path=path)
120 os_path = self._get_os_path(path=path)
121 return is_hidden(os_path, self.root_dir)
121 return is_hidden(os_path, self.root_dir)
122
122
123 def file_exists(self, name, path=''):
123 def file_exists(self, name, path=''):
124 """Returns True if the file exists, else returns False.
124 """Returns True if the file exists, else returns False.
125
125
126 API-style wrapper for os.path.isfile
126 API-style wrapper for os.path.isfile
127
127
128 Parameters
128 Parameters
129 ----------
129 ----------
130 name : string
130 name : string
131 The name of the file you are checking.
131 The name of the file you are checking.
132 path : string
132 path : string
133 The relative path to the file's directory (with '/' as separator)
133 The relative path to the file's directory (with '/' as separator)
134
134
135 Returns
135 Returns
136 -------
136 -------
137 exists : bool
137 exists : bool
138 Whether the file exists.
138 Whether the file exists.
139 """
139 """
140 path = path.strip('/')
140 path = path.strip('/')
141 nbpath = self._get_os_path(name, path=path)
141 nbpath = self._get_os_path(name, path=path)
142 return os.path.isfile(nbpath)
142 return os.path.isfile(nbpath)
143
143
144 def exists(self, name=None, path=''):
144 def exists(self, name=None, path=''):
145 """Returns True if the path [and name] exists, else returns False.
145 """Returns True if the path [and name] exists, else returns False.
146
146
147 API-style wrapper for os.path.exists
147 API-style wrapper for os.path.exists
148
148
149 Parameters
149 Parameters
150 ----------
150 ----------
151 name : string
151 name : string
152 The name of the file you are checking.
152 The name of the file you are checking.
153 path : string
153 path : string
154 The relative path to the file's directory (with '/' as separator)
154 The relative path to the file's directory (with '/' as separator)
155
155
156 Returns
156 Returns
157 -------
157 -------
158 exists : bool
158 exists : bool
159 Whether the target exists.
159 Whether the target exists.
160 """
160 """
161 path = path.strip('/')
161 path = path.strip('/')
162 os_path = self._get_os_path(name, path=path)
162 os_path = self._get_os_path(name, path=path)
163 return os.path.exists(os_path)
163 return os.path.exists(os_path)
164
164
165 def _base_model(self, name, path=''):
165 def _base_model(self, name, path=''):
166 """Build the common base of a contents model"""
166 """Build the common base of a contents model"""
167 os_path = self._get_os_path(name, path)
167 os_path = self._get_os_path(name, path)
168 info = os.stat(os_path)
168 info = os.stat(os_path)
169 last_modified = tz.utcfromtimestamp(info.st_mtime)
169 last_modified = tz.utcfromtimestamp(info.st_mtime)
170 created = tz.utcfromtimestamp(info.st_ctime)
170 created = tz.utcfromtimestamp(info.st_ctime)
171 # Create the base model.
171 # Create the base model.
172 model = {}
172 model = {}
173 model['name'] = name
173 model['name'] = name
174 model['path'] = path
174 model['path'] = path
175 model['last_modified'] = last_modified
175 model['last_modified'] = last_modified
176 model['created'] = created
176 model['created'] = created
177 model['content'] = None
177 model['content'] = None
178 model['format'] = None
178 model['format'] = None
179 model['message'] = None
179 model['message'] = None
180 return model
180 return model
181
181
182 def _dir_model(self, name, path='', content=True):
182 def _dir_model(self, name, path='', content=True):
183 """Build a model for a directory
183 """Build a model for a directory
184
184
185 if content is requested, will include a listing of the directory
185 if content is requested, will include a listing of the directory
186 """
186 """
187 os_path = self._get_os_path(name, path)
187 os_path = self._get_os_path(name, path)
188
188
189 four_o_four = u'directory does not exist: %r' % os_path
189 four_o_four = u'directory does not exist: %r' % os_path
190
190
191 if not os.path.isdir(os_path):
191 if not os.path.isdir(os_path):
192 raise web.HTTPError(404, four_o_four)
192 raise web.HTTPError(404, four_o_four)
193 elif is_hidden(os_path, self.root_dir):
193 elif is_hidden(os_path, self.root_dir):
194 self.log.info("Refusing to serve hidden directory %r, via 404 Error",
194 self.log.info("Refusing to serve hidden directory %r, via 404 Error",
195 os_path
195 os_path
196 )
196 )
197 raise web.HTTPError(404, four_o_four)
197 raise web.HTTPError(404, four_o_four)
198
198
199 if name is None:
199 if name is None:
200 if '/' in path:
200 if '/' in path:
201 path, name = path.rsplit('/', 1)
201 path, name = path.rsplit('/', 1)
202 else:
202 else:
203 name = ''
203 name = ''
204 model = self._base_model(name, path)
204 model = self._base_model(name, path)
205 model['type'] = 'directory'
205 model['type'] = 'directory'
206 dir_path = u'{}/{}'.format(path, name)
206 dir_path = u'{}/{}'.format(path, name)
207 if content:
207 if content:
208 model['content'] = contents = []
208 model['content'] = contents = []
209 for os_path in glob.glob(self._get_os_path('*', dir_path)):
209 for os_path in glob.glob(self._get_os_path('*', dir_path)):
210 name = os.path.basename(os_path)
210 name = os.path.basename(os_path)
211 # skip over broken symlinks in listing
211 # skip over broken symlinks in listing
212 if not os.path.exists(os_path):
212 if not os.path.exists(os_path):
213 self.log.warn("%s doesn't exist", os_path)
213 self.log.warn("%s doesn't exist", os_path)
214 continue
214 continue
215 if self.should_list(name) and not is_hidden(os_path, self.root_dir):
215 if self.should_list(name) and not is_hidden(os_path, self.root_dir):
216 contents.append(self.get_model(name=name, path=dir_path, content=False))
216 contents.append(self.get_model(name=name, path=dir_path, content=False))
217
217
218 model['format'] = 'json'
218 model['format'] = 'json'
219
219
220 return model
220 return model
221
221
222 def _file_model(self, name, path='', content=True):
222 def _file_model(self, name, path='', content=True):
223 """Build a model for a file
223 """Build a model for a file
224
224
225 if content is requested, include the file contents.
225 if content is requested, include the file contents.
226 UTF-8 text files will be unicode, binary files will be base64-encoded.
226 UTF-8 text files will be unicode, binary files will be base64-encoded.
227 """
227 """
228 model = self._base_model(name, path)
228 model = self._base_model(name, path)
229 model['type'] = 'file'
229 model['type'] = 'file'
230 if content:
230 if content:
231 os_path = self._get_os_path(name, path)
231 os_path = self._get_os_path(name, path)
232 with io.open(os_path, 'rb') as f:
232 with io.open(os_path, 'rb') as f:
233 bcontent = f.read()
233 bcontent = f.read()
234 try:
234 try:
235 model['content'] = bcontent.decode('utf8')
235 model['content'] = bcontent.decode('utf8')
236 except UnicodeError as e:
236 except UnicodeError as e:
237 model['content'] = base64.encodestring(bcontent).decode('ascii')
237 model['content'] = base64.encodestring(bcontent).decode('ascii')
238 model['format'] = 'base64'
238 model['format'] = 'base64'
239 else:
239 else:
240 model['format'] = 'text'
240 model['format'] = 'text'
241 return model
241 return model
242
242
243
243
244 def _notebook_model(self, name, path='', content=True):
244 def _notebook_model(self, name, path='', content=True):
245 """Build a notebook model
245 """Build a notebook model
246
246
247 if content is requested, the notebook content will be populated
247 if content is requested, the notebook content will be populated
248 as a JSON structure (not double-serialized)
248 as a JSON structure (not double-serialized)
249 """
249 """
250 model = self._base_model(name, path)
250 model = self._base_model(name, path)
251 model['type'] = 'notebook'
251 model['type'] = 'notebook'
252 if content:
252 if content:
253 os_path = self._get_os_path(name, path)
253 os_path = self._get_os_path(name, path)
254 with io.open(os_path, 'r', encoding='utf-8') as f:
254 with io.open(os_path, 'r', encoding='utf-8') as f:
255 try:
255 try:
256 nb = current.read(f, u'json')
256 nb = nbformat.read(f, as_version=4)
257 except Exception as e:
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 self.mark_trusted_cells(nb, name, path)
259 self.mark_trusted_cells(nb, name, path)
260 model['content'] = nb
260 model['content'] = nb
261 model['format'] = 'json'
261 model['format'] = 'json'
262 self.validate_notebook_model(model)
262 self.validate_notebook_model(model)
263 return model
263 return model
264
264
265 def get_model(self, name, path='', content=True):
265 def get_model(self, name, path='', content=True):
266 """ Takes a path and name for an entity and returns its model
266 """ Takes a path and name for an entity and returns its model
267
267
268 Parameters
268 Parameters
269 ----------
269 ----------
270 name : str
270 name : str
271 the name of the target
271 the name of the target
272 path : str
272 path : str
273 the API path that describes the relative path for the target
273 the API path that describes the relative path for the target
274
274
275 Returns
275 Returns
276 -------
276 -------
277 model : dict
277 model : dict
278 the contents model. If content=True, returns the contents
278 the contents model. If content=True, returns the contents
279 of the file or directory as well.
279 of the file or directory as well.
280 """
280 """
281 path = path.strip('/')
281 path = path.strip('/')
282
282
283 if not self.exists(name=name, path=path):
283 if not self.exists(name=name, path=path):
284 raise web.HTTPError(404, u'No such file or directory: %s/%s' % (path, name))
284 raise web.HTTPError(404, u'No such file or directory: %s/%s' % (path, name))
285
285
286 os_path = self._get_os_path(name, path)
286 os_path = self._get_os_path(name, path)
287 if os.path.isdir(os_path):
287 if os.path.isdir(os_path):
288 model = self._dir_model(name, path, content)
288 model = self._dir_model(name, path, content)
289 elif name.endswith('.ipynb'):
289 elif name.endswith('.ipynb'):
290 model = self._notebook_model(name, path, content)
290 model = self._notebook_model(name, path, content)
291 else:
291 else:
292 model = self._file_model(name, path, content)
292 model = self._file_model(name, path, content)
293 return model
293 return model
294
294
295 def _save_notebook(self, os_path, model, name='', path=''):
295 def _save_notebook(self, os_path, model, name='', path=''):
296 """save a notebook file"""
296 """save a notebook file"""
297 # Save the notebook file
297 # Save the notebook file
298 nb = current.to_notebook_json(model['content'])
298 nb = nbformat.from_dict(model['content'])
299
299
300 self.check_and_sign(nb, name, path)
300 self.check_and_sign(nb, name, path)
301
301
302 if 'name' in nb['metadata']:
302 if 'name' in nb['metadata']:
303 nb['metadata']['name'] = u''
303 nb['metadata']['name'] = u''
304
304
305 with atomic_writing(os_path, encoding='utf-8') as f:
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 def _save_file(self, os_path, model, name='', path=''):
308 def _save_file(self, os_path, model, name='', path=''):
309 """save a non-notebook file"""
309 """save a non-notebook file"""
310 fmt = model.get('format', None)
310 fmt = model.get('format', None)
311 if fmt not in {'text', 'base64'}:
311 if fmt not in {'text', 'base64'}:
312 raise web.HTTPError(400, "Must specify format of file contents as 'text' or 'base64'")
312 raise web.HTTPError(400, "Must specify format of file contents as 'text' or 'base64'")
313 try:
313 try:
314 content = model['content']
314 content = model['content']
315 if fmt == 'text':
315 if fmt == 'text':
316 bcontent = content.encode('utf8')
316 bcontent = content.encode('utf8')
317 else:
317 else:
318 b64_bytes = content.encode('ascii')
318 b64_bytes = content.encode('ascii')
319 bcontent = base64.decodestring(b64_bytes)
319 bcontent = base64.decodestring(b64_bytes)
320 except Exception as e:
320 except Exception as e:
321 raise web.HTTPError(400, u'Encoding error saving %s: %s' % (os_path, e))
321 raise web.HTTPError(400, u'Encoding error saving %s: %s' % (os_path, e))
322 with atomic_writing(os_path, text=False) as f:
322 with atomic_writing(os_path, text=False) as f:
323 f.write(bcontent)
323 f.write(bcontent)
324
324
325 def _save_directory(self, os_path, model, name='', path=''):
325 def _save_directory(self, os_path, model, name='', path=''):
326 """create a directory"""
326 """create a directory"""
327 if is_hidden(os_path, self.root_dir):
327 if is_hidden(os_path, self.root_dir):
328 raise web.HTTPError(400, u'Cannot create hidden directory %r' % os_path)
328 raise web.HTTPError(400, u'Cannot create hidden directory %r' % os_path)
329 if not os.path.exists(os_path):
329 if not os.path.exists(os_path):
330 os.mkdir(os_path)
330 os.mkdir(os_path)
331 elif not os.path.isdir(os_path):
331 elif not os.path.isdir(os_path):
332 raise web.HTTPError(400, u'Not a directory: %s' % (os_path))
332 raise web.HTTPError(400, u'Not a directory: %s' % (os_path))
333 else:
333 else:
334 self.log.debug("Directory %r already exists", os_path)
334 self.log.debug("Directory %r already exists", os_path)
335
335
336 def save(self, model, name='', path=''):
336 def save(self, model, name='', path=''):
337 """Save the file model and return the model with no content."""
337 """Save the file model and return the model with no content."""
338 path = path.strip('/')
338 path = path.strip('/')
339
339
340 if 'type' not in model:
340 if 'type' not in model:
341 raise web.HTTPError(400, u'No file type provided')
341 raise web.HTTPError(400, u'No file type provided')
342 if 'content' not in model and model['type'] != 'directory':
342 if 'content' not in model and model['type'] != 'directory':
343 raise web.HTTPError(400, u'No file content provided')
343 raise web.HTTPError(400, u'No file content provided')
344
344
345 # One checkpoint should always exist
345 # One checkpoint should always exist
346 if self.file_exists(name, path) and not self.list_checkpoints(name, path):
346 if self.file_exists(name, path) and not self.list_checkpoints(name, path):
347 self.create_checkpoint(name, path)
347 self.create_checkpoint(name, path)
348
348
349 new_path = model.get('path', path).strip('/')
349 new_path = model.get('path', path).strip('/')
350 new_name = model.get('name', name)
350 new_name = model.get('name', name)
351
351
352 if path != new_path or name != new_name:
352 if path != new_path or name != new_name:
353 self.rename(name, path, new_name, new_path)
353 self.rename(name, path, new_name, new_path)
354
354
355 os_path = self._get_os_path(new_name, new_path)
355 os_path = self._get_os_path(new_name, new_path)
356 self.log.debug("Saving %s", os_path)
356 self.log.debug("Saving %s", os_path)
357 try:
357 try:
358 if model['type'] == 'notebook':
358 if model['type'] == 'notebook':
359 self._save_notebook(os_path, model, new_name, new_path)
359 self._save_notebook(os_path, model, new_name, new_path)
360 elif model['type'] == 'file':
360 elif model['type'] == 'file':
361 self._save_file(os_path, model, new_name, new_path)
361 self._save_file(os_path, model, new_name, new_path)
362 elif model['type'] == 'directory':
362 elif model['type'] == 'directory':
363 self._save_directory(os_path, model, new_name, new_path)
363 self._save_directory(os_path, model, new_name, new_path)
364 else:
364 else:
365 raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
365 raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
366 except web.HTTPError:
366 except web.HTTPError:
367 raise
367 raise
368 except Exception as e:
368 except Exception as e:
369 raise web.HTTPError(400, u'Unexpected error while saving file: %s %s' % (os_path, e))
369 raise web.HTTPError(400, u'Unexpected error while saving file: %s %s' % (os_path, e))
370
370
371 validation_message = None
371 validation_message = None
372 if model['type'] == 'notebook':
372 if model['type'] == 'notebook':
373 self.validate_notebook_model(model)
373 self.validate_notebook_model(model)
374 validation_message = model.get('message', None)
374 validation_message = model.get('message', None)
375
375
376 model = self.get_model(new_name, new_path, content=False)
376 model = self.get_model(new_name, new_path, content=False)
377 if validation_message:
377 if validation_message:
378 model['message'] = validation_message
378 model['message'] = validation_message
379 return model
379 return model
380
380
381 def update(self, model, name, path=''):
381 def update(self, model, name, path=''):
382 """Update the file's path and/or name
382 """Update the file's path and/or name
383
383
384 For use in PATCH requests, to enable renaming a file without
384 For use in PATCH requests, to enable renaming a file without
385 re-uploading its contents. Only used for renaming at the moment.
385 re-uploading its contents. Only used for renaming at the moment.
386 """
386 """
387 path = path.strip('/')
387 path = path.strip('/')
388 new_name = model.get('name', name)
388 new_name = model.get('name', name)
389 new_path = model.get('path', path).strip('/')
389 new_path = model.get('path', path).strip('/')
390 if path != new_path or name != new_name:
390 if path != new_path or name != new_name:
391 self.rename(name, path, new_name, new_path)
391 self.rename(name, path, new_name, new_path)
392 model = self.get_model(new_name, new_path, content=False)
392 model = self.get_model(new_name, new_path, content=False)
393 return model
393 return model
394
394
395 def delete(self, name, path=''):
395 def delete(self, name, path=''):
396 """Delete file by name and path."""
396 """Delete file by name and path."""
397 path = path.strip('/')
397 path = path.strip('/')
398 os_path = self._get_os_path(name, path)
398 os_path = self._get_os_path(name, path)
399 rm = os.unlink
399 rm = os.unlink
400 if os.path.isdir(os_path):
400 if os.path.isdir(os_path):
401 listing = os.listdir(os_path)
401 listing = os.listdir(os_path)
402 # don't delete non-empty directories (checkpoints dir doesn't count)
402 # don't delete non-empty directories (checkpoints dir doesn't count)
403 if listing and listing != [self.checkpoint_dir]:
403 if listing and listing != [self.checkpoint_dir]:
404 raise web.HTTPError(400, u'Directory %s not empty' % os_path)
404 raise web.HTTPError(400, u'Directory %s not empty' % os_path)
405 elif not os.path.isfile(os_path):
405 elif not os.path.isfile(os_path):
406 raise web.HTTPError(404, u'File does not exist: %s' % os_path)
406 raise web.HTTPError(404, u'File does not exist: %s' % os_path)
407
407
408 # clear checkpoints
408 # clear checkpoints
409 for checkpoint in self.list_checkpoints(name, path):
409 for checkpoint in self.list_checkpoints(name, path):
410 checkpoint_id = checkpoint['id']
410 checkpoint_id = checkpoint['id']
411 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
411 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
412 if os.path.isfile(cp_path):
412 if os.path.isfile(cp_path):
413 self.log.debug("Unlinking checkpoint %s", cp_path)
413 self.log.debug("Unlinking checkpoint %s", cp_path)
414 os.unlink(cp_path)
414 os.unlink(cp_path)
415
415
416 if os.path.isdir(os_path):
416 if os.path.isdir(os_path):
417 self.log.debug("Removing directory %s", os_path)
417 self.log.debug("Removing directory %s", os_path)
418 shutil.rmtree(os_path)
418 shutil.rmtree(os_path)
419 else:
419 else:
420 self.log.debug("Unlinking file %s", os_path)
420 self.log.debug("Unlinking file %s", os_path)
421 rm(os_path)
421 rm(os_path)
422
422
423 def rename(self, old_name, old_path, new_name, new_path):
423 def rename(self, old_name, old_path, new_name, new_path):
424 """Rename a file."""
424 """Rename a file."""
425 old_path = old_path.strip('/')
425 old_path = old_path.strip('/')
426 new_path = new_path.strip('/')
426 new_path = new_path.strip('/')
427 if new_name == old_name and new_path == old_path:
427 if new_name == old_name and new_path == old_path:
428 return
428 return
429
429
430 new_os_path = self._get_os_path(new_name, new_path)
430 new_os_path = self._get_os_path(new_name, new_path)
431 old_os_path = self._get_os_path(old_name, old_path)
431 old_os_path = self._get_os_path(old_name, old_path)
432
432
433 # Should we proceed with the move?
433 # Should we proceed with the move?
434 if os.path.isfile(new_os_path):
434 if os.path.isfile(new_os_path):
435 raise web.HTTPError(409, u'File with name already exists: %s' % new_os_path)
435 raise web.HTTPError(409, u'File with name already exists: %s' % new_os_path)
436
436
437 # Move the file
437 # Move the file
438 try:
438 try:
439 shutil.move(old_os_path, new_os_path)
439 shutil.move(old_os_path, new_os_path)
440 except Exception as e:
440 except Exception as e:
441 raise web.HTTPError(500, u'Unknown error renaming file: %s %s' % (old_os_path, e))
441 raise web.HTTPError(500, u'Unknown error renaming file: %s %s' % (old_os_path, e))
442
442
443 # Move the checkpoints
443 # Move the checkpoints
444 old_checkpoints = self.list_checkpoints(old_name, old_path)
444 old_checkpoints = self.list_checkpoints(old_name, old_path)
445 for cp in old_checkpoints:
445 for cp in old_checkpoints:
446 checkpoint_id = cp['id']
446 checkpoint_id = cp['id']
447 old_cp_path = self.get_checkpoint_path(checkpoint_id, old_name, old_path)
447 old_cp_path = self.get_checkpoint_path(checkpoint_id, old_name, old_path)
448 new_cp_path = self.get_checkpoint_path(checkpoint_id, new_name, new_path)
448 new_cp_path = self.get_checkpoint_path(checkpoint_id, new_name, new_path)
449 if os.path.isfile(old_cp_path):
449 if os.path.isfile(old_cp_path):
450 self.log.debug("Renaming checkpoint %s -> %s", old_cp_path, new_cp_path)
450 self.log.debug("Renaming checkpoint %s -> %s", old_cp_path, new_cp_path)
451 shutil.move(old_cp_path, new_cp_path)
451 shutil.move(old_cp_path, new_cp_path)
452
452
453 # Checkpoint-related utilities
453 # Checkpoint-related utilities
454
454
455 def get_checkpoint_path(self, checkpoint_id, name, path=''):
455 def get_checkpoint_path(self, checkpoint_id, name, path=''):
456 """find the path to a checkpoint"""
456 """find the path to a checkpoint"""
457 path = path.strip('/')
457 path = path.strip('/')
458 basename, ext = os.path.splitext(name)
458 basename, ext = os.path.splitext(name)
459 filename = u"{name}-{checkpoint_id}{ext}".format(
459 filename = u"{name}-{checkpoint_id}{ext}".format(
460 name=basename,
460 name=basename,
461 checkpoint_id=checkpoint_id,
461 checkpoint_id=checkpoint_id,
462 ext=ext,
462 ext=ext,
463 )
463 )
464 os_path = self._get_os_path(path=path)
464 os_path = self._get_os_path(path=path)
465 cp_dir = os.path.join(os_path, self.checkpoint_dir)
465 cp_dir = os.path.join(os_path, self.checkpoint_dir)
466 ensure_dir_exists(cp_dir)
466 ensure_dir_exists(cp_dir)
467 cp_path = os.path.join(cp_dir, filename)
467 cp_path = os.path.join(cp_dir, filename)
468 return cp_path
468 return cp_path
469
469
470 def get_checkpoint_model(self, checkpoint_id, name, path=''):
470 def get_checkpoint_model(self, checkpoint_id, name, path=''):
471 """construct the info dict for a given checkpoint"""
471 """construct the info dict for a given checkpoint"""
472 path = path.strip('/')
472 path = path.strip('/')
473 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
473 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
474 stats = os.stat(cp_path)
474 stats = os.stat(cp_path)
475 last_modified = tz.utcfromtimestamp(stats.st_mtime)
475 last_modified = tz.utcfromtimestamp(stats.st_mtime)
476 info = dict(
476 info = dict(
477 id = checkpoint_id,
477 id = checkpoint_id,
478 last_modified = last_modified,
478 last_modified = last_modified,
479 )
479 )
480 return info
480 return info
481
481
482 # public checkpoint API
482 # public checkpoint API
483
483
484 def create_checkpoint(self, name, path=''):
484 def create_checkpoint(self, name, path=''):
485 """Create a checkpoint from the current state of a file"""
485 """Create a checkpoint from the current state of a file"""
486 path = path.strip('/')
486 path = path.strip('/')
487 src_path = self._get_os_path(name, path)
487 src_path = self._get_os_path(name, path)
488 # only the one checkpoint ID:
488 # only the one checkpoint ID:
489 checkpoint_id = u"checkpoint"
489 checkpoint_id = u"checkpoint"
490 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
490 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
491 self.log.debug("creating checkpoint for %s", name)
491 self.log.debug("creating checkpoint for %s", name)
492 self._copy(src_path, cp_path)
492 self._copy(src_path, cp_path)
493
493
494 # return the checkpoint info
494 # return the checkpoint info
495 return self.get_checkpoint_model(checkpoint_id, name, path)
495 return self.get_checkpoint_model(checkpoint_id, name, path)
496
496
497 def list_checkpoints(self, name, path=''):
497 def list_checkpoints(self, name, path=''):
498 """list the checkpoints for a given file
498 """list the checkpoints for a given file
499
499
500 This contents manager currently only supports one checkpoint per file.
500 This contents manager currently only supports one checkpoint per file.
501 """
501 """
502 path = path.strip('/')
502 path = path.strip('/')
503 checkpoint_id = "checkpoint"
503 checkpoint_id = "checkpoint"
504 os_path = self.get_checkpoint_path(checkpoint_id, name, path)
504 os_path = self.get_checkpoint_path(checkpoint_id, name, path)
505 if not os.path.exists(os_path):
505 if not os.path.exists(os_path):
506 return []
506 return []
507 else:
507 else:
508 return [self.get_checkpoint_model(checkpoint_id, name, path)]
508 return [self.get_checkpoint_model(checkpoint_id, name, path)]
509
509
510
510
511 def restore_checkpoint(self, checkpoint_id, name, path=''):
511 def restore_checkpoint(self, checkpoint_id, name, path=''):
512 """restore a file to a checkpointed state"""
512 """restore a file to a checkpointed state"""
513 path = path.strip('/')
513 path = path.strip('/')
514 self.log.info("restoring %s from checkpoint %s", name, checkpoint_id)
514 self.log.info("restoring %s from checkpoint %s", name, checkpoint_id)
515 nb_path = self._get_os_path(name, path)
515 nb_path = self._get_os_path(name, path)
516 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
516 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
517 if not os.path.isfile(cp_path):
517 if not os.path.isfile(cp_path):
518 self.log.debug("checkpoint file does not exist: %s", cp_path)
518 self.log.debug("checkpoint file does not exist: %s", cp_path)
519 raise web.HTTPError(404,
519 raise web.HTTPError(404,
520 u'checkpoint does not exist: %s-%s' % (name, checkpoint_id)
520 u'checkpoint does not exist: %s-%s' % (name, checkpoint_id)
521 )
521 )
522 # ensure notebook is readable (never restore from an unreadable notebook)
522 # ensure notebook is readable (never restore from an unreadable notebook)
523 if cp_path.endswith('.ipynb'):
523 if cp_path.endswith('.ipynb'):
524 with io.open(cp_path, 'r', encoding='utf-8') as f:
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 self._copy(cp_path, nb_path)
526 self._copy(cp_path, nb_path)
527 self.log.debug("copying %s -> %s", cp_path, nb_path)
527 self.log.debug("copying %s -> %s", cp_path, nb_path)
528
528
529 def delete_checkpoint(self, checkpoint_id, name, path=''):
529 def delete_checkpoint(self, checkpoint_id, name, path=''):
530 """delete a file's checkpoint"""
530 """delete a file's checkpoint"""
531 path = path.strip('/')
531 path = path.strip('/')
532 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
532 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
533 if not os.path.isfile(cp_path):
533 if not os.path.isfile(cp_path):
534 raise web.HTTPError(404,
534 raise web.HTTPError(404,
535 u'Checkpoint does not exist: %s%s-%s' % (path, name, checkpoint_id)
535 u'Checkpoint does not exist: %s%s-%s' % (path, name, checkpoint_id)
536 )
536 )
537 self.log.debug("unlinking %s", cp_path)
537 self.log.debug("unlinking %s", cp_path)
538 os.unlink(cp_path)
538 os.unlink(cp_path)
539
539
540 def info_string(self):
540 def info_string(self):
541 return "Serving notebooks from local directory: %s" % self.root_dir
541 return "Serving notebooks from local directory: %s" % self.root_dir
542
542
543 def get_kernel_path(self, name, path='', model=None):
543 def get_kernel_path(self, name, path='', model=None):
544 """Return the initial working dir a kernel associated with a given notebook"""
544 """Return the initial working dir a kernel associated with a given notebook"""
545 return os.path.join(self.root_dir, path)
545 return os.path.join(self.root_dir, path)
@@ -1,346 +1,344 b''
1 """A base class for contents managers."""
1 """A base class for contents managers."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from fnmatch import fnmatch
6 from fnmatch import fnmatch
7 import itertools
7 import itertools
8 import json
8 import json
9 import os
9 import os
10
10
11 from tornado.web import HTTPError
11 from tornado.web import HTTPError
12
12
13 from IPython.config.configurable import LoggingConfigurable
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 from IPython.utils.traitlets import Instance, Unicode, List
16 from IPython.utils.traitlets import Instance, Unicode, List
16
17
17
18
18 class ContentsManager(LoggingConfigurable):
19 class ContentsManager(LoggingConfigurable):
19 """Base class for serving files and directories.
20 """Base class for serving files and directories.
20
21
21 This serves any text or binary file,
22 This serves any text or binary file,
22 as well as directories,
23 as well as directories,
23 with special handling for JSON notebook documents.
24 with special handling for JSON notebook documents.
24
25
25 Most APIs take a path argument,
26 Most APIs take a path argument,
26 which is always an API-style unicode path,
27 which is always an API-style unicode path,
27 and always refers to a directory.
28 and always refers to a directory.
28
29
29 - unicode, not url-escaped
30 - unicode, not url-escaped
30 - '/'-separated
31 - '/'-separated
31 - leading and trailing '/' will be stripped
32 - leading and trailing '/' will be stripped
32 - if unspecified, path defaults to '',
33 - if unspecified, path defaults to '',
33 indicating the root path.
34 indicating the root path.
34
35
35 name is also unicode, and refers to a specfic target:
36 name is also unicode, and refers to a specfic target:
36
37
37 - unicode, not url-escaped
38 - unicode, not url-escaped
38 - must not contain '/'
39 - must not contain '/'
39 - It refers to an individual filename
40 - It refers to an individual filename
40 - It may refer to a directory name,
41 - It may refer to a directory name,
41 in the case of listing or creating directories.
42 in the case of listing or creating directories.
42
43
43 """
44 """
44
45
45 notary = Instance(sign.NotebookNotary)
46 notary = Instance(sign.NotebookNotary)
46 def _notary_default(self):
47 def _notary_default(self):
47 return sign.NotebookNotary(parent=self)
48 return sign.NotebookNotary(parent=self)
48
49
49 hide_globs = List(Unicode, [
50 hide_globs = List(Unicode, [
50 u'__pycache__', '*.pyc', '*.pyo',
51 u'__pycache__', '*.pyc', '*.pyo',
51 '.DS_Store', '*.so', '*.dylib', '*~',
52 '.DS_Store', '*.so', '*.dylib', '*~',
52 ], config=True, help="""
53 ], config=True, help="""
53 Glob patterns to hide in file and directory listings.
54 Glob patterns to hide in file and directory listings.
54 """)
55 """)
55
56
56 untitled_notebook = Unicode("Untitled", config=True,
57 untitled_notebook = Unicode("Untitled", config=True,
57 help="The base name used when creating untitled notebooks."
58 help="The base name used when creating untitled notebooks."
58 )
59 )
59
60
60 untitled_file = Unicode("untitled", config=True,
61 untitled_file = Unicode("untitled", config=True,
61 help="The base name used when creating untitled files."
62 help="The base name used when creating untitled files."
62 )
63 )
63
64
64 untitled_directory = Unicode("Untitled Folder", config=True,
65 untitled_directory = Unicode("Untitled Folder", config=True,
65 help="The base name used when creating untitled directories."
66 help="The base name used when creating untitled directories."
66 )
67 )
67
68
68 # ContentsManager API part 1: methods that must be
69 # ContentsManager API part 1: methods that must be
69 # implemented in subclasses.
70 # implemented in subclasses.
70
71
71 def path_exists(self, path):
72 def path_exists(self, path):
72 """Does the API-style path (directory) actually exist?
73 """Does the API-style path (directory) actually exist?
73
74
74 Like os.path.isdir
75 Like os.path.isdir
75
76
76 Override this method in subclasses.
77 Override this method in subclasses.
77
78
78 Parameters
79 Parameters
79 ----------
80 ----------
80 path : string
81 path : string
81 The path to check
82 The path to check
82
83
83 Returns
84 Returns
84 -------
85 -------
85 exists : bool
86 exists : bool
86 Whether the path does indeed exist.
87 Whether the path does indeed exist.
87 """
88 """
88 raise NotImplementedError
89 raise NotImplementedError
89
90
90 def is_hidden(self, path):
91 def is_hidden(self, path):
91 """Does the API style path correspond to a hidden directory or file?
92 """Does the API style path correspond to a hidden directory or file?
92
93
93 Parameters
94 Parameters
94 ----------
95 ----------
95 path : string
96 path : string
96 The path to check. This is an API path (`/` separated,
97 The path to check. This is an API path (`/` separated,
97 relative to root dir).
98 relative to root dir).
98
99
99 Returns
100 Returns
100 -------
101 -------
101 hidden : bool
102 hidden : bool
102 Whether the path is hidden.
103 Whether the path is hidden.
103
104
104 """
105 """
105 raise NotImplementedError
106 raise NotImplementedError
106
107
107 def file_exists(self, name, path=''):
108 def file_exists(self, name, path=''):
108 """Does a file exist at the given name and path?
109 """Does a file exist at the given name and path?
109
110
110 Like os.path.isfile
111 Like os.path.isfile
111
112
112 Override this method in subclasses.
113 Override this method in subclasses.
113
114
114 Parameters
115 Parameters
115 ----------
116 ----------
116 name : string
117 name : string
117 The name of the file you are checking.
118 The name of the file you are checking.
118 path : string
119 path : string
119 The relative path to the file's directory (with '/' as separator)
120 The relative path to the file's directory (with '/' as separator)
120
121
121 Returns
122 Returns
122 -------
123 -------
123 exists : bool
124 exists : bool
124 Whether the file exists.
125 Whether the file exists.
125 """
126 """
126 raise NotImplementedError('must be implemented in a subclass')
127 raise NotImplementedError('must be implemented in a subclass')
127
128
128 def exists(self, name, path=''):
129 def exists(self, name, path=''):
129 """Does a file or directory exist at the given name and path?
130 """Does a file or directory exist at the given name and path?
130
131
131 Like os.path.exists
132 Like os.path.exists
132
133
133 Parameters
134 Parameters
134 ----------
135 ----------
135 name : string
136 name : string
136 The name of the file you are checking.
137 The name of the file you are checking.
137 path : string
138 path : string
138 The relative path to the file's directory (with '/' as separator)
139 The relative path to the file's directory (with '/' as separator)
139
140
140 Returns
141 Returns
141 -------
142 -------
142 exists : bool
143 exists : bool
143 Whether the target exists.
144 Whether the target exists.
144 """
145 """
145 return self.file_exists(name, path) or self.path_exists("%s/%s" % (path, name))
146 return self.file_exists(name, path) or self.path_exists("%s/%s" % (path, name))
146
147
147 def get_model(self, name, path='', content=True):
148 def get_model(self, name, path='', content=True):
148 """Get the model of a file or directory with or without content."""
149 """Get the model of a file or directory with or without content."""
149 raise NotImplementedError('must be implemented in a subclass')
150 raise NotImplementedError('must be implemented in a subclass')
150
151
151 def save(self, model, name, path=''):
152 def save(self, model, name, path=''):
152 """Save the file or directory and return the model with no content."""
153 """Save the file or directory and return the model with no content."""
153 raise NotImplementedError('must be implemented in a subclass')
154 raise NotImplementedError('must be implemented in a subclass')
154
155
155 def update(self, model, name, path=''):
156 def update(self, model, name, path=''):
156 """Update the file or directory and return the model with no content.
157 """Update the file or directory and return the model with no content.
157
158
158 For use in PATCH requests, to enable renaming a file without
159 For use in PATCH requests, to enable renaming a file without
159 re-uploading its contents. Only used for renaming at the moment.
160 re-uploading its contents. Only used for renaming at the moment.
160 """
161 """
161 raise NotImplementedError('must be implemented in a subclass')
162 raise NotImplementedError('must be implemented in a subclass')
162
163
163 def delete(self, name, path=''):
164 def delete(self, name, path=''):
164 """Delete file or directory by name and path."""
165 """Delete file or directory by name and path."""
165 raise NotImplementedError('must be implemented in a subclass')
166 raise NotImplementedError('must be implemented in a subclass')
166
167
167 def create_checkpoint(self, name, path=''):
168 def create_checkpoint(self, name, path=''):
168 """Create a checkpoint of the current state of a file
169 """Create a checkpoint of the current state of a file
169
170
170 Returns a checkpoint_id for the new checkpoint.
171 Returns a checkpoint_id for the new checkpoint.
171 """
172 """
172 raise NotImplementedError("must be implemented in a subclass")
173 raise NotImplementedError("must be implemented in a subclass")
173
174
174 def list_checkpoints(self, name, path=''):
175 def list_checkpoints(self, name, path=''):
175 """Return a list of checkpoints for a given file"""
176 """Return a list of checkpoints for a given file"""
176 return []
177 return []
177
178
178 def restore_checkpoint(self, checkpoint_id, name, path=''):
179 def restore_checkpoint(self, checkpoint_id, name, path=''):
179 """Restore a file from one of its checkpoints"""
180 """Restore a file from one of its checkpoints"""
180 raise NotImplementedError("must be implemented in a subclass")
181 raise NotImplementedError("must be implemented in a subclass")
181
182
182 def delete_checkpoint(self, checkpoint_id, name, path=''):
183 def delete_checkpoint(self, checkpoint_id, name, path=''):
183 """delete a checkpoint for a file"""
184 """delete a checkpoint for a file"""
184 raise NotImplementedError("must be implemented in a subclass")
185 raise NotImplementedError("must be implemented in a subclass")
185
186
186 # ContentsManager API part 2: methods that have useable default
187 # ContentsManager API part 2: methods that have useable default
187 # implementations, but can be overridden in subclasses.
188 # implementations, but can be overridden in subclasses.
188
189
189 def info_string(self):
190 def info_string(self):
190 return "Serving contents"
191 return "Serving contents"
191
192
192 def get_kernel_path(self, name, path='', model=None):
193 def get_kernel_path(self, name, path='', model=None):
193 """ Return the path to start kernel in """
194 """ Return the path to start kernel in """
194 return path
195 return path
195
196
196 def increment_filename(self, filename, path=''):
197 def increment_filename(self, filename, path=''):
197 """Increment a filename until it is unique.
198 """Increment a filename until it is unique.
198
199
199 Parameters
200 Parameters
200 ----------
201 ----------
201 filename : unicode
202 filename : unicode
202 The name of a file, including extension
203 The name of a file, including extension
203 path : unicode
204 path : unicode
204 The API path of the target's directory
205 The API path of the target's directory
205
206
206 Returns
207 Returns
207 -------
208 -------
208 name : unicode
209 name : unicode
209 A filename that is unique, based on the input filename.
210 A filename that is unique, based on the input filename.
210 """
211 """
211 path = path.strip('/')
212 path = path.strip('/')
212 basename, ext = os.path.splitext(filename)
213 basename, ext = os.path.splitext(filename)
213 for i in itertools.count():
214 for i in itertools.count():
214 name = u'{basename}{i}{ext}'.format(basename=basename, i=i,
215 name = u'{basename}{i}{ext}'.format(basename=basename, i=i,
215 ext=ext)
216 ext=ext)
216 if not self.file_exists(name, path):
217 if not self.file_exists(name, path):
217 break
218 break
218 return name
219 return name
219
220
220 def validate_notebook_model(self, model):
221 def validate_notebook_model(self, model):
221 """Add failed-validation message to model"""
222 """Add failed-validation message to model"""
222 try:
223 try:
223 current.validate(model['content'])
224 validate(model['content'])
224 except current.ValidationError as e:
225 except ValidationError as e:
225 model['message'] = 'Notebook Validation failed: {}:\n{}'.format(
226 model['message'] = 'Notebook Validation failed: {}:\n{}'.format(
226 e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'),
227 e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'),
227 )
228 )
228 return model
229 return model
229
230
230 def create_file(self, model=None, path='', ext='.ipynb'):
231 def create_file(self, model=None, path='', ext='.ipynb'):
231 """Create a new file or directory and return its model with no content."""
232 """Create a new file or directory and return its model with no content."""
232 path = path.strip('/')
233 path = path.strip('/')
233 if model is None:
234 if model is None:
234 model = {}
235 model = {}
235 if 'content' not in model and model.get('type', None) != 'directory':
236 if 'content' not in model and model.get('type', None) != 'directory':
236 if ext == '.ipynb':
237 if ext == '.ipynb':
237 metadata = current.new_metadata(name=u'')
238 model['content'] = new_notebook()
238 model['content'] = current.new_notebook(metadata=metadata)
239 model['type'] = 'notebook'
239 model['type'] = 'notebook'
240 model['format'] = 'json'
240 model['format'] = 'json'
241 else:
241 else:
242 model['content'] = ''
242 model['content'] = ''
243 model['type'] = 'file'
243 model['type'] = 'file'
244 model['format'] = 'text'
244 model['format'] = 'text'
245 if 'name' not in model:
245 if 'name' not in model:
246 if model['type'] == 'directory':
246 if model['type'] == 'directory':
247 untitled = self.untitled_directory
247 untitled = self.untitled_directory
248 elif model['type'] == 'notebook':
248 elif model['type'] == 'notebook':
249 untitled = self.untitled_notebook
249 untitled = self.untitled_notebook
250 elif model['type'] == 'file':
250 elif model['type'] == 'file':
251 untitled = self.untitled_file
251 untitled = self.untitled_file
252 else:
252 else:
253 raise HTTPError(400, "Unexpected model type: %r" % model['type'])
253 raise HTTPError(400, "Unexpected model type: %r" % model['type'])
254 model['name'] = self.increment_filename(untitled + ext, path)
254 model['name'] = self.increment_filename(untitled + ext, path)
255
255
256 model['path'] = path
256 model['path'] = path
257 model = self.save(model, model['name'], model['path'])
257 model = self.save(model, model['name'], model['path'])
258 return model
258 return model
259
259
260 def copy(self, from_name, to_name=None, path=''):
260 def copy(self, from_name, to_name=None, path=''):
261 """Copy an existing file and return its new model.
261 """Copy an existing file and return its new model.
262
262
263 If to_name not specified, increment `from_name-Copy#.ext`.
263 If to_name not specified, increment `from_name-Copy#.ext`.
264
264
265 copy_from can be a full path to a file,
265 copy_from can be a full path to a file,
266 or just a base name. If a base name, `path` is used.
266 or just a base name. If a base name, `path` is used.
267 """
267 """
268 path = path.strip('/')
268 path = path.strip('/')
269 if '/' in from_name:
269 if '/' in from_name:
270 from_path, from_name = from_name.rsplit('/', 1)
270 from_path, from_name = from_name.rsplit('/', 1)
271 else:
271 else:
272 from_path = path
272 from_path = path
273 model = self.get_model(from_name, from_path)
273 model = self.get_model(from_name, from_path)
274 if model['type'] == 'directory':
274 if model['type'] == 'directory':
275 raise HTTPError(400, "Can't copy directories")
275 raise HTTPError(400, "Can't copy directories")
276 if not to_name:
276 if not to_name:
277 base, ext = os.path.splitext(from_name)
277 base, ext = os.path.splitext(from_name)
278 copy_name = u'{0}-Copy{1}'.format(base, ext)
278 copy_name = u'{0}-Copy{1}'.format(base, ext)
279 to_name = self.increment_filename(copy_name, path)
279 to_name = self.increment_filename(copy_name, path)
280 model['name'] = to_name
280 model['name'] = to_name
281 model['path'] = path
281 model['path'] = path
282 model = self.save(model, to_name, path)
282 model = self.save(model, to_name, path)
283 return model
283 return model
284
284
285 def log_info(self):
285 def log_info(self):
286 self.log.info(self.info_string())
286 self.log.info(self.info_string())
287
287
288 def trust_notebook(self, name, path=''):
288 def trust_notebook(self, name, path=''):
289 """Explicitly trust a notebook
289 """Explicitly trust a notebook
290
290
291 Parameters
291 Parameters
292 ----------
292 ----------
293 name : string
293 name : string
294 The filename of the notebook
294 The filename of the notebook
295 path : string
295 path : string
296 The notebook's directory
296 The notebook's directory
297 """
297 """
298 model = self.get_model(name, path)
298 model = self.get_model(name, path)
299 nb = model['content']
299 nb = model['content']
300 self.log.warn("Trusting notebook %s/%s", path, name)
300 self.log.warn("Trusting notebook %s/%s", path, name)
301 self.notary.mark_cells(nb, True)
301 self.notary.mark_cells(nb, True)
302 self.save(model, name, path)
302 self.save(model, name, path)
303
303
304 def check_and_sign(self, nb, name='', path=''):
304 def check_and_sign(self, nb, name='', path=''):
305 """Check for trusted cells, and sign the notebook.
305 """Check for trusted cells, and sign the notebook.
306
306
307 Called as a part of saving notebooks.
307 Called as a part of saving notebooks.
308
308
309 Parameters
309 Parameters
310 ----------
310 ----------
311 nb : dict
311 nb : dict
312 The notebook object (in nbformat.current format)
312 The notebook dict
313 name : string
313 name : string
314 The filename of the notebook (for logging)
314 The filename of the notebook (for logging)
315 path : string
315 path : string
316 The notebook's directory (for logging)
316 The notebook's directory (for logging)
317 """
317 """
318 if nb['nbformat'] != current.nbformat:
319 return
320 if self.notary.check_cells(nb):
318 if self.notary.check_cells(nb):
321 self.notary.sign(nb)
319 self.notary.sign(nb)
322 else:
320 else:
323 self.log.warn("Saving untrusted notebook %s/%s", path, name)
321 self.log.warn("Saving untrusted notebook %s/%s", path, name)
324
322
325 def mark_trusted_cells(self, nb, name='', path=''):
323 def mark_trusted_cells(self, nb, name='', path=''):
326 """Mark cells as trusted if the notebook signature matches.
324 """Mark cells as trusted if the notebook signature matches.
327
325
328 Called as a part of loading notebooks.
326 Called as a part of loading notebooks.
329
327
330 Parameters
328 Parameters
331 ----------
329 ----------
332 nb : dict
330 nb : dict
333 The notebook object (in nbformat.current format)
331 The notebook object (in current nbformat)
334 name : string
332 name : string
335 The filename of the notebook (for logging)
333 The filename of the notebook (for logging)
336 path : string
334 path : string
337 The notebook's directory (for logging)
335 The notebook's directory (for logging)
338 """
336 """
339 trusted = self.notary.check_signature(nb)
337 trusted = self.notary.check_signature(nb)
340 if not trusted:
338 if not trusted:
341 self.log.warn("Notebook %s/%s is not trusted", path, name)
339 self.log.warn("Notebook %s/%s is not trusted", path, name)
342 self.notary.mark_cells(nb, trusted)
340 self.notary.mark_cells(nb, trusted)
343
341
344 def should_list(self, name):
342 def should_list(self, name):
345 """Should this file/directory name be displayed in a listing?"""
343 """Should this file/directory name be displayed in a listing?"""
346 return not any(fnmatch(name, glob) for glob in self.hide_globs)
344 return not any(fnmatch(name, glob) for glob in self.hide_globs)
@@ -1,485 +1,481 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Test the contents webservice API."""
2 """Test the contents webservice API."""
3
3
4 import base64
4 import base64
5 import io
5 import io
6 import json
6 import json
7 import os
7 import os
8 import shutil
8 import shutil
9 from unicodedata import normalize
9 from unicodedata import normalize
10
10
11 pjoin = os.path.join
11 pjoin = os.path.join
12
12
13 import requests
13 import requests
14
14
15 from IPython.html.utils import url_path_join, url_escape
15 from IPython.html.utils import url_path_join, url_escape
16 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
16 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
17 from IPython.nbformat import current
17 from IPython.nbformat import read, write, from_dict
18 from IPython.nbformat.current import (new_notebook, write, read, new_worksheet,
18 from IPython.nbformat.v4 import (
19 new_heading_cell, to_notebook_json)
19 new_notebook, new_markdown_cell,
20 )
20 from IPython.nbformat import v2
21 from IPython.nbformat import v2
21 from IPython.utils import py3compat
22 from IPython.utils import py3compat
22 from IPython.utils.data import uniq_stable
23 from IPython.utils.data import uniq_stable
23
24
24
25
25 def notebooks_only(dir_model):
26 def notebooks_only(dir_model):
26 return [nb for nb in dir_model['content'] if nb['type']=='notebook']
27 return [nb for nb in dir_model['content'] if nb['type']=='notebook']
27
28
28 def dirs_only(dir_model):
29 def dirs_only(dir_model):
29 return [x for x in dir_model['content'] if x['type']=='directory']
30 return [x for x in dir_model['content'] if x['type']=='directory']
30
31
31
32
32 class API(object):
33 class API(object):
33 """Wrapper for contents API calls."""
34 """Wrapper for contents API calls."""
34 def __init__(self, base_url):
35 def __init__(self, base_url):
35 self.base_url = base_url
36 self.base_url = base_url
36
37
37 def _req(self, verb, path, body=None):
38 def _req(self, verb, path, body=None):
38 response = requests.request(verb,
39 response = requests.request(verb,
39 url_path_join(self.base_url, 'api/contents', path),
40 url_path_join(self.base_url, 'api/contents', path),
40 data=body,
41 data=body,
41 )
42 )
42 response.raise_for_status()
43 response.raise_for_status()
43 return response
44 return response
44
45
45 def list(self, path='/'):
46 def list(self, path='/'):
46 return self._req('GET', path)
47 return self._req('GET', path)
47
48
48 def read(self, name, path='/'):
49 def read(self, name, path='/'):
49 return self._req('GET', url_path_join(path, name))
50 return self._req('GET', url_path_join(path, name))
50
51
51 def create_untitled(self, path='/', ext=None):
52 def create_untitled(self, path='/', ext=None):
52 body = None
53 body = None
53 if ext:
54 if ext:
54 body = json.dumps({'ext': ext})
55 body = json.dumps({'ext': ext})
55 return self._req('POST', path, body)
56 return self._req('POST', path, body)
56
57
57 def upload_untitled(self, body, path='/'):
58 def upload_untitled(self, body, path='/'):
58 return self._req('POST', path, body)
59 return self._req('POST', path, body)
59
60
60 def copy_untitled(self, copy_from, path='/'):
61 def copy_untitled(self, copy_from, path='/'):
61 body = json.dumps({'copy_from':copy_from})
62 body = json.dumps({'copy_from':copy_from})
62 return self._req('POST', path, body)
63 return self._req('POST', path, body)
63
64
64 def create(self, name, path='/'):
65 def create(self, name, path='/'):
65 return self._req('PUT', url_path_join(path, name))
66 return self._req('PUT', url_path_join(path, name))
66
67
67 def upload(self, name, body, path='/'):
68 def upload(self, name, body, path='/'):
68 return self._req('PUT', url_path_join(path, name), body)
69 return self._req('PUT', url_path_join(path, name), body)
69
70
70 def mkdir(self, name, path='/'):
71 def mkdir(self, name, path='/'):
71 return self._req('PUT', url_path_join(path, name), json.dumps({'type': 'directory'}))
72 return self._req('PUT', url_path_join(path, name), json.dumps({'type': 'directory'}))
72
73
73 def copy(self, copy_from, copy_to, path='/'):
74 def copy(self, copy_from, copy_to, path='/'):
74 body = json.dumps({'copy_from':copy_from})
75 body = json.dumps({'copy_from':copy_from})
75 return self._req('PUT', url_path_join(path, copy_to), body)
76 return self._req('PUT', url_path_join(path, copy_to), body)
76
77
77 def save(self, name, body, path='/'):
78 def save(self, name, body, path='/'):
78 return self._req('PUT', url_path_join(path, name), body)
79 return self._req('PUT', url_path_join(path, name), body)
79
80
80 def delete(self, name, path='/'):
81 def delete(self, name, path='/'):
81 return self._req('DELETE', url_path_join(path, name))
82 return self._req('DELETE', url_path_join(path, name))
82
83
83 def rename(self, name, path, new_name):
84 def rename(self, name, path, new_name):
84 body = json.dumps({'name': new_name})
85 body = json.dumps({'name': new_name})
85 return self._req('PATCH', url_path_join(path, name), body)
86 return self._req('PATCH', url_path_join(path, name), body)
86
87
87 def get_checkpoints(self, name, path):
88 def get_checkpoints(self, name, path):
88 return self._req('GET', url_path_join(path, name, 'checkpoints'))
89 return self._req('GET', url_path_join(path, name, 'checkpoints'))
89
90
90 def new_checkpoint(self, name, path):
91 def new_checkpoint(self, name, path):
91 return self._req('POST', url_path_join(path, name, 'checkpoints'))
92 return self._req('POST', url_path_join(path, name, 'checkpoints'))
92
93
93 def restore_checkpoint(self, name, path, checkpoint_id):
94 def restore_checkpoint(self, name, path, checkpoint_id):
94 return self._req('POST', url_path_join(path, name, 'checkpoints', checkpoint_id))
95 return self._req('POST', url_path_join(path, name, 'checkpoints', checkpoint_id))
95
96
96 def delete_checkpoint(self, name, path, checkpoint_id):
97 def delete_checkpoint(self, name, path, checkpoint_id):
97 return self._req('DELETE', url_path_join(path, name, 'checkpoints', checkpoint_id))
98 return self._req('DELETE', url_path_join(path, name, 'checkpoints', checkpoint_id))
98
99
99 class APITest(NotebookTestBase):
100 class APITest(NotebookTestBase):
100 """Test the kernels web service API"""
101 """Test the kernels web service API"""
101 dirs_nbs = [('', 'inroot'),
102 dirs_nbs = [('', 'inroot'),
102 ('Directory with spaces in', 'inspace'),
103 ('Directory with spaces in', 'inspace'),
103 (u'unicodé', 'innonascii'),
104 (u'unicodé', 'innonascii'),
104 ('foo', 'a'),
105 ('foo', 'a'),
105 ('foo', 'b'),
106 ('foo', 'b'),
106 ('foo', 'name with spaces'),
107 ('foo', 'name with spaces'),
107 ('foo', u'unicodé'),
108 ('foo', u'unicodé'),
108 ('foo/bar', 'baz'),
109 ('foo/bar', 'baz'),
109 ('ordering', 'A'),
110 ('ordering', 'A'),
110 ('ordering', 'b'),
111 ('ordering', 'b'),
111 ('ordering', 'C'),
112 ('ordering', 'C'),
112 (u'å b', u'ç d'),
113 (u'å b', u'ç d'),
113 ]
114 ]
114 hidden_dirs = ['.hidden', '__pycache__']
115 hidden_dirs = ['.hidden', '__pycache__']
115
116
116 dirs = uniq_stable([py3compat.cast_unicode(d) for (d,n) in dirs_nbs])
117 dirs = uniq_stable([py3compat.cast_unicode(d) for (d,n) in dirs_nbs])
117 del dirs[0] # remove ''
118 del dirs[0] # remove ''
118 top_level_dirs = {normalize('NFC', d.split('/')[0]) for d in dirs}
119 top_level_dirs = {normalize('NFC', d.split('/')[0]) for d in dirs}
119
120
120 @staticmethod
121 @staticmethod
121 def _blob_for_name(name):
122 def _blob_for_name(name):
122 return name.encode('utf-8') + b'\xFF'
123 return name.encode('utf-8') + b'\xFF'
123
124
124 @staticmethod
125 @staticmethod
125 def _txt_for_name(name):
126 def _txt_for_name(name):
126 return u'%s text file' % name
127 return u'%s text file' % name
127
128
128 def setUp(self):
129 def setUp(self):
129 nbdir = self.notebook_dir.name
130 nbdir = self.notebook_dir.name
130 self.blob = os.urandom(100)
131 self.blob = os.urandom(100)
131 self.b64_blob = base64.encodestring(self.blob).decode('ascii')
132 self.b64_blob = base64.encodestring(self.blob).decode('ascii')
132
133
133
134
134
135
135 for d in (self.dirs + self.hidden_dirs):
136 for d in (self.dirs + self.hidden_dirs):
136 d.replace('/', os.sep)
137 d.replace('/', os.sep)
137 if not os.path.isdir(pjoin(nbdir, d)):
138 if not os.path.isdir(pjoin(nbdir, d)):
138 os.mkdir(pjoin(nbdir, d))
139 os.mkdir(pjoin(nbdir, d))
139
140
140 for d, name in self.dirs_nbs:
141 for d, name in self.dirs_nbs:
141 d = d.replace('/', os.sep)
142 d = d.replace('/', os.sep)
142 # create a notebook
143 # create a notebook
143 with io.open(pjoin(nbdir, d, '%s.ipynb' % name), 'w',
144 with io.open(pjoin(nbdir, d, '%s.ipynb' % name), 'w',
144 encoding='utf-8') as f:
145 encoding='utf-8') as f:
145 nb = new_notebook(name=name)
146 nb = new_notebook()
146 write(nb, f, format='ipynb')
147 write(nb, f, version=4)
147
148
148 # create a text file
149 # create a text file
149 with io.open(pjoin(nbdir, d, '%s.txt' % name), 'w',
150 with io.open(pjoin(nbdir, d, '%s.txt' % name), 'w',
150 encoding='utf-8') as f:
151 encoding='utf-8') as f:
151 f.write(self._txt_for_name(name))
152 f.write(self._txt_for_name(name))
152
153
153 # create a binary file
154 # create a binary file
154 with io.open(pjoin(nbdir, d, '%s.blob' % name), 'wb') as f:
155 with io.open(pjoin(nbdir, d, '%s.blob' % name), 'wb') as f:
155 f.write(self._blob_for_name(name))
156 f.write(self._blob_for_name(name))
156
157
157 self.api = API(self.base_url())
158 self.api = API(self.base_url())
158
159
159 def tearDown(self):
160 def tearDown(self):
160 nbdir = self.notebook_dir.name
161 nbdir = self.notebook_dir.name
161
162
162 for dname in (list(self.top_level_dirs) + self.hidden_dirs):
163 for dname in (list(self.top_level_dirs) + self.hidden_dirs):
163 shutil.rmtree(pjoin(nbdir, dname), ignore_errors=True)
164 shutil.rmtree(pjoin(nbdir, dname), ignore_errors=True)
164
165
165 if os.path.isfile(pjoin(nbdir, 'inroot.ipynb')):
166 if os.path.isfile(pjoin(nbdir, 'inroot.ipynb')):
166 os.unlink(pjoin(nbdir, 'inroot.ipynb'))
167 os.unlink(pjoin(nbdir, 'inroot.ipynb'))
167
168
168 def test_list_notebooks(self):
169 def test_list_notebooks(self):
169 nbs = notebooks_only(self.api.list().json())
170 nbs = notebooks_only(self.api.list().json())
170 self.assertEqual(len(nbs), 1)
171 self.assertEqual(len(nbs), 1)
171 self.assertEqual(nbs[0]['name'], 'inroot.ipynb')
172 self.assertEqual(nbs[0]['name'], 'inroot.ipynb')
172
173
173 nbs = notebooks_only(self.api.list('/Directory with spaces in/').json())
174 nbs = notebooks_only(self.api.list('/Directory with spaces in/').json())
174 self.assertEqual(len(nbs), 1)
175 self.assertEqual(len(nbs), 1)
175 self.assertEqual(nbs[0]['name'], 'inspace.ipynb')
176 self.assertEqual(nbs[0]['name'], 'inspace.ipynb')
176
177
177 nbs = notebooks_only(self.api.list(u'/unicodé/').json())
178 nbs = notebooks_only(self.api.list(u'/unicodé/').json())
178 self.assertEqual(len(nbs), 1)
179 self.assertEqual(len(nbs), 1)
179 self.assertEqual(nbs[0]['name'], 'innonascii.ipynb')
180 self.assertEqual(nbs[0]['name'], 'innonascii.ipynb')
180 self.assertEqual(nbs[0]['path'], u'unicodé')
181 self.assertEqual(nbs[0]['path'], u'unicodé')
181
182
182 nbs = notebooks_only(self.api.list('/foo/bar/').json())
183 nbs = notebooks_only(self.api.list('/foo/bar/').json())
183 self.assertEqual(len(nbs), 1)
184 self.assertEqual(len(nbs), 1)
184 self.assertEqual(nbs[0]['name'], 'baz.ipynb')
185 self.assertEqual(nbs[0]['name'], 'baz.ipynb')
185 self.assertEqual(nbs[0]['path'], 'foo/bar')
186 self.assertEqual(nbs[0]['path'], 'foo/bar')
186
187
187 nbs = notebooks_only(self.api.list('foo').json())
188 nbs = notebooks_only(self.api.list('foo').json())
188 self.assertEqual(len(nbs), 4)
189 self.assertEqual(len(nbs), 4)
189 nbnames = { normalize('NFC', n['name']) for n in nbs }
190 nbnames = { normalize('NFC', n['name']) for n in nbs }
190 expected = [ u'a.ipynb', u'b.ipynb', u'name with spaces.ipynb', u'unicodé.ipynb']
191 expected = [ u'a.ipynb', u'b.ipynb', u'name with spaces.ipynb', u'unicodé.ipynb']
191 expected = { normalize('NFC', name) for name in expected }
192 expected = { normalize('NFC', name) for name in expected }
192 self.assertEqual(nbnames, expected)
193 self.assertEqual(nbnames, expected)
193
194
194 nbs = notebooks_only(self.api.list('ordering').json())
195 nbs = notebooks_only(self.api.list('ordering').json())
195 nbnames = [n['name'] for n in nbs]
196 nbnames = [n['name'] for n in nbs]
196 expected = ['A.ipynb', 'b.ipynb', 'C.ipynb']
197 expected = ['A.ipynb', 'b.ipynb', 'C.ipynb']
197 self.assertEqual(nbnames, expected)
198 self.assertEqual(nbnames, expected)
198
199
199 def test_list_dirs(self):
200 def test_list_dirs(self):
200 dirs = dirs_only(self.api.list().json())
201 dirs = dirs_only(self.api.list().json())
201 dir_names = {normalize('NFC', d['name']) for d in dirs}
202 dir_names = {normalize('NFC', d['name']) for d in dirs}
202 self.assertEqual(dir_names, self.top_level_dirs) # Excluding hidden dirs
203 self.assertEqual(dir_names, self.top_level_dirs) # Excluding hidden dirs
203
204
204 def test_list_nonexistant_dir(self):
205 def test_list_nonexistant_dir(self):
205 with assert_http_error(404):
206 with assert_http_error(404):
206 self.api.list('nonexistant')
207 self.api.list('nonexistant')
207
208
208 def test_get_nb_contents(self):
209 def test_get_nb_contents(self):
209 for d, name in self.dirs_nbs:
210 for d, name in self.dirs_nbs:
210 nb = self.api.read('%s.ipynb' % name, d+'/').json()
211 nb = self.api.read('%s.ipynb' % name, d+'/').json()
211 self.assertEqual(nb['name'], u'%s.ipynb' % name)
212 self.assertEqual(nb['name'], u'%s.ipynb' % name)
212 self.assertEqual(nb['type'], 'notebook')
213 self.assertEqual(nb['type'], 'notebook')
213 self.assertIn('content', nb)
214 self.assertIn('content', nb)
214 self.assertEqual(nb['format'], 'json')
215 self.assertEqual(nb['format'], 'json')
215 self.assertIn('content', nb)
216 self.assertIn('content', nb)
216 self.assertIn('metadata', nb['content'])
217 self.assertIn('metadata', nb['content'])
217 self.assertIsInstance(nb['content']['metadata'], dict)
218 self.assertIsInstance(nb['content']['metadata'], dict)
218
219
219 def test_get_contents_no_such_file(self):
220 def test_get_contents_no_such_file(self):
220 # Name that doesn't exist - should be a 404
221 # Name that doesn't exist - should be a 404
221 with assert_http_error(404):
222 with assert_http_error(404):
222 self.api.read('q.ipynb', 'foo')
223 self.api.read('q.ipynb', 'foo')
223
224
224 def test_get_text_file_contents(self):
225 def test_get_text_file_contents(self):
225 for d, name in self.dirs_nbs:
226 for d, name in self.dirs_nbs:
226 model = self.api.read(u'%s.txt' % name, d+'/').json()
227 model = self.api.read(u'%s.txt' % name, d+'/').json()
227 self.assertEqual(model['name'], u'%s.txt' % name)
228 self.assertEqual(model['name'], u'%s.txt' % name)
228 self.assertIn('content', model)
229 self.assertIn('content', model)
229 self.assertEqual(model['format'], 'text')
230 self.assertEqual(model['format'], 'text')
230 self.assertEqual(model['type'], 'file')
231 self.assertEqual(model['type'], 'file')
231 self.assertEqual(model['content'], self._txt_for_name(name))
232 self.assertEqual(model['content'], self._txt_for_name(name))
232
233
233 # Name that doesn't exist - should be a 404
234 # Name that doesn't exist - should be a 404
234 with assert_http_error(404):
235 with assert_http_error(404):
235 self.api.read('q.txt', 'foo')
236 self.api.read('q.txt', 'foo')
236
237
237 def test_get_binary_file_contents(self):
238 def test_get_binary_file_contents(self):
238 for d, name in self.dirs_nbs:
239 for d, name in self.dirs_nbs:
239 model = self.api.read(u'%s.blob' % name, d+'/').json()
240 model = self.api.read(u'%s.blob' % name, d+'/').json()
240 self.assertEqual(model['name'], u'%s.blob' % name)
241 self.assertEqual(model['name'], u'%s.blob' % name)
241 self.assertIn('content', model)
242 self.assertIn('content', model)
242 self.assertEqual(model['format'], 'base64')
243 self.assertEqual(model['format'], 'base64')
243 self.assertEqual(model['type'], 'file')
244 self.assertEqual(model['type'], 'file')
244 b64_data = base64.encodestring(self._blob_for_name(name)).decode('ascii')
245 b64_data = base64.encodestring(self._blob_for_name(name)).decode('ascii')
245 self.assertEqual(model['content'], b64_data)
246 self.assertEqual(model['content'], b64_data)
246
247
247 # Name that doesn't exist - should be a 404
248 # Name that doesn't exist - should be a 404
248 with assert_http_error(404):
249 with assert_http_error(404):
249 self.api.read('q.txt', 'foo')
250 self.api.read('q.txt', 'foo')
250
251
251 def _check_created(self, resp, name, path, type='notebook'):
252 def _check_created(self, resp, name, path, type='notebook'):
252 self.assertEqual(resp.status_code, 201)
253 self.assertEqual(resp.status_code, 201)
253 location_header = py3compat.str_to_unicode(resp.headers['Location'])
254 location_header = py3compat.str_to_unicode(resp.headers['Location'])
254 self.assertEqual(location_header, url_escape(url_path_join(u'/api/contents', path, name)))
255 self.assertEqual(location_header, url_escape(url_path_join(u'/api/contents', path, name)))
255 rjson = resp.json()
256 rjson = resp.json()
256 self.assertEqual(rjson['name'], name)
257 self.assertEqual(rjson['name'], name)
257 self.assertEqual(rjson['path'], path)
258 self.assertEqual(rjson['path'], path)
258 self.assertEqual(rjson['type'], type)
259 self.assertEqual(rjson['type'], type)
259 isright = os.path.isdir if type == 'directory' else os.path.isfile
260 isright = os.path.isdir if type == 'directory' else os.path.isfile
260 assert isright(pjoin(
261 assert isright(pjoin(
261 self.notebook_dir.name,
262 self.notebook_dir.name,
262 path.replace('/', os.sep),
263 path.replace('/', os.sep),
263 name,
264 name,
264 ))
265 ))
265
266
266 def test_create_untitled(self):
267 def test_create_untitled(self):
267 resp = self.api.create_untitled(path=u'å b')
268 resp = self.api.create_untitled(path=u'å b')
268 self._check_created(resp, 'Untitled0.ipynb', u'å b')
269 self._check_created(resp, 'Untitled0.ipynb', u'å b')
269
270
270 # Second time
271 # Second time
271 resp = self.api.create_untitled(path=u'å b')
272 resp = self.api.create_untitled(path=u'å b')
272 self._check_created(resp, 'Untitled1.ipynb', u'å b')
273 self._check_created(resp, 'Untitled1.ipynb', u'å b')
273
274
274 # And two directories down
275 # And two directories down
275 resp = self.api.create_untitled(path='foo/bar')
276 resp = self.api.create_untitled(path='foo/bar')
276 self._check_created(resp, 'Untitled0.ipynb', 'foo/bar')
277 self._check_created(resp, 'Untitled0.ipynb', 'foo/bar')
277
278
278 def test_create_untitled_txt(self):
279 def test_create_untitled_txt(self):
279 resp = self.api.create_untitled(path='foo/bar', ext='.txt')
280 resp = self.api.create_untitled(path='foo/bar', ext='.txt')
280 self._check_created(resp, 'untitled0.txt', 'foo/bar', type='file')
281 self._check_created(resp, 'untitled0.txt', 'foo/bar', type='file')
281
282
282 resp = self.api.read(path='foo/bar', name='untitled0.txt')
283 resp = self.api.read(path='foo/bar', name='untitled0.txt')
283 model = resp.json()
284 model = resp.json()
284 self.assertEqual(model['type'], 'file')
285 self.assertEqual(model['type'], 'file')
285 self.assertEqual(model['format'], 'text')
286 self.assertEqual(model['format'], 'text')
286 self.assertEqual(model['content'], '')
287 self.assertEqual(model['content'], '')
287
288
288 def test_upload_untitled(self):
289 def test_upload_untitled(self):
289 nb = new_notebook(name='Upload test')
290 nb = new_notebook()
290 nbmodel = {'content': nb, 'type': 'notebook'}
291 nbmodel = {'content': nb, 'type': 'notebook'}
291 resp = self.api.upload_untitled(path=u'å b',
292 resp = self.api.upload_untitled(path=u'å b',
292 body=json.dumps(nbmodel))
293 body=json.dumps(nbmodel))
293 self._check_created(resp, 'Untitled0.ipynb', u'å b')
294 self._check_created(resp, 'Untitled0.ipynb', u'å b')
294
295
295 def test_upload(self):
296 def test_upload(self):
296 nb = new_notebook(name=u'ignored')
297 nb = new_notebook()
297 nbmodel = {'content': nb, 'type': 'notebook'}
298 nbmodel = {'content': nb, 'type': 'notebook'}
298 resp = self.api.upload(u'Upload tést.ipynb', path=u'å b',
299 resp = self.api.upload(u'Upload tést.ipynb', path=u'å b',
299 body=json.dumps(nbmodel))
300 body=json.dumps(nbmodel))
300 self._check_created(resp, u'Upload tést.ipynb', u'å b')
301 self._check_created(resp, u'Upload tést.ipynb', u'å b')
301
302
302 def test_mkdir(self):
303 def test_mkdir(self):
303 resp = self.api.mkdir(u'New ∂ir', path=u'å b')
304 resp = self.api.mkdir(u'New ∂ir', path=u'å b')
304 self._check_created(resp, u'New ∂ir', u'å b', type='directory')
305 self._check_created(resp, u'New ∂ir', u'å b', type='directory')
305
306
306 def test_mkdir_hidden_400(self):
307 def test_mkdir_hidden_400(self):
307 with assert_http_error(400):
308 with assert_http_error(400):
308 resp = self.api.mkdir(u'.hidden', path=u'å b')
309 resp = self.api.mkdir(u'.hidden', path=u'å b')
309
310
310 def test_upload_txt(self):
311 def test_upload_txt(self):
311 body = u'ünicode téxt'
312 body = u'ünicode téxt'
312 model = {
313 model = {
313 'content' : body,
314 'content' : body,
314 'format' : 'text',
315 'format' : 'text',
315 'type' : 'file',
316 'type' : 'file',
316 }
317 }
317 resp = self.api.upload(u'Upload tést.txt', path=u'å b',
318 resp = self.api.upload(u'Upload tést.txt', path=u'å b',
318 body=json.dumps(model))
319 body=json.dumps(model))
319
320
320 # check roundtrip
321 # check roundtrip
321 resp = self.api.read(path=u'å b', name=u'Upload tést.txt')
322 resp = self.api.read(path=u'å b', name=u'Upload tést.txt')
322 model = resp.json()
323 model = resp.json()
323 self.assertEqual(model['type'], 'file')
324 self.assertEqual(model['type'], 'file')
324 self.assertEqual(model['format'], 'text')
325 self.assertEqual(model['format'], 'text')
325 self.assertEqual(model['content'], body)
326 self.assertEqual(model['content'], body)
326
327
327 def test_upload_b64(self):
328 def test_upload_b64(self):
328 body = b'\xFFblob'
329 body = b'\xFFblob'
329 b64body = base64.encodestring(body).decode('ascii')
330 b64body = base64.encodestring(body).decode('ascii')
330 model = {
331 model = {
331 'content' : b64body,
332 'content' : b64body,
332 'format' : 'base64',
333 'format' : 'base64',
333 'type' : 'file',
334 'type' : 'file',
334 }
335 }
335 resp = self.api.upload(u'Upload tést.blob', path=u'å b',
336 resp = self.api.upload(u'Upload tést.blob', path=u'å b',
336 body=json.dumps(model))
337 body=json.dumps(model))
337
338
338 # check roundtrip
339 # check roundtrip
339 resp = self.api.read(path=u'å b', name=u'Upload tést.blob')
340 resp = self.api.read(path=u'å b', name=u'Upload tést.blob')
340 model = resp.json()
341 model = resp.json()
341 self.assertEqual(model['type'], 'file')
342 self.assertEqual(model['type'], 'file')
342 self.assertEqual(model['format'], 'base64')
343 self.assertEqual(model['format'], 'base64')
343 decoded = base64.decodestring(model['content'].encode('ascii'))
344 decoded = base64.decodestring(model['content'].encode('ascii'))
344 self.assertEqual(decoded, body)
345 self.assertEqual(decoded, body)
345
346
346 def test_upload_v2(self):
347 def test_upload_v2(self):
347 nb = v2.new_notebook()
348 nb = v2.new_notebook()
348 ws = v2.new_worksheet()
349 ws = v2.new_worksheet()
349 nb.worksheets.append(ws)
350 nb.worksheets.append(ws)
350 ws.cells.append(v2.new_code_cell(input='print("hi")'))
351 ws.cells.append(v2.new_code_cell(input='print("hi")'))
351 nbmodel = {'content': nb, 'type': 'notebook'}
352 nbmodel = {'content': nb, 'type': 'notebook'}
352 resp = self.api.upload(u'Upload tést.ipynb', path=u'å b',
353 resp = self.api.upload(u'Upload tést.ipynb', path=u'å b',
353 body=json.dumps(nbmodel))
354 body=json.dumps(nbmodel))
354 self._check_created(resp, u'Upload tést.ipynb', u'å b')
355 self._check_created(resp, u'Upload tést.ipynb', u'å b')
355 resp = self.api.read(u'Upload tést.ipynb', u'å b')
356 resp = self.api.read(u'Upload tést.ipynb', u'å b')
356 data = resp.json()
357 data = resp.json()
357 self.assertEqual(data['content']['nbformat'], current.nbformat)
358 self.assertEqual(data['content']['nbformat'], 4)
358 self.assertEqual(data['content']['orig_nbformat'], 2)
359
359
360 def test_copy_untitled(self):
360 def test_copy_untitled(self):
361 resp = self.api.copy_untitled(u'ç d.ipynb', path=u'å b')
361 resp = self.api.copy_untitled(u'ç d.ipynb', path=u'å b')
362 self._check_created(resp, u'ç d-Copy0.ipynb', u'å b')
362 self._check_created(resp, u'ç d-Copy0.ipynb', u'å b')
363
363
364 def test_copy(self):
364 def test_copy(self):
365 resp = self.api.copy(u'ç d.ipynb', u'cøpy.ipynb', path=u'å b')
365 resp = self.api.copy(u'ç d.ipynb', u'cøpy.ipynb', path=u'å b')
366 self._check_created(resp, u'cøpy.ipynb', u'å b')
366 self._check_created(resp, u'cøpy.ipynb', u'å b')
367
367
368 def test_copy_path(self):
368 def test_copy_path(self):
369 resp = self.api.copy(u'foo/a.ipynb', u'cøpyfoo.ipynb', path=u'å b')
369 resp = self.api.copy(u'foo/a.ipynb', u'cøpyfoo.ipynb', path=u'å b')
370 self._check_created(resp, u'cøpyfoo.ipynb', u'å b')
370 self._check_created(resp, u'cøpyfoo.ipynb', u'å b')
371
371
372 def test_copy_dir_400(self):
372 def test_copy_dir_400(self):
373 # can't copy directories
373 # can't copy directories
374 with assert_http_error(400):
374 with assert_http_error(400):
375 resp = self.api.copy(u'å b', u'å c')
375 resp = self.api.copy(u'å b', u'å c')
376
376
377 def test_delete(self):
377 def test_delete(self):
378 for d, name in self.dirs_nbs:
378 for d, name in self.dirs_nbs:
379 resp = self.api.delete('%s.ipynb' % name, d)
379 resp = self.api.delete('%s.ipynb' % name, d)
380 self.assertEqual(resp.status_code, 204)
380 self.assertEqual(resp.status_code, 204)
381
381
382 for d in self.dirs + ['/']:
382 for d in self.dirs + ['/']:
383 nbs = notebooks_only(self.api.list(d).json())
383 nbs = notebooks_only(self.api.list(d).json())
384 self.assertEqual(len(nbs), 0)
384 self.assertEqual(len(nbs), 0)
385
385
386 def test_delete_dirs(self):
386 def test_delete_dirs(self):
387 # depth-first delete everything, so we don't try to delete empty directories
387 # depth-first delete everything, so we don't try to delete empty directories
388 for name in sorted(self.dirs + ['/'], key=len, reverse=True):
388 for name in sorted(self.dirs + ['/'], key=len, reverse=True):
389 listing = self.api.list(name).json()['content']
389 listing = self.api.list(name).json()['content']
390 for model in listing:
390 for model in listing:
391 self.api.delete(model['name'], model['path'])
391 self.api.delete(model['name'], model['path'])
392 listing = self.api.list('/').json()['content']
392 listing = self.api.list('/').json()['content']
393 self.assertEqual(listing, [])
393 self.assertEqual(listing, [])
394
394
395 def test_delete_non_empty_dir(self):
395 def test_delete_non_empty_dir(self):
396 """delete non-empty dir raises 400"""
396 """delete non-empty dir raises 400"""
397 with assert_http_error(400):
397 with assert_http_error(400):
398 self.api.delete(u'å b')
398 self.api.delete(u'å b')
399
399
400 def test_rename(self):
400 def test_rename(self):
401 resp = self.api.rename('a.ipynb', 'foo', 'z.ipynb')
401 resp = self.api.rename('a.ipynb', 'foo', 'z.ipynb')
402 self.assertEqual(resp.headers['Location'].split('/')[-1], 'z.ipynb')
402 self.assertEqual(resp.headers['Location'].split('/')[-1], 'z.ipynb')
403 self.assertEqual(resp.json()['name'], 'z.ipynb')
403 self.assertEqual(resp.json()['name'], 'z.ipynb')
404 assert os.path.isfile(pjoin(self.notebook_dir.name, 'foo', 'z.ipynb'))
404 assert os.path.isfile(pjoin(self.notebook_dir.name, 'foo', 'z.ipynb'))
405
405
406 nbs = notebooks_only(self.api.list('foo').json())
406 nbs = notebooks_only(self.api.list('foo').json())
407 nbnames = set(n['name'] for n in nbs)
407 nbnames = set(n['name'] for n in nbs)
408 self.assertIn('z.ipynb', nbnames)
408 self.assertIn('z.ipynb', nbnames)
409 self.assertNotIn('a.ipynb', nbnames)
409 self.assertNotIn('a.ipynb', nbnames)
410
410
411 def test_rename_existing(self):
411 def test_rename_existing(self):
412 with assert_http_error(409):
412 with assert_http_error(409):
413 self.api.rename('a.ipynb', 'foo', 'b.ipynb')
413 self.api.rename('a.ipynb', 'foo', 'b.ipynb')
414
414
415 def test_save(self):
415 def test_save(self):
416 resp = self.api.read('a.ipynb', 'foo')
416 resp = self.api.read('a.ipynb', 'foo')
417 nbcontent = json.loads(resp.text)['content']
417 nbcontent = json.loads(resp.text)['content']
418 nb = to_notebook_json(nbcontent)
418 nb = from_dict(nbcontent)
419 ws = new_worksheet()
419 nb.cells.append(new_markdown_cell(u'Created by test ³'))
420 nb.worksheets = [ws]
421 ws.cells.append(new_heading_cell(u'Created by test ³'))
422
420
423 nbmodel= {'name': 'a.ipynb', 'path':'foo', 'content': nb, 'type': 'notebook'}
421 nbmodel= {'name': 'a.ipynb', 'path':'foo', 'content': nb, 'type': 'notebook'}
424 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
422 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
425
423
426 nbfile = pjoin(self.notebook_dir.name, 'foo', 'a.ipynb')
424 nbfile = pjoin(self.notebook_dir.name, 'foo', 'a.ipynb')
427 with io.open(nbfile, 'r', encoding='utf-8') as f:
425 with io.open(nbfile, 'r', encoding='utf-8') as f:
428 newnb = read(f, format='ipynb')
426 newnb = read(f, as_version=4)
429 self.assertEqual(newnb.worksheets[0].cells[0].source,
427 self.assertEqual(newnb.cells[0].source,
430 u'Created by test ³')
428 u'Created by test ³')
431 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
429 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
432 newnb = to_notebook_json(nbcontent)
430 newnb = from_dict(nbcontent)
433 self.assertEqual(newnb.worksheets[0].cells[0].source,
431 self.assertEqual(newnb.cells[0].source,
434 u'Created by test ³')
432 u'Created by test ³')
435
433
436 # Save and rename
434 # Save and rename
437 nbmodel= {'name': 'a2.ipynb', 'path':'foo/bar', 'content': nb, 'type': 'notebook'}
435 nbmodel= {'name': 'a2.ipynb', 'path':'foo/bar', 'content': nb, 'type': 'notebook'}
438 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
436 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
439 saved = resp.json()
437 saved = resp.json()
440 self.assertEqual(saved['name'], 'a2.ipynb')
438 self.assertEqual(saved['name'], 'a2.ipynb')
441 self.assertEqual(saved['path'], 'foo/bar')
439 self.assertEqual(saved['path'], 'foo/bar')
442 assert os.path.isfile(pjoin(self.notebook_dir.name,'foo','bar','a2.ipynb'))
440 assert os.path.isfile(pjoin(self.notebook_dir.name,'foo','bar','a2.ipynb'))
443 assert not os.path.isfile(pjoin(self.notebook_dir.name, 'foo', 'a.ipynb'))
441 assert not os.path.isfile(pjoin(self.notebook_dir.name, 'foo', 'a.ipynb'))
444 with assert_http_error(404):
442 with assert_http_error(404):
445 self.api.read('a.ipynb', 'foo')
443 self.api.read('a.ipynb', 'foo')
446
444
447 def test_checkpoints(self):
445 def test_checkpoints(self):
448 resp = self.api.read('a.ipynb', 'foo')
446 resp = self.api.read('a.ipynb', 'foo')
449 r = self.api.new_checkpoint('a.ipynb', 'foo')
447 r = self.api.new_checkpoint('a.ipynb', 'foo')
450 self.assertEqual(r.status_code, 201)
448 self.assertEqual(r.status_code, 201)
451 cp1 = r.json()
449 cp1 = r.json()
452 self.assertEqual(set(cp1), {'id', 'last_modified'})
450 self.assertEqual(set(cp1), {'id', 'last_modified'})
453 self.assertEqual(r.headers['Location'].split('/')[-1], cp1['id'])
451 self.assertEqual(r.headers['Location'].split('/')[-1], cp1['id'])
454
452
455 # Modify it
453 # Modify it
456 nbcontent = json.loads(resp.text)['content']
454 nbcontent = json.loads(resp.text)['content']
457 nb = to_notebook_json(nbcontent)
455 nb = from_dict(nbcontent)
458 ws = new_worksheet()
456 hcell = new_markdown_cell('Created by test')
459 nb.worksheets = [ws]
457 nb.cells.append(hcell)
460 hcell = new_heading_cell('Created by test')
461 ws.cells.append(hcell)
462 # Save
458 # Save
463 nbmodel= {'name': 'a.ipynb', 'path':'foo', 'content': nb, 'type': 'notebook'}
459 nbmodel= {'name': 'a.ipynb', 'path':'foo', 'content': nb, 'type': 'notebook'}
464 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
460 resp = self.api.save('a.ipynb', path='foo', body=json.dumps(nbmodel))
465
461
466 # List checkpoints
462 # List checkpoints
467 cps = self.api.get_checkpoints('a.ipynb', 'foo').json()
463 cps = self.api.get_checkpoints('a.ipynb', 'foo').json()
468 self.assertEqual(cps, [cp1])
464 self.assertEqual(cps, [cp1])
469
465
470 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
466 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
471 nb = to_notebook_json(nbcontent)
467 nb = from_dict(nbcontent)
472 self.assertEqual(nb.worksheets[0].cells[0].source, 'Created by test')
468 self.assertEqual(nb.cells[0].source, 'Created by test')
473
469
474 # Restore cp1
470 # Restore cp1
475 r = self.api.restore_checkpoint('a.ipynb', 'foo', cp1['id'])
471 r = self.api.restore_checkpoint('a.ipynb', 'foo', cp1['id'])
476 self.assertEqual(r.status_code, 204)
472 self.assertEqual(r.status_code, 204)
477 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
473 nbcontent = self.api.read('a.ipynb', 'foo').json()['content']
478 nb = to_notebook_json(nbcontent)
474 nb = from_dict(nbcontent)
479 self.assertEqual(nb.worksheets, [])
475 self.assertEqual(nb.cells, [])
480
476
481 # Delete cp1
477 # Delete cp1
482 r = self.api.delete_checkpoint('a.ipynb', 'foo', cp1['id'])
478 r = self.api.delete_checkpoint('a.ipynb', 'foo', cp1['id'])
483 self.assertEqual(r.status_code, 204)
479 self.assertEqual(r.status_code, 204)
484 cps = self.api.get_checkpoints('a.ipynb', 'foo').json()
480 cps = self.api.get_checkpoints('a.ipynb', 'foo').json()
485 self.assertEqual(cps, [])
481 self.assertEqual(cps, [])
@@ -1,334 +1,332 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Tests for the notebook manager."""
2 """Tests for the notebook manager."""
3 from __future__ import print_function
3 from __future__ import print_function
4
4
5 import logging
5 import logging
6 import os
6 import os
7
7
8 from tornado.web import HTTPError
8 from tornado.web import HTTPError
9 from unittest import TestCase
9 from unittest import TestCase
10 from tempfile import NamedTemporaryFile
10 from tempfile import NamedTemporaryFile
11
11
12 from IPython.nbformat import current
12 from IPython.nbformat import v4 as nbformat
13
13
14 from IPython.utils.tempdir import TemporaryDirectory
14 from IPython.utils.tempdir import TemporaryDirectory
15 from IPython.utils.traitlets import TraitError
15 from IPython.utils.traitlets import TraitError
16 from IPython.html.utils import url_path_join
16 from IPython.html.utils import url_path_join
17 from IPython.testing import decorators as dec
17 from IPython.testing import decorators as dec
18
18
19 from ..filemanager import FileContentsManager
19 from ..filemanager import FileContentsManager
20 from ..manager import ContentsManager
20 from ..manager import ContentsManager
21
21
22
22
23 class TestFileContentsManager(TestCase):
23 class TestFileContentsManager(TestCase):
24
24
25 def test_root_dir(self):
25 def test_root_dir(self):
26 with TemporaryDirectory() as td:
26 with TemporaryDirectory() as td:
27 fm = FileContentsManager(root_dir=td)
27 fm = FileContentsManager(root_dir=td)
28 self.assertEqual(fm.root_dir, td)
28 self.assertEqual(fm.root_dir, td)
29
29
30 def test_missing_root_dir(self):
30 def test_missing_root_dir(self):
31 with TemporaryDirectory() as td:
31 with TemporaryDirectory() as td:
32 root = os.path.join(td, 'notebook', 'dir', 'is', 'missing')
32 root = os.path.join(td, 'notebook', 'dir', 'is', 'missing')
33 self.assertRaises(TraitError, FileContentsManager, root_dir=root)
33 self.assertRaises(TraitError, FileContentsManager, root_dir=root)
34
34
35 def test_invalid_root_dir(self):
35 def test_invalid_root_dir(self):
36 with NamedTemporaryFile() as tf:
36 with NamedTemporaryFile() as tf:
37 self.assertRaises(TraitError, FileContentsManager, root_dir=tf.name)
37 self.assertRaises(TraitError, FileContentsManager, root_dir=tf.name)
38
38
39 def test_get_os_path(self):
39 def test_get_os_path(self):
40 # full filesystem path should be returned with correct operating system
40 # full filesystem path should be returned with correct operating system
41 # separators.
41 # separators.
42 with TemporaryDirectory() as td:
42 with TemporaryDirectory() as td:
43 root = td
43 root = td
44 fm = FileContentsManager(root_dir=root)
44 fm = FileContentsManager(root_dir=root)
45 path = fm._get_os_path('test.ipynb', '/path/to/notebook/')
45 path = fm._get_os_path('test.ipynb', '/path/to/notebook/')
46 rel_path_list = '/path/to/notebook/test.ipynb'.split('/')
46 rel_path_list = '/path/to/notebook/test.ipynb'.split('/')
47 fs_path = os.path.join(fm.root_dir, *rel_path_list)
47 fs_path = os.path.join(fm.root_dir, *rel_path_list)
48 self.assertEqual(path, fs_path)
48 self.assertEqual(path, fs_path)
49
49
50 fm = FileContentsManager(root_dir=root)
50 fm = FileContentsManager(root_dir=root)
51 path = fm._get_os_path('test.ipynb')
51 path = fm._get_os_path('test.ipynb')
52 fs_path = os.path.join(fm.root_dir, 'test.ipynb')
52 fs_path = os.path.join(fm.root_dir, 'test.ipynb')
53 self.assertEqual(path, fs_path)
53 self.assertEqual(path, fs_path)
54
54
55 fm = FileContentsManager(root_dir=root)
55 fm = FileContentsManager(root_dir=root)
56 path = fm._get_os_path('test.ipynb', '////')
56 path = fm._get_os_path('test.ipynb', '////')
57 fs_path = os.path.join(fm.root_dir, 'test.ipynb')
57 fs_path = os.path.join(fm.root_dir, 'test.ipynb')
58 self.assertEqual(path, fs_path)
58 self.assertEqual(path, fs_path)
59
59
60 def test_checkpoint_subdir(self):
60 def test_checkpoint_subdir(self):
61 subd = u'sub ∂ir'
61 subd = u'sub ∂ir'
62 cp_name = 'test-cp.ipynb'
62 cp_name = 'test-cp.ipynb'
63 with TemporaryDirectory() as td:
63 with TemporaryDirectory() as td:
64 root = td
64 root = td
65 os.mkdir(os.path.join(td, subd))
65 os.mkdir(os.path.join(td, subd))
66 fm = FileContentsManager(root_dir=root)
66 fm = FileContentsManager(root_dir=root)
67 cp_dir = fm.get_checkpoint_path('cp', 'test.ipynb', '/')
67 cp_dir = fm.get_checkpoint_path('cp', 'test.ipynb', '/')
68 cp_subdir = fm.get_checkpoint_path('cp', 'test.ipynb', '/%s/' % subd)
68 cp_subdir = fm.get_checkpoint_path('cp', 'test.ipynb', '/%s/' % subd)
69 self.assertNotEqual(cp_dir, cp_subdir)
69 self.assertNotEqual(cp_dir, cp_subdir)
70 self.assertEqual(cp_dir, os.path.join(root, fm.checkpoint_dir, cp_name))
70 self.assertEqual(cp_dir, os.path.join(root, fm.checkpoint_dir, cp_name))
71 self.assertEqual(cp_subdir, os.path.join(root, subd, fm.checkpoint_dir, cp_name))
71 self.assertEqual(cp_subdir, os.path.join(root, subd, fm.checkpoint_dir, cp_name))
72
72
73
73
74 class TestContentsManager(TestCase):
74 class TestContentsManager(TestCase):
75
75
76 def setUp(self):
76 def setUp(self):
77 self._temp_dir = TemporaryDirectory()
77 self._temp_dir = TemporaryDirectory()
78 self.td = self._temp_dir.name
78 self.td = self._temp_dir.name
79 self.contents_manager = FileContentsManager(
79 self.contents_manager = FileContentsManager(
80 root_dir=self.td,
80 root_dir=self.td,
81 log=logging.getLogger()
81 log=logging.getLogger()
82 )
82 )
83
83
84 def tearDown(self):
84 def tearDown(self):
85 self._temp_dir.cleanup()
85 self._temp_dir.cleanup()
86
86
87 def make_dir(self, abs_path, rel_path):
87 def make_dir(self, abs_path, rel_path):
88 """make subdirectory, rel_path is the relative path
88 """make subdirectory, rel_path is the relative path
89 to that directory from the location where the server started"""
89 to that directory from the location where the server started"""
90 os_path = os.path.join(abs_path, rel_path)
90 os_path = os.path.join(abs_path, rel_path)
91 try:
91 try:
92 os.makedirs(os_path)
92 os.makedirs(os_path)
93 except OSError:
93 except OSError:
94 print("Directory already exists: %r" % os_path)
94 print("Directory already exists: %r" % os_path)
95 return os_path
95 return os_path
96
96
97 def add_code_cell(self, nb):
97 def add_code_cell(self, nb):
98 output = current.new_output("display_data", output_javascript="alert('hi');")
98 output = nbformat.new_output("display_data", {'application/javascript': "alert('hi');"})
99 cell = current.new_code_cell("print('hi')", outputs=[output])
99 cell = nbformat.new_code_cell("print('hi')", outputs=[output])
100 if not nb.worksheets:
100 nb.cells.append(cell)
101 nb.worksheets.append(current.new_worksheet())
102 nb.worksheets[0].cells.append(cell)
103
101
104 def new_notebook(self):
102 def new_notebook(self):
105 cm = self.contents_manager
103 cm = self.contents_manager
106 model = cm.create_file()
104 model = cm.create_file()
107 name = model['name']
105 name = model['name']
108 path = model['path']
106 path = model['path']
109
107
110 full_model = cm.get_model(name, path)
108 full_model = cm.get_model(name, path)
111 nb = full_model['content']
109 nb = full_model['content']
112 self.add_code_cell(nb)
110 self.add_code_cell(nb)
113
111
114 cm.save(full_model, name, path)
112 cm.save(full_model, name, path)
115 return nb, name, path
113 return nb, name, path
116
114
117 def test_create_file(self):
115 def test_create_file(self):
118 cm = self.contents_manager
116 cm = self.contents_manager
119 # Test in root directory
117 # Test in root directory
120 model = cm.create_file()
118 model = cm.create_file()
121 assert isinstance(model, dict)
119 assert isinstance(model, dict)
122 self.assertIn('name', model)
120 self.assertIn('name', model)
123 self.assertIn('path', model)
121 self.assertIn('path', model)
124 self.assertEqual(model['name'], 'Untitled0.ipynb')
122 self.assertEqual(model['name'], 'Untitled0.ipynb')
125 self.assertEqual(model['path'], '')
123 self.assertEqual(model['path'], '')
126
124
127 # Test in sub-directory
125 # Test in sub-directory
128 sub_dir = '/foo/'
126 sub_dir = '/foo/'
129 self.make_dir(cm.root_dir, 'foo')
127 self.make_dir(cm.root_dir, 'foo')
130 model = cm.create_file(None, sub_dir)
128 model = cm.create_file(None, sub_dir)
131 assert isinstance(model, dict)
129 assert isinstance(model, dict)
132 self.assertIn('name', model)
130 self.assertIn('name', model)
133 self.assertIn('path', model)
131 self.assertIn('path', model)
134 self.assertEqual(model['name'], 'Untitled0.ipynb')
132 self.assertEqual(model['name'], 'Untitled0.ipynb')
135 self.assertEqual(model['path'], sub_dir.strip('/'))
133 self.assertEqual(model['path'], sub_dir.strip('/'))
136
134
137 def test_get(self):
135 def test_get(self):
138 cm = self.contents_manager
136 cm = self.contents_manager
139 # Create a notebook
137 # Create a notebook
140 model = cm.create_file()
138 model = cm.create_file()
141 name = model['name']
139 name = model['name']
142 path = model['path']
140 path = model['path']
143
141
144 # Check that we 'get' on the notebook we just created
142 # Check that we 'get' on the notebook we just created
145 model2 = cm.get_model(name, path)
143 model2 = cm.get_model(name, path)
146 assert isinstance(model2, dict)
144 assert isinstance(model2, dict)
147 self.assertIn('name', model2)
145 self.assertIn('name', model2)
148 self.assertIn('path', model2)
146 self.assertIn('path', model2)
149 self.assertEqual(model['name'], name)
147 self.assertEqual(model['name'], name)
150 self.assertEqual(model['path'], path)
148 self.assertEqual(model['path'], path)
151
149
152 # Test in sub-directory
150 # Test in sub-directory
153 sub_dir = '/foo/'
151 sub_dir = '/foo/'
154 self.make_dir(cm.root_dir, 'foo')
152 self.make_dir(cm.root_dir, 'foo')
155 model = cm.create_file(None, sub_dir)
153 model = cm.create_file(None, sub_dir)
156 model2 = cm.get_model(name, sub_dir)
154 model2 = cm.get_model(name, sub_dir)
157 assert isinstance(model2, dict)
155 assert isinstance(model2, dict)
158 self.assertIn('name', model2)
156 self.assertIn('name', model2)
159 self.assertIn('path', model2)
157 self.assertIn('path', model2)
160 self.assertIn('content', model2)
158 self.assertIn('content', model2)
161 self.assertEqual(model2['name'], 'Untitled0.ipynb')
159 self.assertEqual(model2['name'], 'Untitled0.ipynb')
162 self.assertEqual(model2['path'], sub_dir.strip('/'))
160 self.assertEqual(model2['path'], sub_dir.strip('/'))
163
161
164 @dec.skip_win32
162 @dec.skip_win32
165 def test_bad_symlink(self):
163 def test_bad_symlink(self):
166 cm = self.contents_manager
164 cm = self.contents_manager
167 path = 'test bad symlink'
165 path = 'test bad symlink'
168 os_path = self.make_dir(cm.root_dir, path)
166 os_path = self.make_dir(cm.root_dir, path)
169
167
170 file_model = cm.create_file(path=path, ext='.txt')
168 file_model = cm.create_file(path=path, ext='.txt')
171
169
172 # create a broken symlink
170 # create a broken symlink
173 os.symlink("target", os.path.join(os_path, "bad symlink"))
171 os.symlink("target", os.path.join(os_path, "bad symlink"))
174 model = cm.get_model(path)
172 model = cm.get_model(path)
175 self.assertEqual(model['content'], [file_model])
173 self.assertEqual(model['content'], [file_model])
176
174
177 @dec.skip_win32
175 @dec.skip_win32
178 def test_good_symlink(self):
176 def test_good_symlink(self):
179 cm = self.contents_manager
177 cm = self.contents_manager
180 path = 'test good symlink'
178 path = 'test good symlink'
181 os_path = self.make_dir(cm.root_dir, path)
179 os_path = self.make_dir(cm.root_dir, path)
182
180
183 file_model = cm.create_file(path=path, ext='.txt')
181 file_model = cm.create_file(path=path, ext='.txt')
184
182
185 # create a good symlink
183 # create a good symlink
186 os.symlink(file_model['name'], os.path.join(os_path, "good symlink"))
184 os.symlink(file_model['name'], os.path.join(os_path, "good symlink"))
187 symlink_model = cm.get_model(name="good symlink", path=path, content=False)
185 symlink_model = cm.get_model(name="good symlink", path=path, content=False)
188
186
189 dir_model = cm.get_model(path)
187 dir_model = cm.get_model(path)
190 self.assertEqual(
188 self.assertEqual(
191 sorted(dir_model['content'], key=lambda x: x['name']),
189 sorted(dir_model['content'], key=lambda x: x['name']),
192 [symlink_model, file_model],
190 [symlink_model, file_model],
193 )
191 )
194
192
195 def test_update(self):
193 def test_update(self):
196 cm = self.contents_manager
194 cm = self.contents_manager
197 # Create a notebook
195 # Create a notebook
198 model = cm.create_file()
196 model = cm.create_file()
199 name = model['name']
197 name = model['name']
200 path = model['path']
198 path = model['path']
201
199
202 # Change the name in the model for rename
200 # Change the name in the model for rename
203 model['name'] = 'test.ipynb'
201 model['name'] = 'test.ipynb'
204 model = cm.update(model, name, path)
202 model = cm.update(model, name, path)
205 assert isinstance(model, dict)
203 assert isinstance(model, dict)
206 self.assertIn('name', model)
204 self.assertIn('name', model)
207 self.assertIn('path', model)
205 self.assertIn('path', model)
208 self.assertEqual(model['name'], 'test.ipynb')
206 self.assertEqual(model['name'], 'test.ipynb')
209
207
210 # Make sure the old name is gone
208 # Make sure the old name is gone
211 self.assertRaises(HTTPError, cm.get_model, name, path)
209 self.assertRaises(HTTPError, cm.get_model, name, path)
212
210
213 # Test in sub-directory
211 # Test in sub-directory
214 # Create a directory and notebook in that directory
212 # Create a directory and notebook in that directory
215 sub_dir = '/foo/'
213 sub_dir = '/foo/'
216 self.make_dir(cm.root_dir, 'foo')
214 self.make_dir(cm.root_dir, 'foo')
217 model = cm.create_file(None, sub_dir)
215 model = cm.create_file(None, sub_dir)
218 name = model['name']
216 name = model['name']
219 path = model['path']
217 path = model['path']
220
218
221 # Change the name in the model for rename
219 # Change the name in the model for rename
222 model['name'] = 'test_in_sub.ipynb'
220 model['name'] = 'test_in_sub.ipynb'
223 model = cm.update(model, name, path)
221 model = cm.update(model, name, path)
224 assert isinstance(model, dict)
222 assert isinstance(model, dict)
225 self.assertIn('name', model)
223 self.assertIn('name', model)
226 self.assertIn('path', model)
224 self.assertIn('path', model)
227 self.assertEqual(model['name'], 'test_in_sub.ipynb')
225 self.assertEqual(model['name'], 'test_in_sub.ipynb')
228 self.assertEqual(model['path'], sub_dir.strip('/'))
226 self.assertEqual(model['path'], sub_dir.strip('/'))
229
227
230 # Make sure the old name is gone
228 # Make sure the old name is gone
231 self.assertRaises(HTTPError, cm.get_model, name, path)
229 self.assertRaises(HTTPError, cm.get_model, name, path)
232
230
233 def test_save(self):
231 def test_save(self):
234 cm = self.contents_manager
232 cm = self.contents_manager
235 # Create a notebook
233 # Create a notebook
236 model = cm.create_file()
234 model = cm.create_file()
237 name = model['name']
235 name = model['name']
238 path = model['path']
236 path = model['path']
239
237
240 # Get the model with 'content'
238 # Get the model with 'content'
241 full_model = cm.get_model(name, path)
239 full_model = cm.get_model(name, path)
242
240
243 # Save the notebook
241 # Save the notebook
244 model = cm.save(full_model, name, path)
242 model = cm.save(full_model, name, path)
245 assert isinstance(model, dict)
243 assert isinstance(model, dict)
246 self.assertIn('name', model)
244 self.assertIn('name', model)
247 self.assertIn('path', model)
245 self.assertIn('path', model)
248 self.assertEqual(model['name'], name)
246 self.assertEqual(model['name'], name)
249 self.assertEqual(model['path'], path)
247 self.assertEqual(model['path'], path)
250
248
251 # Test in sub-directory
249 # Test in sub-directory
252 # Create a directory and notebook in that directory
250 # Create a directory and notebook in that directory
253 sub_dir = '/foo/'
251 sub_dir = '/foo/'
254 self.make_dir(cm.root_dir, 'foo')
252 self.make_dir(cm.root_dir, 'foo')
255 model = cm.create_file(None, sub_dir)
253 model = cm.create_file(None, sub_dir)
256 name = model['name']
254 name = model['name']
257 path = model['path']
255 path = model['path']
258 model = cm.get_model(name, path)
256 model = cm.get_model(name, path)
259
257
260 # Change the name in the model for rename
258 # Change the name in the model for rename
261 model = cm.save(model, name, path)
259 model = cm.save(model, name, path)
262 assert isinstance(model, dict)
260 assert isinstance(model, dict)
263 self.assertIn('name', model)
261 self.assertIn('name', model)
264 self.assertIn('path', model)
262 self.assertIn('path', model)
265 self.assertEqual(model['name'], 'Untitled0.ipynb')
263 self.assertEqual(model['name'], 'Untitled0.ipynb')
266 self.assertEqual(model['path'], sub_dir.strip('/'))
264 self.assertEqual(model['path'], sub_dir.strip('/'))
267
265
268 def test_delete(self):
266 def test_delete(self):
269 cm = self.contents_manager
267 cm = self.contents_manager
270 # Create a notebook
268 # Create a notebook
271 nb, name, path = self.new_notebook()
269 nb, name, path = self.new_notebook()
272
270
273 # Delete the notebook
271 # Delete the notebook
274 cm.delete(name, path)
272 cm.delete(name, path)
275
273
276 # Check that a 'get' on the deleted notebook raises and error
274 # Check that a 'get' on the deleted notebook raises and error
277 self.assertRaises(HTTPError, cm.get_model, name, path)
275 self.assertRaises(HTTPError, cm.get_model, name, path)
278
276
279 def test_copy(self):
277 def test_copy(self):
280 cm = self.contents_manager
278 cm = self.contents_manager
281 path = u'å b'
279 path = u'å b'
282 name = u'nb √.ipynb'
280 name = u'nb √.ipynb'
283 os.mkdir(os.path.join(cm.root_dir, path))
281 os.mkdir(os.path.join(cm.root_dir, path))
284 orig = cm.create_file({'name' : name}, path=path)
282 orig = cm.create_file({'name' : name}, path=path)
285
283
286 # copy with unspecified name
284 # copy with unspecified name
287 copy = cm.copy(name, path=path)
285 copy = cm.copy(name, path=path)
288 self.assertEqual(copy['name'], orig['name'].replace('.ipynb', '-Copy0.ipynb'))
286 self.assertEqual(copy['name'], orig['name'].replace('.ipynb', '-Copy0.ipynb'))
289
287
290 # copy with specified name
288 # copy with specified name
291 copy2 = cm.copy(name, u'copy 2.ipynb', path=path)
289 copy2 = cm.copy(name, u'copy 2.ipynb', path=path)
292 self.assertEqual(copy2['name'], u'copy 2.ipynb')
290 self.assertEqual(copy2['name'], u'copy 2.ipynb')
293
291
294 def test_trust_notebook(self):
292 def test_trust_notebook(self):
295 cm = self.contents_manager
293 cm = self.contents_manager
296 nb, name, path = self.new_notebook()
294 nb, name, path = self.new_notebook()
297
295
298 untrusted = cm.get_model(name, path)['content']
296 untrusted = cm.get_model(name, path)['content']
299 assert not cm.notary.check_cells(untrusted)
297 assert not cm.notary.check_cells(untrusted)
300
298
301 # print(untrusted)
299 # print(untrusted)
302 cm.trust_notebook(name, path)
300 cm.trust_notebook(name, path)
303 trusted = cm.get_model(name, path)['content']
301 trusted = cm.get_model(name, path)['content']
304 # print(trusted)
302 # print(trusted)
305 assert cm.notary.check_cells(trusted)
303 assert cm.notary.check_cells(trusted)
306
304
307 def test_mark_trusted_cells(self):
305 def test_mark_trusted_cells(self):
308 cm = self.contents_manager
306 cm = self.contents_manager
309 nb, name, path = self.new_notebook()
307 nb, name, path = self.new_notebook()
310
308
311 cm.mark_trusted_cells(nb, name, path)
309 cm.mark_trusted_cells(nb, name, path)
312 for cell in nb.worksheets[0].cells:
310 for cell in nb.cells:
313 if cell.cell_type == 'code':
311 if cell.cell_type == 'code':
314 assert not cell.metadata.trusted
312 assert not cell.metadata.trusted
315
313
316 cm.trust_notebook(name, path)
314 cm.trust_notebook(name, path)
317 nb = cm.get_model(name, path)['content']
315 nb = cm.get_model(name, path)['content']
318 for cell in nb.worksheets[0].cells:
316 for cell in nb.cells:
319 if cell.cell_type == 'code':
317 if cell.cell_type == 'code':
320 assert cell.metadata.trusted
318 assert cell.metadata.trusted
321
319
322 def test_check_and_sign(self):
320 def test_check_and_sign(self):
323 cm = self.contents_manager
321 cm = self.contents_manager
324 nb, name, path = self.new_notebook()
322 nb, name, path = self.new_notebook()
325
323
326 cm.mark_trusted_cells(nb, name, path)
324 cm.mark_trusted_cells(nb, name, path)
327 cm.check_and_sign(nb, name, path)
325 cm.check_and_sign(nb, name, path)
328 assert not cm.notary.check_signature(nb)
326 assert not cm.notary.check_signature(nb)
329
327
330 cm.trust_notebook(name, path)
328 cm.trust_notebook(name, path)
331 nb = cm.get_model(name, path)['content']
329 nb = cm.get_model(name, path)['content']
332 cm.mark_trusted_cells(nb, name, path)
330 cm.mark_trusted_cells(nb, name, path)
333 cm.check_and_sign(nb, name, path)
331 cm.check_and_sign(nb, name, path)
334 assert cm.notary.check_signature(nb)
332 assert cm.notary.check_signature(nb)
@@ -1,116 +1,117 b''
1 """Test the sessions web service API."""
1 """Test the sessions web service API."""
2
2
3 import errno
3 import errno
4 import io
4 import io
5 import os
5 import os
6 import json
6 import json
7 import requests
7 import requests
8 import shutil
8 import shutil
9
9
10 pjoin = os.path.join
10 pjoin = os.path.join
11
11
12 from IPython.html.utils import url_path_join
12 from IPython.html.utils import url_path_join
13 from IPython.html.tests.launchnotebook import NotebookTestBase, assert_http_error
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 class SessionAPI(object):
17 class SessionAPI(object):
17 """Wrapper for notebook API calls."""
18 """Wrapper for notebook API calls."""
18 def __init__(self, base_url):
19 def __init__(self, base_url):
19 self.base_url = base_url
20 self.base_url = base_url
20
21
21 def _req(self, verb, path, body=None):
22 def _req(self, verb, path, body=None):
22 response = requests.request(verb,
23 response = requests.request(verb,
23 url_path_join(self.base_url, 'api/sessions', path), data=body)
24 url_path_join(self.base_url, 'api/sessions', path), data=body)
24
25
25 if 400 <= response.status_code < 600:
26 if 400 <= response.status_code < 600:
26 try:
27 try:
27 response.reason = response.json()['message']
28 response.reason = response.json()['message']
28 except:
29 except:
29 pass
30 pass
30 response.raise_for_status()
31 response.raise_for_status()
31
32
32 return response
33 return response
33
34
34 def list(self):
35 def list(self):
35 return self._req('GET', '')
36 return self._req('GET', '')
36
37
37 def get(self, id):
38 def get(self, id):
38 return self._req('GET', id)
39 return self._req('GET', id)
39
40
40 def create(self, name, path, kernel_name='python'):
41 def create(self, name, path, kernel_name='python'):
41 body = json.dumps({'notebook': {'name':name, 'path':path},
42 body = json.dumps({'notebook': {'name':name, 'path':path},
42 'kernel': {'name': kernel_name}})
43 'kernel': {'name': kernel_name}})
43 return self._req('POST', '', body)
44 return self._req('POST', '', body)
44
45
45 def modify(self, id, name, path):
46 def modify(self, id, name, path):
46 body = json.dumps({'notebook': {'name':name, 'path':path}})
47 body = json.dumps({'notebook': {'name':name, 'path':path}})
47 return self._req('PATCH', id, body)
48 return self._req('PATCH', id, body)
48
49
49 def delete(self, id):
50 def delete(self, id):
50 return self._req('DELETE', id)
51 return self._req('DELETE', id)
51
52
52 class SessionAPITest(NotebookTestBase):
53 class SessionAPITest(NotebookTestBase):
53 """Test the sessions web service API"""
54 """Test the sessions web service API"""
54 def setUp(self):
55 def setUp(self):
55 nbdir = self.notebook_dir.name
56 nbdir = self.notebook_dir.name
56 try:
57 try:
57 os.mkdir(pjoin(nbdir, 'foo'))
58 os.mkdir(pjoin(nbdir, 'foo'))
58 except OSError as e:
59 except OSError as e:
59 # Deleting the folder in an earlier test may have failed
60 # Deleting the folder in an earlier test may have failed
60 if e.errno != errno.EEXIST:
61 if e.errno != errno.EEXIST:
61 raise
62 raise
62
63
63 with io.open(pjoin(nbdir, 'foo', 'nb1.ipynb'), 'w',
64 with io.open(pjoin(nbdir, 'foo', 'nb1.ipynb'), 'w',
64 encoding='utf-8') as f:
65 encoding='utf-8') as f:
65 nb = new_notebook(name='nb1')
66 nb = new_notebook()
66 write(nb, f, format='ipynb')
67 write(nb, f, version=4)
67
68
68 self.sess_api = SessionAPI(self.base_url())
69 self.sess_api = SessionAPI(self.base_url())
69
70
70 def tearDown(self):
71 def tearDown(self):
71 for session in self.sess_api.list().json():
72 for session in self.sess_api.list().json():
72 self.sess_api.delete(session['id'])
73 self.sess_api.delete(session['id'])
73 shutil.rmtree(pjoin(self.notebook_dir.name, 'foo'),
74 shutil.rmtree(pjoin(self.notebook_dir.name, 'foo'),
74 ignore_errors=True)
75 ignore_errors=True)
75
76
76 def test_create(self):
77 def test_create(self):
77 sessions = self.sess_api.list().json()
78 sessions = self.sess_api.list().json()
78 self.assertEqual(len(sessions), 0)
79 self.assertEqual(len(sessions), 0)
79
80
80 resp = self.sess_api.create('nb1.ipynb', 'foo')
81 resp = self.sess_api.create('nb1.ipynb', 'foo')
81 self.assertEqual(resp.status_code, 201)
82 self.assertEqual(resp.status_code, 201)
82 newsession = resp.json()
83 newsession = resp.json()
83 self.assertIn('id', newsession)
84 self.assertIn('id', newsession)
84 self.assertEqual(newsession['notebook']['name'], 'nb1.ipynb')
85 self.assertEqual(newsession['notebook']['name'], 'nb1.ipynb')
85 self.assertEqual(newsession['notebook']['path'], 'foo')
86 self.assertEqual(newsession['notebook']['path'], 'foo')
86 self.assertEqual(resp.headers['Location'], '/api/sessions/{0}'.format(newsession['id']))
87 self.assertEqual(resp.headers['Location'], '/api/sessions/{0}'.format(newsession['id']))
87
88
88 sessions = self.sess_api.list().json()
89 sessions = self.sess_api.list().json()
89 self.assertEqual(sessions, [newsession])
90 self.assertEqual(sessions, [newsession])
90
91
91 # Retrieve it
92 # Retrieve it
92 sid = newsession['id']
93 sid = newsession['id']
93 got = self.sess_api.get(sid).json()
94 got = self.sess_api.get(sid).json()
94 self.assertEqual(got, newsession)
95 self.assertEqual(got, newsession)
95
96
96 def test_delete(self):
97 def test_delete(self):
97 newsession = self.sess_api.create('nb1.ipynb', 'foo').json()
98 newsession = self.sess_api.create('nb1.ipynb', 'foo').json()
98 sid = newsession['id']
99 sid = newsession['id']
99
100
100 resp = self.sess_api.delete(sid)
101 resp = self.sess_api.delete(sid)
101 self.assertEqual(resp.status_code, 204)
102 self.assertEqual(resp.status_code, 204)
102
103
103 sessions = self.sess_api.list().json()
104 sessions = self.sess_api.list().json()
104 self.assertEqual(sessions, [])
105 self.assertEqual(sessions, [])
105
106
106 with assert_http_error(404):
107 with assert_http_error(404):
107 self.sess_api.get(sid)
108 self.sess_api.get(sid)
108
109
109 def test_modify(self):
110 def test_modify(self):
110 newsession = self.sess_api.create('nb1.ipynb', 'foo').json()
111 newsession = self.sess_api.create('nb1.ipynb', 'foo').json()
111 sid = newsession['id']
112 sid = newsession['id']
112
113
113 changed = self.sess_api.modify(sid, 'nb2.ipynb', '').json()
114 changed = self.sess_api.modify(sid, 'nb2.ipynb', '').json()
114 self.assertEqual(changed['id'], sid)
115 self.assertEqual(changed['id'], sid)
115 self.assertEqual(changed['notebook']['name'], 'nb2.ipynb')
116 self.assertEqual(changed['notebook']['name'], 'nb2.ipynb')
116 self.assertEqual(changed['notebook']['path'], '')
117 self.assertEqual(changed['notebook']['path'], '')
@@ -1,532 +1,526 b''
1 // Copyright (c) IPython Development Team.
1 // Copyright (c) IPython Development Team.
2 // Distributed under the terms of the Modified BSD License.
2 // Distributed under the terms of the Modified BSD License.
3 /**
3 /**
4 *
4 *
5 *
5 *
6 * @module codecell
6 * @module codecell
7 * @namespace codecell
7 * @namespace codecell
8 * @class CodeCell
8 * @class CodeCell
9 */
9 */
10
10
11
11
12 define([
12 define([
13 'base/js/namespace',
13 'base/js/namespace',
14 'jquery',
14 'jquery',
15 'base/js/utils',
15 'base/js/utils',
16 'base/js/keyboard',
16 'base/js/keyboard',
17 'notebook/js/cell',
17 'notebook/js/cell',
18 'notebook/js/outputarea',
18 'notebook/js/outputarea',
19 'notebook/js/completer',
19 'notebook/js/completer',
20 'notebook/js/celltoolbar',
20 'notebook/js/celltoolbar',
21 'codemirror/lib/codemirror',
21 'codemirror/lib/codemirror',
22 'codemirror/mode/python/python',
22 'codemirror/mode/python/python',
23 'notebook/js/codemirror-ipython'
23 'notebook/js/codemirror-ipython'
24 ], function(IPython, $, utils, keyboard, cell, outputarea, completer, celltoolbar, CodeMirror, cmpython, cmip) {
24 ], function(IPython, $, utils, keyboard, cell, outputarea, completer, celltoolbar, CodeMirror, cmpython, cmip) {
25 "use strict";
25 "use strict";
26 var Cell = cell.Cell;
26 var Cell = cell.Cell;
27
27
28 /* local util for codemirror */
28 /* local util for codemirror */
29 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;};
29 var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;};
30
30
31 /**
31 /**
32 *
32 *
33 * function to delete until previous non blanking space character
33 * function to delete until previous non blanking space character
34 * or first multiple of 4 tabstop.
34 * or first multiple of 4 tabstop.
35 * @private
35 * @private
36 */
36 */
37 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
37 CodeMirror.commands.delSpaceToPrevTabStop = function(cm){
38 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
38 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
39 if (!posEq(from, to)) { cm.replaceRange("", from, to); return; }
39 if (!posEq(from, to)) { cm.replaceRange("", from, to); return; }
40 var cur = cm.getCursor(), line = cm.getLine(cur.line);
40 var cur = cm.getCursor(), line = cm.getLine(cur.line);
41 var tabsize = cm.getOption('tabSize');
41 var tabsize = cm.getOption('tabSize');
42 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
42 var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize;
43 from = {ch:cur.ch-chToPrevTabStop,line:cur.line};
43 from = {ch:cur.ch-chToPrevTabStop,line:cur.line};
44 var select = cm.getRange(from,cur);
44 var select = cm.getRange(from,cur);
45 if( select.match(/^\ +$/) !== null){
45 if( select.match(/^\ +$/) !== null){
46 cm.replaceRange("",from,cur);
46 cm.replaceRange("",from,cur);
47 } else {
47 } else {
48 cm.deleteH(-1,"char");
48 cm.deleteH(-1,"char");
49 }
49 }
50 };
50 };
51
51
52 var keycodes = keyboard.keycodes;
52 var keycodes = keyboard.keycodes;
53
53
54 var CodeCell = function (kernel, options) {
54 var CodeCell = function (kernel, options) {
55 // Constructor
55 // Constructor
56 //
56 //
57 // A Cell conceived to write code.
57 // A Cell conceived to write code.
58 //
58 //
59 // Parameters:
59 // Parameters:
60 // kernel: Kernel instance
60 // kernel: Kernel instance
61 // The kernel doesn't have to be set at creation time, in that case
61 // The kernel doesn't have to be set at creation time, in that case
62 // it will be null and set_kernel has to be called later.
62 // it will be null and set_kernel has to be called later.
63 // options: dictionary
63 // options: dictionary
64 // Dictionary of keyword arguments.
64 // Dictionary of keyword arguments.
65 // events: $(Events) instance
65 // events: $(Events) instance
66 // config: dictionary
66 // config: dictionary
67 // keyboard_manager: KeyboardManager instance
67 // keyboard_manager: KeyboardManager instance
68 // notebook: Notebook instance
68 // notebook: Notebook instance
69 // tooltip: Tooltip instance
69 // tooltip: Tooltip instance
70 this.kernel = kernel || null;
70 this.kernel = kernel || null;
71 this.notebook = options.notebook;
71 this.notebook = options.notebook;
72 this.collapsed = false;
72 this.collapsed = false;
73 this.events = options.events;
73 this.events = options.events;
74 this.tooltip = options.tooltip;
74 this.tooltip = options.tooltip;
75 this.config = options.config;
75 this.config = options.config;
76
76
77 // create all attributed in constructor function
77 // create all attributed in constructor function
78 // even if null for V8 VM optimisation
78 // even if null for V8 VM optimisation
79 this.input_prompt_number = null;
79 this.input_prompt_number = null;
80 this.celltoolbar = null;
80 this.celltoolbar = null;
81 this.output_area = null;
81 this.output_area = null;
82 this.last_msg_id = null;
82 this.last_msg_id = null;
83 this.completer = null;
83 this.completer = null;
84
84
85
85
86 var config = utils.mergeopt(CodeCell, this.config);
86 var config = utils.mergeopt(CodeCell, this.config);
87 Cell.apply(this,[{
87 Cell.apply(this,[{
88 config: config,
88 config: config,
89 keyboard_manager: options.keyboard_manager,
89 keyboard_manager: options.keyboard_manager,
90 events: this.events}]);
90 events: this.events}]);
91
91
92 // Attributes we want to override in this subclass.
92 // Attributes we want to override in this subclass.
93 this.cell_type = "code";
93 this.cell_type = "code";
94
94
95 var that = this;
95 var that = this;
96 this.element.focusout(
96 this.element.focusout(
97 function() { that.auto_highlight(); }
97 function() { that.auto_highlight(); }
98 );
98 );
99 };
99 };
100
100
101 CodeCell.options_default = {
101 CodeCell.options_default = {
102 cm_config : {
102 cm_config : {
103 extraKeys: {
103 extraKeys: {
104 "Tab" : "indentMore",
104 "Tab" : "indentMore",
105 "Shift-Tab" : "indentLess",
105 "Shift-Tab" : "indentLess",
106 "Backspace" : "delSpaceToPrevTabStop",
106 "Backspace" : "delSpaceToPrevTabStop",
107 "Cmd-/" : "toggleComment",
107 "Cmd-/" : "toggleComment",
108 "Ctrl-/" : "toggleComment"
108 "Ctrl-/" : "toggleComment"
109 },
109 },
110 mode: 'ipython',
110 mode: 'ipython',
111 theme: 'ipython',
111 theme: 'ipython',
112 matchBrackets: true
112 matchBrackets: true
113 }
113 }
114 };
114 };
115
115
116 CodeCell.msg_cells = {};
116 CodeCell.msg_cells = {};
117
117
118 CodeCell.prototype = Object.create(Cell.prototype);
118 CodeCell.prototype = Object.create(Cell.prototype);
119
119
120 /**
120 /**
121 * @method auto_highlight
121 * @method auto_highlight
122 */
122 */
123 CodeCell.prototype.auto_highlight = function () {
123 CodeCell.prototype.auto_highlight = function () {
124 this._auto_highlight(this.config.cell_magic_highlight);
124 this._auto_highlight(this.config.cell_magic_highlight);
125 };
125 };
126
126
127 /** @method create_element */
127 /** @method create_element */
128 CodeCell.prototype.create_element = function () {
128 CodeCell.prototype.create_element = function () {
129 Cell.prototype.create_element.apply(this, arguments);
129 Cell.prototype.create_element.apply(this, arguments);
130
130
131 var cell = $('<div></div>').addClass('cell code_cell');
131 var cell = $('<div></div>').addClass('cell code_cell');
132 cell.attr('tabindex','2');
132 cell.attr('tabindex','2');
133
133
134 var input = $('<div></div>').addClass('input');
134 var input = $('<div></div>').addClass('input');
135 var prompt = $('<div/>').addClass('prompt input_prompt');
135 var prompt = $('<div/>').addClass('prompt input_prompt');
136 var inner_cell = $('<div/>').addClass('inner_cell');
136 var inner_cell = $('<div/>').addClass('inner_cell');
137 this.celltoolbar = new celltoolbar.CellToolbar({
137 this.celltoolbar = new celltoolbar.CellToolbar({
138 cell: this,
138 cell: this,
139 notebook: this.notebook});
139 notebook: this.notebook});
140 inner_cell.append(this.celltoolbar.element);
140 inner_cell.append(this.celltoolbar.element);
141 var input_area = $('<div/>').addClass('input_area');
141 var input_area = $('<div/>').addClass('input_area');
142 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
142 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
143 this.code_mirror.on('keydown', $.proxy(this.handle_keyevent,this))
143 this.code_mirror.on('keydown', $.proxy(this.handle_keyevent,this))
144 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
144 $(this.code_mirror.getInputField()).attr("spellcheck", "false");
145 inner_cell.append(input_area);
145 inner_cell.append(input_area);
146 input.append(prompt).append(inner_cell);
146 input.append(prompt).append(inner_cell);
147
147
148 var widget_area = $('<div/>')
148 var widget_area = $('<div/>')
149 .addClass('widget-area')
149 .addClass('widget-area')
150 .hide();
150 .hide();
151 this.widget_area = widget_area;
151 this.widget_area = widget_area;
152 var widget_prompt = $('<div/>')
152 var widget_prompt = $('<div/>')
153 .addClass('prompt')
153 .addClass('prompt')
154 .appendTo(widget_area);
154 .appendTo(widget_area);
155 var widget_subarea = $('<div/>')
155 var widget_subarea = $('<div/>')
156 .addClass('widget-subarea')
156 .addClass('widget-subarea')
157 .appendTo(widget_area);
157 .appendTo(widget_area);
158 this.widget_subarea = widget_subarea;
158 this.widget_subarea = widget_subarea;
159 var widget_clear_buton = $('<button />')
159 var widget_clear_buton = $('<button />')
160 .addClass('close')
160 .addClass('close')
161 .html('&times;')
161 .html('&times;')
162 .click(function() {
162 .click(function() {
163 widget_area.slideUp('', function(){ widget_subarea.html(''); });
163 widget_area.slideUp('', function(){ widget_subarea.html(''); });
164 })
164 })
165 .appendTo(widget_prompt);
165 .appendTo(widget_prompt);
166
166
167 var output = $('<div></div>');
167 var output = $('<div></div>');
168 cell.append(input).append(widget_area).append(output);
168 cell.append(input).append(widget_area).append(output);
169 this.element = cell;
169 this.element = cell;
170 this.output_area = new outputarea.OutputArea({
170 this.output_area = new outputarea.OutputArea({
171 selector: output,
171 selector: output,
172 prompt_area: true,
172 prompt_area: true,
173 events: this.events,
173 events: this.events,
174 keyboard_manager: this.keyboard_manager});
174 keyboard_manager: this.keyboard_manager});
175 this.completer = new completer.Completer(this, this.events);
175 this.completer = new completer.Completer(this, this.events);
176 };
176 };
177
177
178 /** @method bind_events */
178 /** @method bind_events */
179 CodeCell.prototype.bind_events = function () {
179 CodeCell.prototype.bind_events = function () {
180 Cell.prototype.bind_events.apply(this);
180 Cell.prototype.bind_events.apply(this);
181 var that = this;
181 var that = this;
182
182
183 this.element.focusout(
183 this.element.focusout(
184 function() { that.auto_highlight(); }
184 function() { that.auto_highlight(); }
185 );
185 );
186 };
186 };
187
187
188
188
189 /**
189 /**
190 * This method gets called in CodeMirror's onKeyDown/onKeyPress
190 * This method gets called in CodeMirror's onKeyDown/onKeyPress
191 * handlers and is used to provide custom key handling. Its return
191 * handlers and is used to provide custom key handling. Its return
192 * value is used to determine if CodeMirror should ignore the event:
192 * value is used to determine if CodeMirror should ignore the event:
193 * true = ignore, false = don't ignore.
193 * true = ignore, false = don't ignore.
194 * @method handle_codemirror_keyevent
194 * @method handle_codemirror_keyevent
195 */
195 */
196 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
196 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
197
197
198 var that = this;
198 var that = this;
199 // whatever key is pressed, first, cancel the tooltip request before
199 // whatever key is pressed, first, cancel the tooltip request before
200 // they are sent, and remove tooltip if any, except for tab again
200 // they are sent, and remove tooltip if any, except for tab again
201 var tooltip_closed = null;
201 var tooltip_closed = null;
202 if (event.type === 'keydown' && event.which != keycodes.tab ) {
202 if (event.type === 'keydown' && event.which != keycodes.tab ) {
203 tooltip_closed = this.tooltip.remove_and_cancel_tooltip();
203 tooltip_closed = this.tooltip.remove_and_cancel_tooltip();
204 }
204 }
205
205
206 var cur = editor.getCursor();
206 var cur = editor.getCursor();
207 if (event.keyCode === keycodes.enter){
207 if (event.keyCode === keycodes.enter){
208 this.auto_highlight();
208 this.auto_highlight();
209 }
209 }
210
210
211 if (event.which === keycodes.down && event.type === 'keypress' && this.tooltip.time_before_tooltip >= 0) {
211 if (event.which === keycodes.down && event.type === 'keypress' && this.tooltip.time_before_tooltip >= 0) {
212 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
212 // triger on keypress (!) otherwise inconsistent event.which depending on plateform
213 // browser and keyboard layout !
213 // browser and keyboard layout !
214 // Pressing '(' , request tooltip, don't forget to reappend it
214 // Pressing '(' , request tooltip, don't forget to reappend it
215 // The second argument says to hide the tooltip if the docstring
215 // The second argument says to hide the tooltip if the docstring
216 // is actually empty
216 // is actually empty
217 this.tooltip.pending(that, true);
217 this.tooltip.pending(that, true);
218 } else if ( tooltip_closed && event.which === keycodes.esc && event.type === 'keydown') {
218 } else if ( tooltip_closed && event.which === keycodes.esc && event.type === 'keydown') {
219 // If tooltip is active, cancel it. The call to
219 // If tooltip is active, cancel it. The call to
220 // remove_and_cancel_tooltip above doesn't pass, force=true.
220 // remove_and_cancel_tooltip above doesn't pass, force=true.
221 // Because of this it won't actually close the tooltip
221 // Because of this it won't actually close the tooltip
222 // if it is in sticky mode. Thus, we have to check again if it is open
222 // if it is in sticky mode. Thus, we have to check again if it is open
223 // and close it with force=true.
223 // and close it with force=true.
224 if (!this.tooltip._hidden) {
224 if (!this.tooltip._hidden) {
225 this.tooltip.remove_and_cancel_tooltip(true);
225 this.tooltip.remove_and_cancel_tooltip(true);
226 }
226 }
227 // If we closed the tooltip, don't let CM or the global handlers
227 // If we closed the tooltip, don't let CM or the global handlers
228 // handle this event.
228 // handle this event.
229 event.codemirrorIgnore = true;
229 event.codemirrorIgnore = true;
230 event.preventDefault();
230 event.preventDefault();
231 return true;
231 return true;
232 } else if (event.keyCode === keycodes.tab && event.type === 'keydown' && event.shiftKey) {
232 } else if (event.keyCode === keycodes.tab && event.type === 'keydown' && event.shiftKey) {
233 if (editor.somethingSelected() || editor.getSelections().length !== 1){
233 if (editor.somethingSelected() || editor.getSelections().length !== 1){
234 var anchor = editor.getCursor("anchor");
234 var anchor = editor.getCursor("anchor");
235 var head = editor.getCursor("head");
235 var head = editor.getCursor("head");
236 if( anchor.line != head.line){
236 if( anchor.line != head.line){
237 return false;
237 return false;
238 }
238 }
239 }
239 }
240 this.tooltip.request(that);
240 this.tooltip.request(that);
241 event.codemirrorIgnore = true;
241 event.codemirrorIgnore = true;
242 event.preventDefault();
242 event.preventDefault();
243 return true;
243 return true;
244 } else if (event.keyCode === keycodes.tab && event.type == 'keydown') {
244 } else if (event.keyCode === keycodes.tab && event.type == 'keydown') {
245 // Tab completion.
245 // Tab completion.
246 this.tooltip.remove_and_cancel_tooltip();
246 this.tooltip.remove_and_cancel_tooltip();
247
247
248 // completion does not work on multicursor, it might be possible though in some cases
248 // completion does not work on multicursor, it might be possible though in some cases
249 if (editor.somethingSelected() || editor.getSelections().length > 1) {
249 if (editor.somethingSelected() || editor.getSelections().length > 1) {
250 return false;
250 return false;
251 }
251 }
252 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
252 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
253 if (pre_cursor.trim() === "") {
253 if (pre_cursor.trim() === "") {
254 // Don't autocomplete if the part of the line before the cursor
254 // Don't autocomplete if the part of the line before the cursor
255 // is empty. In this case, let CodeMirror handle indentation.
255 // is empty. In this case, let CodeMirror handle indentation.
256 return false;
256 return false;
257 } else {
257 } else {
258 event.codemirrorIgnore = true;
258 event.codemirrorIgnore = true;
259 event.preventDefault();
259 event.preventDefault();
260 this.completer.startCompletion();
260 this.completer.startCompletion();
261 return true;
261 return true;
262 }
262 }
263 }
263 }
264
264
265 // keyboard event wasn't one of those unique to code cells, let's see
265 // keyboard event wasn't one of those unique to code cells, let's see
266 // if it's one of the generic ones (i.e. check edit mode shortcuts)
266 // if it's one of the generic ones (i.e. check edit mode shortcuts)
267 return Cell.prototype.handle_codemirror_keyevent.apply(this, [editor, event]);
267 return Cell.prototype.handle_codemirror_keyevent.apply(this, [editor, event]);
268 };
268 };
269
269
270 // Kernel related calls.
270 // Kernel related calls.
271
271
272 CodeCell.prototype.set_kernel = function (kernel) {
272 CodeCell.prototype.set_kernel = function (kernel) {
273 this.kernel = kernel;
273 this.kernel = kernel;
274 };
274 };
275
275
276 /**
276 /**
277 * Execute current code cell to the kernel
277 * Execute current code cell to the kernel
278 * @method execute
278 * @method execute
279 */
279 */
280 CodeCell.prototype.execute = function () {
280 CodeCell.prototype.execute = function () {
281 this.output_area.clear_output();
281 this.output_area.clear_output();
282
282
283 // Clear widget area
283 // Clear widget area
284 this.widget_subarea.html('');
284 this.widget_subarea.html('');
285 this.widget_subarea.height('');
285 this.widget_subarea.height('');
286 this.widget_area.height('');
286 this.widget_area.height('');
287 this.widget_area.hide();
287 this.widget_area.hide();
288
288
289 this.set_input_prompt('*');
289 this.set_input_prompt('*');
290 this.element.addClass("running");
290 this.element.addClass("running");
291 if (this.last_msg_id) {
291 if (this.last_msg_id) {
292 this.kernel.clear_callbacks_for_msg(this.last_msg_id);
292 this.kernel.clear_callbacks_for_msg(this.last_msg_id);
293 }
293 }
294 var callbacks = this.get_callbacks();
294 var callbacks = this.get_callbacks();
295
295
296 var old_msg_id = this.last_msg_id;
296 var old_msg_id = this.last_msg_id;
297 this.last_msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
297 this.last_msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true});
298 if (old_msg_id) {
298 if (old_msg_id) {
299 delete CodeCell.msg_cells[old_msg_id];
299 delete CodeCell.msg_cells[old_msg_id];
300 }
300 }
301 CodeCell.msg_cells[this.last_msg_id] = this;
301 CodeCell.msg_cells[this.last_msg_id] = this;
302 this.render();
302 this.render();
303 };
303 };
304
304
305 /**
305 /**
306 * Construct the default callbacks for
306 * Construct the default callbacks for
307 * @method get_callbacks
307 * @method get_callbacks
308 */
308 */
309 CodeCell.prototype.get_callbacks = function () {
309 CodeCell.prototype.get_callbacks = function () {
310 return {
310 return {
311 shell : {
311 shell : {
312 reply : $.proxy(this._handle_execute_reply, this),
312 reply : $.proxy(this._handle_execute_reply, this),
313 payload : {
313 payload : {
314 set_next_input : $.proxy(this._handle_set_next_input, this),
314 set_next_input : $.proxy(this._handle_set_next_input, this),
315 page : $.proxy(this._open_with_pager, this)
315 page : $.proxy(this._open_with_pager, this)
316 }
316 }
317 },
317 },
318 iopub : {
318 iopub : {
319 output : $.proxy(this.output_area.handle_output, this.output_area),
319 output : $.proxy(this.output_area.handle_output, this.output_area),
320 clear_output : $.proxy(this.output_area.handle_clear_output, this.output_area),
320 clear_output : $.proxy(this.output_area.handle_clear_output, this.output_area),
321 },
321 },
322 input : $.proxy(this._handle_input_request, this)
322 input : $.proxy(this._handle_input_request, this)
323 };
323 };
324 };
324 };
325
325
326 CodeCell.prototype._open_with_pager = function (payload) {
326 CodeCell.prototype._open_with_pager = function (payload) {
327 this.events.trigger('open_with_text.Pager', payload);
327 this.events.trigger('open_with_text.Pager', payload);
328 };
328 };
329
329
330 /**
330 /**
331 * @method _handle_execute_reply
331 * @method _handle_execute_reply
332 * @private
332 * @private
333 */
333 */
334 CodeCell.prototype._handle_execute_reply = function (msg) {
334 CodeCell.prototype._handle_execute_reply = function (msg) {
335 this.set_input_prompt(msg.content.execution_count);
335 this.set_input_prompt(msg.content.execution_count);
336 this.element.removeClass("running");
336 this.element.removeClass("running");
337 this.events.trigger('set_dirty.Notebook', {value: true});
337 this.events.trigger('set_dirty.Notebook', {value: true});
338 };
338 };
339
339
340 /**
340 /**
341 * @method _handle_set_next_input
341 * @method _handle_set_next_input
342 * @private
342 * @private
343 */
343 */
344 CodeCell.prototype._handle_set_next_input = function (payload) {
344 CodeCell.prototype._handle_set_next_input = function (payload) {
345 var data = {'cell': this, 'text': payload.text};
345 var data = {'cell': this, 'text': payload.text};
346 this.events.trigger('set_next_input.Notebook', data);
346 this.events.trigger('set_next_input.Notebook', data);
347 };
347 };
348
348
349 /**
349 /**
350 * @method _handle_input_request
350 * @method _handle_input_request
351 * @private
351 * @private
352 */
352 */
353 CodeCell.prototype._handle_input_request = function (msg) {
353 CodeCell.prototype._handle_input_request = function (msg) {
354 this.output_area.append_raw_input(msg);
354 this.output_area.append_raw_input(msg);
355 };
355 };
356
356
357
357
358 // Basic cell manipulation.
358 // Basic cell manipulation.
359
359
360 CodeCell.prototype.select = function () {
360 CodeCell.prototype.select = function () {
361 var cont = Cell.prototype.select.apply(this);
361 var cont = Cell.prototype.select.apply(this);
362 if (cont) {
362 if (cont) {
363 this.code_mirror.refresh();
363 this.code_mirror.refresh();
364 this.auto_highlight();
364 this.auto_highlight();
365 }
365 }
366 return cont;
366 return cont;
367 };
367 };
368
368
369 CodeCell.prototype.render = function () {
369 CodeCell.prototype.render = function () {
370 var cont = Cell.prototype.render.apply(this);
370 var cont = Cell.prototype.render.apply(this);
371 // Always execute, even if we are already in the rendered state
371 // Always execute, even if we are already in the rendered state
372 return cont;
372 return cont;
373 };
373 };
374
374
375 CodeCell.prototype.select_all = function () {
375 CodeCell.prototype.select_all = function () {
376 var start = {line: 0, ch: 0};
376 var start = {line: 0, ch: 0};
377 var nlines = this.code_mirror.lineCount();
377 var nlines = this.code_mirror.lineCount();
378 var last_line = this.code_mirror.getLine(nlines-1);
378 var last_line = this.code_mirror.getLine(nlines-1);
379 var end = {line: nlines-1, ch: last_line.length};
379 var end = {line: nlines-1, ch: last_line.length};
380 this.code_mirror.setSelection(start, end);
380 this.code_mirror.setSelection(start, end);
381 };
381 };
382
382
383
383
384 CodeCell.prototype.collapse_output = function () {
384 CodeCell.prototype.collapse_output = function () {
385 this.collapsed = true;
386 this.output_area.collapse();
385 this.output_area.collapse();
387 };
386 };
388
387
389
388
390 CodeCell.prototype.expand_output = function () {
389 CodeCell.prototype.expand_output = function () {
391 this.collapsed = false;
392 this.output_area.expand();
390 this.output_area.expand();
393 this.output_area.unscroll_area();
391 this.output_area.unscroll_area();
394 };
392 };
395
393
396 CodeCell.prototype.scroll_output = function () {
394 CodeCell.prototype.scroll_output = function () {
397 this.output_area.expand();
395 this.output_area.expand();
398 this.output_area.scroll_if_long();
396 this.output_area.scroll_if_long();
399 };
397 };
400
398
401 CodeCell.prototype.toggle_output = function () {
399 CodeCell.prototype.toggle_output = function () {
402 this.collapsed = Boolean(1 - this.collapsed);
403 this.output_area.toggle_output();
400 this.output_area.toggle_output();
404 };
401 };
405
402
406 CodeCell.prototype.toggle_output_scroll = function () {
403 CodeCell.prototype.toggle_output_scroll = function () {
407 this.output_area.toggle_scroll();
404 this.output_area.toggle_scroll();
408 };
405 };
409
406
410
407
411 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
408 CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
412 var ns;
409 var ns;
413 if (prompt_value === undefined || prompt_value === null) {
410 if (prompt_value === undefined || prompt_value === null) {
414 ns = "&nbsp;";
411 ns = "&nbsp;";
415 } else {
412 } else {
416 ns = encodeURIComponent(prompt_value);
413 ns = encodeURIComponent(prompt_value);
417 }
414 }
418 return 'In&nbsp;[' + ns + ']:';
415 return 'In&nbsp;[' + ns + ']:';
419 };
416 };
420
417
421 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
418 CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
422 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
419 var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
423 for(var i=1; i < lines_number; i++) {
420 for(var i=1; i < lines_number; i++) {
424 html.push(['...:']);
421 html.push(['...:']);
425 }
422 }
426 return html.join('<br/>');
423 return html.join('<br/>');
427 };
424 };
428
425
429 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
426 CodeCell.input_prompt_function = CodeCell.input_prompt_classical;
430
427
431
428
432 CodeCell.prototype.set_input_prompt = function (number) {
429 CodeCell.prototype.set_input_prompt = function (number) {
433 var nline = 1;
430 var nline = 1;
434 if (this.code_mirror !== undefined) {
431 if (this.code_mirror !== undefined) {
435 nline = this.code_mirror.lineCount();
432 nline = this.code_mirror.lineCount();
436 }
433 }
437 this.input_prompt_number = number;
434 this.input_prompt_number = number;
438 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
435 var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
439 // This HTML call is okay because the user contents are escaped.
436 // This HTML call is okay because the user contents are escaped.
440 this.element.find('div.input_prompt').html(prompt_html);
437 this.element.find('div.input_prompt').html(prompt_html);
441 };
438 };
442
439
443
440
444 CodeCell.prototype.clear_input = function () {
441 CodeCell.prototype.clear_input = function () {
445 this.code_mirror.setValue('');
442 this.code_mirror.setValue('');
446 };
443 };
447
444
448
445
449 CodeCell.prototype.get_text = function () {
446 CodeCell.prototype.get_text = function () {
450 return this.code_mirror.getValue();
447 return this.code_mirror.getValue();
451 };
448 };
452
449
453
450
454 CodeCell.prototype.set_text = function (code) {
451 CodeCell.prototype.set_text = function (code) {
455 return this.code_mirror.setValue(code);
452 return this.code_mirror.setValue(code);
456 };
453 };
457
454
458
455
459 CodeCell.prototype.clear_output = function (wait) {
456 CodeCell.prototype.clear_output = function (wait) {
460 this.output_area.clear_output(wait);
457 this.output_area.clear_output(wait);
461 this.set_input_prompt();
458 this.set_input_prompt();
462 };
459 };
463
460
464
461
465 // JSON serialization
462 // JSON serialization
466
463
467 CodeCell.prototype.fromJSON = function (data) {
464 CodeCell.prototype.fromJSON = function (data) {
468 Cell.prototype.fromJSON.apply(this, arguments);
465 Cell.prototype.fromJSON.apply(this, arguments);
469 if (data.cell_type === 'code') {
466 if (data.cell_type === 'code') {
470 if (data.input !== undefined) {
467 if (data.source !== undefined) {
471 this.set_text(data.input);
468 this.set_text(data.source);
472 // make this value the starting point, so that we can only undo
469 // make this value the starting point, so that we can only undo
473 // to this state, instead of a blank cell
470 // to this state, instead of a blank cell
474 this.code_mirror.clearHistory();
471 this.code_mirror.clearHistory();
475 this.auto_highlight();
472 this.auto_highlight();
476 }
473 }
477 if (data.prompt_number !== undefined) {
474 this.set_input_prompt(data.execution_count);
478 this.set_input_prompt(data.prompt_number);
479 } else {
480 this.set_input_prompt();
481 }
482 this.output_area.trusted = data.metadata.trusted || false;
475 this.output_area.trusted = data.metadata.trusted || false;
483 this.output_area.fromJSON(data.outputs);
476 this.output_area.fromJSON(data.outputs);
484 if (data.collapsed !== undefined) {
477 if (data.metadata.collapsed !== undefined) {
485 if (data.collapsed) {
478 if (data.metadata.collapsed) {
486 this.collapse_output();
479 this.collapse_output();
487 } else {
480 } else {
488 this.expand_output();
481 this.expand_output();
489 }
482 }
490 }
483 }
491 }
484 }
492 };
485 };
493
486
494
487
495 CodeCell.prototype.toJSON = function () {
488 CodeCell.prototype.toJSON = function () {
496 var data = Cell.prototype.toJSON.apply(this);
489 var data = Cell.prototype.toJSON.apply(this);
497 data.input = this.get_text();
490 data.source = this.get_text();
498 // is finite protect against undefined and '*' value
491 // is finite protect against undefined and '*' value
499 if (isFinite(this.input_prompt_number)) {
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 var outputs = this.output_area.toJSON();
497 var outputs = this.output_area.toJSON();
503 data.outputs = outputs;
498 data.outputs = outputs;
504 data.language = 'python';
505 data.metadata.trusted = this.output_area.trusted;
499 data.metadata.trusted = this.output_area.trusted;
506 data.collapsed = this.output_area.collapsed;
500 data.metadata.collapsed = this.output_area.collapsed;
507 return data;
501 return data;
508 };
502 };
509
503
510 /**
504 /**
511 * handle cell level logic when a cell is unselected
505 * handle cell level logic when a cell is unselected
512 * @method unselect
506 * @method unselect
513 * @return is the action being taken
507 * @return is the action being taken
514 */
508 */
515 CodeCell.prototype.unselect = function () {
509 CodeCell.prototype.unselect = function () {
516 var cont = Cell.prototype.unselect.apply(this);
510 var cont = Cell.prototype.unselect.apply(this);
517 if (cont) {
511 if (cont) {
518 // When a code cell is usnelected, make sure that the corresponding
512 // When a code cell is usnelected, make sure that the corresponding
519 // tooltip and completer to that cell is closed.
513 // tooltip and completer to that cell is closed.
520 this.tooltip.remove_and_cancel_tooltip(true);
514 this.tooltip.remove_and_cancel_tooltip(true);
521 if (this.completer !== null) {
515 if (this.completer !== null) {
522 this.completer.close();
516 this.completer.close();
523 }
517 }
524 }
518 }
525 return cont;
519 return cont;
526 };
520 };
527
521
528 // Backwards compatability.
522 // Backwards compatability.
529 IPython.CodeCell = CodeCell;
523 IPython.CodeCell = CodeCell;
530
524
531 return {'CodeCell': CodeCell};
525 return {'CodeCell': CodeCell};
532 });
526 });
@@ -1,226 +1,214 b''
1 // Copyright (c) IPython Development Team.
1 // Copyright (c) IPython Development Team.
2 // Distributed under the terms of the Modified BSD License.
2 // Distributed under the terms of the Modified BSD License.
3
3
4 define([
4 define([
5 'base/js/namespace',
5 'base/js/namespace',
6 'jquery',
6 'jquery',
7 'notebook/js/toolbar',
7 'notebook/js/toolbar',
8 'notebook/js/celltoolbar',
8 'notebook/js/celltoolbar',
9 ], function(IPython, $, toolbar, celltoolbar) {
9 ], function(IPython, $, toolbar, celltoolbar) {
10 "use strict";
10 "use strict";
11
11
12 var MainToolBar = function (selector, options) {
12 var MainToolBar = function (selector, options) {
13 // Constructor
13 // Constructor
14 //
14 //
15 // Parameters:
15 // Parameters:
16 // selector: string
16 // selector: string
17 // options: dictionary
17 // options: dictionary
18 // Dictionary of keyword arguments.
18 // Dictionary of keyword arguments.
19 // events: $(Events) instance
19 // events: $(Events) instance
20 // notebook: Notebook instance
20 // notebook: Notebook instance
21 toolbar.ToolBar.apply(this, arguments);
21 toolbar.ToolBar.apply(this, arguments);
22 this.events = options.events;
22 this.events = options.events;
23 this.notebook = options.notebook;
23 this.notebook = options.notebook;
24 this.construct();
24 this.construct();
25 this.add_celltype_list();
25 this.add_celltype_list();
26 this.add_celltoolbar_list();
26 this.add_celltoolbar_list();
27 this.bind_events();
27 this.bind_events();
28 };
28 };
29
29
30 MainToolBar.prototype = Object.create(toolbar.ToolBar.prototype);
30 MainToolBar.prototype = Object.create(toolbar.ToolBar.prototype);
31
31
32 MainToolBar.prototype.construct = function () {
32 MainToolBar.prototype.construct = function () {
33 var that = this;
33 var that = this;
34 this.add_buttons_group([
34 this.add_buttons_group([
35 {
35 {
36 id : 'save_b',
36 id : 'save_b',
37 label : 'Save and Checkpoint',
37 label : 'Save and Checkpoint',
38 icon : 'fa-save',
38 icon : 'fa-save',
39 callback : function () {
39 callback : function () {
40 that.notebook.save_checkpoint();
40 that.notebook.save_checkpoint();
41 }
41 }
42 }
42 }
43 ]);
43 ]);
44
44
45 this.add_buttons_group([
45 this.add_buttons_group([
46 {
46 {
47 id : 'insert_below_b',
47 id : 'insert_below_b',
48 label : 'Insert Cell Below',
48 label : 'Insert Cell Below',
49 icon : 'fa-plus',
49 icon : 'fa-plus',
50 callback : function () {
50 callback : function () {
51 that.notebook.insert_cell_below('code');
51 that.notebook.insert_cell_below('code');
52 that.notebook.select_next();
52 that.notebook.select_next();
53 that.notebook.focus_cell();
53 that.notebook.focus_cell();
54 }
54 }
55 }
55 }
56 ],'insert_above_below');
56 ],'insert_above_below');
57
57
58 this.add_buttons_group([
58 this.add_buttons_group([
59 {
59 {
60 id : 'cut_b',
60 id : 'cut_b',
61 label : 'Cut Cell',
61 label : 'Cut Cell',
62 icon : 'fa-cut',
62 icon : 'fa-cut',
63 callback : function () {
63 callback : function () {
64 that.notebook.cut_cell();
64 that.notebook.cut_cell();
65 }
65 }
66 },
66 },
67 {
67 {
68 id : 'copy_b',
68 id : 'copy_b',
69 label : 'Copy Cell',
69 label : 'Copy Cell',
70 icon : 'fa-copy',
70 icon : 'fa-copy',
71 callback : function () {
71 callback : function () {
72 that.notebook.copy_cell();
72 that.notebook.copy_cell();
73 }
73 }
74 },
74 },
75 {
75 {
76 id : 'paste_b',
76 id : 'paste_b',
77 label : 'Paste Cell Below',
77 label : 'Paste Cell Below',
78 icon : 'fa-paste',
78 icon : 'fa-paste',
79 callback : function () {
79 callback : function () {
80 that.notebook.paste_cell_below();
80 that.notebook.paste_cell_below();
81 }
81 }
82 }
82 }
83 ],'cut_copy_paste');
83 ],'cut_copy_paste');
84
84
85 this.add_buttons_group([
85 this.add_buttons_group([
86 {
86 {
87 id : 'move_up_b',
87 id : 'move_up_b',
88 label : 'Move Cell Up',
88 label : 'Move Cell Up',
89 icon : 'fa-arrow-up',
89 icon : 'fa-arrow-up',
90 callback : function () {
90 callback : function () {
91 that.notebook.move_cell_up();
91 that.notebook.move_cell_up();
92 }
92 }
93 },
93 },
94 {
94 {
95 id : 'move_down_b',
95 id : 'move_down_b',
96 label : 'Move Cell Down',
96 label : 'Move Cell Down',
97 icon : 'fa-arrow-down',
97 icon : 'fa-arrow-down',
98 callback : function () {
98 callback : function () {
99 that.notebook.move_cell_down();
99 that.notebook.move_cell_down();
100 }
100 }
101 }
101 }
102 ],'move_up_down');
102 ],'move_up_down');
103
103
104
104
105 this.add_buttons_group([
105 this.add_buttons_group([
106 {
106 {
107 id : 'run_b',
107 id : 'run_b',
108 label : 'Run Cell',
108 label : 'Run Cell',
109 icon : 'fa-play',
109 icon : 'fa-play',
110 callback : function () {
110 callback : function () {
111 // emulate default shift-enter behavior
111 // emulate default shift-enter behavior
112 that.notebook.execute_cell_and_select_below();
112 that.notebook.execute_cell_and_select_below();
113 }
113 }
114 },
114 },
115 {
115 {
116 id : 'interrupt_b',
116 id : 'interrupt_b',
117 label : 'Interrupt',
117 label : 'Interrupt',
118 icon : 'fa-stop',
118 icon : 'fa-stop',
119 callback : function () {
119 callback : function () {
120 that.notebook.kernel.interrupt();
120 that.notebook.kernel.interrupt();
121 }
121 }
122 },
122 },
123 {
123 {
124 id : 'repeat_b',
124 id : 'repeat_b',
125 label : 'Restart Kernel',
125 label : 'Restart Kernel',
126 icon : 'fa-repeat',
126 icon : 'fa-repeat',
127 callback : function () {
127 callback : function () {
128 that.notebook.restart_kernel();
128 that.notebook.restart_kernel();
129 }
129 }
130 }
130 }
131 ],'run_int');
131 ],'run_int');
132 };
132 };
133
133
134 MainToolBar.prototype.add_celltype_list = function () {
134 MainToolBar.prototype.add_celltype_list = function () {
135 this.element
135 this.element
136 .append($('<select/>')
136 .append($('<select/>')
137 .attr('id','cell_type')
137 .attr('id','cell_type')
138 .addClass('form-control select-xs')
138 .addClass('form-control select-xs')
139 .append($('<option/>').attr('value','code').text('Code'))
139 .append($('<option/>').attr('value','code').text('Code'))
140 .append($('<option/>').attr('value','markdown').text('Markdown'))
140 .append($('<option/>').attr('value','markdown').text('Markdown'))
141 .append($('<option/>').attr('value','raw').text('Raw NBConvert'))
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 MainToolBar.prototype.add_celltoolbar_list = function () {
145 MainToolBar.prototype.add_celltoolbar_list = function () {
152 var label = $('<span/>').addClass("navbar-text").text('Cell Toolbar:');
146 var label = $('<span/>').addClass("navbar-text").text('Cell Toolbar:');
153 var select = $('<select/>')
147 var select = $('<select/>')
154 .attr('id', 'ctb_select')
148 .attr('id', 'ctb_select')
155 .addClass('form-control select-xs')
149 .addClass('form-control select-xs')
156 .append($('<option/>').attr('value', '').text('None'));
150 .append($('<option/>').attr('value', '').text('None'));
157 this.element.append(label).append(select);
151 this.element.append(label).append(select);
158 var that = this;
152 var that = this;
159 select.change(function() {
153 select.change(function() {
160 var val = $(this).val();
154 var val = $(this).val();
161 if (val ==='') {
155 if (val ==='') {
162 celltoolbar.CellToolbar.global_hide();
156 celltoolbar.CellToolbar.global_hide();
163 delete that.notebook.metadata.celltoolbar;
157 delete that.notebook.metadata.celltoolbar;
164 } else {
158 } else {
165 celltoolbar.CellToolbar.global_show();
159 celltoolbar.CellToolbar.global_show();
166 celltoolbar.CellToolbar.activate_preset(val, that.events);
160 celltoolbar.CellToolbar.activate_preset(val, that.events);
167 that.notebook.metadata.celltoolbar = val;
161 that.notebook.metadata.celltoolbar = val;
168 }
162 }
169 });
163 });
170 // Setup the currently registered presets.
164 // Setup the currently registered presets.
171 var presets = celltoolbar.CellToolbar.list_presets();
165 var presets = celltoolbar.CellToolbar.list_presets();
172 for (var i=0; i<presets.length; i++) {
166 for (var i=0; i<presets.length; i++) {
173 var name = presets[i];
167 var name = presets[i];
174 select.append($('<option/>').attr('value', name).text(name));
168 select.append($('<option/>').attr('value', name).text(name));
175 }
169 }
176 // Setup future preset registrations.
170 // Setup future preset registrations.
177 this.events.on('preset_added.CellToolbar', function (event, data) {
171 this.events.on('preset_added.CellToolbar', function (event, data) {
178 var name = data.name;
172 var name = data.name;
179 select.append($('<option/>').attr('value', name).text(name));
173 select.append($('<option/>').attr('value', name).text(name));
180 });
174 });
181 // Update select value when a preset is activated.
175 // Update select value when a preset is activated.
182 this.events.on('preset_activated.CellToolbar', function (event, data) {
176 this.events.on('preset_activated.CellToolbar', function (event, data) {
183 if (select.val() !== data.name)
177 if (select.val() !== data.name)
184 select.val(data.name);
178 select.val(data.name);
185 });
179 });
186 };
180 };
187
181
188 MainToolBar.prototype.bind_events = function () {
182 MainToolBar.prototype.bind_events = function () {
189 var that = this;
183 var that = this;
190
184
191 this.element.find('#cell_type').change(function () {
185 this.element.find('#cell_type').change(function () {
192 var cell_type = $(this).val();
186 var cell_type = $(this).val();
193 if (cell_type === 'code') {
187 switch (cell_type) {
188 case 'code':
194 that.notebook.to_code();
189 that.notebook.to_code();
195 } else if (cell_type === 'markdown') {
190 break;
191 case 'markdown':
196 that.notebook.to_markdown();
192 that.notebook.to_markdown();
197 } else if (cell_type === 'raw') {
193 break;
194 case 'raw':
198 that.notebook.to_raw();
195 that.notebook.to_raw();
199 } else if (cell_type === 'heading1') {
196 break;
200 that.notebook.to_heading(undefined, 1);
197 default:
201 } else if (cell_type === 'heading2') {
198 console.log("unrecognized cell type:", cell_type);
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);
211 }
199 }
212 });
200 });
213 this.events.on('selected_cell_type_changed.Notebook', function (event, data) {
201 this.events.on('selected_cell_type_changed.Notebook', function (event, data) {
214 if (data.cell_type === 'heading') {
202 if (data.cell_type === 'heading') {
215 that.element.find('#cell_type').val(data.cell_type+data.level);
203 that.element.find('#cell_type').val(data.cell_type+data.level);
216 } else {
204 } else {
217 that.element.find('#cell_type').val(data.cell_type);
205 that.element.find('#cell_type').val(data.cell_type);
218 }
206 }
219 });
207 });
220 };
208 };
221
209
222 // Backwards compatability.
210 // Backwards compatability.
223 IPython.MainToolBar = MainToolBar;
211 IPython.MainToolBar = MainToolBar;
224
212
225 return {'MainToolBar': MainToolBar};
213 return {'MainToolBar': MainToolBar};
226 });
214 });
@@ -1,2707 +1,2682 b''
1 // Copyright (c) IPython Development Team.
1 // Copyright (c) IPython Development Team.
2 // Distributed under the terms of the Modified BSD License.
2 // Distributed under the terms of the Modified BSD License.
3
3
4 define([
4 define([
5 'base/js/namespace',
5 'base/js/namespace',
6 'jquery',
6 'jquery',
7 'base/js/utils',
7 'base/js/utils',
8 'base/js/dialog',
8 'base/js/dialog',
9 'notebook/js/textcell',
9 'notebook/js/textcell',
10 'notebook/js/codecell',
10 'notebook/js/codecell',
11 'services/sessions/session',
11 'services/sessions/session',
12 'notebook/js/celltoolbar',
12 'notebook/js/celltoolbar',
13 'components/marked/lib/marked',
13 'components/marked/lib/marked',
14 'highlight',
14 'highlight',
15 'notebook/js/mathjaxutils',
15 'notebook/js/mathjaxutils',
16 'base/js/keyboard',
16 'base/js/keyboard',
17 'notebook/js/tooltip',
17 'notebook/js/tooltip',
18 'notebook/js/celltoolbarpresets/default',
18 'notebook/js/celltoolbarpresets/default',
19 'notebook/js/celltoolbarpresets/rawcell',
19 'notebook/js/celltoolbarpresets/rawcell',
20 'notebook/js/celltoolbarpresets/slideshow',
20 'notebook/js/celltoolbarpresets/slideshow',
21 'notebook/js/scrollmanager'
21 'notebook/js/scrollmanager'
22 ], function (
22 ], function (
23 IPython,
23 IPython,
24 $,
24 $,
25 utils,
25 utils,
26 dialog,
26 dialog,
27 textcell,
27 textcell,
28 codecell,
28 codecell,
29 session,
29 session,
30 celltoolbar,
30 celltoolbar,
31 marked,
31 marked,
32 hljs,
32 hljs,
33 mathjaxutils,
33 mathjaxutils,
34 keyboard,
34 keyboard,
35 tooltip,
35 tooltip,
36 default_celltoolbar,
36 default_celltoolbar,
37 rawcell_celltoolbar,
37 rawcell_celltoolbar,
38 slideshow_celltoolbar,
38 slideshow_celltoolbar,
39 scrollmanager
39 scrollmanager
40 ) {
40 ) {
41
41
42 var Notebook = function (selector, options) {
42 var Notebook = function (selector, options) {
43 // Constructor
43 // Constructor
44 //
44 //
45 // A notebook contains and manages cells.
45 // A notebook contains and manages cells.
46 //
46 //
47 // Parameters:
47 // Parameters:
48 // selector: string
48 // selector: string
49 // options: dictionary
49 // options: dictionary
50 // Dictionary of keyword arguments.
50 // Dictionary of keyword arguments.
51 // events: $(Events) instance
51 // events: $(Events) instance
52 // keyboard_manager: KeyboardManager instance
52 // keyboard_manager: KeyboardManager instance
53 // save_widget: SaveWidget instance
53 // save_widget: SaveWidget instance
54 // config: dictionary
54 // config: dictionary
55 // base_url : string
55 // base_url : string
56 // notebook_path : string
56 // notebook_path : string
57 // notebook_name : string
57 // notebook_name : string
58 this.config = utils.mergeopt(Notebook, options.config);
58 this.config = utils.mergeopt(Notebook, options.config);
59 this.base_url = options.base_url;
59 this.base_url = options.base_url;
60 this.notebook_path = options.notebook_path;
60 this.notebook_path = options.notebook_path;
61 this.notebook_name = options.notebook_name;
61 this.notebook_name = options.notebook_name;
62 this.events = options.events;
62 this.events = options.events;
63 this.keyboard_manager = options.keyboard_manager;
63 this.keyboard_manager = options.keyboard_manager;
64 this.save_widget = options.save_widget;
64 this.save_widget = options.save_widget;
65 this.tooltip = new tooltip.Tooltip(this.events);
65 this.tooltip = new tooltip.Tooltip(this.events);
66 this.ws_url = options.ws_url;
66 this.ws_url = options.ws_url;
67 this._session_starting = false;
67 this._session_starting = false;
68 this.default_cell_type = this.config.default_cell_type || 'code';
68 this.default_cell_type = this.config.default_cell_type || 'code';
69
69
70 // Create default scroll manager.
70 // Create default scroll manager.
71 this.scroll_manager = new scrollmanager.ScrollManager(this);
71 this.scroll_manager = new scrollmanager.ScrollManager(this);
72
72
73 // TODO: This code smells (and the other `= this` line a couple lines down)
73 // TODO: This code smells (and the other `= this` line a couple lines down)
74 // We need a better way to deal with circular instance references.
74 // We need a better way to deal with circular instance references.
75 this.keyboard_manager.notebook = this;
75 this.keyboard_manager.notebook = this;
76 this.save_widget.notebook = this;
76 this.save_widget.notebook = this;
77
77
78 mathjaxutils.init();
78 mathjaxutils.init();
79
79
80 if (marked) {
80 if (marked) {
81 marked.setOptions({
81 marked.setOptions({
82 gfm : true,
82 gfm : true,
83 tables: true,
83 tables: true,
84 langPrefix: "language-",
84 langPrefix: "language-",
85 highlight: function(code, lang) {
85 highlight: function(code, lang) {
86 if (!lang) {
86 if (!lang) {
87 // no language, no highlight
87 // no language, no highlight
88 return code;
88 return code;
89 }
89 }
90 var highlighted;
90 var highlighted;
91 try {
91 try {
92 highlighted = hljs.highlight(lang, code, false);
92 highlighted = hljs.highlight(lang, code, false);
93 } catch(err) {
93 } catch(err) {
94 highlighted = hljs.highlightAuto(code);
94 highlighted = hljs.highlightAuto(code);
95 }
95 }
96 return highlighted.value;
96 return highlighted.value;
97 }
97 }
98 });
98 });
99 }
99 }
100
100
101 this.element = $(selector);
101 this.element = $(selector);
102 this.element.scroll();
102 this.element.scroll();
103 this.element.data("notebook", this);
103 this.element.data("notebook", this);
104 this.next_prompt_number = 1;
104 this.next_prompt_number = 1;
105 this.session = null;
105 this.session = null;
106 this.kernel = null;
106 this.kernel = null;
107 this.clipboard = null;
107 this.clipboard = null;
108 this.undelete_backup = null;
108 this.undelete_backup = null;
109 this.undelete_index = null;
109 this.undelete_index = null;
110 this.undelete_below = false;
110 this.undelete_below = false;
111 this.paste_enabled = false;
111 this.paste_enabled = false;
112 // It is important to start out in command mode to match the intial mode
112 // It is important to start out in command mode to match the intial mode
113 // of the KeyboardManager.
113 // of the KeyboardManager.
114 this.mode = 'command';
114 this.mode = 'command';
115 this.set_dirty(false);
115 this.set_dirty(false);
116 this.metadata = {};
116 this.metadata = {};
117 this._checkpoint_after_save = false;
117 this._checkpoint_after_save = false;
118 this.last_checkpoint = null;
118 this.last_checkpoint = null;
119 this.checkpoints = [];
119 this.checkpoints = [];
120 this.autosave_interval = 0;
120 this.autosave_interval = 0;
121 this.autosave_timer = null;
121 this.autosave_timer = null;
122 // autosave *at most* every two minutes
122 // autosave *at most* every two minutes
123 this.minimum_autosave_interval = 120000;
123 this.minimum_autosave_interval = 120000;
124 // single worksheet for now
125 this.worksheet_metadata = {};
126 this.notebook_name_blacklist_re = /[\/\\:]/;
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 this.nbformat_minor = 0; // Increment this when changing the nbformat
126 this.nbformat_minor = 0; // Increment this when changing the nbformat
129 this.codemirror_mode = 'ipython';
127 this.codemirror_mode = 'ipython';
130 this.create_elements();
128 this.create_elements();
131 this.bind_events();
129 this.bind_events();
132 this.save_notebook = function() { // don't allow save until notebook_loaded
130 this.save_notebook = function() { // don't allow save until notebook_loaded
133 this.save_notebook_error(null, null, "Load failed, save is disabled");
131 this.save_notebook_error(null, null, "Load failed, save is disabled");
134 };
132 };
135
133
136 // Trigger cell toolbar registration.
134 // Trigger cell toolbar registration.
137 default_celltoolbar.register(this);
135 default_celltoolbar.register(this);
138 rawcell_celltoolbar.register(this);
136 rawcell_celltoolbar.register(this);
139 slideshow_celltoolbar.register(this);
137 slideshow_celltoolbar.register(this);
140 };
138 };
141
139
142 Notebook.options_default = {
140 Notebook.options_default = {
143 // can be any cell type, or the special values of
141 // can be any cell type, or the special values of
144 // 'above', 'below', or 'selected' to get the value from another cell.
142 // 'above', 'below', or 'selected' to get the value from another cell.
145 Notebook: {
143 Notebook: {
146 default_cell_type: 'code',
144 default_cell_type: 'code',
147 }
145 }
148 };
146 };
149
147
150
148
151 /**
149 /**
152 * Create an HTML and CSS representation of the notebook.
150 * Create an HTML and CSS representation of the notebook.
153 *
151 *
154 * @method create_elements
152 * @method create_elements
155 */
153 */
156 Notebook.prototype.create_elements = function () {
154 Notebook.prototype.create_elements = function () {
157 var that = this;
155 var that = this;
158 this.element.attr('tabindex','-1');
156 this.element.attr('tabindex','-1');
159 this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
157 this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
160 // We add this end_space div to the end of the notebook div to:
158 // We add this end_space div to the end of the notebook div to:
161 // i) provide a margin between the last cell and the end of the notebook
159 // i) provide a margin between the last cell and the end of the notebook
162 // ii) to prevent the div from scrolling up when the last cell is being
160 // ii) to prevent the div from scrolling up when the last cell is being
163 // edited, but is too low on the page, which browsers will do automatically.
161 // edited, but is too low on the page, which browsers will do automatically.
164 var end_space = $('<div/>').addClass('end_space');
162 var end_space = $('<div/>').addClass('end_space');
165 end_space.dblclick(function (e) {
163 end_space.dblclick(function (e) {
166 var ncells = that.ncells();
164 var ncells = that.ncells();
167 that.insert_cell_below('code',ncells-1);
165 that.insert_cell_below('code',ncells-1);
168 });
166 });
169 this.element.append(this.container);
167 this.element.append(this.container);
170 this.container.append(end_space);
168 this.container.append(end_space);
171 };
169 };
172
170
173 /**
171 /**
174 * Bind JavaScript events: key presses and custom IPython events.
172 * Bind JavaScript events: key presses and custom IPython events.
175 *
173 *
176 * @method bind_events
174 * @method bind_events
177 */
175 */
178 Notebook.prototype.bind_events = function () {
176 Notebook.prototype.bind_events = function () {
179 var that = this;
177 var that = this;
180
178
181 this.events.on('set_next_input.Notebook', function (event, data) {
179 this.events.on('set_next_input.Notebook', function (event, data) {
182 var index = that.find_cell_index(data.cell);
180 var index = that.find_cell_index(data.cell);
183 var new_cell = that.insert_cell_below('code',index);
181 var new_cell = that.insert_cell_below('code',index);
184 new_cell.set_text(data.text);
182 new_cell.set_text(data.text);
185 that.dirty = true;
183 that.dirty = true;
186 });
184 });
187
185
188 this.events.on('set_dirty.Notebook', function (event, data) {
186 this.events.on('set_dirty.Notebook', function (event, data) {
189 that.dirty = data.value;
187 that.dirty = data.value;
190 });
188 });
191
189
192 this.events.on('trust_changed.Notebook', function (event, trusted) {
190 this.events.on('trust_changed.Notebook', function (event, trusted) {
193 that.trusted = trusted;
191 that.trusted = trusted;
194 });
192 });
195
193
196 this.events.on('select.Cell', function (event, data) {
194 this.events.on('select.Cell', function (event, data) {
197 var index = that.find_cell_index(data.cell);
195 var index = that.find_cell_index(data.cell);
198 that.select(index);
196 that.select(index);
199 });
197 });
200
198
201 this.events.on('edit_mode.Cell', function (event, data) {
199 this.events.on('edit_mode.Cell', function (event, data) {
202 that.handle_edit_mode(data.cell);
200 that.handle_edit_mode(data.cell);
203 });
201 });
204
202
205 this.events.on('command_mode.Cell', function (event, data) {
203 this.events.on('command_mode.Cell', function (event, data) {
206 that.handle_command_mode(data.cell);
204 that.handle_command_mode(data.cell);
207 });
205 });
208
206
209 this.events.on('spec_changed.Kernel', function(event, data) {
207 this.events.on('spec_changed.Kernel', function(event, data) {
210 that.metadata.kernelspec =
208 that.metadata.kernelspec =
211 {name: data.name, display_name: data.display_name};
209 {name: data.name, display_name: data.display_name};
212 });
210 });
213
211
214 this.events.on('kernel_ready.Kernel', function(event, data) {
212 this.events.on('kernel_ready.Kernel', function(event, data) {
215 var kinfo = data.kernel.info_reply
213 var kinfo = data.kernel.info_reply
216 var langinfo = kinfo.language_info || {};
214 var langinfo = kinfo.language_info || {};
217 if (!langinfo.name) langinfo.name = kinfo.language;
215 if (!langinfo.name) langinfo.name = kinfo.language;
218
216
219 that.metadata.language_info = langinfo;
217 that.metadata.language_info = langinfo;
220 // Mode 'null' should be plain, unhighlighted text.
218 // Mode 'null' should be plain, unhighlighted text.
221 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null'
219 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null'
222 that.set_codemirror_mode(cm_mode);
220 that.set_codemirror_mode(cm_mode);
223 });
221 });
224
222
225 var collapse_time = function (time) {
223 var collapse_time = function (time) {
226 var app_height = $('#ipython-main-app').height(); // content height
224 var app_height = $('#ipython-main-app').height(); // content height
227 var splitter_height = $('div#pager_splitter').outerHeight(true);
225 var splitter_height = $('div#pager_splitter').outerHeight(true);
228 var new_height = app_height - splitter_height;
226 var new_height = app_height - splitter_height;
229 that.element.animate({height : new_height + 'px'}, time);
227 that.element.animate({height : new_height + 'px'}, time);
230 };
228 };
231
229
232 this.element.bind('collapse_pager', function (event, extrap) {
230 this.element.bind('collapse_pager', function (event, extrap) {
233 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
231 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
234 collapse_time(time);
232 collapse_time(time);
235 });
233 });
236
234
237 var expand_time = function (time) {
235 var expand_time = function (time) {
238 var app_height = $('#ipython-main-app').height(); // content height
236 var app_height = $('#ipython-main-app').height(); // content height
239 var splitter_height = $('div#pager_splitter').outerHeight(true);
237 var splitter_height = $('div#pager_splitter').outerHeight(true);
240 var pager_height = $('div#pager').outerHeight(true);
238 var pager_height = $('div#pager').outerHeight(true);
241 var new_height = app_height - pager_height - splitter_height;
239 var new_height = app_height - pager_height - splitter_height;
242 that.element.animate({height : new_height + 'px'}, time);
240 that.element.animate({height : new_height + 'px'}, time);
243 };
241 };
244
242
245 this.element.bind('expand_pager', function (event, extrap) {
243 this.element.bind('expand_pager', function (event, extrap) {
246 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
244 var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
247 expand_time(time);
245 expand_time(time);
248 });
246 });
249
247
250 // Firefox 22 broke $(window).on("beforeunload")
248 // Firefox 22 broke $(window).on("beforeunload")
251 // I'm not sure why or how.
249 // I'm not sure why or how.
252 window.onbeforeunload = function (e) {
250 window.onbeforeunload = function (e) {
253 // TODO: Make killing the kernel configurable.
251 // TODO: Make killing the kernel configurable.
254 var kill_kernel = false;
252 var kill_kernel = false;
255 if (kill_kernel) {
253 if (kill_kernel) {
256 that.session.delete();
254 that.session.delete();
257 }
255 }
258 // if we are autosaving, trigger an autosave on nav-away.
256 // if we are autosaving, trigger an autosave on nav-away.
259 // still warn, because if we don't the autosave may fail.
257 // still warn, because if we don't the autosave may fail.
260 if (that.dirty) {
258 if (that.dirty) {
261 if ( that.autosave_interval ) {
259 if ( that.autosave_interval ) {
262 // schedule autosave in a timeout
260 // schedule autosave in a timeout
263 // this gives you a chance to forcefully discard changes
261 // this gives you a chance to forcefully discard changes
264 // by reloading the page if you *really* want to.
262 // by reloading the page if you *really* want to.
265 // the timer doesn't start until you *dismiss* the dialog.
263 // the timer doesn't start until you *dismiss* the dialog.
266 setTimeout(function () {
264 setTimeout(function () {
267 if (that.dirty) {
265 if (that.dirty) {
268 that.save_notebook();
266 that.save_notebook();
269 }
267 }
270 }, 1000);
268 }, 1000);
271 return "Autosave in progress, latest changes may be lost.";
269 return "Autosave in progress, latest changes may be lost.";
272 } else {
270 } else {
273 return "Unsaved changes will be lost.";
271 return "Unsaved changes will be lost.";
274 }
272 }
275 }
273 }
276 // Null is the *only* return value that will make the browser not
274 // Null is the *only* return value that will make the browser not
277 // pop up the "don't leave" dialog.
275 // pop up the "don't leave" dialog.
278 return null;
276 return null;
279 };
277 };
280 };
278 };
281
279
282 /**
280 /**
283 * Set the dirty flag, and trigger the set_dirty.Notebook event
281 * Set the dirty flag, and trigger the set_dirty.Notebook event
284 *
282 *
285 * @method set_dirty
283 * @method set_dirty
286 */
284 */
287 Notebook.prototype.set_dirty = function (value) {
285 Notebook.prototype.set_dirty = function (value) {
288 if (value === undefined) {
286 if (value === undefined) {
289 value = true;
287 value = true;
290 }
288 }
291 if (this.dirty == value) {
289 if (this.dirty == value) {
292 return;
290 return;
293 }
291 }
294 this.events.trigger('set_dirty.Notebook', {value: value});
292 this.events.trigger('set_dirty.Notebook', {value: value});
295 };
293 };
296
294
297 /**
295 /**
298 * Scroll the top of the page to a given cell.
296 * Scroll the top of the page to a given cell.
299 *
297 *
300 * @method scroll_to_cell
298 * @method scroll_to_cell
301 * @param {Number} cell_number An index of the cell to view
299 * @param {Number} cell_number An index of the cell to view
302 * @param {Number} time Animation time in milliseconds
300 * @param {Number} time Animation time in milliseconds
303 * @return {Number} Pixel offset from the top of the container
301 * @return {Number} Pixel offset from the top of the container
304 */
302 */
305 Notebook.prototype.scroll_to_cell = function (cell_number, time) {
303 Notebook.prototype.scroll_to_cell = function (cell_number, time) {
306 var cells = this.get_cells();
304 var cells = this.get_cells();
307 time = time || 0;
305 time = time || 0;
308 cell_number = Math.min(cells.length-1,cell_number);
306 cell_number = Math.min(cells.length-1,cell_number);
309 cell_number = Math.max(0 ,cell_number);
307 cell_number = Math.max(0 ,cell_number);
310 var scroll_value = cells[cell_number].element.position().top-cells[0].element.position().top ;
308 var scroll_value = cells[cell_number].element.position().top-cells[0].element.position().top ;
311 this.element.animate({scrollTop:scroll_value}, time);
309 this.element.animate({scrollTop:scroll_value}, time);
312 return scroll_value;
310 return scroll_value;
313 };
311 };
314
312
315 /**
313 /**
316 * Scroll to the bottom of the page.
314 * Scroll to the bottom of the page.
317 *
315 *
318 * @method scroll_to_bottom
316 * @method scroll_to_bottom
319 */
317 */
320 Notebook.prototype.scroll_to_bottom = function () {
318 Notebook.prototype.scroll_to_bottom = function () {
321 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
319 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
322 };
320 };
323
321
324 /**
322 /**
325 * Scroll to the top of the page.
323 * Scroll to the top of the page.
326 *
324 *
327 * @method scroll_to_top
325 * @method scroll_to_top
328 */
326 */
329 Notebook.prototype.scroll_to_top = function () {
327 Notebook.prototype.scroll_to_top = function () {
330 this.element.animate({scrollTop:0}, 0);
328 this.element.animate({scrollTop:0}, 0);
331 };
329 };
332
330
333 // Edit Notebook metadata
331 // Edit Notebook metadata
334
332
335 Notebook.prototype.edit_metadata = function () {
333 Notebook.prototype.edit_metadata = function () {
336 var that = this;
334 var that = this;
337 dialog.edit_metadata({
335 dialog.edit_metadata({
338 md: this.metadata,
336 md: this.metadata,
339 callback: function (md) {
337 callback: function (md) {
340 that.metadata = md;
338 that.metadata = md;
341 },
339 },
342 name: 'Notebook',
340 name: 'Notebook',
343 notebook: this,
341 notebook: this,
344 keyboard_manager: this.keyboard_manager});
342 keyboard_manager: this.keyboard_manager});
345 };
343 };
346
344
347 // Cell indexing, retrieval, etc.
345 // Cell indexing, retrieval, etc.
348
346
349 /**
347 /**
350 * Get all cell elements in the notebook.
348 * Get all cell elements in the notebook.
351 *
349 *
352 * @method get_cell_elements
350 * @method get_cell_elements
353 * @return {jQuery} A selector of all cell elements
351 * @return {jQuery} A selector of all cell elements
354 */
352 */
355 Notebook.prototype.get_cell_elements = function () {
353 Notebook.prototype.get_cell_elements = function () {
356 return this.container.children("div.cell");
354 return this.container.children("div.cell");
357 };
355 };
358
356
359 /**
357 /**
360 * Get a particular cell element.
358 * Get a particular cell element.
361 *
359 *
362 * @method get_cell_element
360 * @method get_cell_element
363 * @param {Number} index An index of a cell to select
361 * @param {Number} index An index of a cell to select
364 * @return {jQuery} A selector of the given cell.
362 * @return {jQuery} A selector of the given cell.
365 */
363 */
366 Notebook.prototype.get_cell_element = function (index) {
364 Notebook.prototype.get_cell_element = function (index) {
367 var result = null;
365 var result = null;
368 var e = this.get_cell_elements().eq(index);
366 var e = this.get_cell_elements().eq(index);
369 if (e.length !== 0) {
367 if (e.length !== 0) {
370 result = e;
368 result = e;
371 }
369 }
372 return result;
370 return result;
373 };
371 };
374
372
375 /**
373 /**
376 * Try to get a particular cell by msg_id.
374 * Try to get a particular cell by msg_id.
377 *
375 *
378 * @method get_msg_cell
376 * @method get_msg_cell
379 * @param {String} msg_id A message UUID
377 * @param {String} msg_id A message UUID
380 * @return {Cell} Cell or null if no cell was found.
378 * @return {Cell} Cell or null if no cell was found.
381 */
379 */
382 Notebook.prototype.get_msg_cell = function (msg_id) {
380 Notebook.prototype.get_msg_cell = function (msg_id) {
383 return codecell.CodeCell.msg_cells[msg_id] || null;
381 return codecell.CodeCell.msg_cells[msg_id] || null;
384 };
382 };
385
383
386 /**
384 /**
387 * Count the cells in this notebook.
385 * Count the cells in this notebook.
388 *
386 *
389 * @method ncells
387 * @method ncells
390 * @return {Number} The number of cells in this notebook
388 * @return {Number} The number of cells in this notebook
391 */
389 */
392 Notebook.prototype.ncells = function () {
390 Notebook.prototype.ncells = function () {
393 return this.get_cell_elements().length;
391 return this.get_cell_elements().length;
394 };
392 };
395
393
396 /**
394 /**
397 * Get all Cell objects in this notebook.
395 * Get all Cell objects in this notebook.
398 *
396 *
399 * @method get_cells
397 * @method get_cells
400 * @return {Array} This notebook's Cell objects
398 * @return {Array} This notebook's Cell objects
401 */
399 */
402 // TODO: we are often calling cells as cells()[i], which we should optimize
400 // TODO: we are often calling cells as cells()[i], which we should optimize
403 // to cells(i) or a new method.
401 // to cells(i) or a new method.
404 Notebook.prototype.get_cells = function () {
402 Notebook.prototype.get_cells = function () {
405 return this.get_cell_elements().toArray().map(function (e) {
403 return this.get_cell_elements().toArray().map(function (e) {
406 return $(e).data("cell");
404 return $(e).data("cell");
407 });
405 });
408 };
406 };
409
407
410 /**
408 /**
411 * Get a Cell object from this notebook.
409 * Get a Cell object from this notebook.
412 *
410 *
413 * @method get_cell
411 * @method get_cell
414 * @param {Number} index An index of a cell to retrieve
412 * @param {Number} index An index of a cell to retrieve
415 * @return {Cell} Cell or null if no cell was found.
413 * @return {Cell} Cell or null if no cell was found.
416 */
414 */
417 Notebook.prototype.get_cell = function (index) {
415 Notebook.prototype.get_cell = function (index) {
418 var result = null;
416 var result = null;
419 var ce = this.get_cell_element(index);
417 var ce = this.get_cell_element(index);
420 if (ce !== null) {
418 if (ce !== null) {
421 result = ce.data('cell');
419 result = ce.data('cell');
422 }
420 }
423 return result;
421 return result;
424 };
422 };
425
423
426 /**
424 /**
427 * Get the cell below a given cell.
425 * Get the cell below a given cell.
428 *
426 *
429 * @method get_next_cell
427 * @method get_next_cell
430 * @param {Cell} cell The provided cell
428 * @param {Cell} cell The provided cell
431 * @return {Cell} the next cell or null if no cell was found.
429 * @return {Cell} the next cell or null if no cell was found.
432 */
430 */
433 Notebook.prototype.get_next_cell = function (cell) {
431 Notebook.prototype.get_next_cell = function (cell) {
434 var result = null;
432 var result = null;
435 var index = this.find_cell_index(cell);
433 var index = this.find_cell_index(cell);
436 if (this.is_valid_cell_index(index+1)) {
434 if (this.is_valid_cell_index(index+1)) {
437 result = this.get_cell(index+1);
435 result = this.get_cell(index+1);
438 }
436 }
439 return result;
437 return result;
440 };
438 };
441
439
442 /**
440 /**
443 * Get the cell above a given cell.
441 * Get the cell above a given cell.
444 *
442 *
445 * @method get_prev_cell
443 * @method get_prev_cell
446 * @param {Cell} cell The provided cell
444 * @param {Cell} cell The provided cell
447 * @return {Cell} The previous cell or null if no cell was found.
445 * @return {Cell} The previous cell or null if no cell was found.
448 */
446 */
449 Notebook.prototype.get_prev_cell = function (cell) {
447 Notebook.prototype.get_prev_cell = function (cell) {
450 var result = null;
448 var result = null;
451 var index = this.find_cell_index(cell);
449 var index = this.find_cell_index(cell);
452 if (index !== null && index > 0) {
450 if (index !== null && index > 0) {
453 result = this.get_cell(index-1);
451 result = this.get_cell(index-1);
454 }
452 }
455 return result;
453 return result;
456 };
454 };
457
455
458 /**
456 /**
459 * Get the numeric index of a given cell.
457 * Get the numeric index of a given cell.
460 *
458 *
461 * @method find_cell_index
459 * @method find_cell_index
462 * @param {Cell} cell The provided cell
460 * @param {Cell} cell The provided cell
463 * @return {Number} The cell's numeric index or null if no cell was found.
461 * @return {Number} The cell's numeric index or null if no cell was found.
464 */
462 */
465 Notebook.prototype.find_cell_index = function (cell) {
463 Notebook.prototype.find_cell_index = function (cell) {
466 var result = null;
464 var result = null;
467 this.get_cell_elements().filter(function (index) {
465 this.get_cell_elements().filter(function (index) {
468 if ($(this).data("cell") === cell) {
466 if ($(this).data("cell") === cell) {
469 result = index;
467 result = index;
470 }
468 }
471 });
469 });
472 return result;
470 return result;
473 };
471 };
474
472
475 /**
473 /**
476 * Get a given index , or the selected index if none is provided.
474 * Get a given index , or the selected index if none is provided.
477 *
475 *
478 * @method index_or_selected
476 * @method index_or_selected
479 * @param {Number} index A cell's index
477 * @param {Number} index A cell's index
480 * @return {Number} The given index, or selected index if none is provided.
478 * @return {Number} The given index, or selected index if none is provided.
481 */
479 */
482 Notebook.prototype.index_or_selected = function (index) {
480 Notebook.prototype.index_or_selected = function (index) {
483 var i;
481 var i;
484 if (index === undefined || index === null) {
482 if (index === undefined || index === null) {
485 i = this.get_selected_index();
483 i = this.get_selected_index();
486 if (i === null) {
484 if (i === null) {
487 i = 0;
485 i = 0;
488 }
486 }
489 } else {
487 } else {
490 i = index;
488 i = index;
491 }
489 }
492 return i;
490 return i;
493 };
491 };
494
492
495 /**
493 /**
496 * Get the currently selected cell.
494 * Get the currently selected cell.
497 * @method get_selected_cell
495 * @method get_selected_cell
498 * @return {Cell} The selected cell
496 * @return {Cell} The selected cell
499 */
497 */
500 Notebook.prototype.get_selected_cell = function () {
498 Notebook.prototype.get_selected_cell = function () {
501 var index = this.get_selected_index();
499 var index = this.get_selected_index();
502 return this.get_cell(index);
500 return this.get_cell(index);
503 };
501 };
504
502
505 /**
503 /**
506 * Check whether a cell index is valid.
504 * Check whether a cell index is valid.
507 *
505 *
508 * @method is_valid_cell_index
506 * @method is_valid_cell_index
509 * @param {Number} index A cell index
507 * @param {Number} index A cell index
510 * @return True if the index is valid, false otherwise
508 * @return True if the index is valid, false otherwise
511 */
509 */
512 Notebook.prototype.is_valid_cell_index = function (index) {
510 Notebook.prototype.is_valid_cell_index = function (index) {
513 if (index !== null && index >= 0 && index < this.ncells()) {
511 if (index !== null && index >= 0 && index < this.ncells()) {
514 return true;
512 return true;
515 } else {
513 } else {
516 return false;
514 return false;
517 }
515 }
518 };
516 };
519
517
520 /**
518 /**
521 * Get the index of the currently selected cell.
519 * Get the index of the currently selected cell.
522
520
523 * @method get_selected_index
521 * @method get_selected_index
524 * @return {Number} The selected cell's numeric index
522 * @return {Number} The selected cell's numeric index
525 */
523 */
526 Notebook.prototype.get_selected_index = function () {
524 Notebook.prototype.get_selected_index = function () {
527 var result = null;
525 var result = null;
528 this.get_cell_elements().filter(function (index) {
526 this.get_cell_elements().filter(function (index) {
529 if ($(this).data("cell").selected === true) {
527 if ($(this).data("cell").selected === true) {
530 result = index;
528 result = index;
531 }
529 }
532 });
530 });
533 return result;
531 return result;
534 };
532 };
535
533
536
534
537 // Cell selection.
535 // Cell selection.
538
536
539 /**
537 /**
540 * Programmatically select a cell.
538 * Programmatically select a cell.
541 *
539 *
542 * @method select
540 * @method select
543 * @param {Number} index A cell's index
541 * @param {Number} index A cell's index
544 * @return {Notebook} This notebook
542 * @return {Notebook} This notebook
545 */
543 */
546 Notebook.prototype.select = function (index) {
544 Notebook.prototype.select = function (index) {
547 if (this.is_valid_cell_index(index)) {
545 if (this.is_valid_cell_index(index)) {
548 var sindex = this.get_selected_index();
546 var sindex = this.get_selected_index();
549 if (sindex !== null && index !== sindex) {
547 if (sindex !== null && index !== sindex) {
550 // If we are about to select a different cell, make sure we are
548 // If we are about to select a different cell, make sure we are
551 // first in command mode.
549 // first in command mode.
552 if (this.mode !== 'command') {
550 if (this.mode !== 'command') {
553 this.command_mode();
551 this.command_mode();
554 }
552 }
555 this.get_cell(sindex).unselect();
553 this.get_cell(sindex).unselect();
556 }
554 }
557 var cell = this.get_cell(index);
555 var cell = this.get_cell(index);
558 cell.select();
556 cell.select();
559 if (cell.cell_type === 'heading') {
557 if (cell.cell_type === 'heading') {
560 this.events.trigger('selected_cell_type_changed.Notebook',
558 this.events.trigger('selected_cell_type_changed.Notebook',
561 {'cell_type':cell.cell_type,level:cell.level}
559 {'cell_type':cell.cell_type,level:cell.level}
562 );
560 );
563 } else {
561 } else {
564 this.events.trigger('selected_cell_type_changed.Notebook',
562 this.events.trigger('selected_cell_type_changed.Notebook',
565 {'cell_type':cell.cell_type}
563 {'cell_type':cell.cell_type}
566 );
564 );
567 }
565 }
568 }
566 }
569 return this;
567 return this;
570 };
568 };
571
569
572 /**
570 /**
573 * Programmatically select the next cell.
571 * Programmatically select the next cell.
574 *
572 *
575 * @method select_next
573 * @method select_next
576 * @return {Notebook} This notebook
574 * @return {Notebook} This notebook
577 */
575 */
578 Notebook.prototype.select_next = function () {
576 Notebook.prototype.select_next = function () {
579 var index = this.get_selected_index();
577 var index = this.get_selected_index();
580 this.select(index+1);
578 this.select(index+1);
581 return this;
579 return this;
582 };
580 };
583
581
584 /**
582 /**
585 * Programmatically select the previous cell.
583 * Programmatically select the previous cell.
586 *
584 *
587 * @method select_prev
585 * @method select_prev
588 * @return {Notebook} This notebook
586 * @return {Notebook} This notebook
589 */
587 */
590 Notebook.prototype.select_prev = function () {
588 Notebook.prototype.select_prev = function () {
591 var index = this.get_selected_index();
589 var index = this.get_selected_index();
592 this.select(index-1);
590 this.select(index-1);
593 return this;
591 return this;
594 };
592 };
595
593
596
594
597 // Edit/Command mode
595 // Edit/Command mode
598
596
599 /**
597 /**
600 * Gets the index of the cell that is in edit mode.
598 * Gets the index of the cell that is in edit mode.
601 *
599 *
602 * @method get_edit_index
600 * @method get_edit_index
603 *
601 *
604 * @return index {int}
602 * @return index {int}
605 **/
603 **/
606 Notebook.prototype.get_edit_index = function () {
604 Notebook.prototype.get_edit_index = function () {
607 var result = null;
605 var result = null;
608 this.get_cell_elements().filter(function (index) {
606 this.get_cell_elements().filter(function (index) {
609 if ($(this).data("cell").mode === 'edit') {
607 if ($(this).data("cell").mode === 'edit') {
610 result = index;
608 result = index;
611 }
609 }
612 });
610 });
613 return result;
611 return result;
614 };
612 };
615
613
616 /**
614 /**
617 * Handle when a a cell blurs and the notebook should enter command mode.
615 * Handle when a a cell blurs and the notebook should enter command mode.
618 *
616 *
619 * @method handle_command_mode
617 * @method handle_command_mode
620 * @param [cell] {Cell} Cell to enter command mode on.
618 * @param [cell] {Cell} Cell to enter command mode on.
621 **/
619 **/
622 Notebook.prototype.handle_command_mode = function (cell) {
620 Notebook.prototype.handle_command_mode = function (cell) {
623 if (this.mode !== 'command') {
621 if (this.mode !== 'command') {
624 cell.command_mode();
622 cell.command_mode();
625 this.mode = 'command';
623 this.mode = 'command';
626 this.events.trigger('command_mode.Notebook');
624 this.events.trigger('command_mode.Notebook');
627 this.keyboard_manager.command_mode();
625 this.keyboard_manager.command_mode();
628 }
626 }
629 };
627 };
630
628
631 /**
629 /**
632 * Make the notebook enter command mode.
630 * Make the notebook enter command mode.
633 *
631 *
634 * @method command_mode
632 * @method command_mode
635 **/
633 **/
636 Notebook.prototype.command_mode = function () {
634 Notebook.prototype.command_mode = function () {
637 var cell = this.get_cell(this.get_edit_index());
635 var cell = this.get_cell(this.get_edit_index());
638 if (cell && this.mode !== 'command') {
636 if (cell && this.mode !== 'command') {
639 // We don't call cell.command_mode, but rather call cell.focus_cell()
637 // We don't call cell.command_mode, but rather call cell.focus_cell()
640 // which will blur and CM editor and trigger the call to
638 // which will blur and CM editor and trigger the call to
641 // handle_command_mode.
639 // handle_command_mode.
642 cell.focus_cell();
640 cell.focus_cell();
643 }
641 }
644 };
642 };
645
643
646 /**
644 /**
647 * Handle when a cell fires it's edit_mode event.
645 * Handle when a cell fires it's edit_mode event.
648 *
646 *
649 * @method handle_edit_mode
647 * @method handle_edit_mode
650 * @param [cell] {Cell} Cell to enter edit mode on.
648 * @param [cell] {Cell} Cell to enter edit mode on.
651 **/
649 **/
652 Notebook.prototype.handle_edit_mode = function (cell) {
650 Notebook.prototype.handle_edit_mode = function (cell) {
653 if (cell && this.mode !== 'edit') {
651 if (cell && this.mode !== 'edit') {
654 cell.edit_mode();
652 cell.edit_mode();
655 this.mode = 'edit';
653 this.mode = 'edit';
656 this.events.trigger('edit_mode.Notebook');
654 this.events.trigger('edit_mode.Notebook');
657 this.keyboard_manager.edit_mode();
655 this.keyboard_manager.edit_mode();
658 }
656 }
659 };
657 };
660
658
661 /**
659 /**
662 * Make a cell enter edit mode.
660 * Make a cell enter edit mode.
663 *
661 *
664 * @method edit_mode
662 * @method edit_mode
665 **/
663 **/
666 Notebook.prototype.edit_mode = function () {
664 Notebook.prototype.edit_mode = function () {
667 var cell = this.get_selected_cell();
665 var cell = this.get_selected_cell();
668 if (cell && this.mode !== 'edit') {
666 if (cell && this.mode !== 'edit') {
669 cell.unrender();
667 cell.unrender();
670 cell.focus_editor();
668 cell.focus_editor();
671 }
669 }
672 };
670 };
673
671
674 /**
672 /**
675 * Focus the currently selected cell.
673 * Focus the currently selected cell.
676 *
674 *
677 * @method focus_cell
675 * @method focus_cell
678 **/
676 **/
679 Notebook.prototype.focus_cell = function () {
677 Notebook.prototype.focus_cell = function () {
680 var cell = this.get_selected_cell();
678 var cell = this.get_selected_cell();
681 if (cell === null) {return;} // No cell is selected
679 if (cell === null) {return;} // No cell is selected
682 cell.focus_cell();
680 cell.focus_cell();
683 };
681 };
684
682
685 // Cell movement
683 // Cell movement
686
684
687 /**
685 /**
688 * Move given (or selected) cell up and select it.
686 * Move given (or selected) cell up and select it.
689 *
687 *
690 * @method move_cell_up
688 * @method move_cell_up
691 * @param [index] {integer} cell index
689 * @param [index] {integer} cell index
692 * @return {Notebook} This notebook
690 * @return {Notebook} This notebook
693 **/
691 **/
694 Notebook.prototype.move_cell_up = function (index) {
692 Notebook.prototype.move_cell_up = function (index) {
695 var i = this.index_or_selected(index);
693 var i = this.index_or_selected(index);
696 if (this.is_valid_cell_index(i) && i > 0) {
694 if (this.is_valid_cell_index(i) && i > 0) {
697 var pivot = this.get_cell_element(i-1);
695 var pivot = this.get_cell_element(i-1);
698 var tomove = this.get_cell_element(i);
696 var tomove = this.get_cell_element(i);
699 if (pivot !== null && tomove !== null) {
697 if (pivot !== null && tomove !== null) {
700 tomove.detach();
698 tomove.detach();
701 pivot.before(tomove);
699 pivot.before(tomove);
702 this.select(i-1);
700 this.select(i-1);
703 var cell = this.get_selected_cell();
701 var cell = this.get_selected_cell();
704 cell.focus_cell();
702 cell.focus_cell();
705 }
703 }
706 this.set_dirty(true);
704 this.set_dirty(true);
707 }
705 }
708 return this;
706 return this;
709 };
707 };
710
708
711
709
712 /**
710 /**
713 * Move given (or selected) cell down and select it
711 * Move given (or selected) cell down and select it
714 *
712 *
715 * @method move_cell_down
713 * @method move_cell_down
716 * @param [index] {integer} cell index
714 * @param [index] {integer} cell index
717 * @return {Notebook} This notebook
715 * @return {Notebook} This notebook
718 **/
716 **/
719 Notebook.prototype.move_cell_down = function (index) {
717 Notebook.prototype.move_cell_down = function (index) {
720 var i = this.index_or_selected(index);
718 var i = this.index_or_selected(index);
721 if (this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
719 if (this.is_valid_cell_index(i) && this.is_valid_cell_index(i+1)) {
722 var pivot = this.get_cell_element(i+1);
720 var pivot = this.get_cell_element(i+1);
723 var tomove = this.get_cell_element(i);
721 var tomove = this.get_cell_element(i);
724 if (pivot !== null && tomove !== null) {
722 if (pivot !== null && tomove !== null) {
725 tomove.detach();
723 tomove.detach();
726 pivot.after(tomove);
724 pivot.after(tomove);
727 this.select(i+1);
725 this.select(i+1);
728 var cell = this.get_selected_cell();
726 var cell = this.get_selected_cell();
729 cell.focus_cell();
727 cell.focus_cell();
730 }
728 }
731 }
729 }
732 this.set_dirty();
730 this.set_dirty();
733 return this;
731 return this;
734 };
732 };
735
733
736
734
737 // Insertion, deletion.
735 // Insertion, deletion.
738
736
739 /**
737 /**
740 * Delete a cell from the notebook.
738 * Delete a cell from the notebook.
741 *
739 *
742 * @method delete_cell
740 * @method delete_cell
743 * @param [index] A cell's numeric index
741 * @param [index] A cell's numeric index
744 * @return {Notebook} This notebook
742 * @return {Notebook} This notebook
745 */
743 */
746 Notebook.prototype.delete_cell = function (index) {
744 Notebook.prototype.delete_cell = function (index) {
747 var i = this.index_or_selected(index);
745 var i = this.index_or_selected(index);
748 var cell = this.get_cell(i);
746 var cell = this.get_cell(i);
749 if (!cell.is_deletable()) {
747 if (!cell.is_deletable()) {
750 return this;
748 return this;
751 }
749 }
752
750
753 this.undelete_backup = cell.toJSON();
751 this.undelete_backup = cell.toJSON();
754 $('#undelete_cell').removeClass('disabled');
752 $('#undelete_cell').removeClass('disabled');
755 if (this.is_valid_cell_index(i)) {
753 if (this.is_valid_cell_index(i)) {
756 var old_ncells = this.ncells();
754 var old_ncells = this.ncells();
757 var ce = this.get_cell_element(i);
755 var ce = this.get_cell_element(i);
758 ce.remove();
756 ce.remove();
759 if (i === 0) {
757 if (i === 0) {
760 // Always make sure we have at least one cell.
758 // Always make sure we have at least one cell.
761 if (old_ncells === 1) {
759 if (old_ncells === 1) {
762 this.insert_cell_below('code');
760 this.insert_cell_below('code');
763 }
761 }
764 this.select(0);
762 this.select(0);
765 this.undelete_index = 0;
763 this.undelete_index = 0;
766 this.undelete_below = false;
764 this.undelete_below = false;
767 } else if (i === old_ncells-1 && i !== 0) {
765 } else if (i === old_ncells-1 && i !== 0) {
768 this.select(i-1);
766 this.select(i-1);
769 this.undelete_index = i - 1;
767 this.undelete_index = i - 1;
770 this.undelete_below = true;
768 this.undelete_below = true;
771 } else {
769 } else {
772 this.select(i);
770 this.select(i);
773 this.undelete_index = i;
771 this.undelete_index = i;
774 this.undelete_below = false;
772 this.undelete_below = false;
775 }
773 }
776 this.events.trigger('delete.Cell', {'cell': cell, 'index': i});
774 this.events.trigger('delete.Cell', {'cell': cell, 'index': i});
777 this.set_dirty(true);
775 this.set_dirty(true);
778 }
776 }
779 return this;
777 return this;
780 };
778 };
781
779
782 /**
780 /**
783 * Restore the most recently deleted cell.
781 * Restore the most recently deleted cell.
784 *
782 *
785 * @method undelete
783 * @method undelete
786 */
784 */
787 Notebook.prototype.undelete_cell = function() {
785 Notebook.prototype.undelete_cell = function() {
788 if (this.undelete_backup !== null && this.undelete_index !== null) {
786 if (this.undelete_backup !== null && this.undelete_index !== null) {
789 var current_index = this.get_selected_index();
787 var current_index = this.get_selected_index();
790 if (this.undelete_index < current_index) {
788 if (this.undelete_index < current_index) {
791 current_index = current_index + 1;
789 current_index = current_index + 1;
792 }
790 }
793 if (this.undelete_index >= this.ncells()) {
791 if (this.undelete_index >= this.ncells()) {
794 this.select(this.ncells() - 1);
792 this.select(this.ncells() - 1);
795 }
793 }
796 else {
794 else {
797 this.select(this.undelete_index);
795 this.select(this.undelete_index);
798 }
796 }
799 var cell_data = this.undelete_backup;
797 var cell_data = this.undelete_backup;
800 var new_cell = null;
798 var new_cell = null;
801 if (this.undelete_below) {
799 if (this.undelete_below) {
802 new_cell = this.insert_cell_below(cell_data.cell_type);
800 new_cell = this.insert_cell_below(cell_data.cell_type);
803 } else {
801 } else {
804 new_cell = this.insert_cell_above(cell_data.cell_type);
802 new_cell = this.insert_cell_above(cell_data.cell_type);
805 }
803 }
806 new_cell.fromJSON(cell_data);
804 new_cell.fromJSON(cell_data);
807 if (this.undelete_below) {
805 if (this.undelete_below) {
808 this.select(current_index+1);
806 this.select(current_index+1);
809 } else {
807 } else {
810 this.select(current_index);
808 this.select(current_index);
811 }
809 }
812 this.undelete_backup = null;
810 this.undelete_backup = null;
813 this.undelete_index = null;
811 this.undelete_index = null;
814 }
812 }
815 $('#undelete_cell').addClass('disabled');
813 $('#undelete_cell').addClass('disabled');
816 };
814 };
817
815
818 /**
816 /**
819 * Insert a cell so that after insertion the cell is at given index.
817 * Insert a cell so that after insertion the cell is at given index.
820 *
818 *
821 * If cell type is not provided, it will default to the type of the
819 * If cell type is not provided, it will default to the type of the
822 * currently active cell.
820 * currently active cell.
823 *
821 *
824 * Similar to insert_above, but index parameter is mandatory
822 * Similar to insert_above, but index parameter is mandatory
825 *
823 *
826 * Index will be brought back into the accessible range [0,n]
824 * Index will be brought back into the accessible range [0,n]
827 *
825 *
828 * @method insert_cell_at_index
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 * @param [index] {int} a valid index where to insert cell
828 * @param [index] {int} a valid index where to insert cell
831 *
829 *
832 * @return cell {cell|null} created cell or null
830 * @return cell {cell|null} created cell or null
833 **/
831 **/
834 Notebook.prototype.insert_cell_at_index = function(type, index){
832 Notebook.prototype.insert_cell_at_index = function(type, index){
835
833
836 var ncells = this.ncells();
834 var ncells = this.ncells();
837 index = Math.min(index, ncells);
835 index = Math.min(index, ncells);
838 index = Math.max(index, 0);
836 index = Math.max(index, 0);
839 var cell = null;
837 var cell = null;
840 type = type || this.default_cell_type;
838 type = type || this.default_cell_type;
841 if (type === 'above') {
839 if (type === 'above') {
842 if (index > 0) {
840 if (index > 0) {
843 type = this.get_cell(index-1).cell_type;
841 type = this.get_cell(index-1).cell_type;
844 } else {
842 } else {
845 type = 'code';
843 type = 'code';
846 }
844 }
847 } else if (type === 'below') {
845 } else if (type === 'below') {
848 if (index < ncells) {
846 if (index < ncells) {
849 type = this.get_cell(index).cell_type;
847 type = this.get_cell(index).cell_type;
850 } else {
848 } else {
851 type = 'code';
849 type = 'code';
852 }
850 }
853 } else if (type === 'selected') {
851 } else if (type === 'selected') {
854 type = this.get_selected_cell().cell_type;
852 type = this.get_selected_cell().cell_type;
855 }
853 }
856
854
857 if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
855 if (ncells === 0 || this.is_valid_cell_index(index) || index === ncells) {
858 var cell_options = {
856 var cell_options = {
859 events: this.events,
857 events: this.events,
860 config: this.config,
858 config: this.config,
861 keyboard_manager: this.keyboard_manager,
859 keyboard_manager: this.keyboard_manager,
862 notebook: this,
860 notebook: this,
863 tooltip: this.tooltip,
861 tooltip: this.tooltip,
864 };
862 };
865 if (type === 'code') {
863 switch(type) {
864 case 'code':
866 cell = new codecell.CodeCell(this.kernel, cell_options);
865 cell = new codecell.CodeCell(this.kernel, cell_options);
867 cell.set_input_prompt();
866 cell.set_input_prompt();
868 } else if (type === 'markdown') {
867 break;
868 case 'markdown':
869 cell = new textcell.MarkdownCell(cell_options);
869 cell = new textcell.MarkdownCell(cell_options);
870 } else if (type === 'raw') {
870 break;
871 case 'raw':
871 cell = new textcell.RawCell(cell_options);
872 cell = new textcell.RawCell(cell_options);
872 } else if (type === 'heading') {
873 break;
873 cell = new textcell.HeadingCell(cell_options);
874 default:
875 console.log("invalid cell type: ", type);
874 }
876 }
875
877
876 if(this._insert_element_at_index(cell.element,index)) {
878 if(this._insert_element_at_index(cell.element,index)) {
877 cell.render();
879 cell.render();
878 this.events.trigger('create.Cell', {'cell': cell, 'index': index});
880 this.events.trigger('create.Cell', {'cell': cell, 'index': index});
879 cell.refresh();
881 cell.refresh();
880 // We used to select the cell after we refresh it, but there
882 // We used to select the cell after we refresh it, but there
881 // are now cases were this method is called where select is
883 // are now cases were this method is called where select is
882 // not appropriate. The selection logic should be handled by the
884 // not appropriate. The selection logic should be handled by the
883 // caller of the the top level insert_cell methods.
885 // caller of the the top level insert_cell methods.
884 this.set_dirty(true);
886 this.set_dirty(true);
885 }
887 }
886 }
888 }
887 return cell;
889 return cell;
888
890
889 };
891 };
890
892
891 /**
893 /**
892 * Insert an element at given cell index.
894 * Insert an element at given cell index.
893 *
895 *
894 * @method _insert_element_at_index
896 * @method _insert_element_at_index
895 * @param element {dom_element} a cell element
897 * @param element {dom_element} a cell element
896 * @param [index] {int} a valid index where to inser cell
898 * @param [index] {int} a valid index where to inser cell
897 * @private
899 * @private
898 *
900 *
899 * return true if everything whent fine.
901 * return true if everything whent fine.
900 **/
902 **/
901 Notebook.prototype._insert_element_at_index = function(element, index){
903 Notebook.prototype._insert_element_at_index = function(element, index){
902 if (element === undefined){
904 if (element === undefined){
903 return false;
905 return false;
904 }
906 }
905
907
906 var ncells = this.ncells();
908 var ncells = this.ncells();
907
909
908 if (ncells === 0) {
910 if (ncells === 0) {
909 // special case append if empty
911 // special case append if empty
910 this.element.find('div.end_space').before(element);
912 this.element.find('div.end_space').before(element);
911 } else if ( ncells === index ) {
913 } else if ( ncells === index ) {
912 // special case append it the end, but not empty
914 // special case append it the end, but not empty
913 this.get_cell_element(index-1).after(element);
915 this.get_cell_element(index-1).after(element);
914 } else if (this.is_valid_cell_index(index)) {
916 } else if (this.is_valid_cell_index(index)) {
915 // otherwise always somewhere to append to
917 // otherwise always somewhere to append to
916 this.get_cell_element(index).before(element);
918 this.get_cell_element(index).before(element);
917 } else {
919 } else {
918 return false;
920 return false;
919 }
921 }
920
922
921 if (this.undelete_index !== null && index <= this.undelete_index) {
923 if (this.undelete_index !== null && index <= this.undelete_index) {
922 this.undelete_index = this.undelete_index + 1;
924 this.undelete_index = this.undelete_index + 1;
923 this.set_dirty(true);
925 this.set_dirty(true);
924 }
926 }
925 return true;
927 return true;
926 };
928 };
927
929
928 /**
930 /**
929 * Insert a cell of given type above given index, or at top
931 * Insert a cell of given type above given index, or at top
930 * of notebook if index smaller than 0.
932 * of notebook if index smaller than 0.
931 *
933 *
932 * default index value is the one of currently selected cell
934 * default index value is the one of currently selected cell
933 *
935 *
934 * @method insert_cell_above
936 * @method insert_cell_above
935 * @param [type] {string} cell type
937 * @param [type] {string} cell type
936 * @param [index] {integer}
938 * @param [index] {integer}
937 *
939 *
938 * @return handle to created cell or null
940 * @return handle to created cell or null
939 **/
941 **/
940 Notebook.prototype.insert_cell_above = function (type, index) {
942 Notebook.prototype.insert_cell_above = function (type, index) {
941 index = this.index_or_selected(index);
943 index = this.index_or_selected(index);
942 return this.insert_cell_at_index(type, index);
944 return this.insert_cell_at_index(type, index);
943 };
945 };
944
946
945 /**
947 /**
946 * Insert a cell of given type below given index, or at bottom
948 * Insert a cell of given type below given index, or at bottom
947 * of notebook if index greater than number of cells
949 * of notebook if index greater than number of cells
948 *
950 *
949 * default index value is the one of currently selected cell
951 * default index value is the one of currently selected cell
950 *
952 *
951 * @method insert_cell_below
953 * @method insert_cell_below
952 * @param [type] {string} cell type
954 * @param [type] {string} cell type
953 * @param [index] {integer}
955 * @param [index] {integer}
954 *
956 *
955 * @return handle to created cell or null
957 * @return handle to created cell or null
956 *
958 *
957 **/
959 **/
958 Notebook.prototype.insert_cell_below = function (type, index) {
960 Notebook.prototype.insert_cell_below = function (type, index) {
959 index = this.index_or_selected(index);
961 index = this.index_or_selected(index);
960 return this.insert_cell_at_index(type, index+1);
962 return this.insert_cell_at_index(type, index+1);
961 };
963 };
962
964
963
965
964 /**
966 /**
965 * Insert cell at end of notebook
967 * Insert cell at end of notebook
966 *
968 *
967 * @method insert_cell_at_bottom
969 * @method insert_cell_at_bottom
968 * @param {String} type cell type
970 * @param {String} type cell type
969 *
971 *
970 * @return the added cell; or null
972 * @return the added cell; or null
971 **/
973 **/
972 Notebook.prototype.insert_cell_at_bottom = function (type){
974 Notebook.prototype.insert_cell_at_bottom = function (type){
973 var len = this.ncells();
975 var len = this.ncells();
974 return this.insert_cell_below(type,len-1);
976 return this.insert_cell_below(type,len-1);
975 };
977 };
976
978
977 /**
979 /**
978 * Turn a cell into a code cell.
980 * Turn a cell into a code cell.
979 *
981 *
980 * @method to_code
982 * @method to_code
981 * @param {Number} [index] A cell's index
983 * @param {Number} [index] A cell's index
982 */
984 */
983 Notebook.prototype.to_code = function (index) {
985 Notebook.prototype.to_code = function (index) {
984 var i = this.index_or_selected(index);
986 var i = this.index_or_selected(index);
985 if (this.is_valid_cell_index(i)) {
987 if (this.is_valid_cell_index(i)) {
986 var source_cell = this.get_cell(i);
988 var source_cell = this.get_cell(i);
987 if (!(source_cell instanceof codecell.CodeCell)) {
989 if (!(source_cell instanceof codecell.CodeCell)) {
988 var target_cell = this.insert_cell_below('code',i);
990 var target_cell = this.insert_cell_below('code',i);
989 var text = source_cell.get_text();
991 var text = source_cell.get_text();
990 if (text === source_cell.placeholder) {
992 if (text === source_cell.placeholder) {
991 text = '';
993 text = '';
992 }
994 }
993 //metadata
995 //metadata
994 target_cell.metadata = source_cell.metadata;
996 target_cell.metadata = source_cell.metadata;
995
997
996 target_cell.set_text(text);
998 target_cell.set_text(text);
997 // make this value the starting point, so that we can only undo
999 // make this value the starting point, so that we can only undo
998 // to this state, instead of a blank cell
1000 // to this state, instead of a blank cell
999 target_cell.code_mirror.clearHistory();
1001 target_cell.code_mirror.clearHistory();
1000 source_cell.element.remove();
1002 source_cell.element.remove();
1001 this.select(i);
1003 this.select(i);
1002 var cursor = source_cell.code_mirror.getCursor();
1004 var cursor = source_cell.code_mirror.getCursor();
1003 target_cell.code_mirror.setCursor(cursor);
1005 target_cell.code_mirror.setCursor(cursor);
1004 this.set_dirty(true);
1006 this.set_dirty(true);
1005 }
1007 }
1006 }
1008 }
1007 };
1009 };
1008
1010
1009 /**
1011 /**
1010 * Turn a cell into a Markdown cell.
1012 * Turn a cell into a Markdown cell.
1011 *
1013 *
1012 * @method to_markdown
1014 * @method to_markdown
1013 * @param {Number} [index] A cell's index
1015 * @param {Number} [index] A cell's index
1014 */
1016 */
1015 Notebook.prototype.to_markdown = function (index) {
1017 Notebook.prototype.to_markdown = function (index) {
1016 var i = this.index_or_selected(index);
1018 var i = this.index_or_selected(index);
1017 if (this.is_valid_cell_index(i)) {
1019 if (this.is_valid_cell_index(i)) {
1018 var source_cell = this.get_cell(i);
1020 var source_cell = this.get_cell(i);
1019
1021
1020 if (!(source_cell instanceof textcell.MarkdownCell)) {
1022 if (!(source_cell instanceof textcell.MarkdownCell)) {
1021 var target_cell = this.insert_cell_below('markdown',i);
1023 var target_cell = this.insert_cell_below('markdown',i);
1022 var text = source_cell.get_text();
1024 var text = source_cell.get_text();
1023
1025
1024 if (text === source_cell.placeholder) {
1026 if (text === source_cell.placeholder) {
1025 text = '';
1027 text = '';
1026 }
1028 }
1027 // metadata
1029 // metadata
1028 target_cell.metadata = source_cell.metadata
1030 target_cell.metadata = source_cell.metadata
1029 // We must show the editor before setting its contents
1031 // We must show the editor before setting its contents
1030 target_cell.unrender();
1032 target_cell.unrender();
1031 target_cell.set_text(text);
1033 target_cell.set_text(text);
1032 // make this value the starting point, so that we can only undo
1034 // make this value the starting point, so that we can only undo
1033 // to this state, instead of a blank cell
1035 // to this state, instead of a blank cell
1034 target_cell.code_mirror.clearHistory();
1036 target_cell.code_mirror.clearHistory();
1035 source_cell.element.remove();
1037 source_cell.element.remove();
1036 this.select(i);
1038 this.select(i);
1037 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1039 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1038 target_cell.render();
1040 target_cell.render();
1039 }
1041 }
1040 var cursor = source_cell.code_mirror.getCursor();
1042 var cursor = source_cell.code_mirror.getCursor();
1041 target_cell.code_mirror.setCursor(cursor);
1043 target_cell.code_mirror.setCursor(cursor);
1042 this.set_dirty(true);
1044 this.set_dirty(true);
1043 }
1045 }
1044 }
1046 }
1045 };
1047 };
1046
1048
1047 /**
1049 /**
1048 * Turn a cell into a raw text cell.
1050 * Turn a cell into a raw text cell.
1049 *
1051 *
1050 * @method to_raw
1052 * @method to_raw
1051 * @param {Number} [index] A cell's index
1053 * @param {Number} [index] A cell's index
1052 */
1054 */
1053 Notebook.prototype.to_raw = function (index) {
1055 Notebook.prototype.to_raw = function (index) {
1054 var i = this.index_or_selected(index);
1056 var i = this.index_or_selected(index);
1055 if (this.is_valid_cell_index(i)) {
1057 if (this.is_valid_cell_index(i)) {
1056 var target_cell = null;
1058 var target_cell = null;
1057 var source_cell = this.get_cell(i);
1059 var source_cell = this.get_cell(i);
1058
1060
1059 if (!(source_cell instanceof textcell.RawCell)) {
1061 if (!(source_cell instanceof textcell.RawCell)) {
1060 target_cell = this.insert_cell_below('raw',i);
1062 target_cell = this.insert_cell_below('raw',i);
1061 var text = source_cell.get_text();
1063 var text = source_cell.get_text();
1062 if (text === source_cell.placeholder) {
1064 if (text === source_cell.placeholder) {
1063 text = '';
1065 text = '';
1064 }
1066 }
1065 //metadata
1067 //metadata
1066 target_cell.metadata = source_cell.metadata;
1068 target_cell.metadata = source_cell.metadata;
1067 // We must show the editor before setting its contents
1069 // We must show the editor before setting its contents
1068 target_cell.unrender();
1070 target_cell.unrender();
1069 target_cell.set_text(text);
1071 target_cell.set_text(text);
1070 // make this value the starting point, so that we can only undo
1072 // make this value the starting point, so that we can only undo
1071 // to this state, instead of a blank cell
1073 // to this state, instead of a blank cell
1072 target_cell.code_mirror.clearHistory();
1074 target_cell.code_mirror.clearHistory();
1073 source_cell.element.remove();
1075 source_cell.element.remove();
1074 this.select(i);
1076 this.select(i);
1075 var cursor = source_cell.code_mirror.getCursor();
1077 var cursor = source_cell.code_mirror.getCursor();
1076 target_cell.code_mirror.setCursor(cursor);
1078 target_cell.code_mirror.setCursor(cursor);
1077 this.set_dirty(true);
1079 this.set_dirty(true);
1078 }
1080 }
1079 }
1081 }
1080 };
1082 };
1081
1083
1082 /**
1084 /**
1083 * Turn a cell into a heading cell.
1085 * Turn a cell into a heading cell.
1084 *
1086 *
1085 * @method to_heading
1087 * @method to_heading
1086 * @param {Number} [index] A cell's index
1088 * @param {Number} [index] A cell's index
1087 * @param {Number} [level] A heading level (e.g., 1 becomes &lt;h1&gt;)
1089 * @param {Number} [level] A heading level (e.g., 1 becomes &lt;h1&gt;)
1088 */
1090 */
1089 Notebook.prototype.to_heading = function (index, level) {
1091 Notebook.prototype.to_heading = function (index, level) {
1090 level = level || 1;
1092 level = level || 1;
1091 var i = this.index_or_selected(index);
1093 var i = this.index_or_selected(index);
1092 if (this.is_valid_cell_index(i)) {
1094 if (this.is_valid_cell_index(i)) {
1093 var source_cell = this.get_cell(i);
1095 var source_cell = this.get_cell(i);
1094 var target_cell = null;
1096 var target_cell = null;
1095 if (source_cell instanceof textcell.HeadingCell) {
1097 if (source_cell instanceof textcell.MarkdownCell) {
1096 source_cell.set_level(level);
1098 source_cell.set_heading_level(level);
1097 } else {
1099 } else {
1098 target_cell = this.insert_cell_below('heading',i);
1100 target_cell = this.insert_cell_below('markdown',i);
1099 var text = source_cell.get_text();
1101 var text = source_cell.get_text();
1100 if (text === source_cell.placeholder) {
1102 if (text === source_cell.placeholder) {
1101 text = '';
1103 text = '';
1102 }
1104 }
1103 //metadata
1105 //metadata
1104 target_cell.metadata = source_cell.metadata;
1106 target_cell.metadata = source_cell.metadata;
1105 // We must show the editor before setting its contents
1107 // We must show the editor before setting its contents
1106 target_cell.set_level(level);
1107 target_cell.unrender();
1108 target_cell.unrender();
1108 target_cell.set_text(text);
1109 target_cell.set_text(text);
1110 target_cell.set_heading_level(level);
1109 // make this value the starting point, so that we can only undo
1111 // make this value the starting point, so that we can only undo
1110 // to this state, instead of a blank cell
1112 // to this state, instead of a blank cell
1111 target_cell.code_mirror.clearHistory();
1113 target_cell.code_mirror.clearHistory();
1112 source_cell.element.remove();
1114 source_cell.element.remove();
1113 this.select(i);
1115 this.select(i);
1114 var cursor = source_cell.code_mirror.getCursor();
1116 var cursor = source_cell.code_mirror.getCursor();
1115 target_cell.code_mirror.setCursor(cursor);
1117 target_cell.code_mirror.setCursor(cursor);
1116 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1118 if ((source_cell instanceof textcell.TextCell) && source_cell.rendered) {
1117 target_cell.render();
1119 target_cell.render();
1118 }
1120 }
1119 }
1121 }
1120 this.set_dirty(true);
1122 this.set_dirty(true);
1121 this.events.trigger('selected_cell_type_changed.Notebook',
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 // Cut/Copy/Paste
1130 // Cut/Copy/Paste
1129
1131
1130 /**
1132 /**
1131 * Enable UI elements for pasting cells.
1133 * Enable UI elements for pasting cells.
1132 *
1134 *
1133 * @method enable_paste
1135 * @method enable_paste
1134 */
1136 */
1135 Notebook.prototype.enable_paste = function () {
1137 Notebook.prototype.enable_paste = function () {
1136 var that = this;
1138 var that = this;
1137 if (!this.paste_enabled) {
1139 if (!this.paste_enabled) {
1138 $('#paste_cell_replace').removeClass('disabled')
1140 $('#paste_cell_replace').removeClass('disabled')
1139 .on('click', function () {that.paste_cell_replace();});
1141 .on('click', function () {that.paste_cell_replace();});
1140 $('#paste_cell_above').removeClass('disabled')
1142 $('#paste_cell_above').removeClass('disabled')
1141 .on('click', function () {that.paste_cell_above();});
1143 .on('click', function () {that.paste_cell_above();});
1142 $('#paste_cell_below').removeClass('disabled')
1144 $('#paste_cell_below').removeClass('disabled')
1143 .on('click', function () {that.paste_cell_below();});
1145 .on('click', function () {that.paste_cell_below();});
1144 this.paste_enabled = true;
1146 this.paste_enabled = true;
1145 }
1147 }
1146 };
1148 };
1147
1149
1148 /**
1150 /**
1149 * Disable UI elements for pasting cells.
1151 * Disable UI elements for pasting cells.
1150 *
1152 *
1151 * @method disable_paste
1153 * @method disable_paste
1152 */
1154 */
1153 Notebook.prototype.disable_paste = function () {
1155 Notebook.prototype.disable_paste = function () {
1154 if (this.paste_enabled) {
1156 if (this.paste_enabled) {
1155 $('#paste_cell_replace').addClass('disabled').off('click');
1157 $('#paste_cell_replace').addClass('disabled').off('click');
1156 $('#paste_cell_above').addClass('disabled').off('click');
1158 $('#paste_cell_above').addClass('disabled').off('click');
1157 $('#paste_cell_below').addClass('disabled').off('click');
1159 $('#paste_cell_below').addClass('disabled').off('click');
1158 this.paste_enabled = false;
1160 this.paste_enabled = false;
1159 }
1161 }
1160 };
1162 };
1161
1163
1162 /**
1164 /**
1163 * Cut a cell.
1165 * Cut a cell.
1164 *
1166 *
1165 * @method cut_cell
1167 * @method cut_cell
1166 */
1168 */
1167 Notebook.prototype.cut_cell = function () {
1169 Notebook.prototype.cut_cell = function () {
1168 this.copy_cell();
1170 this.copy_cell();
1169 this.delete_cell();
1171 this.delete_cell();
1170 };
1172 };
1171
1173
1172 /**
1174 /**
1173 * Copy a cell.
1175 * Copy a cell.
1174 *
1176 *
1175 * @method copy_cell
1177 * @method copy_cell
1176 */
1178 */
1177 Notebook.prototype.copy_cell = function () {
1179 Notebook.prototype.copy_cell = function () {
1178 var cell = this.get_selected_cell();
1180 var cell = this.get_selected_cell();
1179 this.clipboard = cell.toJSON();
1181 this.clipboard = cell.toJSON();
1180 // remove undeletable status from the copied cell
1182 // remove undeletable status from the copied cell
1181 if (this.clipboard.metadata.deletable !== undefined) {
1183 if (this.clipboard.metadata.deletable !== undefined) {
1182 delete this.clipboard.metadata.deletable;
1184 delete this.clipboard.metadata.deletable;
1183 }
1185 }
1184 this.enable_paste();
1186 this.enable_paste();
1185 };
1187 };
1186
1188
1187 /**
1189 /**
1188 * Replace the selected cell with a cell in the clipboard.
1190 * Replace the selected cell with a cell in the clipboard.
1189 *
1191 *
1190 * @method paste_cell_replace
1192 * @method paste_cell_replace
1191 */
1193 */
1192 Notebook.prototype.paste_cell_replace = function () {
1194 Notebook.prototype.paste_cell_replace = function () {
1193 if (this.clipboard !== null && this.paste_enabled) {
1195 if (this.clipboard !== null && this.paste_enabled) {
1194 var cell_data = this.clipboard;
1196 var cell_data = this.clipboard;
1195 var new_cell = this.insert_cell_above(cell_data.cell_type);
1197 var new_cell = this.insert_cell_above(cell_data.cell_type);
1196 new_cell.fromJSON(cell_data);
1198 new_cell.fromJSON(cell_data);
1197 var old_cell = this.get_next_cell(new_cell);
1199 var old_cell = this.get_next_cell(new_cell);
1198 this.delete_cell(this.find_cell_index(old_cell));
1200 this.delete_cell(this.find_cell_index(old_cell));
1199 this.select(this.find_cell_index(new_cell));
1201 this.select(this.find_cell_index(new_cell));
1200 }
1202 }
1201 };
1203 };
1202
1204
1203 /**
1205 /**
1204 * Paste a cell from the clipboard above the selected cell.
1206 * Paste a cell from the clipboard above the selected cell.
1205 *
1207 *
1206 * @method paste_cell_above
1208 * @method paste_cell_above
1207 */
1209 */
1208 Notebook.prototype.paste_cell_above = function () {
1210 Notebook.prototype.paste_cell_above = function () {
1209 if (this.clipboard !== null && this.paste_enabled) {
1211 if (this.clipboard !== null && this.paste_enabled) {
1210 var cell_data = this.clipboard;
1212 var cell_data = this.clipboard;
1211 var new_cell = this.insert_cell_above(cell_data.cell_type);
1213 var new_cell = this.insert_cell_above(cell_data.cell_type);
1212 new_cell.fromJSON(cell_data);
1214 new_cell.fromJSON(cell_data);
1213 new_cell.focus_cell();
1215 new_cell.focus_cell();
1214 }
1216 }
1215 };
1217 };
1216
1218
1217 /**
1219 /**
1218 * Paste a cell from the clipboard below the selected cell.
1220 * Paste a cell from the clipboard below the selected cell.
1219 *
1221 *
1220 * @method paste_cell_below
1222 * @method paste_cell_below
1221 */
1223 */
1222 Notebook.prototype.paste_cell_below = function () {
1224 Notebook.prototype.paste_cell_below = function () {
1223 if (this.clipboard !== null && this.paste_enabled) {
1225 if (this.clipboard !== null && this.paste_enabled) {
1224 var cell_data = this.clipboard;
1226 var cell_data = this.clipboard;
1225 var new_cell = this.insert_cell_below(cell_data.cell_type);
1227 var new_cell = this.insert_cell_below(cell_data.cell_type);
1226 new_cell.fromJSON(cell_data);
1228 new_cell.fromJSON(cell_data);
1227 new_cell.focus_cell();
1229 new_cell.focus_cell();
1228 }
1230 }
1229 };
1231 };
1230
1232
1231 // Split/merge
1233 // Split/merge
1232
1234
1233 /**
1235 /**
1234 * Split the selected cell into two, at the cursor.
1236 * Split the selected cell into two, at the cursor.
1235 *
1237 *
1236 * @method split_cell
1238 * @method split_cell
1237 */
1239 */
1238 Notebook.prototype.split_cell = function () {
1240 Notebook.prototype.split_cell = function () {
1239 var mdc = textcell.MarkdownCell;
1241 var mdc = textcell.MarkdownCell;
1240 var rc = textcell.RawCell;
1242 var rc = textcell.RawCell;
1241 var cell = this.get_selected_cell();
1243 var cell = this.get_selected_cell();
1242 if (cell.is_splittable()) {
1244 if (cell.is_splittable()) {
1243 var texta = cell.get_pre_cursor();
1245 var texta = cell.get_pre_cursor();
1244 var textb = cell.get_post_cursor();
1246 var textb = cell.get_post_cursor();
1245 cell.set_text(textb);
1247 cell.set_text(textb);
1246 var new_cell = this.insert_cell_above(cell.cell_type);
1248 var new_cell = this.insert_cell_above(cell.cell_type);
1247 // Unrender the new cell so we can call set_text.
1249 // Unrender the new cell so we can call set_text.
1248 new_cell.unrender();
1250 new_cell.unrender();
1249 new_cell.set_text(texta);
1251 new_cell.set_text(texta);
1250 }
1252 }
1251 };
1253 };
1252
1254
1253 /**
1255 /**
1254 * Combine the selected cell into the cell above it.
1256 * Combine the selected cell into the cell above it.
1255 *
1257 *
1256 * @method merge_cell_above
1258 * @method merge_cell_above
1257 */
1259 */
1258 Notebook.prototype.merge_cell_above = function () {
1260 Notebook.prototype.merge_cell_above = function () {
1259 var mdc = textcell.MarkdownCell;
1261 var mdc = textcell.MarkdownCell;
1260 var rc = textcell.RawCell;
1262 var rc = textcell.RawCell;
1261 var index = this.get_selected_index();
1263 var index = this.get_selected_index();
1262 var cell = this.get_cell(index);
1264 var cell = this.get_cell(index);
1263 var render = cell.rendered;
1265 var render = cell.rendered;
1264 if (!cell.is_mergeable()) {
1266 if (!cell.is_mergeable()) {
1265 return;
1267 return;
1266 }
1268 }
1267 if (index > 0) {
1269 if (index > 0) {
1268 var upper_cell = this.get_cell(index-1);
1270 var upper_cell = this.get_cell(index-1);
1269 if (!upper_cell.is_mergeable()) {
1271 if (!upper_cell.is_mergeable()) {
1270 return;
1272 return;
1271 }
1273 }
1272 var upper_text = upper_cell.get_text();
1274 var upper_text = upper_cell.get_text();
1273 var text = cell.get_text();
1275 var text = cell.get_text();
1274 if (cell instanceof codecell.CodeCell) {
1276 if (cell instanceof codecell.CodeCell) {
1275 cell.set_text(upper_text+'\n'+text);
1277 cell.set_text(upper_text+'\n'+text);
1276 } else {
1278 } else {
1277 cell.unrender(); // Must unrender before we set_text.
1279 cell.unrender(); // Must unrender before we set_text.
1278 cell.set_text(upper_text+'\n\n'+text);
1280 cell.set_text(upper_text+'\n\n'+text);
1279 if (render) {
1281 if (render) {
1280 // The rendered state of the final cell should match
1282 // The rendered state of the final cell should match
1281 // that of the original selected cell;
1283 // that of the original selected cell;
1282 cell.render();
1284 cell.render();
1283 }
1285 }
1284 }
1286 }
1285 this.delete_cell(index-1);
1287 this.delete_cell(index-1);
1286 this.select(this.find_cell_index(cell));
1288 this.select(this.find_cell_index(cell));
1287 }
1289 }
1288 };
1290 };
1289
1291
1290 /**
1292 /**
1291 * Combine the selected cell into the cell below it.
1293 * Combine the selected cell into the cell below it.
1292 *
1294 *
1293 * @method merge_cell_below
1295 * @method merge_cell_below
1294 */
1296 */
1295 Notebook.prototype.merge_cell_below = function () {
1297 Notebook.prototype.merge_cell_below = function () {
1296 var mdc = textcell.MarkdownCell;
1298 var mdc = textcell.MarkdownCell;
1297 var rc = textcell.RawCell;
1299 var rc = textcell.RawCell;
1298 var index = this.get_selected_index();
1300 var index = this.get_selected_index();
1299 var cell = this.get_cell(index);
1301 var cell = this.get_cell(index);
1300 var render = cell.rendered;
1302 var render = cell.rendered;
1301 if (!cell.is_mergeable()) {
1303 if (!cell.is_mergeable()) {
1302 return;
1304 return;
1303 }
1305 }
1304 if (index < this.ncells()-1) {
1306 if (index < this.ncells()-1) {
1305 var lower_cell = this.get_cell(index+1);
1307 var lower_cell = this.get_cell(index+1);
1306 if (!lower_cell.is_mergeable()) {
1308 if (!lower_cell.is_mergeable()) {
1307 return;
1309 return;
1308 }
1310 }
1309 var lower_text = lower_cell.get_text();
1311 var lower_text = lower_cell.get_text();
1310 var text = cell.get_text();
1312 var text = cell.get_text();
1311 if (cell instanceof codecell.CodeCell) {
1313 if (cell instanceof codecell.CodeCell) {
1312 cell.set_text(text+'\n'+lower_text);
1314 cell.set_text(text+'\n'+lower_text);
1313 } else {
1315 } else {
1314 cell.unrender(); // Must unrender before we set_text.
1316 cell.unrender(); // Must unrender before we set_text.
1315 cell.set_text(text+'\n\n'+lower_text);
1317 cell.set_text(text+'\n\n'+lower_text);
1316 if (render) {
1318 if (render) {
1317 // The rendered state of the final cell should match
1319 // The rendered state of the final cell should match
1318 // that of the original selected cell;
1320 // that of the original selected cell;
1319 cell.render();
1321 cell.render();
1320 }
1322 }
1321 }
1323 }
1322 this.delete_cell(index+1);
1324 this.delete_cell(index+1);
1323 this.select(this.find_cell_index(cell));
1325 this.select(this.find_cell_index(cell));
1324 }
1326 }
1325 };
1327 };
1326
1328
1327
1329
1328 // Cell collapsing and output clearing
1330 // Cell collapsing and output clearing
1329
1331
1330 /**
1332 /**
1331 * Hide a cell's output.
1333 * Hide a cell's output.
1332 *
1334 *
1333 * @method collapse_output
1335 * @method collapse_output
1334 * @param {Number} index A cell's numeric index
1336 * @param {Number} index A cell's numeric index
1335 */
1337 */
1336 Notebook.prototype.collapse_output = function (index) {
1338 Notebook.prototype.collapse_output = function (index) {
1337 var i = this.index_or_selected(index);
1339 var i = this.index_or_selected(index);
1338 var cell = this.get_cell(i);
1340 var cell = this.get_cell(i);
1339 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1341 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1340 cell.collapse_output();
1342 cell.collapse_output();
1341 this.set_dirty(true);
1343 this.set_dirty(true);
1342 }
1344 }
1343 };
1345 };
1344
1346
1345 /**
1347 /**
1346 * Hide each code cell's output area.
1348 * Hide each code cell's output area.
1347 *
1349 *
1348 * @method collapse_all_output
1350 * @method collapse_all_output
1349 */
1351 */
1350 Notebook.prototype.collapse_all_output = function () {
1352 Notebook.prototype.collapse_all_output = function () {
1351 $.map(this.get_cells(), function (cell, i) {
1353 $.map(this.get_cells(), function (cell, i) {
1352 if (cell instanceof codecell.CodeCell) {
1354 if (cell instanceof codecell.CodeCell) {
1353 cell.collapse_output();
1355 cell.collapse_output();
1354 }
1356 }
1355 });
1357 });
1356 // this should not be set if the `collapse` key is removed from nbformat
1358 // this should not be set if the `collapse` key is removed from nbformat
1357 this.set_dirty(true);
1359 this.set_dirty(true);
1358 };
1360 };
1359
1361
1360 /**
1362 /**
1361 * Show a cell's output.
1363 * Show a cell's output.
1362 *
1364 *
1363 * @method expand_output
1365 * @method expand_output
1364 * @param {Number} index A cell's numeric index
1366 * @param {Number} index A cell's numeric index
1365 */
1367 */
1366 Notebook.prototype.expand_output = function (index) {
1368 Notebook.prototype.expand_output = function (index) {
1367 var i = this.index_or_selected(index);
1369 var i = this.index_or_selected(index);
1368 var cell = this.get_cell(i);
1370 var cell = this.get_cell(i);
1369 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1371 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1370 cell.expand_output();
1372 cell.expand_output();
1371 this.set_dirty(true);
1373 this.set_dirty(true);
1372 }
1374 }
1373 };
1375 };
1374
1376
1375 /**
1377 /**
1376 * Expand each code cell's output area, and remove scrollbars.
1378 * Expand each code cell's output area, and remove scrollbars.
1377 *
1379 *
1378 * @method expand_all_output
1380 * @method expand_all_output
1379 */
1381 */
1380 Notebook.prototype.expand_all_output = function () {
1382 Notebook.prototype.expand_all_output = function () {
1381 $.map(this.get_cells(), function (cell, i) {
1383 $.map(this.get_cells(), function (cell, i) {
1382 if (cell instanceof codecell.CodeCell) {
1384 if (cell instanceof codecell.CodeCell) {
1383 cell.expand_output();
1385 cell.expand_output();
1384 }
1386 }
1385 });
1387 });
1386 // this should not be set if the `collapse` key is removed from nbformat
1388 // this should not be set if the `collapse` key is removed from nbformat
1387 this.set_dirty(true);
1389 this.set_dirty(true);
1388 };
1390 };
1389
1391
1390 /**
1392 /**
1391 * Clear the selected CodeCell's output area.
1393 * Clear the selected CodeCell's output area.
1392 *
1394 *
1393 * @method clear_output
1395 * @method clear_output
1394 * @param {Number} index A cell's numeric index
1396 * @param {Number} index A cell's numeric index
1395 */
1397 */
1396 Notebook.prototype.clear_output = function (index) {
1398 Notebook.prototype.clear_output = function (index) {
1397 var i = this.index_or_selected(index);
1399 var i = this.index_or_selected(index);
1398 var cell = this.get_cell(i);
1400 var cell = this.get_cell(i);
1399 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1401 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1400 cell.clear_output();
1402 cell.clear_output();
1401 this.set_dirty(true);
1403 this.set_dirty(true);
1402 }
1404 }
1403 };
1405 };
1404
1406
1405 /**
1407 /**
1406 * Clear each code cell's output area.
1408 * Clear each code cell's output area.
1407 *
1409 *
1408 * @method clear_all_output
1410 * @method clear_all_output
1409 */
1411 */
1410 Notebook.prototype.clear_all_output = function () {
1412 Notebook.prototype.clear_all_output = function () {
1411 $.map(this.get_cells(), function (cell, i) {
1413 $.map(this.get_cells(), function (cell, i) {
1412 if (cell instanceof codecell.CodeCell) {
1414 if (cell instanceof codecell.CodeCell) {
1413 cell.clear_output();
1415 cell.clear_output();
1414 }
1416 }
1415 });
1417 });
1416 this.set_dirty(true);
1418 this.set_dirty(true);
1417 };
1419 };
1418
1420
1419 /**
1421 /**
1420 * Scroll the selected CodeCell's output area.
1422 * Scroll the selected CodeCell's output area.
1421 *
1423 *
1422 * @method scroll_output
1424 * @method scroll_output
1423 * @param {Number} index A cell's numeric index
1425 * @param {Number} index A cell's numeric index
1424 */
1426 */
1425 Notebook.prototype.scroll_output = function (index) {
1427 Notebook.prototype.scroll_output = function (index) {
1426 var i = this.index_or_selected(index);
1428 var i = this.index_or_selected(index);
1427 var cell = this.get_cell(i);
1429 var cell = this.get_cell(i);
1428 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1430 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1429 cell.scroll_output();
1431 cell.scroll_output();
1430 this.set_dirty(true);
1432 this.set_dirty(true);
1431 }
1433 }
1432 };
1434 };
1433
1435
1434 /**
1436 /**
1435 * Expand each code cell's output area, and add a scrollbar for long output.
1437 * Expand each code cell's output area, and add a scrollbar for long output.
1436 *
1438 *
1437 * @method scroll_all_output
1439 * @method scroll_all_output
1438 */
1440 */
1439 Notebook.prototype.scroll_all_output = function () {
1441 Notebook.prototype.scroll_all_output = function () {
1440 $.map(this.get_cells(), function (cell, i) {
1442 $.map(this.get_cells(), function (cell, i) {
1441 if (cell instanceof codecell.CodeCell) {
1443 if (cell instanceof codecell.CodeCell) {
1442 cell.scroll_output();
1444 cell.scroll_output();
1443 }
1445 }
1444 });
1446 });
1445 // this should not be set if the `collapse` key is removed from nbformat
1447 // this should not be set if the `collapse` key is removed from nbformat
1446 this.set_dirty(true);
1448 this.set_dirty(true);
1447 };
1449 };
1448
1450
1449 /** Toggle whether a cell's output is collapsed or expanded.
1451 /** Toggle whether a cell's output is collapsed or expanded.
1450 *
1452 *
1451 * @method toggle_output
1453 * @method toggle_output
1452 * @param {Number} index A cell's numeric index
1454 * @param {Number} index A cell's numeric index
1453 */
1455 */
1454 Notebook.prototype.toggle_output = function (index) {
1456 Notebook.prototype.toggle_output = function (index) {
1455 var i = this.index_or_selected(index);
1457 var i = this.index_or_selected(index);
1456 var cell = this.get_cell(i);
1458 var cell = this.get_cell(i);
1457 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1459 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1458 cell.toggle_output();
1460 cell.toggle_output();
1459 this.set_dirty(true);
1461 this.set_dirty(true);
1460 }
1462 }
1461 };
1463 };
1462
1464
1463 /**
1465 /**
1464 * Hide/show the output of all cells.
1466 * Hide/show the output of all cells.
1465 *
1467 *
1466 * @method toggle_all_output
1468 * @method toggle_all_output
1467 */
1469 */
1468 Notebook.prototype.toggle_all_output = function () {
1470 Notebook.prototype.toggle_all_output = function () {
1469 $.map(this.get_cells(), function (cell, i) {
1471 $.map(this.get_cells(), function (cell, i) {
1470 if (cell instanceof codecell.CodeCell) {
1472 if (cell instanceof codecell.CodeCell) {
1471 cell.toggle_output();
1473 cell.toggle_output();
1472 }
1474 }
1473 });
1475 });
1474 // this should not be set if the `collapse` key is removed from nbformat
1476 // this should not be set if the `collapse` key is removed from nbformat
1475 this.set_dirty(true);
1477 this.set_dirty(true);
1476 };
1478 };
1477
1479
1478 /**
1480 /**
1479 * Toggle a scrollbar for long cell outputs.
1481 * Toggle a scrollbar for long cell outputs.
1480 *
1482 *
1481 * @method toggle_output_scroll
1483 * @method toggle_output_scroll
1482 * @param {Number} index A cell's numeric index
1484 * @param {Number} index A cell's numeric index
1483 */
1485 */
1484 Notebook.prototype.toggle_output_scroll = function (index) {
1486 Notebook.prototype.toggle_output_scroll = function (index) {
1485 var i = this.index_or_selected(index);
1487 var i = this.index_or_selected(index);
1486 var cell = this.get_cell(i);
1488 var cell = this.get_cell(i);
1487 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1489 if (cell !== null && (cell instanceof codecell.CodeCell)) {
1488 cell.toggle_output_scroll();
1490 cell.toggle_output_scroll();
1489 this.set_dirty(true);
1491 this.set_dirty(true);
1490 }
1492 }
1491 };
1493 };
1492
1494
1493 /**
1495 /**
1494 * Toggle the scrolling of long output on all cells.
1496 * Toggle the scrolling of long output on all cells.
1495 *
1497 *
1496 * @method toggle_all_output_scrolling
1498 * @method toggle_all_output_scrolling
1497 */
1499 */
1498 Notebook.prototype.toggle_all_output_scroll = function () {
1500 Notebook.prototype.toggle_all_output_scroll = function () {
1499 $.map(this.get_cells(), function (cell, i) {
1501 $.map(this.get_cells(), function (cell, i) {
1500 if (cell instanceof codecell.CodeCell) {
1502 if (cell instanceof codecell.CodeCell) {
1501 cell.toggle_output_scroll();
1503 cell.toggle_output_scroll();
1502 }
1504 }
1503 });
1505 });
1504 // this should not be set if the `collapse` key is removed from nbformat
1506 // this should not be set if the `collapse` key is removed from nbformat
1505 this.set_dirty(true);
1507 this.set_dirty(true);
1506 };
1508 };
1507
1509
1508 // Other cell functions: line numbers, ...
1510 // Other cell functions: line numbers, ...
1509
1511
1510 /**
1512 /**
1511 * Toggle line numbers in the selected cell's input area.
1513 * Toggle line numbers in the selected cell's input area.
1512 *
1514 *
1513 * @method cell_toggle_line_numbers
1515 * @method cell_toggle_line_numbers
1514 */
1516 */
1515 Notebook.prototype.cell_toggle_line_numbers = function() {
1517 Notebook.prototype.cell_toggle_line_numbers = function() {
1516 this.get_selected_cell().toggle_line_numbers();
1518 this.get_selected_cell().toggle_line_numbers();
1517 };
1519 };
1518
1520
1519 /**
1521 /**
1520 * Set the codemirror mode for all code cells, including the default for
1522 * Set the codemirror mode for all code cells, including the default for
1521 * new code cells.
1523 * new code cells.
1522 *
1524 *
1523 * @method set_codemirror_mode
1525 * @method set_codemirror_mode
1524 */
1526 */
1525 Notebook.prototype.set_codemirror_mode = function(newmode){
1527 Notebook.prototype.set_codemirror_mode = function(newmode){
1526 if (newmode === this.codemirror_mode) {
1528 if (newmode === this.codemirror_mode) {
1527 return;
1529 return;
1528 }
1530 }
1529 this.codemirror_mode = newmode;
1531 this.codemirror_mode = newmode;
1530 codecell.CodeCell.options_default.cm_config.mode = newmode;
1532 codecell.CodeCell.options_default.cm_config.mode = newmode;
1531 modename = newmode.mode || newmode.name || newmode
1533 modename = newmode.mode || newmode.name || newmode;
1532
1534
1533 that = this;
1535 that = this;
1534 utils.requireCodeMirrorMode(modename, function () {
1536 utils.requireCodeMirrorMode(modename, function () {
1535 $.map(that.get_cells(), function(cell, i) {
1537 $.map(that.get_cells(), function(cell, i) {
1536 if (cell.cell_type === 'code'){
1538 if (cell.cell_type === 'code'){
1537 cell.code_mirror.setOption('mode', newmode);
1539 cell.code_mirror.setOption('mode', newmode);
1538 // This is currently redundant, because cm_config ends up as
1540 // This is currently redundant, because cm_config ends up as
1539 // codemirror's own .options object, but I don't want to
1541 // codemirror's own .options object, but I don't want to
1540 // rely on that.
1542 // rely on that.
1541 cell.cm_config.mode = newmode;
1543 cell.cm_config.mode = newmode;
1542 }
1544 }
1543 });
1545 });
1544 })
1546 });
1545 };
1547 };
1546
1548
1547 // Session related things
1549 // Session related things
1548
1550
1549 /**
1551 /**
1550 * Start a new session and set it on each code cell.
1552 * Start a new session and set it on each code cell.
1551 *
1553 *
1552 * @method start_session
1554 * @method start_session
1553 */
1555 */
1554 Notebook.prototype.start_session = function (kernel_name) {
1556 Notebook.prototype.start_session = function (kernel_name) {
1555 var that = this;
1557 var that = this;
1556 if (this._session_starting) {
1558 if (this._session_starting) {
1557 throw new session.SessionAlreadyStarting();
1559 throw new session.SessionAlreadyStarting();
1558 }
1560 }
1559 this._session_starting = true;
1561 this._session_starting = true;
1560
1562
1561 var options = {
1563 var options = {
1562 base_url: this.base_url,
1564 base_url: this.base_url,
1563 ws_url: this.ws_url,
1565 ws_url: this.ws_url,
1564 notebook_path: this.notebook_path,
1566 notebook_path: this.notebook_path,
1565 notebook_name: this.notebook_name,
1567 notebook_name: this.notebook_name,
1566 kernel_name: kernel_name,
1568 kernel_name: kernel_name,
1567 notebook: this
1569 notebook: this
1568 };
1570 };
1569
1571
1570 var success = $.proxy(this._session_started, this);
1572 var success = $.proxy(this._session_started, this);
1571 var failure = $.proxy(this._session_start_failed, this);
1573 var failure = $.proxy(this._session_start_failed, this);
1572
1574
1573 if (this.session !== null) {
1575 if (this.session !== null) {
1574 this.session.restart(options, success, failure);
1576 this.session.restart(options, success, failure);
1575 } else {
1577 } else {
1576 this.session = new session.Session(options);
1578 this.session = new session.Session(options);
1577 this.session.start(success, failure);
1579 this.session.start(success, failure);
1578 }
1580 }
1579 };
1581 };
1580
1582
1581
1583
1582 /**
1584 /**
1583 * Once a session is started, link the code cells to the kernel and pass the
1585 * Once a session is started, link the code cells to the kernel and pass the
1584 * comm manager to the widget manager
1586 * comm manager to the widget manager
1585 *
1587 *
1586 */
1588 */
1587 Notebook.prototype._session_started = function (){
1589 Notebook.prototype._session_started = function (){
1588 this._session_starting = false;
1590 this._session_starting = false;
1589 this.kernel = this.session.kernel;
1591 this.kernel = this.session.kernel;
1590 var ncells = this.ncells();
1592 var ncells = this.ncells();
1591 for (var i=0; i<ncells; i++) {
1593 for (var i=0; i<ncells; i++) {
1592 var cell = this.get_cell(i);
1594 var cell = this.get_cell(i);
1593 if (cell instanceof codecell.CodeCell) {
1595 if (cell instanceof codecell.CodeCell) {
1594 cell.set_kernel(this.session.kernel);
1596 cell.set_kernel(this.session.kernel);
1595 }
1597 }
1596 }
1598 }
1597 };
1599 };
1598 Notebook.prototype._session_start_failed = function (jqxhr, status, error){
1600 Notebook.prototype._session_start_failed = function (jqxhr, status, error){
1599 this._session_starting = false;
1601 this._session_starting = false;
1600 utils.log_ajax_error(jqxhr, status, error);
1602 utils.log_ajax_error(jqxhr, status, error);
1601 };
1603 };
1602
1604
1603 /**
1605 /**
1604 * Prompt the user to restart the IPython kernel.
1606 * Prompt the user to restart the IPython kernel.
1605 *
1607 *
1606 * @method restart_kernel
1608 * @method restart_kernel
1607 */
1609 */
1608 Notebook.prototype.restart_kernel = function () {
1610 Notebook.prototype.restart_kernel = function () {
1609 var that = this;
1611 var that = this;
1610 dialog.modal({
1612 dialog.modal({
1611 notebook: this,
1613 notebook: this,
1612 keyboard_manager: this.keyboard_manager,
1614 keyboard_manager: this.keyboard_manager,
1613 title : "Restart kernel or continue running?",
1615 title : "Restart kernel or continue running?",
1614 body : $("<p/>").text(
1616 body : $("<p/>").text(
1615 'Do you want to restart the current kernel? You will lose all variables defined in it.'
1617 'Do you want to restart the current kernel? You will lose all variables defined in it.'
1616 ),
1618 ),
1617 buttons : {
1619 buttons : {
1618 "Continue running" : {},
1620 "Continue running" : {},
1619 "Restart" : {
1621 "Restart" : {
1620 "class" : "btn-danger",
1622 "class" : "btn-danger",
1621 "click" : function() {
1623 "click" : function() {
1622 that.kernel.restart();
1624 that.kernel.restart();
1623 }
1625 }
1624 }
1626 }
1625 }
1627 }
1626 });
1628 });
1627 };
1629 };
1628
1630
1629 /**
1631 /**
1630 * Execute or render cell outputs and go into command mode.
1632 * Execute or render cell outputs and go into command mode.
1631 *
1633 *
1632 * @method execute_cell
1634 * @method execute_cell
1633 */
1635 */
1634 Notebook.prototype.execute_cell = function () {
1636 Notebook.prototype.execute_cell = function () {
1635 // mode = shift, ctrl, alt
1637 // mode = shift, ctrl, alt
1636 var cell = this.get_selected_cell();
1638 var cell = this.get_selected_cell();
1637 var cell_index = this.find_cell_index(cell);
1639 var cell_index = this.find_cell_index(cell);
1638
1640
1639 cell.execute();
1641 cell.execute();
1640 this.command_mode();
1642 this.command_mode();
1641 this.set_dirty(true);
1643 this.set_dirty(true);
1642 };
1644 };
1643
1645
1644 /**
1646 /**
1645 * Execute or render cell outputs and insert a new cell below.
1647 * Execute or render cell outputs and insert a new cell below.
1646 *
1648 *
1647 * @method execute_cell_and_insert_below
1649 * @method execute_cell_and_insert_below
1648 */
1650 */
1649 Notebook.prototype.execute_cell_and_insert_below = function () {
1651 Notebook.prototype.execute_cell_and_insert_below = function () {
1650 var cell = this.get_selected_cell();
1652 var cell = this.get_selected_cell();
1651 var cell_index = this.find_cell_index(cell);
1653 var cell_index = this.find_cell_index(cell);
1652
1654
1653 cell.execute();
1655 cell.execute();
1654
1656
1655 // If we are at the end always insert a new cell and return
1657 // If we are at the end always insert a new cell and return
1656 if (cell_index === (this.ncells()-1)) {
1658 if (cell_index === (this.ncells()-1)) {
1657 this.command_mode();
1659 this.command_mode();
1658 this.insert_cell_below();
1660 this.insert_cell_below();
1659 this.select(cell_index+1);
1661 this.select(cell_index+1);
1660 this.edit_mode();
1662 this.edit_mode();
1661 this.scroll_to_bottom();
1663 this.scroll_to_bottom();
1662 this.set_dirty(true);
1664 this.set_dirty(true);
1663 return;
1665 return;
1664 }
1666 }
1665
1667
1666 this.command_mode();
1668 this.command_mode();
1667 this.insert_cell_below();
1669 this.insert_cell_below();
1668 this.select(cell_index+1);
1670 this.select(cell_index+1);
1669 this.edit_mode();
1671 this.edit_mode();
1670 this.set_dirty(true);
1672 this.set_dirty(true);
1671 };
1673 };
1672
1674
1673 /**
1675 /**
1674 * Execute or render cell outputs and select the next cell.
1676 * Execute or render cell outputs and select the next cell.
1675 *
1677 *
1676 * @method execute_cell_and_select_below
1678 * @method execute_cell_and_select_below
1677 */
1679 */
1678 Notebook.prototype.execute_cell_and_select_below = function () {
1680 Notebook.prototype.execute_cell_and_select_below = function () {
1679
1681
1680 var cell = this.get_selected_cell();
1682 var cell = this.get_selected_cell();
1681 var cell_index = this.find_cell_index(cell);
1683 var cell_index = this.find_cell_index(cell);
1682
1684
1683 cell.execute();
1685 cell.execute();
1684
1686
1685 // If we are at the end always insert a new cell and return
1687 // If we are at the end always insert a new cell and return
1686 if (cell_index === (this.ncells()-1)) {
1688 if (cell_index === (this.ncells()-1)) {
1687 this.command_mode();
1689 this.command_mode();
1688 this.insert_cell_below();
1690 this.insert_cell_below();
1689 this.select(cell_index+1);
1691 this.select(cell_index+1);
1690 this.edit_mode();
1692 this.edit_mode();
1691 this.scroll_to_bottom();
1693 this.scroll_to_bottom();
1692 this.set_dirty(true);
1694 this.set_dirty(true);
1693 return;
1695 return;
1694 }
1696 }
1695
1697
1696 this.command_mode();
1698 this.command_mode();
1697 this.select(cell_index+1);
1699 this.select(cell_index+1);
1698 this.focus_cell();
1700 this.focus_cell();
1699 this.set_dirty(true);
1701 this.set_dirty(true);
1700 };
1702 };
1701
1703
1702 /**
1704 /**
1703 * Execute all cells below the selected cell.
1705 * Execute all cells below the selected cell.
1704 *
1706 *
1705 * @method execute_cells_below
1707 * @method execute_cells_below
1706 */
1708 */
1707 Notebook.prototype.execute_cells_below = function () {
1709 Notebook.prototype.execute_cells_below = function () {
1708 this.execute_cell_range(this.get_selected_index(), this.ncells());
1710 this.execute_cell_range(this.get_selected_index(), this.ncells());
1709 this.scroll_to_bottom();
1711 this.scroll_to_bottom();
1710 };
1712 };
1711
1713
1712 /**
1714 /**
1713 * Execute all cells above the selected cell.
1715 * Execute all cells above the selected cell.
1714 *
1716 *
1715 * @method execute_cells_above
1717 * @method execute_cells_above
1716 */
1718 */
1717 Notebook.prototype.execute_cells_above = function () {
1719 Notebook.prototype.execute_cells_above = function () {
1718 this.execute_cell_range(0, this.get_selected_index());
1720 this.execute_cell_range(0, this.get_selected_index());
1719 };
1721 };
1720
1722
1721 /**
1723 /**
1722 * Execute all cells.
1724 * Execute all cells.
1723 *
1725 *
1724 * @method execute_all_cells
1726 * @method execute_all_cells
1725 */
1727 */
1726 Notebook.prototype.execute_all_cells = function () {
1728 Notebook.prototype.execute_all_cells = function () {
1727 this.execute_cell_range(0, this.ncells());
1729 this.execute_cell_range(0, this.ncells());
1728 this.scroll_to_bottom();
1730 this.scroll_to_bottom();
1729 };
1731 };
1730
1732
1731 /**
1733 /**
1732 * Execute a contiguous range of cells.
1734 * Execute a contiguous range of cells.
1733 *
1735 *
1734 * @method execute_cell_range
1736 * @method execute_cell_range
1735 * @param {Number} start Index of the first cell to execute (inclusive)
1737 * @param {Number} start Index of the first cell to execute (inclusive)
1736 * @param {Number} end Index of the last cell to execute (exclusive)
1738 * @param {Number} end Index of the last cell to execute (exclusive)
1737 */
1739 */
1738 Notebook.prototype.execute_cell_range = function (start, end) {
1740 Notebook.prototype.execute_cell_range = function (start, end) {
1739 this.command_mode();
1741 this.command_mode();
1740 for (var i=start; i<end; i++) {
1742 for (var i=start; i<end; i++) {
1741 this.select(i);
1743 this.select(i);
1742 this.execute_cell();
1744 this.execute_cell();
1743 }
1745 }
1744 };
1746 };
1745
1747
1746 // Persistance and loading
1748 // Persistance and loading
1747
1749
1748 /**
1750 /**
1749 * Getter method for this notebook's name.
1751 * Getter method for this notebook's name.
1750 *
1752 *
1751 * @method get_notebook_name
1753 * @method get_notebook_name
1752 * @return {String} This notebook's name (excluding file extension)
1754 * @return {String} This notebook's name (excluding file extension)
1753 */
1755 */
1754 Notebook.prototype.get_notebook_name = function () {
1756 Notebook.prototype.get_notebook_name = function () {
1755 var nbname = this.notebook_name.substring(0,this.notebook_name.length-6);
1757 var nbname = this.notebook_name.substring(0,this.notebook_name.length-6);
1756 return nbname;
1758 return nbname;
1757 };
1759 };
1758
1760
1759 /**
1761 /**
1760 * Setter method for this notebook's name.
1762 * Setter method for this notebook's name.
1761 *
1763 *
1762 * @method set_notebook_name
1764 * @method set_notebook_name
1763 * @param {String} name A new name for this notebook
1765 * @param {String} name A new name for this notebook
1764 */
1766 */
1765 Notebook.prototype.set_notebook_name = function (name) {
1767 Notebook.prototype.set_notebook_name = function (name) {
1766 this.notebook_name = name;
1768 this.notebook_name = name;
1767 };
1769 };
1768
1770
1769 /**
1771 /**
1770 * Check that a notebook's name is valid.
1772 * Check that a notebook's name is valid.
1771 *
1773 *
1772 * @method test_notebook_name
1774 * @method test_notebook_name
1773 * @param {String} nbname A name for this notebook
1775 * @param {String} nbname A name for this notebook
1774 * @return {Boolean} True if the name is valid, false if invalid
1776 * @return {Boolean} True if the name is valid, false if invalid
1775 */
1777 */
1776 Notebook.prototype.test_notebook_name = function (nbname) {
1778 Notebook.prototype.test_notebook_name = function (nbname) {
1777 nbname = nbname || '';
1779 nbname = nbname || '';
1778 if (nbname.length>0 && !this.notebook_name_blacklist_re.test(nbname)) {
1780 if (nbname.length>0 && !this.notebook_name_blacklist_re.test(nbname)) {
1779 return true;
1781 return true;
1780 } else {
1782 } else {
1781 return false;
1783 return false;
1782 }
1784 }
1783 };
1785 };
1784
1786
1785 /**
1787 /**
1786 * Load a notebook from JSON (.ipynb).
1788 * Load a notebook from JSON (.ipynb).
1787 *
1789 *
1788 * This currently handles one worksheet: others are deleted.
1789 *
1790 * @method fromJSON
1790 * @method fromJSON
1791 * @param {Object} data JSON representation of a notebook
1791 * @param {Object} data JSON representation of a notebook
1792 */
1792 */
1793 Notebook.prototype.fromJSON = function (data) {
1793 Notebook.prototype.fromJSON = function (data) {
1794
1794
1795 var content = data.content;
1795 var content = data.content;
1796 var ncells = this.ncells();
1796 var ncells = this.ncells();
1797 var i;
1797 var i;
1798 for (i=0; i<ncells; i++) {
1798 for (i=0; i<ncells; i++) {
1799 // Always delete cell 0 as they get renumbered as they are deleted.
1799 // Always delete cell 0 as they get renumbered as they are deleted.
1800 this.delete_cell(0);
1800 this.delete_cell(0);
1801 }
1801 }
1802 // Save the metadata and name.
1802 // Save the metadata and name.
1803 this.metadata = content.metadata;
1803 this.metadata = content.metadata;
1804 this.notebook_name = data.name;
1804 this.notebook_name = data.name;
1805 var trusted = true;
1805 var trusted = true;
1806
1806
1807 // Trigger an event changing the kernel spec - this will set the default
1807 // Trigger an event changing the kernel spec - this will set the default
1808 // codemirror mode
1808 // codemirror mode
1809 if (this.metadata.kernelspec !== undefined) {
1809 if (this.metadata.kernelspec !== undefined) {
1810 this.events.trigger('spec_changed.Kernel', this.metadata.kernelspec);
1810 this.events.trigger('spec_changed.Kernel', this.metadata.kernelspec);
1811 }
1811 }
1812
1812
1813 // Set the codemirror mode from language_info metadata
1813 // Set the codemirror mode from language_info metadata
1814 if (this.metadata.language_info !== undefined) {
1814 if (this.metadata.language_info !== undefined) {
1815 var langinfo = this.metadata.language_info;
1815 var langinfo = this.metadata.language_info;
1816 // Mode 'null' should be plain, unhighlighted text.
1816 // Mode 'null' should be plain, unhighlighted text.
1817 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null'
1817 var cm_mode = langinfo.codemirror_mode || langinfo.language || 'null'
1818 this.set_codemirror_mode(cm_mode);
1818 this.set_codemirror_mode(cm_mode);
1819 }
1819 }
1820
1820
1821 // Only handle 1 worksheet for now.
1821 var new_cells = content.cells;
1822 var worksheet = content.worksheets[0];
1822 ncells = new_cells.length;
1823 if (worksheet !== undefined) {
1823 var cell_data = null;
1824 if (worksheet.metadata) {
1824 var new_cell = null;
1825 this.worksheet_metadata = worksheet.metadata;
1825 for (i=0; i<ncells; i++) {
1826 }
1826 cell_data = new_cells[i];
1827 var new_cells = worksheet.cells;
1827 new_cell = this.insert_cell_at_index(cell_data.cell_type, i);
1828 ncells = new_cells.length;
1828 new_cell.fromJSON(cell_data);
1829 var cell_data = null;
1829 if (new_cell.cell_type == 'code' && !new_cell.output_area.trusted) {
1830 var new_cell = null;
1830 trusted = false;
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 }
1844 }
1831 }
1845 }
1832 }
1846 if (trusted !== this.trusted) {
1833 if (trusted !== this.trusted) {
1847 this.trusted = trusted;
1834 this.trusted = trusted;
1848 this.events.trigger("trust_changed.Notebook", trusted);
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 * Dump this notebook into a JSON-friendly object.
1840 * Dump this notebook into a JSON-friendly object.
1869 *
1841 *
1870 * @method toJSON
1842 * @method toJSON
1871 * @return {Object} A JSON-friendly representation of this notebook.
1843 * @return {Object} A JSON-friendly representation of this notebook.
1872 */
1844 */
1873 Notebook.prototype.toJSON = function () {
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 var cells = this.get_cells();
1850 var cells = this.get_cells();
1875 var ncells = cells.length;
1851 var ncells = cells.length;
1876 var cell_array = new Array(ncells);
1852 var cell_array = new Array(ncells);
1877 var trusted = true;
1853 var trusted = true;
1878 for (var i=0; i<ncells; i++) {
1854 for (var i=0; i<ncells; i++) {
1879 var cell = cells[i];
1855 var cell = cells[i];
1880 if (cell.cell_type == 'code' && !cell.output_area.trusted) {
1856 if (cell.cell_type == 'code' && !cell.output_area.trusted) {
1881 trusted = false;
1857 trusted = false;
1882 }
1858 }
1883 cell_array[i] = cell.toJSON();
1859 cell_array[i] = cell.toJSON();
1884 }
1860 }
1885 var data = {
1861 var data = {
1886 // Only handle 1 worksheet for now.
1862 cells: cell_array,
1887 worksheets : [{
1888 cells: cell_array,
1889 metadata: this.worksheet_metadata
1890 }],
1891 metadata : this.metadata
1863 metadata : this.metadata
1892 };
1864 };
1893 if (trusted != this.trusted) {
1865 if (trusted != this.trusted) {
1894 this.trusted = trusted;
1866 this.trusted = trusted;
1895 this.events.trigger("trust_changed.Notebook", trusted);
1867 this.events.trigger("trust_changed.Notebook", trusted);
1896 }
1868 }
1897 return data;
1869 return data;
1898 };
1870 };
1899
1871
1900 /**
1872 /**
1901 * Start an autosave timer, for periodically saving the notebook.
1873 * Start an autosave timer, for periodically saving the notebook.
1902 *
1874 *
1903 * @method set_autosave_interval
1875 * @method set_autosave_interval
1904 * @param {Integer} interval the autosave interval in milliseconds
1876 * @param {Integer} interval the autosave interval in milliseconds
1905 */
1877 */
1906 Notebook.prototype.set_autosave_interval = function (interval) {
1878 Notebook.prototype.set_autosave_interval = function (interval) {
1907 var that = this;
1879 var that = this;
1908 // clear previous interval, so we don't get simultaneous timers
1880 // clear previous interval, so we don't get simultaneous timers
1909 if (this.autosave_timer) {
1881 if (this.autosave_timer) {
1910 clearInterval(this.autosave_timer);
1882 clearInterval(this.autosave_timer);
1911 }
1883 }
1912
1884
1913 this.autosave_interval = this.minimum_autosave_interval = interval;
1885 this.autosave_interval = this.minimum_autosave_interval = interval;
1914 if (interval) {
1886 if (interval) {
1915 this.autosave_timer = setInterval(function() {
1887 this.autosave_timer = setInterval(function() {
1916 if (that.dirty) {
1888 if (that.dirty) {
1917 that.save_notebook();
1889 that.save_notebook();
1918 }
1890 }
1919 }, interval);
1891 }, interval);
1920 this.events.trigger("autosave_enabled.Notebook", interval);
1892 this.events.trigger("autosave_enabled.Notebook", interval);
1921 } else {
1893 } else {
1922 this.autosave_timer = null;
1894 this.autosave_timer = null;
1923 this.events.trigger("autosave_disabled.Notebook");
1895 this.events.trigger("autosave_disabled.Notebook");
1924 }
1896 }
1925 };
1897 };
1926
1898
1927 /**
1899 /**
1928 * Save this notebook on the server. This becomes a notebook instance's
1900 * Save this notebook on the server. This becomes a notebook instance's
1929 * .save_notebook method *after* the entire notebook has been loaded.
1901 * .save_notebook method *after* the entire notebook has been loaded.
1930 *
1902 *
1931 * @method save_notebook
1903 * @method save_notebook
1932 */
1904 */
1933 Notebook.prototype.save_notebook = function (extra_settings) {
1905 Notebook.prototype.save_notebook = function (extra_settings) {
1934 // Create a JSON model to be sent to the server.
1906 // Create a JSON model to be sent to the server.
1935 var model = {};
1907 var model = {};
1936 model.name = this.notebook_name;
1908 model.name = this.notebook_name;
1937 model.path = this.notebook_path;
1909 model.path = this.notebook_path;
1938 model.type = 'notebook';
1910 model.type = 'notebook';
1939 model.format = 'json';
1911 model.format = 'json';
1940 model.content = this.toJSON();
1912 model.content = this.toJSON();
1941 model.content.nbformat = this.nbformat;
1913 model.content.nbformat = this.nbformat;
1942 model.content.nbformat_minor = this.nbformat_minor;
1914 model.content.nbformat_minor = this.nbformat_minor;
1943 // time the ajax call for autosave tuning purposes.
1915 // time the ajax call for autosave tuning purposes.
1944 var start = new Date().getTime();
1916 var start = new Date().getTime();
1945 // We do the call with settings so we can set cache to false.
1917 // We do the call with settings so we can set cache to false.
1946 var settings = {
1918 var settings = {
1947 processData : false,
1919 processData : false,
1948 cache : false,
1920 cache : false,
1949 type : "PUT",
1921 type : "PUT",
1950 data : JSON.stringify(model),
1922 data : JSON.stringify(model),
1951 contentType: 'application/json',
1923 contentType: 'application/json',
1952 dataType : "json",
1924 dataType : "json",
1953 success : $.proxy(this.save_notebook_success, this, start),
1925 success : $.proxy(this.save_notebook_success, this, start),
1954 error : $.proxy(this.save_notebook_error, this)
1926 error : $.proxy(this.save_notebook_error, this)
1955 };
1927 };
1956 if (extra_settings) {
1928 if (extra_settings) {
1957 for (var key in extra_settings) {
1929 for (var key in extra_settings) {
1958 settings[key] = extra_settings[key];
1930 settings[key] = extra_settings[key];
1959 }
1931 }
1960 }
1932 }
1961 this.events.trigger('notebook_saving.Notebook');
1933 this.events.trigger('notebook_saving.Notebook');
1962 var url = utils.url_join_encode(
1934 var url = utils.url_join_encode(
1963 this.base_url,
1935 this.base_url,
1964 'api/contents',
1936 'api/contents',
1965 this.notebook_path,
1937 this.notebook_path,
1966 this.notebook_name
1938 this.notebook_name
1967 );
1939 );
1968 $.ajax(url, settings);
1940 $.ajax(url, settings);
1969 };
1941 };
1970
1942
1971 /**
1943 /**
1972 * Success callback for saving a notebook.
1944 * Success callback for saving a notebook.
1973 *
1945 *
1974 * @method save_notebook_success
1946 * @method save_notebook_success
1975 * @param {Integer} start the time when the save request started
1947 * @param {Integer} start the time when the save request started
1976 * @param {Object} data JSON representation of a notebook
1948 * @param {Object} data JSON representation of a notebook
1977 * @param {String} status Description of response status
1949 * @param {String} status Description of response status
1978 * @param {jqXHR} xhr jQuery Ajax object
1950 * @param {jqXHR} xhr jQuery Ajax object
1979 */
1951 */
1980 Notebook.prototype.save_notebook_success = function (start, data, status, xhr) {
1952 Notebook.prototype.save_notebook_success = function (start, data, status, xhr) {
1981 this.set_dirty(false);
1953 this.set_dirty(false);
1982 if (data.message) {
1954 if (data.message) {
1983 // save succeeded, but validation failed.
1955 // save succeeded, but validation failed.
1984 var body = $("<div>");
1956 var body = $("<div>");
1985 var title = "Notebook validation failed";
1957 var title = "Notebook validation failed";
1986
1958
1987 body.append($("<p>").text(
1959 body.append($("<p>").text(
1988 "The save operation succeeded," +
1960 "The save operation succeeded," +
1989 " but the notebook does not appear to be valid." +
1961 " but the notebook does not appear to be valid." +
1990 " The validation error was:"
1962 " The validation error was:"
1991 )).append($("<div>").addClass("validation-error").append(
1963 )).append($("<div>").addClass("validation-error").append(
1992 $("<pre>").text(data.message)
1964 $("<pre>").text(data.message)
1993 ));
1965 ));
1994 dialog.modal({
1966 dialog.modal({
1995 notebook: this,
1967 notebook: this,
1996 keyboard_manager: this.keyboard_manager,
1968 keyboard_manager: this.keyboard_manager,
1997 title: title,
1969 title: title,
1998 body: body,
1970 body: body,
1999 buttons : {
1971 buttons : {
2000 OK : {
1972 OK : {
2001 "class" : "btn-primary"
1973 "class" : "btn-primary"
2002 }
1974 }
2003 }
1975 }
2004 });
1976 });
2005 }
1977 }
2006 this.events.trigger('notebook_saved.Notebook');
1978 this.events.trigger('notebook_saved.Notebook');
2007 this._update_autosave_interval(start);
1979 this._update_autosave_interval(start);
2008 if (this._checkpoint_after_save) {
1980 if (this._checkpoint_after_save) {
2009 this.create_checkpoint();
1981 this.create_checkpoint();
2010 this._checkpoint_after_save = false;
1982 this._checkpoint_after_save = false;
2011 }
1983 }
2012 };
1984 };
2013
1985
2014 /**
1986 /**
2015 * update the autosave interval based on how long the last save took
1987 * update the autosave interval based on how long the last save took
2016 *
1988 *
2017 * @method _update_autosave_interval
1989 * @method _update_autosave_interval
2018 * @param {Integer} timestamp when the save request started
1990 * @param {Integer} timestamp when the save request started
2019 */
1991 */
2020 Notebook.prototype._update_autosave_interval = function (start) {
1992 Notebook.prototype._update_autosave_interval = function (start) {
2021 var duration = (new Date().getTime() - start);
1993 var duration = (new Date().getTime() - start);
2022 if (this.autosave_interval) {
1994 if (this.autosave_interval) {
2023 // new save interval: higher of 10x save duration or parameter (default 30 seconds)
1995 // new save interval: higher of 10x save duration or parameter (default 30 seconds)
2024 var interval = Math.max(10 * duration, this.minimum_autosave_interval);
1996 var interval = Math.max(10 * duration, this.minimum_autosave_interval);
2025 // round to 10 seconds, otherwise we will be setting a new interval too often
1997 // round to 10 seconds, otherwise we will be setting a new interval too often
2026 interval = 10000 * Math.round(interval / 10000);
1998 interval = 10000 * Math.round(interval / 10000);
2027 // set new interval, if it's changed
1999 // set new interval, if it's changed
2028 if (interval != this.autosave_interval) {
2000 if (interval != this.autosave_interval) {
2029 this.set_autosave_interval(interval);
2001 this.set_autosave_interval(interval);
2030 }
2002 }
2031 }
2003 }
2032 };
2004 };
2033
2005
2034 /**
2006 /**
2035 * Failure callback for saving a notebook.
2007 * Failure callback for saving a notebook.
2036 *
2008 *
2037 * @method save_notebook_error
2009 * @method save_notebook_error
2038 * @param {jqXHR} xhr jQuery Ajax object
2010 * @param {jqXHR} xhr jQuery Ajax object
2039 * @param {String} status Description of response status
2011 * @param {String} status Description of response status
2040 * @param {String} error HTTP error message
2012 * @param {String} error HTTP error message
2041 */
2013 */
2042 Notebook.prototype.save_notebook_error = function (xhr, status, error) {
2014 Notebook.prototype.save_notebook_error = function (xhr, status, error) {
2043 this.events.trigger('notebook_save_failed.Notebook', [xhr, status, error]);
2015 this.events.trigger('notebook_save_failed.Notebook', [xhr, status, error]);
2044 };
2016 };
2045
2017
2046 /**
2018 /**
2047 * Explicitly trust the output of this notebook.
2019 * Explicitly trust the output of this notebook.
2048 *
2020 *
2049 * @method trust_notebook
2021 * @method trust_notebook
2050 */
2022 */
2051 Notebook.prototype.trust_notebook = function (extra_settings) {
2023 Notebook.prototype.trust_notebook = function (extra_settings) {
2052 var body = $("<div>").append($("<p>")
2024 var body = $("<div>").append($("<p>")
2053 .text("A trusted IPython notebook may execute hidden malicious code ")
2025 .text("A trusted IPython notebook may execute hidden malicious code ")
2054 .append($("<strong>")
2026 .append($("<strong>")
2055 .append(
2027 .append(
2056 $("<em>").text("when you open it")
2028 $("<em>").text("when you open it")
2057 )
2029 )
2058 ).append(".").append(
2030 ).append(".").append(
2059 " Selecting trust will immediately reload this notebook in a trusted state."
2031 " Selecting trust will immediately reload this notebook in a trusted state."
2060 ).append(
2032 ).append(
2061 " For more information, see the "
2033 " For more information, see the "
2062 ).append($("<a>").attr("href", "http://ipython.org/ipython-doc/2/notebook/security.html")
2034 ).append($("<a>").attr("href", "http://ipython.org/ipython-doc/2/notebook/security.html")
2063 .text("IPython security documentation")
2035 .text("IPython security documentation")
2064 ).append(".")
2036 ).append(".")
2065 );
2037 );
2066
2038
2067 var nb = this;
2039 var nb = this;
2068 dialog.modal({
2040 dialog.modal({
2069 notebook: this,
2041 notebook: this,
2070 keyboard_manager: this.keyboard_manager,
2042 keyboard_manager: this.keyboard_manager,
2071 title: "Trust this notebook?",
2043 title: "Trust this notebook?",
2072 body: body,
2044 body: body,
2073
2045
2074 buttons: {
2046 buttons: {
2075 Cancel : {},
2047 Cancel : {},
2076 Trust : {
2048 Trust : {
2077 class : "btn-danger",
2049 class : "btn-danger",
2078 click : function () {
2050 click : function () {
2079 var cells = nb.get_cells();
2051 var cells = nb.get_cells();
2080 for (var i = 0; i < cells.length; i++) {
2052 for (var i = 0; i < cells.length; i++) {
2081 var cell = cells[i];
2053 var cell = cells[i];
2082 if (cell.cell_type == 'code') {
2054 if (cell.cell_type == 'code') {
2083 cell.output_area.trusted = true;
2055 cell.output_area.trusted = true;
2084 }
2056 }
2085 }
2057 }
2086 nb.events.on('notebook_saved.Notebook', function () {
2058 nb.events.on('notebook_saved.Notebook', function () {
2087 window.location.reload();
2059 window.location.reload();
2088 });
2060 });
2089 nb.save_notebook();
2061 nb.save_notebook();
2090 }
2062 }
2091 }
2063 }
2092 }
2064 }
2093 });
2065 });
2094 };
2066 };
2095
2067
2096 Notebook.prototype.new_notebook = function(){
2068 Notebook.prototype.new_notebook = function(){
2097 var path = this.notebook_path;
2069 var path = this.notebook_path;
2098 var base_url = this.base_url;
2070 var base_url = this.base_url;
2099 var settings = {
2071 var settings = {
2100 processData : false,
2072 processData : false,
2101 cache : false,
2073 cache : false,
2102 type : "POST",
2074 type : "POST",
2103 dataType : "json",
2075 dataType : "json",
2104 async : false,
2076 async : false,
2105 success : function (data, status, xhr){
2077 success : function (data, status, xhr){
2106 var notebook_name = data.name;
2078 var notebook_name = data.name;
2107 window.open(
2079 window.open(
2108 utils.url_join_encode(
2080 utils.url_join_encode(
2109 base_url,
2081 base_url,
2110 'notebooks',
2082 'notebooks',
2111 path,
2083 path,
2112 notebook_name
2084 notebook_name
2113 ),
2085 ),
2114 '_blank'
2086 '_blank'
2115 );
2087 );
2116 },
2088 },
2117 error : utils.log_ajax_error,
2089 error : utils.log_ajax_error,
2118 };
2090 };
2119 var url = utils.url_join_encode(
2091 var url = utils.url_join_encode(
2120 base_url,
2092 base_url,
2121 'api/contents',
2093 'api/contents',
2122 path
2094 path
2123 );
2095 );
2124 $.ajax(url,settings);
2096 $.ajax(url,settings);
2125 };
2097 };
2126
2098
2127
2099
2128 Notebook.prototype.copy_notebook = function(){
2100 Notebook.prototype.copy_notebook = function(){
2129 var path = this.notebook_path;
2101 var path = this.notebook_path;
2130 var base_url = this.base_url;
2102 var base_url = this.base_url;
2131 var settings = {
2103 var settings = {
2132 processData : false,
2104 processData : false,
2133 cache : false,
2105 cache : false,
2134 type : "POST",
2106 type : "POST",
2135 dataType : "json",
2107 dataType : "json",
2136 data : JSON.stringify({copy_from : this.notebook_name}),
2108 data : JSON.stringify({copy_from : this.notebook_name}),
2137 async : false,
2109 async : false,
2138 success : function (data, status, xhr) {
2110 success : function (data, status, xhr) {
2139 window.open(utils.url_join_encode(
2111 window.open(utils.url_join_encode(
2140 base_url,
2112 base_url,
2141 'notebooks',
2113 'notebooks',
2142 data.path,
2114 data.path,
2143 data.name
2115 data.name
2144 ), '_blank');
2116 ), '_blank');
2145 },
2117 },
2146 error : utils.log_ajax_error,
2118 error : utils.log_ajax_error,
2147 };
2119 };
2148 var url = utils.url_join_encode(
2120 var url = utils.url_join_encode(
2149 base_url,
2121 base_url,
2150 'api/contents',
2122 'api/contents',
2151 path
2123 path
2152 );
2124 );
2153 $.ajax(url,settings);
2125 $.ajax(url,settings);
2154 };
2126 };
2155
2127
2156 Notebook.prototype.rename = function (nbname) {
2128 Notebook.prototype.rename = function (nbname) {
2157 var that = this;
2129 var that = this;
2158 if (!nbname.match(/\.ipynb$/)) {
2130 if (!nbname.match(/\.ipynb$/)) {
2159 nbname = nbname + ".ipynb";
2131 nbname = nbname + ".ipynb";
2160 }
2132 }
2161 var data = {name: nbname};
2133 var data = {name: nbname};
2162 var settings = {
2134 var settings = {
2163 processData : false,
2135 processData : false,
2164 cache : false,
2136 cache : false,
2165 type : "PATCH",
2137 type : "PATCH",
2166 data : JSON.stringify(data),
2138 data : JSON.stringify(data),
2167 dataType: "json",
2139 dataType: "json",
2168 contentType: 'application/json',
2140 contentType: 'application/json',
2169 success : $.proxy(that.rename_success, this),
2141 success : $.proxy(that.rename_success, this),
2170 error : $.proxy(that.rename_error, this)
2142 error : $.proxy(that.rename_error, this)
2171 };
2143 };
2172 this.events.trigger('rename_notebook.Notebook', data);
2144 this.events.trigger('rename_notebook.Notebook', data);
2173 var url = utils.url_join_encode(
2145 var url = utils.url_join_encode(
2174 this.base_url,
2146 this.base_url,
2175 'api/contents',
2147 'api/contents',
2176 this.notebook_path,
2148 this.notebook_path,
2177 this.notebook_name
2149 this.notebook_name
2178 );
2150 );
2179 $.ajax(url, settings);
2151 $.ajax(url, settings);
2180 };
2152 };
2181
2153
2182 Notebook.prototype.delete = function () {
2154 Notebook.prototype.delete = function () {
2183 var that = this;
2155 var that = this;
2184 var settings = {
2156 var settings = {
2185 processData : false,
2157 processData : false,
2186 cache : false,
2158 cache : false,
2187 type : "DELETE",
2159 type : "DELETE",
2188 dataType: "json",
2160 dataType: "json",
2189 error : utils.log_ajax_error,
2161 error : utils.log_ajax_error,
2190 };
2162 };
2191 var url = utils.url_join_encode(
2163 var url = utils.url_join_encode(
2192 this.base_url,
2164 this.base_url,
2193 'api/contents',
2165 'api/contents',
2194 this.notebook_path,
2166 this.notebook_path,
2195 this.notebook_name
2167 this.notebook_name
2196 );
2168 );
2197 $.ajax(url, settings);
2169 $.ajax(url, settings);
2198 };
2170 };
2199
2171
2200
2172
2201 Notebook.prototype.rename_success = function (json, status, xhr) {
2173 Notebook.prototype.rename_success = function (json, status, xhr) {
2202 var name = this.notebook_name = json.name;
2174 var name = this.notebook_name = json.name;
2203 var path = json.path;
2175 var path = json.path;
2204 this.session.rename_notebook(name, path);
2176 this.session.rename_notebook(name, path);
2205 this.events.trigger('notebook_renamed.Notebook', json);
2177 this.events.trigger('notebook_renamed.Notebook', json);
2206 };
2178 };
2207
2179
2208 Notebook.prototype.rename_error = function (xhr, status, error) {
2180 Notebook.prototype.rename_error = function (xhr, status, error) {
2209 var that = this;
2181 var that = this;
2210 var dialog_body = $('<div/>').append(
2182 var dialog_body = $('<div/>').append(
2211 $("<p/>").text('This notebook name already exists.')
2183 $("<p/>").text('This notebook name already exists.')
2212 );
2184 );
2213 this.events.trigger('notebook_rename_failed.Notebook', [xhr, status, error]);
2185 this.events.trigger('notebook_rename_failed.Notebook', [xhr, status, error]);
2214 dialog.modal({
2186 dialog.modal({
2215 notebook: this,
2187 notebook: this,
2216 keyboard_manager: this.keyboard_manager,
2188 keyboard_manager: this.keyboard_manager,
2217 title: "Notebook Rename Error!",
2189 title: "Notebook Rename Error!",
2218 body: dialog_body,
2190 body: dialog_body,
2219 buttons : {
2191 buttons : {
2220 "Cancel": {},
2192 "Cancel": {},
2221 "OK": {
2193 "OK": {
2222 class: "btn-primary",
2194 class: "btn-primary",
2223 click: function () {
2195 click: function () {
2224 this.save_widget.rename_notebook({notebook:that});
2196 this.save_widget.rename_notebook({notebook:that});
2225 }}
2197 }}
2226 },
2198 },
2227 open : function (event, ui) {
2199 open : function (event, ui) {
2228 var that = $(this);
2200 var that = $(this);
2229 // Upon ENTER, click the OK button.
2201 // Upon ENTER, click the OK button.
2230 that.find('input[type="text"]').keydown(function (event, ui) {
2202 that.find('input[type="text"]').keydown(function (event, ui) {
2231 if (event.which === this.keyboard.keycodes.enter) {
2203 if (event.which === this.keyboard.keycodes.enter) {
2232 that.find('.btn-primary').first().click();
2204 that.find('.btn-primary').first().click();
2233 }
2205 }
2234 });
2206 });
2235 that.find('input[type="text"]').focus();
2207 that.find('input[type="text"]').focus();
2236 }
2208 }
2237 });
2209 });
2238 };
2210 };
2239
2211
2240 /**
2212 /**
2241 * Request a notebook's data from the server.
2213 * Request a notebook's data from the server.
2242 *
2214 *
2243 * @method load_notebook
2215 * @method load_notebook
2244 * @param {String} notebook_name and path A notebook to load
2216 * @param {String} notebook_name and path A notebook to load
2245 */
2217 */
2246 Notebook.prototype.load_notebook = function (notebook_name, notebook_path) {
2218 Notebook.prototype.load_notebook = function (notebook_name, notebook_path) {
2247 var that = this;
2219 var that = this;
2248 this.notebook_name = notebook_name;
2220 this.notebook_name = notebook_name;
2249 this.notebook_path = notebook_path;
2221 this.notebook_path = notebook_path;
2250 // We do the call with settings so we can set cache to false.
2222 // We do the call with settings so we can set cache to false.
2251 var settings = {
2223 var settings = {
2252 processData : false,
2224 processData : false,
2253 cache : false,
2225 cache : false,
2254 type : "GET",
2226 type : "GET",
2255 dataType : "json",
2227 dataType : "json",
2256 success : $.proxy(this.load_notebook_success,this),
2228 success : $.proxy(this.load_notebook_success,this),
2257 error : $.proxy(this.load_notebook_error,this),
2229 error : $.proxy(this.load_notebook_error,this),
2258 };
2230 };
2259 this.events.trigger('notebook_loading.Notebook');
2231 this.events.trigger('notebook_loading.Notebook');
2260 var url = utils.url_join_encode(
2232 var url = utils.url_join_encode(
2261 this.base_url,
2233 this.base_url,
2262 'api/contents',
2234 'api/contents',
2263 this.notebook_path,
2235 this.notebook_path,
2264 this.notebook_name
2236 this.notebook_name
2265 );
2237 );
2266 $.ajax(url, settings);
2238 $.ajax(url, settings);
2267 };
2239 };
2268
2240
2269 /**
2241 /**
2270 * Success callback for loading a notebook from the server.
2242 * Success callback for loading a notebook from the server.
2271 *
2243 *
2272 * Load notebook data from the JSON response.
2244 * Load notebook data from the JSON response.
2273 *
2245 *
2274 * @method load_notebook_success
2246 * @method load_notebook_success
2275 * @param {Object} data JSON representation of a notebook
2247 * @param {Object} data JSON representation of a notebook
2276 * @param {String} status Description of response status
2248 * @param {String} status Description of response status
2277 * @param {jqXHR} xhr jQuery Ajax object
2249 * @param {jqXHR} xhr jQuery Ajax object
2278 */
2250 */
2279 Notebook.prototype.load_notebook_success = function (data, status, xhr) {
2251 Notebook.prototype.load_notebook_success = function (data, status, xhr) {
2280 var failed;
2252 var failed;
2281 try {
2253 try {
2282 this.fromJSON(data);
2254 this.fromJSON(data);
2283 } catch (e) {
2255 } catch (e) {
2284 failed = e;
2256 failed = e;
2285 console.log("Notebook failed to load from JSON:", e);
2257 console.log("Notebook failed to load from JSON:", e);
2286 }
2258 }
2287 if (failed || data.message) {
2259 if (failed || data.message) {
2288 // *either* fromJSON failed or validation failed
2260 // *either* fromJSON failed or validation failed
2289 var body = $("<div>");
2261 var body = $("<div>");
2290 var title;
2262 var title;
2291 if (failed) {
2263 if (failed) {
2292 title = "Notebook failed to load";
2264 title = "Notebook failed to load";
2293 body.append($("<p>").text(
2265 body.append($("<p>").text(
2294 "The error was: "
2266 "The error was: "
2295 )).append($("<div>").addClass("js-error").text(
2267 )).append($("<div>").addClass("js-error").text(
2296 failed.toString()
2268 failed.toString()
2297 )).append($("<p>").text(
2269 )).append($("<p>").text(
2298 "See the error console for details."
2270 "See the error console for details."
2299 ));
2271 ));
2300 } else {
2272 } else {
2301 title = "Notebook validation failed";
2273 title = "Notebook validation failed";
2302 }
2274 }
2303
2275
2304 if (data.message) {
2276 if (data.message) {
2305 var msg;
2277 var msg;
2306 if (failed) {
2278 if (failed) {
2307 msg = "The notebook also failed validation:"
2279 msg = "The notebook also failed validation:"
2308 } else {
2280 } else {
2309 msg = "An invalid notebook may not function properly." +
2281 msg = "An invalid notebook may not function properly." +
2310 " The validation error was:"
2282 " The validation error was:"
2311 }
2283 }
2312 body.append($("<p>").text(
2284 body.append($("<p>").text(
2313 msg
2285 msg
2314 )).append($("<div>").addClass("validation-error").append(
2286 )).append($("<div>").addClass("validation-error").append(
2315 $("<pre>").text(data.message)
2287 $("<pre>").text(data.message)
2316 ));
2288 ));
2317 }
2289 }
2318
2290
2319 dialog.modal({
2291 dialog.modal({
2320 notebook: this,
2292 notebook: this,
2321 keyboard_manager: this.keyboard_manager,
2293 keyboard_manager: this.keyboard_manager,
2322 title: title,
2294 title: title,
2323 body: body,
2295 body: body,
2324 buttons : {
2296 buttons : {
2325 OK : {
2297 OK : {
2326 "class" : "btn-primary"
2298 "class" : "btn-primary"
2327 }
2299 }
2328 }
2300 }
2329 });
2301 });
2330 }
2302 }
2331 if (this.ncells() === 0) {
2303 if (this.ncells() === 0) {
2332 this.insert_cell_below('code');
2304 this.insert_cell_below('code');
2333 this.edit_mode(0);
2305 this.edit_mode(0);
2334 } else {
2306 } else {
2335 this.select(0);
2307 this.select(0);
2336 this.handle_command_mode(this.get_cell(0));
2308 this.handle_command_mode(this.get_cell(0));
2337 }
2309 }
2338 this.set_dirty(false);
2310 this.set_dirty(false);
2339 this.scroll_to_top();
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 var msg = "This notebook has been converted from an older " +
2316 var msg = "This notebook has been converted from an older " +
2342 "notebook format (v"+data.orig_nbformat+") to the current notebook " +
2317 "notebook format (v"+orig_nbformat+") to the current notebook " +
2343 "format (v"+data.nbformat+"). The next time you save this notebook, the " +
2318 "format (v"+nbmodel.nbformat+"). The next time you save this notebook, the " +
2344 "newer notebook format will be used and older versions of IPython " +
2319 "newer notebook format will be used and older versions of IPython " +
2345 "may not be able to read it. To keep the older version, close the " +
2320 "may not be able to read it. To keep the older version, close the " +
2346 "notebook without saving it.";
2321 "notebook without saving it.";
2347 dialog.modal({
2322 dialog.modal({
2348 notebook: this,
2323 notebook: this,
2349 keyboard_manager: this.keyboard_manager,
2324 keyboard_manager: this.keyboard_manager,
2350 title : "Notebook converted",
2325 title : "Notebook converted",
2351 body : msg,
2326 body : msg,
2352 buttons : {
2327 buttons : {
2353 OK : {
2328 OK : {
2354 class : "btn-primary"
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 var that = this;
2334 var that = this;
2360 var orig_vs = 'v' + data.nbformat + '.' + data.orig_nbformat_minor;
2335 var orig_vs = 'v' + nbmodel.nbformat + '.' + orig_nbformat_minor;
2361 var this_vs = 'v' + data.nbformat + '.' + this.nbformat_minor;
2336 var this_vs = 'v' + nbmodel.nbformat + '.' + this.nbformat_minor;
2362 var msg = "This notebook is version " + orig_vs + ", but we only fully support up to " +
2337 var msg = "This notebook is version " + orig_vs + ", but we only fully support up to " +
2363 this_vs + ". You can still work with this notebook, but some features " +
2338 this_vs + ". You can still work with this notebook, but some features " +
2364 "introduced in later notebook versions may not be available.";
2339 "introduced in later notebook versions may not be available.";
2365
2340
2366 dialog.modal({
2341 dialog.modal({
2367 notebook: this,
2342 notebook: this,
2368 keyboard_manager: this.keyboard_manager,
2343 keyboard_manager: this.keyboard_manager,
2369 title : "Newer Notebook",
2344 title : "Newer Notebook",
2370 body : msg,
2345 body : msg,
2371 buttons : {
2346 buttons : {
2372 OK : {
2347 OK : {
2373 class : "btn-danger"
2348 class : "btn-danger"
2374 }
2349 }
2375 }
2350 }
2376 });
2351 });
2377
2352
2378 }
2353 }
2379
2354
2380 // Create the session after the notebook is completely loaded to prevent
2355 // Create the session after the notebook is completely loaded to prevent
2381 // code execution upon loading, which is a security risk.
2356 // code execution upon loading, which is a security risk.
2382 if (this.session === null) {
2357 if (this.session === null) {
2383 var kernelspec = this.metadata.kernelspec || {};
2358 var kernelspec = this.metadata.kernelspec || {};
2384 var kernel_name = kernelspec.name;
2359 var kernel_name = kernelspec.name;
2385
2360
2386 this.start_session(kernel_name);
2361 this.start_session(kernel_name);
2387 }
2362 }
2388 // load our checkpoint list
2363 // load our checkpoint list
2389 this.list_checkpoints();
2364 this.list_checkpoints();
2390
2365
2391 // load toolbar state
2366 // load toolbar state
2392 if (this.metadata.celltoolbar) {
2367 if (this.metadata.celltoolbar) {
2393 celltoolbar.CellToolbar.global_show();
2368 celltoolbar.CellToolbar.global_show();
2394 celltoolbar.CellToolbar.activate_preset(this.metadata.celltoolbar);
2369 celltoolbar.CellToolbar.activate_preset(this.metadata.celltoolbar);
2395 } else {
2370 } else {
2396 celltoolbar.CellToolbar.global_hide();
2371 celltoolbar.CellToolbar.global_hide();
2397 }
2372 }
2398
2373
2399 // now that we're fully loaded, it is safe to restore save functionality
2374 // now that we're fully loaded, it is safe to restore save functionality
2400 delete(this.save_notebook);
2375 delete(this.save_notebook);
2401 this.events.trigger('notebook_loaded.Notebook');
2376 this.events.trigger('notebook_loaded.Notebook');
2402 };
2377 };
2403
2378
2404 /**
2379 /**
2405 * Failure callback for loading a notebook from the server.
2380 * Failure callback for loading a notebook from the server.
2406 *
2381 *
2407 * @method load_notebook_error
2382 * @method load_notebook_error
2408 * @param {jqXHR} xhr jQuery Ajax object
2383 * @param {jqXHR} xhr jQuery Ajax object
2409 * @param {String} status Description of response status
2384 * @param {String} status Description of response status
2410 * @param {String} error HTTP error message
2385 * @param {String} error HTTP error message
2411 */
2386 */
2412 Notebook.prototype.load_notebook_error = function (xhr, status, error) {
2387 Notebook.prototype.load_notebook_error = function (xhr, status, error) {
2413 this.events.trigger('notebook_load_failed.Notebook', [xhr, status, error]);
2388 this.events.trigger('notebook_load_failed.Notebook', [xhr, status, error]);
2414 utils.log_ajax_error(xhr, status, error);
2389 utils.log_ajax_error(xhr, status, error);
2415 var msg;
2390 var msg = $("<div>");
2416 if (xhr.status === 400) {
2391 if (xhr.status === 400) {
2417 msg = escape(utils.ajax_error_msg(xhr));
2392 msg.text(utils.ajax_error_msg(xhr));
2418 } else if (xhr.status === 500) {
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 "This version can load notebook formats " +
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 dialog.modal({
2398 dialog.modal({
2424 notebook: this,
2399 notebook: this,
2425 keyboard_manager: this.keyboard_manager,
2400 keyboard_manager: this.keyboard_manager,
2426 title: "Error loading notebook",
2401 title: "Error loading notebook",
2427 body : msg,
2402 body : msg,
2428 buttons : {
2403 buttons : {
2429 "OK": {}
2404 "OK": {}
2430 }
2405 }
2431 });
2406 });
2432 };
2407 };
2433
2408
2434 /********************* checkpoint-related *********************/
2409 /********************* checkpoint-related *********************/
2435
2410
2436 /**
2411 /**
2437 * Save the notebook then immediately create a checkpoint.
2412 * Save the notebook then immediately create a checkpoint.
2438 *
2413 *
2439 * @method save_checkpoint
2414 * @method save_checkpoint
2440 */
2415 */
2441 Notebook.prototype.save_checkpoint = function () {
2416 Notebook.prototype.save_checkpoint = function () {
2442 this._checkpoint_after_save = true;
2417 this._checkpoint_after_save = true;
2443 this.save_notebook();
2418 this.save_notebook();
2444 };
2419 };
2445
2420
2446 /**
2421 /**
2447 * Add a checkpoint for this notebook.
2422 * Add a checkpoint for this notebook.
2448 * for use as a callback from checkpoint creation.
2423 * for use as a callback from checkpoint creation.
2449 *
2424 *
2450 * @method add_checkpoint
2425 * @method add_checkpoint
2451 */
2426 */
2452 Notebook.prototype.add_checkpoint = function (checkpoint) {
2427 Notebook.prototype.add_checkpoint = function (checkpoint) {
2453 var found = false;
2428 var found = false;
2454 for (var i = 0; i < this.checkpoints.length; i++) {
2429 for (var i = 0; i < this.checkpoints.length; i++) {
2455 var existing = this.checkpoints[i];
2430 var existing = this.checkpoints[i];
2456 if (existing.id == checkpoint.id) {
2431 if (existing.id == checkpoint.id) {
2457 found = true;
2432 found = true;
2458 this.checkpoints[i] = checkpoint;
2433 this.checkpoints[i] = checkpoint;
2459 break;
2434 break;
2460 }
2435 }
2461 }
2436 }
2462 if (!found) {
2437 if (!found) {
2463 this.checkpoints.push(checkpoint);
2438 this.checkpoints.push(checkpoint);
2464 }
2439 }
2465 this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
2440 this.last_checkpoint = this.checkpoints[this.checkpoints.length - 1];
2466 };
2441 };
2467
2442
2468 /**
2443 /**
2469 * List checkpoints for this notebook.
2444 * List checkpoints for this notebook.
2470 *
2445 *
2471 * @method list_checkpoints
2446 * @method list_checkpoints
2472 */
2447 */
2473 Notebook.prototype.list_checkpoints = function () {
2448 Notebook.prototype.list_checkpoints = function () {
2474 var url = utils.url_join_encode(
2449 var url = utils.url_join_encode(
2475 this.base_url,
2450 this.base_url,
2476 'api/contents',
2451 'api/contents',
2477 this.notebook_path,
2452 this.notebook_path,
2478 this.notebook_name,
2453 this.notebook_name,
2479 'checkpoints'
2454 'checkpoints'
2480 );
2455 );
2481 $.get(url).done(
2456 $.get(url).done(
2482 $.proxy(this.list_checkpoints_success, this)
2457 $.proxy(this.list_checkpoints_success, this)
2483 ).fail(
2458 ).fail(
2484 $.proxy(this.list_checkpoints_error, this)
2459 $.proxy(this.list_checkpoints_error, this)
2485 );
2460 );
2486 };
2461 };
2487
2462
2488 /**
2463 /**
2489 * Success callback for listing checkpoints.
2464 * Success callback for listing checkpoints.
2490 *
2465 *
2491 * @method list_checkpoint_success
2466 * @method list_checkpoint_success
2492 * @param {Object} data JSON representation of a checkpoint
2467 * @param {Object} data JSON representation of a checkpoint
2493 * @param {String} status Description of response status
2468 * @param {String} status Description of response status
2494 * @param {jqXHR} xhr jQuery Ajax object
2469 * @param {jqXHR} xhr jQuery Ajax object
2495 */
2470 */
2496 Notebook.prototype.list_checkpoints_success = function (data, status, xhr) {
2471 Notebook.prototype.list_checkpoints_success = function (data, status, xhr) {
2497 data = $.parseJSON(data);
2472 data = $.parseJSON(data);
2498 this.checkpoints = data;
2473 this.checkpoints = data;
2499 if (data.length) {
2474 if (data.length) {
2500 this.last_checkpoint = data[data.length - 1];
2475 this.last_checkpoint = data[data.length - 1];
2501 } else {
2476 } else {
2502 this.last_checkpoint = null;
2477 this.last_checkpoint = null;
2503 }
2478 }
2504 this.events.trigger('checkpoints_listed.Notebook', [data]);
2479 this.events.trigger('checkpoints_listed.Notebook', [data]);
2505 };
2480 };
2506
2481
2507 /**
2482 /**
2508 * Failure callback for listing a checkpoint.
2483 * Failure callback for listing a checkpoint.
2509 *
2484 *
2510 * @method list_checkpoint_error
2485 * @method list_checkpoint_error
2511 * @param {jqXHR} xhr jQuery Ajax object
2486 * @param {jqXHR} xhr jQuery Ajax object
2512 * @param {String} status Description of response status
2487 * @param {String} status Description of response status
2513 * @param {String} error_msg HTTP error message
2488 * @param {String} error_msg HTTP error message
2514 */
2489 */
2515 Notebook.prototype.list_checkpoints_error = function (xhr, status, error_msg) {
2490 Notebook.prototype.list_checkpoints_error = function (xhr, status, error_msg) {
2516 this.events.trigger('list_checkpoints_failed.Notebook');
2491 this.events.trigger('list_checkpoints_failed.Notebook');
2517 };
2492 };
2518
2493
2519 /**
2494 /**
2520 * Create a checkpoint of this notebook on the server from the most recent save.
2495 * Create a checkpoint of this notebook on the server from the most recent save.
2521 *
2496 *
2522 * @method create_checkpoint
2497 * @method create_checkpoint
2523 */
2498 */
2524 Notebook.prototype.create_checkpoint = function () {
2499 Notebook.prototype.create_checkpoint = function () {
2525 var url = utils.url_join_encode(
2500 var url = utils.url_join_encode(
2526 this.base_url,
2501 this.base_url,
2527 'api/contents',
2502 'api/contents',
2528 this.notebook_path,
2503 this.notebook_path,
2529 this.notebook_name,
2504 this.notebook_name,
2530 'checkpoints'
2505 'checkpoints'
2531 );
2506 );
2532 $.post(url).done(
2507 $.post(url).done(
2533 $.proxy(this.create_checkpoint_success, this)
2508 $.proxy(this.create_checkpoint_success, this)
2534 ).fail(
2509 ).fail(
2535 $.proxy(this.create_checkpoint_error, this)
2510 $.proxy(this.create_checkpoint_error, this)
2536 );
2511 );
2537 };
2512 };
2538
2513
2539 /**
2514 /**
2540 * Success callback for creating a checkpoint.
2515 * Success callback for creating a checkpoint.
2541 *
2516 *
2542 * @method create_checkpoint_success
2517 * @method create_checkpoint_success
2543 * @param {Object} data JSON representation of a checkpoint
2518 * @param {Object} data JSON representation of a checkpoint
2544 * @param {String} status Description of response status
2519 * @param {String} status Description of response status
2545 * @param {jqXHR} xhr jQuery Ajax object
2520 * @param {jqXHR} xhr jQuery Ajax object
2546 */
2521 */
2547 Notebook.prototype.create_checkpoint_success = function (data, status, xhr) {
2522 Notebook.prototype.create_checkpoint_success = function (data, status, xhr) {
2548 data = $.parseJSON(data);
2523 data = $.parseJSON(data);
2549 this.add_checkpoint(data);
2524 this.add_checkpoint(data);
2550 this.events.trigger('checkpoint_created.Notebook', data);
2525 this.events.trigger('checkpoint_created.Notebook', data);
2551 };
2526 };
2552
2527
2553 /**
2528 /**
2554 * Failure callback for creating a checkpoint.
2529 * Failure callback for creating a checkpoint.
2555 *
2530 *
2556 * @method create_checkpoint_error
2531 * @method create_checkpoint_error
2557 * @param {jqXHR} xhr jQuery Ajax object
2532 * @param {jqXHR} xhr jQuery Ajax object
2558 * @param {String} status Description of response status
2533 * @param {String} status Description of response status
2559 * @param {String} error_msg HTTP error message
2534 * @param {String} error_msg HTTP error message
2560 */
2535 */
2561 Notebook.prototype.create_checkpoint_error = function (xhr, status, error_msg) {
2536 Notebook.prototype.create_checkpoint_error = function (xhr, status, error_msg) {
2562 this.events.trigger('checkpoint_failed.Notebook');
2537 this.events.trigger('checkpoint_failed.Notebook');
2563 };
2538 };
2564
2539
2565 Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
2540 Notebook.prototype.restore_checkpoint_dialog = function (checkpoint) {
2566 var that = this;
2541 var that = this;
2567 checkpoint = checkpoint || this.last_checkpoint;
2542 checkpoint = checkpoint || this.last_checkpoint;
2568 if ( ! checkpoint ) {
2543 if ( ! checkpoint ) {
2569 console.log("restore dialog, but no checkpoint to restore to!");
2544 console.log("restore dialog, but no checkpoint to restore to!");
2570 return;
2545 return;
2571 }
2546 }
2572 var body = $('<div/>').append(
2547 var body = $('<div/>').append(
2573 $('<p/>').addClass("p-space").text(
2548 $('<p/>').addClass("p-space").text(
2574 "Are you sure you want to revert the notebook to " +
2549 "Are you sure you want to revert the notebook to " +
2575 "the latest checkpoint?"
2550 "the latest checkpoint?"
2576 ).append(
2551 ).append(
2577 $("<strong/>").text(
2552 $("<strong/>").text(
2578 " This cannot be undone."
2553 " This cannot be undone."
2579 )
2554 )
2580 )
2555 )
2581 ).append(
2556 ).append(
2582 $('<p/>').addClass("p-space").text("The checkpoint was last updated at:")
2557 $('<p/>').addClass("p-space").text("The checkpoint was last updated at:")
2583 ).append(
2558 ).append(
2584 $('<p/>').addClass("p-space").text(
2559 $('<p/>').addClass("p-space").text(
2585 Date(checkpoint.last_modified)
2560 Date(checkpoint.last_modified)
2586 ).css("text-align", "center")
2561 ).css("text-align", "center")
2587 );
2562 );
2588
2563
2589 dialog.modal({
2564 dialog.modal({
2590 notebook: this,
2565 notebook: this,
2591 keyboard_manager: this.keyboard_manager,
2566 keyboard_manager: this.keyboard_manager,
2592 title : "Revert notebook to checkpoint",
2567 title : "Revert notebook to checkpoint",
2593 body : body,
2568 body : body,
2594 buttons : {
2569 buttons : {
2595 Revert : {
2570 Revert : {
2596 class : "btn-danger",
2571 class : "btn-danger",
2597 click : function () {
2572 click : function () {
2598 that.restore_checkpoint(checkpoint.id);
2573 that.restore_checkpoint(checkpoint.id);
2599 }
2574 }
2600 },
2575 },
2601 Cancel : {}
2576 Cancel : {}
2602 }
2577 }
2603 });
2578 });
2604 };
2579 };
2605
2580
2606 /**
2581 /**
2607 * Restore the notebook to a checkpoint state.
2582 * Restore the notebook to a checkpoint state.
2608 *
2583 *
2609 * @method restore_checkpoint
2584 * @method restore_checkpoint
2610 * @param {String} checkpoint ID
2585 * @param {String} checkpoint ID
2611 */
2586 */
2612 Notebook.prototype.restore_checkpoint = function (checkpoint) {
2587 Notebook.prototype.restore_checkpoint = function (checkpoint) {
2613 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2588 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2614 var url = utils.url_join_encode(
2589 var url = utils.url_join_encode(
2615 this.base_url,
2590 this.base_url,
2616 'api/contents',
2591 'api/contents',
2617 this.notebook_path,
2592 this.notebook_path,
2618 this.notebook_name,
2593 this.notebook_name,
2619 'checkpoints',
2594 'checkpoints',
2620 checkpoint
2595 checkpoint
2621 );
2596 );
2622 $.post(url).done(
2597 $.post(url).done(
2623 $.proxy(this.restore_checkpoint_success, this)
2598 $.proxy(this.restore_checkpoint_success, this)
2624 ).fail(
2599 ).fail(
2625 $.proxy(this.restore_checkpoint_error, this)
2600 $.proxy(this.restore_checkpoint_error, this)
2626 );
2601 );
2627 };
2602 };
2628
2603
2629 /**
2604 /**
2630 * Success callback for restoring a notebook to a checkpoint.
2605 * Success callback for restoring a notebook to a checkpoint.
2631 *
2606 *
2632 * @method restore_checkpoint_success
2607 * @method restore_checkpoint_success
2633 * @param {Object} data (ignored, should be empty)
2608 * @param {Object} data (ignored, should be empty)
2634 * @param {String} status Description of response status
2609 * @param {String} status Description of response status
2635 * @param {jqXHR} xhr jQuery Ajax object
2610 * @param {jqXHR} xhr jQuery Ajax object
2636 */
2611 */
2637 Notebook.prototype.restore_checkpoint_success = function (data, status, xhr) {
2612 Notebook.prototype.restore_checkpoint_success = function (data, status, xhr) {
2638 this.events.trigger('checkpoint_restored.Notebook');
2613 this.events.trigger('checkpoint_restored.Notebook');
2639 this.load_notebook(this.notebook_name, this.notebook_path);
2614 this.load_notebook(this.notebook_name, this.notebook_path);
2640 };
2615 };
2641
2616
2642 /**
2617 /**
2643 * Failure callback for restoring a notebook to a checkpoint.
2618 * Failure callback for restoring a notebook to a checkpoint.
2644 *
2619 *
2645 * @method restore_checkpoint_error
2620 * @method restore_checkpoint_error
2646 * @param {jqXHR} xhr jQuery Ajax object
2621 * @param {jqXHR} xhr jQuery Ajax object
2647 * @param {String} status Description of response status
2622 * @param {String} status Description of response status
2648 * @param {String} error_msg HTTP error message
2623 * @param {String} error_msg HTTP error message
2649 */
2624 */
2650 Notebook.prototype.restore_checkpoint_error = function (xhr, status, error_msg) {
2625 Notebook.prototype.restore_checkpoint_error = function (xhr, status, error_msg) {
2651 this.events.trigger('checkpoint_restore_failed.Notebook');
2626 this.events.trigger('checkpoint_restore_failed.Notebook');
2652 };
2627 };
2653
2628
2654 /**
2629 /**
2655 * Delete a notebook checkpoint.
2630 * Delete a notebook checkpoint.
2656 *
2631 *
2657 * @method delete_checkpoint
2632 * @method delete_checkpoint
2658 * @param {String} checkpoint ID
2633 * @param {String} checkpoint ID
2659 */
2634 */
2660 Notebook.prototype.delete_checkpoint = function (checkpoint) {
2635 Notebook.prototype.delete_checkpoint = function (checkpoint) {
2661 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2636 this.events.trigger('notebook_restoring.Notebook', checkpoint);
2662 var url = utils.url_join_encode(
2637 var url = utils.url_join_encode(
2663 this.base_url,
2638 this.base_url,
2664 'api/contents',
2639 'api/contents',
2665 this.notebook_path,
2640 this.notebook_path,
2666 this.notebook_name,
2641 this.notebook_name,
2667 'checkpoints',
2642 'checkpoints',
2668 checkpoint
2643 checkpoint
2669 );
2644 );
2670 $.ajax(url, {
2645 $.ajax(url, {
2671 type: 'DELETE',
2646 type: 'DELETE',
2672 success: $.proxy(this.delete_checkpoint_success, this),
2647 success: $.proxy(this.delete_checkpoint_success, this),
2673 error: $.proxy(this.delete_checkpoint_error, this)
2648 error: $.proxy(this.delete_checkpoint_error, this)
2674 });
2649 });
2675 };
2650 };
2676
2651
2677 /**
2652 /**
2678 * Success callback for deleting a notebook checkpoint
2653 * Success callback for deleting a notebook checkpoint
2679 *
2654 *
2680 * @method delete_checkpoint_success
2655 * @method delete_checkpoint_success
2681 * @param {Object} data (ignored, should be empty)
2656 * @param {Object} data (ignored, should be empty)
2682 * @param {String} status Description of response status
2657 * @param {String} status Description of response status
2683 * @param {jqXHR} xhr jQuery Ajax object
2658 * @param {jqXHR} xhr jQuery Ajax object
2684 */
2659 */
2685 Notebook.prototype.delete_checkpoint_success = function (data, status, xhr) {
2660 Notebook.prototype.delete_checkpoint_success = function (data, status, xhr) {
2686 this.events.trigger('checkpoint_deleted.Notebook', data);
2661 this.events.trigger('checkpoint_deleted.Notebook', data);
2687 this.load_notebook(this.notebook_name, this.notebook_path);
2662 this.load_notebook(this.notebook_name, this.notebook_path);
2688 };
2663 };
2689
2664
2690 /**
2665 /**
2691 * Failure callback for deleting a notebook checkpoint.
2666 * Failure callback for deleting a notebook checkpoint.
2692 *
2667 *
2693 * @method delete_checkpoint_error
2668 * @method delete_checkpoint_error
2694 * @param {jqXHR} xhr jQuery Ajax object
2669 * @param {jqXHR} xhr jQuery Ajax object
2695 * @param {String} status Description of response status
2670 * @param {String} status Description of response status
2696 * @param {String} error HTTP error message
2671 * @param {String} error HTTP error message
2697 */
2672 */
2698 Notebook.prototype.delete_checkpoint_error = function (xhr, status, error) {
2673 Notebook.prototype.delete_checkpoint_error = function (xhr, status, error) {
2699 this.events.trigger('checkpoint_delete_failed.Notebook', [xhr, status, error]);
2674 this.events.trigger('checkpoint_delete_failed.Notebook', [xhr, status, error]);
2700 };
2675 };
2701
2676
2702
2677
2703 // For backwards compatability.
2678 // For backwards compatability.
2704 IPython.Notebook = Notebook;
2679 IPython.Notebook = Notebook;
2705
2680
2706 return {'Notebook': Notebook};
2681 return {'Notebook': Notebook};
2707 });
2682 });
@@ -1,1002 +1,931 b''
1 // Copyright (c) IPython Development Team.
1 // Copyright (c) IPython Development Team.
2 // Distributed under the terms of the Modified BSD License.
2 // Distributed under the terms of the Modified BSD License.
3
3
4 define([
4 define([
5 'base/js/namespace',
5 'base/js/namespace',
6 'jqueryui',
6 'jqueryui',
7 'base/js/utils',
7 'base/js/utils',
8 'base/js/security',
8 'base/js/security',
9 'base/js/keyboard',
9 'base/js/keyboard',
10 'notebook/js/mathjaxutils',
10 'notebook/js/mathjaxutils',
11 'components/marked/lib/marked',
11 'components/marked/lib/marked',
12 ], function(IPython, $, utils, security, keyboard, mathjaxutils, marked) {
12 ], function(IPython, $, utils, security, keyboard, mathjaxutils, marked) {
13 "use strict";
13 "use strict";
14
14
15 /**
15 /**
16 * @class OutputArea
16 * @class OutputArea
17 *
17 *
18 * @constructor
18 * @constructor
19 */
19 */
20
20
21 var OutputArea = function (options) {
21 var OutputArea = function (options) {
22 this.selector = options.selector;
22 this.selector = options.selector;
23 this.events = options.events;
23 this.events = options.events;
24 this.keyboard_manager = options.keyboard_manager;
24 this.keyboard_manager = options.keyboard_manager;
25 this.wrapper = $(options.selector);
25 this.wrapper = $(options.selector);
26 this.outputs = [];
26 this.outputs = [];
27 this.collapsed = false;
27 this.collapsed = false;
28 this.scrolled = false;
28 this.scrolled = false;
29 this.trusted = true;
29 this.trusted = true;
30 this.clear_queued = null;
30 this.clear_queued = null;
31 if (options.prompt_area === undefined) {
31 if (options.prompt_area === undefined) {
32 this.prompt_area = true;
32 this.prompt_area = true;
33 } else {
33 } else {
34 this.prompt_area = options.prompt_area;
34 this.prompt_area = options.prompt_area;
35 }
35 }
36 this.create_elements();
36 this.create_elements();
37 this.style();
37 this.style();
38 this.bind_events();
38 this.bind_events();
39 };
39 };
40
40
41
41
42 /**
42 /**
43 * Class prototypes
43 * Class prototypes
44 **/
44 **/
45
45
46 OutputArea.prototype.create_elements = function () {
46 OutputArea.prototype.create_elements = function () {
47 this.element = $("<div/>");
47 this.element = $("<div/>");
48 this.collapse_button = $("<div/>");
48 this.collapse_button = $("<div/>");
49 this.prompt_overlay = $("<div/>");
49 this.prompt_overlay = $("<div/>");
50 this.wrapper.append(this.prompt_overlay);
50 this.wrapper.append(this.prompt_overlay);
51 this.wrapper.append(this.element);
51 this.wrapper.append(this.element);
52 this.wrapper.append(this.collapse_button);
52 this.wrapper.append(this.collapse_button);
53 };
53 };
54
54
55
55
56 OutputArea.prototype.style = function () {
56 OutputArea.prototype.style = function () {
57 this.collapse_button.hide();
57 this.collapse_button.hide();
58 this.prompt_overlay.hide();
58 this.prompt_overlay.hide();
59
59
60 this.wrapper.addClass('output_wrapper');
60 this.wrapper.addClass('output_wrapper');
61 this.element.addClass('output');
61 this.element.addClass('output');
62
62
63 this.collapse_button.addClass("btn btn-default output_collapsed");
63 this.collapse_button.addClass("btn btn-default output_collapsed");
64 this.collapse_button.attr('title', 'click to expand output');
64 this.collapse_button.attr('title', 'click to expand output');
65 this.collapse_button.text('. . .');
65 this.collapse_button.text('. . .');
66
66
67 this.prompt_overlay.addClass('out_prompt_overlay prompt');
67 this.prompt_overlay.addClass('out_prompt_overlay prompt');
68 this.prompt_overlay.attr('title', 'click to expand output; double click to hide output');
68 this.prompt_overlay.attr('title', 'click to expand output; double click to hide output');
69
69
70 this.collapse();
70 this.collapse();
71 };
71 };
72
72
73 /**
73 /**
74 * Should the OutputArea scroll?
74 * Should the OutputArea scroll?
75 * Returns whether the height (in lines) exceeds a threshold.
75 * Returns whether the height (in lines) exceeds a threshold.
76 *
76 *
77 * @private
77 * @private
78 * @method _should_scroll
78 * @method _should_scroll
79 * @param [lines=100]{Integer}
79 * @param [lines=100]{Integer}
80 * @return {Bool}
80 * @return {Bool}
81 *
81 *
82 */
82 */
83 OutputArea.prototype._should_scroll = function (lines) {
83 OutputArea.prototype._should_scroll = function (lines) {
84 if (lines <=0 ){ return }
84 if (lines <=0 ){ return; }
85 if (!lines) {
85 if (!lines) {
86 lines = 100;
86 lines = 100;
87 }
87 }
88 // line-height from http://stackoverflow.com/questions/1185151
88 // line-height from http://stackoverflow.com/questions/1185151
89 var fontSize = this.element.css('font-size');
89 var fontSize = this.element.css('font-size');
90 var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
90 var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
91
91
92 return (this.element.height() > lines * lineHeight);
92 return (this.element.height() > lines * lineHeight);
93 };
93 };
94
94
95
95
96 OutputArea.prototype.bind_events = function () {
96 OutputArea.prototype.bind_events = function () {
97 var that = this;
97 var that = this;
98 this.prompt_overlay.dblclick(function () { that.toggle_output(); });
98 this.prompt_overlay.dblclick(function () { that.toggle_output(); });
99 this.prompt_overlay.click(function () { that.toggle_scroll(); });
99 this.prompt_overlay.click(function () { that.toggle_scroll(); });
100
100
101 this.element.resize(function () {
101 this.element.resize(function () {
102 // FIXME: Firefox on Linux misbehaves, so automatic scrolling is disabled
102 // FIXME: Firefox on Linux misbehaves, so automatic scrolling is disabled
103 if ( utils.browser[0] === "Firefox" ) {
103 if ( utils.browser[0] === "Firefox" ) {
104 return;
104 return;
105 }
105 }
106 // maybe scroll output,
106 // maybe scroll output,
107 // if it's grown large enough and hasn't already been scrolled.
107 // if it's grown large enough and hasn't already been scrolled.
108 if ( !that.scrolled && that._should_scroll(OutputArea.auto_scroll_threshold)) {
108 if ( !that.scrolled && that._should_scroll(OutputArea.auto_scroll_threshold)) {
109 that.scroll_area();
109 that.scroll_area();
110 }
110 }
111 });
111 });
112 this.collapse_button.click(function () {
112 this.collapse_button.click(function () {
113 that.expand();
113 that.expand();
114 });
114 });
115 };
115 };
116
116
117
117
118 OutputArea.prototype.collapse = function () {
118 OutputArea.prototype.collapse = function () {
119 if (!this.collapsed) {
119 if (!this.collapsed) {
120 this.element.hide();
120 this.element.hide();
121 this.prompt_overlay.hide();
121 this.prompt_overlay.hide();
122 if (this.element.html()){
122 if (this.element.html()){
123 this.collapse_button.show();
123 this.collapse_button.show();
124 }
124 }
125 this.collapsed = true;
125 this.collapsed = true;
126 }
126 }
127 };
127 };
128
128
129
129
130 OutputArea.prototype.expand = function () {
130 OutputArea.prototype.expand = function () {
131 if (this.collapsed) {
131 if (this.collapsed) {
132 this.collapse_button.hide();
132 this.collapse_button.hide();
133 this.element.show();
133 this.element.show();
134 this.prompt_overlay.show();
134 this.prompt_overlay.show();
135 this.collapsed = false;
135 this.collapsed = false;
136 }
136 }
137 };
137 };
138
138
139
139
140 OutputArea.prototype.toggle_output = function () {
140 OutputArea.prototype.toggle_output = function () {
141 if (this.collapsed) {
141 if (this.collapsed) {
142 this.expand();
142 this.expand();
143 } else {
143 } else {
144 this.collapse();
144 this.collapse();
145 }
145 }
146 };
146 };
147
147
148
148
149 OutputArea.prototype.scroll_area = function () {
149 OutputArea.prototype.scroll_area = function () {
150 this.element.addClass('output_scroll');
150 this.element.addClass('output_scroll');
151 this.prompt_overlay.attr('title', 'click to unscroll output; double click to hide');
151 this.prompt_overlay.attr('title', 'click to unscroll output; double click to hide');
152 this.scrolled = true;
152 this.scrolled = true;
153 };
153 };
154
154
155
155
156 OutputArea.prototype.unscroll_area = function () {
156 OutputArea.prototype.unscroll_area = function () {
157 this.element.removeClass('output_scroll');
157 this.element.removeClass('output_scroll');
158 this.prompt_overlay.attr('title', 'click to scroll output; double click to hide');
158 this.prompt_overlay.attr('title', 'click to scroll output; double click to hide');
159 this.scrolled = false;
159 this.scrolled = false;
160 };
160 };
161
161
162 /**
162 /**
163 *
163 *
164 * Scroll OutputArea if height supperior than a threshold (in lines).
164 * Scroll OutputArea if height supperior than a threshold (in lines).
165 *
165 *
166 * Threshold is a maximum number of lines. If unspecified, defaults to
166 * Threshold is a maximum number of lines. If unspecified, defaults to
167 * OutputArea.minimum_scroll_threshold.
167 * OutputArea.minimum_scroll_threshold.
168 *
168 *
169 * Negative threshold will prevent the OutputArea from ever scrolling.
169 * Negative threshold will prevent the OutputArea from ever scrolling.
170 *
170 *
171 * @method scroll_if_long
171 * @method scroll_if_long
172 *
172 *
173 * @param [lines=20]{Number} Default to 20 if not set,
173 * @param [lines=20]{Number} Default to 20 if not set,
174 * behavior undefined for value of `0`.
174 * behavior undefined for value of `0`.
175 *
175 *
176 **/
176 **/
177 OutputArea.prototype.scroll_if_long = function (lines) {
177 OutputArea.prototype.scroll_if_long = function (lines) {
178 var n = lines | OutputArea.minimum_scroll_threshold;
178 var n = lines | OutputArea.minimum_scroll_threshold;
179 if(n <= 0){
179 if(n <= 0){
180 return
180 return;
181 }
181 }
182
182
183 if (this._should_scroll(n)) {
183 if (this._should_scroll(n)) {
184 // only allow scrolling long-enough output
184 // only allow scrolling long-enough output
185 this.scroll_area();
185 this.scroll_area();
186 }
186 }
187 };
187 };
188
188
189
189
190 OutputArea.prototype.toggle_scroll = function () {
190 OutputArea.prototype.toggle_scroll = function () {
191 if (this.scrolled) {
191 if (this.scrolled) {
192 this.unscroll_area();
192 this.unscroll_area();
193 } else {
193 } else {
194 // only allow scrolling long-enough output
194 // only allow scrolling long-enough output
195 this.scroll_if_long();
195 this.scroll_if_long();
196 }
196 }
197 };
197 };
198
198
199
199
200 // typeset with MathJax if MathJax is available
200 // typeset with MathJax if MathJax is available
201 OutputArea.prototype.typeset = function () {
201 OutputArea.prototype.typeset = function () {
202 if (window.MathJax){
202 if (window.MathJax){
203 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
203 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
204 }
204 }
205 };
205 };
206
206
207
207
208 OutputArea.prototype.handle_output = function (msg) {
208 OutputArea.prototype.handle_output = function (msg) {
209 var json = {};
209 var json = {};
210 var msg_type = json.output_type = msg.header.msg_type;
210 var msg_type = json.output_type = msg.header.msg_type;
211 var content = msg.content;
211 var content = msg.content;
212 if (msg_type === "stream") {
212 if (msg_type === "stream") {
213 json.text = content.text;
213 json.text = content.text;
214 json.stream = content.name;
214 json.name = content.name;
215 } else if (msg_type === "display_data") {
215 } else if (msg_type === "display_data") {
216 json = content.data;
216 json.data = content.data;
217 json.output_type = msg_type;
217 json.output_type = msg_type;
218 json.metadata = content.metadata;
218 json.metadata = content.metadata;
219 } else if (msg_type === "execute_result") {
219 } else if (msg_type === "execute_result") {
220 json = content.data;
220 json.data = content.data;
221 json.output_type = msg_type;
221 json.output_type = msg_type;
222 json.metadata = content.metadata;
222 json.metadata = content.metadata;
223 json.prompt_number = content.execution_count;
223 json.execution_count = content.execution_count;
224 } else if (msg_type === "error") {
224 } else if (msg_type === "error") {
225 json.ename = content.ename;
225 json.ename = content.ename;
226 json.evalue = content.evalue;
226 json.evalue = content.evalue;
227 json.traceback = content.traceback;
227 json.traceback = content.traceback;
228 } else {
228 } else {
229 console.log("unhandled output message", msg);
229 console.log("unhandled output message", msg);
230 return;
230 return;
231 }
231 }
232 this.append_output(json);
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 OutputArea.output_types = [
236 OutputArea.output_types = [
247 'application/javascript',
237 'application/javascript',
248 'text/html',
238 'text/html',
249 'text/markdown',
239 'text/markdown',
250 'text/latex',
240 'text/latex',
251 'image/svg+xml',
241 'image/svg+xml',
252 'image/png',
242 'image/png',
253 'image/jpeg',
243 'image/jpeg',
254 'application/pdf',
244 'application/pdf',
255 'text/plain'
245 'text/plain'
256 ];
246 ];
257
247
258 OutputArea.prototype.validate_output = function (json) {
248 OutputArea.prototype.validate_output = function (json) {
259 // scrub invalid outputs
249 // scrub invalid outputs
260 // TODO: right now everything is a string, but JSON really shouldn't be.
250 var data = json.data;
261 // nbformat 4 will fix that.
262 $.map(OutputArea.output_types, function(key){
251 $.map(OutputArea.output_types, function(key){
263 if (json[key] !== undefined && typeof json[key] !== 'string') {
252 if (key !== 'application/json' &&
264 console.log("Invalid type for " + key, json[key]);
253 data[key] !== undefined &&
265 delete json[key];
254 typeof data[key] !== 'string'
255 ) {
256 console.log("Invalid type for " + key, data[key]);
257 delete data[key];
266 }
258 }
267 });
259 });
268 return json;
260 return json;
269 };
261 };
270
262
271 OutputArea.prototype.append_output = function (json) {
263 OutputArea.prototype.append_output = function (json) {
272 this.expand();
264 this.expand();
273
265
274 // validate output data types
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 // Clear the output if clear is queued.
271 // Clear the output if clear is queued.
278 var needs_height_reset = false;
272 var needs_height_reset = false;
279 if (this.clear_queued) {
273 if (this.clear_queued) {
280 this.clear_output(false);
274 this.clear_output(false);
281 needs_height_reset = true;
275 needs_height_reset = true;
282 }
276 }
283
277
284 var record_output = true;
278 var record_output = true;
285
279
286 if (json.output_type === 'execute_result') {
280 if (json.output_type === 'execute_result') {
287 this.append_execute_result(json);
281 this.append_execute_result(json);
288 } else if (json.output_type === 'error') {
282 } else if (json.output_type === 'error') {
289 this.append_error(json);
283 this.append_error(json);
290 } else if (json.output_type === 'stream') {
284 } else if (json.output_type === 'stream') {
291 // append_stream might have merged the output with earlier stream output
285 // append_stream might have merged the output with earlier stream output
292 record_output = this.append_stream(json);
286 record_output = this.append_stream(json);
293 }
287 }
294
288
295 // We must release the animation fixed height in a callback since Gecko
289 // We must release the animation fixed height in a callback since Gecko
296 // (FireFox) doesn't render the image immediately as the data is
290 // (FireFox) doesn't render the image immediately as the data is
297 // available.
291 // available.
298 var that = this;
292 var that = this;
299 var handle_appended = function ($el) {
293 var handle_appended = function ($el) {
300 // Only reset the height to automatic if the height is currently
294 // Only reset the height to automatic if the height is currently
301 // fixed (done by wait=True flag on clear_output).
295 // fixed (done by wait=True flag on clear_output).
302 if (needs_height_reset) {
296 if (needs_height_reset) {
303 that.element.height('');
297 that.element.height('');
304 }
298 }
305 that.element.trigger('resize');
299 that.element.trigger('resize');
306 };
300 };
307 if (json.output_type === 'display_data') {
301 if (json.output_type === 'display_data') {
308 this.append_display_data(json, handle_appended);
302 this.append_display_data(json, handle_appended);
309 } else {
303 } else {
310 handle_appended();
304 handle_appended();
311 }
305 }
312
306
313 if (record_output) {
307 if (record_output) {
314 this.outputs.push(json);
308 this.outputs.push(json);
315 }
309 }
316 };
310 };
317
311
318
312
319 OutputArea.prototype.create_output_area = function () {
313 OutputArea.prototype.create_output_area = function () {
320 var oa = $("<div/>").addClass("output_area");
314 var oa = $("<div/>").addClass("output_area");
321 if (this.prompt_area) {
315 if (this.prompt_area) {
322 oa.append($('<div/>').addClass('prompt'));
316 oa.append($('<div/>').addClass('prompt'));
323 }
317 }
324 return oa;
318 return oa;
325 };
319 };
326
320
327
321
328 function _get_metadata_key(metadata, key, mime) {
322 function _get_metadata_key(metadata, key, mime) {
329 var mime_md = metadata[mime];
323 var mime_md = metadata[mime];
330 // mime-specific higher priority
324 // mime-specific higher priority
331 if (mime_md && mime_md[key] !== undefined) {
325 if (mime_md && mime_md[key] !== undefined) {
332 return mime_md[key];
326 return mime_md[key];
333 }
327 }
334 // fallback on global
328 // fallback on global
335 return metadata[key];
329 return metadata[key];
336 }
330 }
337
331
338 OutputArea.prototype.create_output_subarea = function(md, classes, mime) {
332 OutputArea.prototype.create_output_subarea = function(md, classes, mime) {
339 var subarea = $('<div/>').addClass('output_subarea').addClass(classes);
333 var subarea = $('<div/>').addClass('output_subarea').addClass(classes);
340 if (_get_metadata_key(md, 'isolated', mime)) {
334 if (_get_metadata_key(md, 'isolated', mime)) {
341 // Create an iframe to isolate the subarea from the rest of the
335 // Create an iframe to isolate the subarea from the rest of the
342 // document
336 // document
343 var iframe = $('<iframe/>').addClass('box-flex1');
337 var iframe = $('<iframe/>').addClass('box-flex1');
344 iframe.css({'height':1, 'width':'100%', 'display':'block'});
338 iframe.css({'height':1, 'width':'100%', 'display':'block'});
345 iframe.attr('frameborder', 0);
339 iframe.attr('frameborder', 0);
346 iframe.attr('scrolling', 'auto');
340 iframe.attr('scrolling', 'auto');
347
341
348 // Once the iframe is loaded, the subarea is dynamically inserted
342 // Once the iframe is loaded, the subarea is dynamically inserted
349 iframe.on('load', function() {
343 iframe.on('load', function() {
350 // Workaround needed by Firefox, to properly render svg inside
344 // Workaround needed by Firefox, to properly render svg inside
351 // iframes, see http://stackoverflow.com/questions/10177190/
345 // iframes, see http://stackoverflow.com/questions/10177190/
352 // svg-dynamically-added-to-iframe-does-not-render-correctly
346 // svg-dynamically-added-to-iframe-does-not-render-correctly
353 this.contentDocument.open();
347 this.contentDocument.open();
354
348
355 // Insert the subarea into the iframe
349 // Insert the subarea into the iframe
356 // We must directly write the html. When using Jquery's append
350 // We must directly write the html. When using Jquery's append
357 // method, javascript is evaluated in the parent document and
351 // method, javascript is evaluated in the parent document and
358 // not in the iframe document. At this point, subarea doesn't
352 // not in the iframe document. At this point, subarea doesn't
359 // contain any user content.
353 // contain any user content.
360 this.contentDocument.write(subarea.html());
354 this.contentDocument.write(subarea.html());
361
355
362 this.contentDocument.close();
356 this.contentDocument.close();
363
357
364 var body = this.contentDocument.body;
358 var body = this.contentDocument.body;
365 // Adjust the iframe height automatically
359 // Adjust the iframe height automatically
366 iframe.height(body.scrollHeight + 'px');
360 iframe.height(body.scrollHeight + 'px');
367 });
361 });
368
362
369 // Elements should be appended to the inner subarea and not to the
363 // Elements should be appended to the inner subarea and not to the
370 // iframe
364 // iframe
371 iframe.append = function(that) {
365 iframe.append = function(that) {
372 subarea.append(that);
366 subarea.append(that);
373 };
367 };
374
368
375 return iframe;
369 return iframe;
376 } else {
370 } else {
377 return subarea;
371 return subarea;
378 }
372 }
379 }
373 };
380
374
381
375
382 OutputArea.prototype._append_javascript_error = function (err, element) {
376 OutputArea.prototype._append_javascript_error = function (err, element) {
383 // display a message when a javascript error occurs in display output
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 if ( element === undefined ) return;
379 if ( element === undefined ) return;
386 element
380 element
387 .append($('<div/>').text(msg).addClass('js-error'))
381 .append($('<div/>').text(msg).addClass('js-error'))
388 .append($('<div/>').text(err.toString()).addClass('js-error'))
382 .append($('<div/>').text(err.toString()).addClass('js-error'))
389 .append($('<div/>').text('See your browser Javascript console for more details.').addClass('js-error'));
383 .append($('<div/>').text('See your browser Javascript console for more details.').addClass('js-error'));
390 };
384 };
391
385
392 OutputArea.prototype._safe_append = function (toinsert) {
386 OutputArea.prototype._safe_append = function (toinsert) {
393 // safely append an item to the document
387 // safely append an item to the document
394 // this is an object created by user code,
388 // this is an object created by user code,
395 // and may have errors, which should not be raised
389 // and may have errors, which should not be raised
396 // under any circumstances.
390 // under any circumstances.
397 try {
391 try {
398 this.element.append(toinsert);
392 this.element.append(toinsert);
399 } catch(err) {
393 } catch(err) {
400 console.log(err);
394 console.log(err);
401 // Create an actual output_area and output_subarea, which creates
395 // Create an actual output_area and output_subarea, which creates
402 // the prompt area and the proper indentation.
396 // the prompt area and the proper indentation.
403 var toinsert = this.create_output_area();
397 var toinsert = this.create_output_area();
404 var subarea = $('<div/>').addClass('output_subarea');
398 var subarea = $('<div/>').addClass('output_subarea');
405 toinsert.append(subarea);
399 toinsert.append(subarea);
406 this._append_javascript_error(err, subarea);
400 this._append_javascript_error(err, subarea);
407 this.element.append(toinsert);
401 this.element.append(toinsert);
408 }
402 }
409 };
403 };
410
404
411
405
412 OutputArea.prototype.append_execute_result = function (json) {
406 OutputArea.prototype.append_execute_result = function (json) {
413 var n = json.prompt_number || ' ';
407 var n = json.execution_count || ' ';
414 var toinsert = this.create_output_area();
408 var toinsert = this.create_output_area();
415 if (this.prompt_area) {
409 if (this.prompt_area) {
416 toinsert.find('div.prompt').addClass('output_prompt').text('Out[' + n + ']:');
410 toinsert.find('div.prompt').addClass('output_prompt').text('Out[' + n + ']:');
417 }
411 }
418 var inserted = this.append_mime_type(json, toinsert);
412 var inserted = this.append_mime_type(json, toinsert);
419 if (inserted) {
413 if (inserted) {
420 inserted.addClass('output_result');
414 inserted.addClass('output_result');
421 }
415 }
422 this._safe_append(toinsert);
416 this._safe_append(toinsert);
423 // If we just output latex, typeset it.
417 // If we just output latex, typeset it.
424 if ((json['text/latex'] !== undefined) ||
418 if ((json['text/latex'] !== undefined) ||
425 (json['text/html'] !== undefined) ||
419 (json['text/html'] !== undefined) ||
426 (json['text/markdown'] !== undefined)) {
420 (json['text/markdown'] !== undefined)) {
427 this.typeset();
421 this.typeset();
428 }
422 }
429 };
423 };
430
424
431
425
432 OutputArea.prototype.append_error = function (json) {
426 OutputArea.prototype.append_error = function (json) {
433 var tb = json.traceback;
427 var tb = json.traceback;
434 if (tb !== undefined && tb.length > 0) {
428 if (tb !== undefined && tb.length > 0) {
435 var s = '';
429 var s = '';
436 var len = tb.length;
430 var len = tb.length;
437 for (var i=0; i<len; i++) {
431 for (var i=0; i<len; i++) {
438 s = s + tb[i] + '\n';
432 s = s + tb[i] + '\n';
439 }
433 }
440 s = s + '\n';
434 s = s + '\n';
441 var toinsert = this.create_output_area();
435 var toinsert = this.create_output_area();
442 var append_text = OutputArea.append_map['text/plain'];
436 var append_text = OutputArea.append_map['text/plain'];
443 if (append_text) {
437 if (append_text) {
444 append_text.apply(this, [s, {}, toinsert]).addClass('output_error');
438 append_text.apply(this, [s, {}, toinsert]).addClass('output_error');
445 }
439 }
446 this._safe_append(toinsert);
440 this._safe_append(toinsert);
447 }
441 }
448 };
442 };
449
443
450
444
451 OutputArea.prototype.append_stream = function (json) {
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 var text = json.text;
446 var text = json.text;
458 var subclass = "output_"+json.stream;
447 var subclass = "output_"+json.name;
459 if (this.outputs.length > 0){
448 if (this.outputs.length > 0){
460 // have at least one output to consider
449 // have at least one output to consider
461 var last = this.outputs[this.outputs.length-1];
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 // latest output was in the same stream,
452 // latest output was in the same stream,
464 // so append directly into its pre tag
453 // so append directly into its pre tag
465 // escape ANSI & HTML specials:
454 // escape ANSI & HTML specials:
466 last.text = utils.fixCarriageReturn(last.text + json.text);
455 last.text = utils.fixCarriageReturn(last.text + json.text);
467 var pre = this.element.find('div.'+subclass).last().find('pre');
456 var pre = this.element.find('div.'+subclass).last().find('pre');
468 var html = utils.fixConsole(last.text);
457 var html = utils.fixConsole(last.text);
469 // The only user content injected with this HTML call is
458 // The only user content injected with this HTML call is
470 // escaped by the fixConsole() method.
459 // escaped by the fixConsole() method.
471 pre.html(html);
460 pre.html(html);
472 // return false signals that we merged this output with the previous one,
461 // return false signals that we merged this output with the previous one,
473 // and the new output shouldn't be recorded.
462 // and the new output shouldn't be recorded.
474 return false;
463 return false;
475 }
464 }
476 }
465 }
477
466
478 if (!text.replace("\r", "")) {
467 if (!text.replace("\r", "")) {
479 // text is nothing (empty string, \r, etc.)
468 // text is nothing (empty string, \r, etc.)
480 // so don't append any elements, which might add undesirable space
469 // so don't append any elements, which might add undesirable space
481 // return true to indicate the output should be recorded.
470 // return true to indicate the output should be recorded.
482 return true;
471 return true;
483 }
472 }
484
473
485 // If we got here, attach a new div
474 // If we got here, attach a new div
486 var toinsert = this.create_output_area();
475 var toinsert = this.create_output_area();
487 var append_text = OutputArea.append_map['text/plain'];
476 var append_text = OutputArea.append_map['text/plain'];
488 if (append_text) {
477 if (append_text) {
489 append_text.apply(this, [text, {}, toinsert]).addClass("output_stream " + subclass);
478 append_text.apply(this, [text, {}, toinsert]).addClass("output_stream " + subclass);
490 }
479 }
491 this._safe_append(toinsert);
480 this._safe_append(toinsert);
492 return true;
481 return true;
493 };
482 };
494
483
495
484
496 OutputArea.prototype.append_display_data = function (json, handle_inserted) {
485 OutputArea.prototype.append_display_data = function (json, handle_inserted) {
497 var toinsert = this.create_output_area();
486 var toinsert = this.create_output_area();
498 if (this.append_mime_type(json, toinsert, handle_inserted)) {
487 if (this.append_mime_type(json, toinsert, handle_inserted)) {
499 this._safe_append(toinsert);
488 this._safe_append(toinsert);
500 // If we just output latex, typeset it.
489 // If we just output latex, typeset it.
501 if ((json['text/latex'] !== undefined) ||
490 if ((json['text/latex'] !== undefined) ||
502 (json['text/html'] !== undefined) ||
491 (json['text/html'] !== undefined) ||
503 (json['text/markdown'] !== undefined)) {
492 (json['text/markdown'] !== undefined)) {
504 this.typeset();
493 this.typeset();
505 }
494 }
506 }
495 }
507 };
496 };
508
497
509
498
510 OutputArea.safe_outputs = {
499 OutputArea.safe_outputs = {
511 'text/plain' : true,
500 'text/plain' : true,
512 'text/latex' : true,
501 'text/latex' : true,
513 'image/png' : true,
502 'image/png' : true,
514 'image/jpeg' : true
503 'image/jpeg' : true
515 };
504 };
516
505
517 OutputArea.prototype.append_mime_type = function (json, element, handle_inserted) {
506 OutputArea.prototype.append_mime_type = function (json, element, handle_inserted) {
518 for (var i=0; i < OutputArea.display_order.length; i++) {
507 for (var i=0; i < OutputArea.display_order.length; i++) {
519 var type = OutputArea.display_order[i];
508 var type = OutputArea.display_order[i];
520 var append = OutputArea.append_map[type];
509 var append = OutputArea.append_map[type];
521 if ((json[type] !== undefined) && append) {
510 if ((json.data[type] !== undefined) && append) {
522 var value = json[type];
511 var value = json.data[type];
523 if (!this.trusted && !OutputArea.safe_outputs[type]) {
512 if (!this.trusted && !OutputArea.safe_outputs[type]) {
524 // not trusted, sanitize HTML
513 // not trusted, sanitize HTML
525 if (type==='text/html' || type==='text/svg') {
514 if (type==='text/html' || type==='text/svg') {
526 value = security.sanitize_html(value);
515 value = security.sanitize_html(value);
527 } else {
516 } else {
528 // don't display if we don't know how to sanitize it
517 // don't display if we don't know how to sanitize it
529 console.log("Ignoring untrusted " + type + " output.");
518 console.log("Ignoring untrusted " + type + " output.");
530 continue;
519 continue;
531 }
520 }
532 }
521 }
533 var md = json.metadata || {};
522 var md = json.metadata || {};
534 var toinsert = append.apply(this, [value, md, element, handle_inserted]);
523 var toinsert = append.apply(this, [value, md, element, handle_inserted]);
535 // Since only the png and jpeg mime types call the inserted
524 // Since only the png and jpeg mime types call the inserted
536 // callback, if the mime type is something other we must call the
525 // callback, if the mime type is something other we must call the
537 // inserted callback only when the element is actually inserted
526 // inserted callback only when the element is actually inserted
538 // into the DOM. Use a timeout of 0 to do this.
527 // into the DOM. Use a timeout of 0 to do this.
539 if (['image/png', 'image/jpeg'].indexOf(type) < 0 && handle_inserted !== undefined) {
528 if (['image/png', 'image/jpeg'].indexOf(type) < 0 && handle_inserted !== undefined) {
540 setTimeout(handle_inserted, 0);
529 setTimeout(handle_inserted, 0);
541 }
530 }
542 this.events.trigger('output_appended.OutputArea', [type, value, md, toinsert]);
531 this.events.trigger('output_appended.OutputArea', [type, value, md, toinsert]);
543 return toinsert;
532 return toinsert;
544 }
533 }
545 }
534 }
546 return null;
535 return null;
547 };
536 };
548
537
549
538
550 var append_html = function (html, md, element) {
539 var append_html = function (html, md, element) {
551 var type = 'text/html';
540 var type = 'text/html';
552 var toinsert = this.create_output_subarea(md, "output_html rendered_html", type);
541 var toinsert = this.create_output_subarea(md, "output_html rendered_html", type);
553 this.keyboard_manager.register_events(toinsert);
542 this.keyboard_manager.register_events(toinsert);
554 toinsert.append(html);
543 toinsert.append(html);
555 element.append(toinsert);
544 element.append(toinsert);
556 return toinsert;
545 return toinsert;
557 };
546 };
558
547
559
548
560 var append_markdown = function(markdown, md, element) {
549 var append_markdown = function(markdown, md, element) {
561 var type = 'text/markdown';
550 var type = 'text/markdown';
562 var toinsert = this.create_output_subarea(md, "output_markdown", type);
551 var toinsert = this.create_output_subarea(md, "output_markdown", type);
563 var text_and_math = mathjaxutils.remove_math(markdown);
552 var text_and_math = mathjaxutils.remove_math(markdown);
564 var text = text_and_math[0];
553 var text = text_and_math[0];
565 var math = text_and_math[1];
554 var math = text_and_math[1];
566 var html = marked.parser(marked.lexer(text));
555 var html = marked.parser(marked.lexer(text));
567 html = mathjaxutils.replace_math(html, math);
556 html = mathjaxutils.replace_math(html, math);
568 toinsert.append(html);
557 toinsert.append(html);
569 element.append(toinsert);
558 element.append(toinsert);
570 return toinsert;
559 return toinsert;
571 };
560 };
572
561
573
562
574 var append_javascript = function (js, md, element) {
563 var append_javascript = function (js, md, element) {
575 // We just eval the JS code, element appears in the local scope.
564 // We just eval the JS code, element appears in the local scope.
576 var type = 'application/javascript';
565 var type = 'application/javascript';
577 var toinsert = this.create_output_subarea(md, "output_javascript", type);
566 var toinsert = this.create_output_subarea(md, "output_javascript", type);
578 this.keyboard_manager.register_events(toinsert);
567 this.keyboard_manager.register_events(toinsert);
579 element.append(toinsert);
568 element.append(toinsert);
580
569
581 // Fix for ipython/issues/5293, make sure `element` is the area which
570 // Fix for ipython/issues/5293, make sure `element` is the area which
582 // output can be inserted into at the time of JS execution.
571 // output can be inserted into at the time of JS execution.
583 element = toinsert;
572 element = toinsert;
584 try {
573 try {
585 eval(js);
574 eval(js);
586 } catch(err) {
575 } catch(err) {
587 console.log(err);
576 console.log(err);
588 this._append_javascript_error(err, toinsert);
577 this._append_javascript_error(err, toinsert);
589 }
578 }
590 return toinsert;
579 return toinsert;
591 };
580 };
592
581
593
582
594 var append_text = function (data, md, element) {
583 var append_text = function (data, md, element) {
595 var type = 'text/plain';
584 var type = 'text/plain';
596 var toinsert = this.create_output_subarea(md, "output_text", type);
585 var toinsert = this.create_output_subarea(md, "output_text", type);
597 // escape ANSI & HTML specials in plaintext:
586 // escape ANSI & HTML specials in plaintext:
598 data = utils.fixConsole(data);
587 data = utils.fixConsole(data);
599 data = utils.fixCarriageReturn(data);
588 data = utils.fixCarriageReturn(data);
600 data = utils.autoLinkUrls(data);
589 data = utils.autoLinkUrls(data);
601 // The only user content injected with this HTML call is
590 // The only user content injected with this HTML call is
602 // escaped by the fixConsole() method.
591 // escaped by the fixConsole() method.
603 toinsert.append($("<pre/>").html(data));
592 toinsert.append($("<pre/>").html(data));
604 element.append(toinsert);
593 element.append(toinsert);
605 return toinsert;
594 return toinsert;
606 };
595 };
607
596
608
597
609 var append_svg = function (svg_html, md, element) {
598 var append_svg = function (svg_html, md, element) {
610 var type = 'image/svg+xml';
599 var type = 'image/svg+xml';
611 var toinsert = this.create_output_subarea(md, "output_svg", type);
600 var toinsert = this.create_output_subarea(md, "output_svg", type);
612
601
613 // Get the svg element from within the HTML.
602 // Get the svg element from within the HTML.
614 var svg = $('<div />').html(svg_html).find('svg');
603 var svg = $('<div />').html(svg_html).find('svg');
615 var svg_area = $('<div />');
604 var svg_area = $('<div />');
616 var width = svg.attr('width');
605 var width = svg.attr('width');
617 var height = svg.attr('height');
606 var height = svg.attr('height');
618 svg
607 svg
619 .width('100%')
608 .width('100%')
620 .height('100%');
609 .height('100%');
621 svg_area
610 svg_area
622 .width(width)
611 .width(width)
623 .height(height);
612 .height(height);
624
613
625 // The jQuery resize handlers don't seem to work on the svg element.
614 // The jQuery resize handlers don't seem to work on the svg element.
626 // When the svg renders completely, measure it's size and set the parent
615 // When the svg renders completely, measure it's size and set the parent
627 // div to that size. Then set the svg to 100% the size of the parent
616 // div to that size. Then set the svg to 100% the size of the parent
628 // div and make the parent div resizable.
617 // div and make the parent div resizable.
629 this._dblclick_to_reset_size(svg_area, true, false);
618 this._dblclick_to_reset_size(svg_area, true, false);
630
619
631 svg_area.append(svg);
620 svg_area.append(svg);
632 toinsert.append(svg_area);
621 toinsert.append(svg_area);
633 element.append(toinsert);
622 element.append(toinsert);
634
623
635 return toinsert;
624 return toinsert;
636 };
625 };
637
626
638 OutputArea.prototype._dblclick_to_reset_size = function (img, immediately, resize_parent) {
627 OutputArea.prototype._dblclick_to_reset_size = function (img, immediately, resize_parent) {
639 // Add a resize handler to an element
628 // Add a resize handler to an element
640 //
629 //
641 // img: jQuery element
630 // img: jQuery element
642 // immediately: bool=False
631 // immediately: bool=False
643 // Wait for the element to load before creating the handle.
632 // Wait for the element to load before creating the handle.
644 // resize_parent: bool=True
633 // resize_parent: bool=True
645 // Should the parent of the element be resized when the element is
634 // Should the parent of the element be resized when the element is
646 // reset (by double click).
635 // reset (by double click).
647 var callback = function (){
636 var callback = function (){
648 var h0 = img.height();
637 var h0 = img.height();
649 var w0 = img.width();
638 var w0 = img.width();
650 if (!(h0 && w0)) {
639 if (!(h0 && w0)) {
651 // zero size, don't make it resizable
640 // zero size, don't make it resizable
652 return;
641 return;
653 }
642 }
654 img.resizable({
643 img.resizable({
655 aspectRatio: true,
644 aspectRatio: true,
656 autoHide: true
645 autoHide: true
657 });
646 });
658 img.dblclick(function () {
647 img.dblclick(function () {
659 // resize wrapper & image together for some reason:
648 // resize wrapper & image together for some reason:
660 img.height(h0);
649 img.height(h0);
661 img.width(w0);
650 img.width(w0);
662 if (resize_parent === undefined || resize_parent) {
651 if (resize_parent === undefined || resize_parent) {
663 img.parent().height(h0);
652 img.parent().height(h0);
664 img.parent().width(w0);
653 img.parent().width(w0);
665 }
654 }
666 });
655 });
667 };
656 };
668
657
669 if (immediately) {
658 if (immediately) {
670 callback();
659 callback();
671 } else {
660 } else {
672 img.on("load", callback);
661 img.on("load", callback);
673 }
662 }
674 };
663 };
675
664
676 var set_width_height = function (img, md, mime) {
665 var set_width_height = function (img, md, mime) {
677 // set width and height of an img element from metadata
666 // set width and height of an img element from metadata
678 var height = _get_metadata_key(md, 'height', mime);
667 var height = _get_metadata_key(md, 'height', mime);
679 if (height !== undefined) img.attr('height', height);
668 if (height !== undefined) img.attr('height', height);
680 var width = _get_metadata_key(md, 'width', mime);
669 var width = _get_metadata_key(md, 'width', mime);
681 if (width !== undefined) img.attr('width', width);
670 if (width !== undefined) img.attr('width', width);
682 };
671 };
683
672
684 var append_png = function (png, md, element, handle_inserted) {
673 var append_png = function (png, md, element, handle_inserted) {
685 var type = 'image/png';
674 var type = 'image/png';
686 var toinsert = this.create_output_subarea(md, "output_png", type);
675 var toinsert = this.create_output_subarea(md, "output_png", type);
687 var img = $("<img/>");
676 var img = $("<img/>");
688 if (handle_inserted !== undefined) {
677 if (handle_inserted !== undefined) {
689 img.on('load', function(){
678 img.on('load', function(){
690 handle_inserted(img);
679 handle_inserted(img);
691 });
680 });
692 }
681 }
693 img[0].src = 'data:image/png;base64,'+ png;
682 img[0].src = 'data:image/png;base64,'+ png;
694 set_width_height(img, md, 'image/png');
683 set_width_height(img, md, 'image/png');
695 this._dblclick_to_reset_size(img);
684 this._dblclick_to_reset_size(img);
696 toinsert.append(img);
685 toinsert.append(img);
697 element.append(toinsert);
686 element.append(toinsert);
698 return toinsert;
687 return toinsert;
699 };
688 };
700
689
701
690
702 var append_jpeg = function (jpeg, md, element, handle_inserted) {
691 var append_jpeg = function (jpeg, md, element, handle_inserted) {
703 var type = 'image/jpeg';
692 var type = 'image/jpeg';
704 var toinsert = this.create_output_subarea(md, "output_jpeg", type);
693 var toinsert = this.create_output_subarea(md, "output_jpeg", type);
705 var img = $("<img/>");
694 var img = $("<img/>");
706 if (handle_inserted !== undefined) {
695 if (handle_inserted !== undefined) {
707 img.on('load', function(){
696 img.on('load', function(){
708 handle_inserted(img);
697 handle_inserted(img);
709 });
698 });
710 }
699 }
711 img[0].src = 'data:image/jpeg;base64,'+ jpeg;
700 img[0].src = 'data:image/jpeg;base64,'+ jpeg;
712 set_width_height(img, md, 'image/jpeg');
701 set_width_height(img, md, 'image/jpeg');
713 this._dblclick_to_reset_size(img);
702 this._dblclick_to_reset_size(img);
714 toinsert.append(img);
703 toinsert.append(img);
715 element.append(toinsert);
704 element.append(toinsert);
716 return toinsert;
705 return toinsert;
717 };
706 };
718
707
719
708
720 var append_pdf = function (pdf, md, element) {
709 var append_pdf = function (pdf, md, element) {
721 var type = 'application/pdf';
710 var type = 'application/pdf';
722 var toinsert = this.create_output_subarea(md, "output_pdf", type);
711 var toinsert = this.create_output_subarea(md, "output_pdf", type);
723 var a = $('<a/>').attr('href', 'data:application/pdf;base64,'+pdf);
712 var a = $('<a/>').attr('href', 'data:application/pdf;base64,'+pdf);
724 a.attr('target', '_blank');
713 a.attr('target', '_blank');
725 a.text('View PDF')
714 a.text('View PDF');
726 toinsert.append(a);
715 toinsert.append(a);
727 element.append(toinsert);
716 element.append(toinsert);
728 return toinsert;
717 return toinsert;
729 }
718 };
730
719
731 var append_latex = function (latex, md, element) {
720 var append_latex = function (latex, md, element) {
732 // This method cannot do the typesetting because the latex first has to
721 // This method cannot do the typesetting because the latex first has to
733 // be on the page.
722 // be on the page.
734 var type = 'text/latex';
723 var type = 'text/latex';
735 var toinsert = this.create_output_subarea(md, "output_latex", type);
724 var toinsert = this.create_output_subarea(md, "output_latex", type);
736 toinsert.append(latex);
725 toinsert.append(latex);
737 element.append(toinsert);
726 element.append(toinsert);
738 return toinsert;
727 return toinsert;
739 };
728 };
740
729
741
730
742 OutputArea.prototype.append_raw_input = function (msg) {
731 OutputArea.prototype.append_raw_input = function (msg) {
743 var that = this;
732 var that = this;
744 this.expand();
733 this.expand();
745 var content = msg.content;
734 var content = msg.content;
746 var area = this.create_output_area();
735 var area = this.create_output_area();
747
736
748 // disable any other raw_inputs, if they are left around
737 // disable any other raw_inputs, if they are left around
749 $("div.output_subarea.raw_input_container").remove();
738 $("div.output_subarea.raw_input_container").remove();
750
739
751 var input_type = content.password ? 'password' : 'text';
740 var input_type = content.password ? 'password' : 'text';
752
741
753 area.append(
742 area.append(
754 $("<div/>")
743 $("<div/>")
755 .addClass("box-flex1 output_subarea raw_input_container")
744 .addClass("box-flex1 output_subarea raw_input_container")
756 .append(
745 .append(
757 $("<span/>")
746 $("<span/>")
758 .addClass("raw_input_prompt")
747 .addClass("raw_input_prompt")
759 .text(content.prompt)
748 .text(content.prompt)
760 )
749 )
761 .append(
750 .append(
762 $("<input/>")
751 $("<input/>")
763 .addClass("raw_input")
752 .addClass("raw_input")
764 .attr('type', input_type)
753 .attr('type', input_type)
765 .attr("size", 47)
754 .attr("size", 47)
766 .keydown(function (event, ui) {
755 .keydown(function (event, ui) {
767 // make sure we submit on enter,
756 // make sure we submit on enter,
768 // and don't re-execute the *cell* on shift-enter
757 // and don't re-execute the *cell* on shift-enter
769 if (event.which === keyboard.keycodes.enter) {
758 if (event.which === keyboard.keycodes.enter) {
770 that._submit_raw_input();
759 that._submit_raw_input();
771 return false;
760 return false;
772 }
761 }
773 })
762 })
774 )
763 )
775 );
764 );
776
765
777 this.element.append(area);
766 this.element.append(area);
778 var raw_input = area.find('input.raw_input');
767 var raw_input = area.find('input.raw_input');
779 // Register events that enable/disable the keyboard manager while raw
768 // Register events that enable/disable the keyboard manager while raw
780 // input is focused.
769 // input is focused.
781 this.keyboard_manager.register_events(raw_input);
770 this.keyboard_manager.register_events(raw_input);
782 // Note, the following line used to read raw_input.focus().focus().
771 // Note, the following line used to read raw_input.focus().focus().
783 // This seemed to be needed otherwise only the cell would be focused.
772 // This seemed to be needed otherwise only the cell would be focused.
784 // But with the modal UI, this seems to work fine with one call to focus().
773 // But with the modal UI, this seems to work fine with one call to focus().
785 raw_input.focus();
774 raw_input.focus();
786 }
775 };
787
776
788 OutputArea.prototype._submit_raw_input = function (evt) {
777 OutputArea.prototype._submit_raw_input = function (evt) {
789 var container = this.element.find("div.raw_input_container");
778 var container = this.element.find("div.raw_input_container");
790 var theprompt = container.find("span.raw_input_prompt");
779 var theprompt = container.find("span.raw_input_prompt");
791 var theinput = container.find("input.raw_input");
780 var theinput = container.find("input.raw_input");
792 var value = theinput.val();
781 var value = theinput.val();
793 var echo = value;
782 var echo = value;
794 // don't echo if it's a password
783 // don't echo if it's a password
795 if (theinput.attr('type') == 'password') {
784 if (theinput.attr('type') == 'password') {
796 echo = '········';
785 echo = '········';
797 }
786 }
798 var content = {
787 var content = {
799 output_type : 'stream',
788 output_type : 'stream',
800 stream : 'stdout',
789 stream : 'stdout',
801 text : theprompt.text() + echo + '\n'
790 text : theprompt.text() + echo + '\n'
802 }
791 };
803 // remove form container
792 // remove form container
804 container.parent().remove();
793 container.parent().remove();
805 // replace with plaintext version in stdout
794 // replace with plaintext version in stdout
806 this.append_output(content, false);
795 this.append_output(content, false);
807 this.events.trigger('send_input_reply.Kernel', value);
796 this.events.trigger('send_input_reply.Kernel', value);
808 }
797 };
809
798
810
799
811 OutputArea.prototype.handle_clear_output = function (msg) {
800 OutputArea.prototype.handle_clear_output = function (msg) {
812 // msg spec v4 had stdout, stderr, display keys
801 // msg spec v4 had stdout, stderr, display keys
813 // v4.1 replaced these with just wait
802 // v4.1 replaced these with just wait
814 // The default behavior is the same (stdout=stderr=display=True, wait=False),
803 // The default behavior is the same (stdout=stderr=display=True, wait=False),
815 // so v4 messages will still be properly handled,
804 // so v4 messages will still be properly handled,
816 // except for the rarely used clearing less than all output.
805 // except for the rarely used clearing less than all output.
817 this.clear_output(msg.content.wait || false);
806 this.clear_output(msg.content.wait || false);
818 };
807 };
819
808
820
809
821 OutputArea.prototype.clear_output = function(wait) {
810 OutputArea.prototype.clear_output = function(wait) {
822 if (wait) {
811 if (wait) {
823
812
824 // If a clear is queued, clear before adding another to the queue.
813 // If a clear is queued, clear before adding another to the queue.
825 if (this.clear_queued) {
814 if (this.clear_queued) {
826 this.clear_output(false);
815 this.clear_output(false);
827 };
816 }
828
817
829 this.clear_queued = true;
818 this.clear_queued = true;
830 } else {
819 } else {
831
820
832 // Fix the output div's height if the clear_output is waiting for
821 // Fix the output div's height if the clear_output is waiting for
833 // new output (it is being used in an animation).
822 // new output (it is being used in an animation).
834 if (this.clear_queued) {
823 if (this.clear_queued) {
835 var height = this.element.height();
824 var height = this.element.height();
836 this.element.height(height);
825 this.element.height(height);
837 this.clear_queued = false;
826 this.clear_queued = false;
838 }
827 }
839
828
840 // Clear all
829 // Clear all
841 // Remove load event handlers from img tags because we don't want
830 // Remove load event handlers from img tags because we don't want
842 // them to fire if the image is never added to the page.
831 // them to fire if the image is never added to the page.
843 this.element.find('img').off('load');
832 this.element.find('img').off('load');
844 this.element.html("");
833 this.element.html("");
845 this.outputs = [];
834 this.outputs = [];
846 this.trusted = true;
835 this.trusted = true;
847 this.unscroll_area();
836 this.unscroll_area();
848 return;
837 return;
849 };
838 }
850 };
839 };
851
840
852
841
853 // JSON serialization
842 // JSON serialization
854
843
855 OutputArea.prototype.fromJSON = function (outputs) {
844 OutputArea.prototype.fromJSON = function (outputs, metadata) {
856 var len = outputs.length;
845 var len = outputs.length;
857 var data;
846 metadata = metadata || {};
858
847
859 for (var i=0; i<len; i++) {
848 for (var i=0; i<len; i++) {
860 data = outputs[i];
849 this.append_output(outputs[i]);
861 var msg_type = data.output_type;
850 }
862 if (msg_type == "pyout") {
851
863 // pyout message has been renamed to execute_result,
852 if (metadata.collapsed !== undefined) {
864 // but the nbformat has not been updated,
853 this.collapsed = metadata.collapsed;
865 // so transform back to pyout for json.
854 if (metadata.collapsed) {
866 msg_type = data.output_type = "execute_result";
855 this.collapse_output();
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";
872 }
856 }
873 if (msg_type === "display_data" || msg_type === "execute_result") {
857 }
874 // convert short keys to mime keys
858 if (metadata.autoscroll !== undefined) {
875 // TODO: remove mapping of short keys when we update to nbformat 4
859 this.collapsed = metadata.collapsed;
876 data = this.rename_keys(data, OutputArea.mime_map_r);
860 if (metadata.collapsed) {
877 data.metadata = this.rename_keys(data.metadata, OutputArea.mime_map_r);
861 this.collapse_output();
878 // msg spec JSON is an object, nbformat v3 JSON is a JSON string
862 } else {
879 if (data["application/json"] !== undefined && typeof data["application/json"] === 'string') {
863 this.expand_output();
880 data["application/json"] = JSON.parse(data["application/json"]);
881 }
882 }
864 }
883
884 this.append_output(data);
885 }
865 }
886 };
866 };
887
867
888
868
889 OutputArea.prototype.toJSON = function () {
869 OutputArea.prototype.toJSON = function () {
890 var outputs = [];
870 return this.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;
919 };
871 };
920
872
921 /**
873 /**
922 * Class properties
874 * Class properties
923 **/
875 **/
924
876
925 /**
877 /**
926 * Threshold to trigger autoscroll when the OutputArea is resized,
878 * Threshold to trigger autoscroll when the OutputArea is resized,
927 * typically when new outputs are added.
879 * typically when new outputs are added.
928 *
880 *
929 * Behavior is undefined if autoscroll is lower than minimum_scroll_threshold,
881 * Behavior is undefined if autoscroll is lower than minimum_scroll_threshold,
930 * unless it is < 0, in which case autoscroll will never be triggered
882 * unless it is < 0, in which case autoscroll will never be triggered
931 *
883 *
932 * @property auto_scroll_threshold
884 * @property auto_scroll_threshold
933 * @type Number
885 * @type Number
934 * @default 100
886 * @default 100
935 *
887 *
936 **/
888 **/
937 OutputArea.auto_scroll_threshold = 100;
889 OutputArea.auto_scroll_threshold = 100;
938
890
939 /**
891 /**
940 * Lower limit (in lines) for OutputArea to be made scrollable. OutputAreas
892 * Lower limit (in lines) for OutputArea to be made scrollable. OutputAreas
941 * shorter than this are never scrolled.
893 * shorter than this are never scrolled.
942 *
894 *
943 * @property minimum_scroll_threshold
895 * @property minimum_scroll_threshold
944 * @type Number
896 * @type Number
945 * @default 20
897 * @default 20
946 *
898 *
947 **/
899 **/
948 OutputArea.minimum_scroll_threshold = 20;
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 OutputArea.display_order = [
903 OutputArea.display_order = [
975 'application/javascript',
904 'application/javascript',
976 'text/html',
905 'text/html',
977 'text/markdown',
906 'text/markdown',
978 'text/latex',
907 'text/latex',
979 'image/svg+xml',
908 'image/svg+xml',
980 'image/png',
909 'image/png',
981 'image/jpeg',
910 'image/jpeg',
982 'application/pdf',
911 'application/pdf',
983 'text/plain'
912 'text/plain'
984 ];
913 ];
985
914
986 OutputArea.append_map = {
915 OutputArea.append_map = {
987 "text/plain" : append_text,
916 "text/plain" : append_text,
988 "text/html" : append_html,
917 "text/html" : append_html,
989 "text/markdown": append_markdown,
918 "text/markdown": append_markdown,
990 "image/svg+xml" : append_svg,
919 "image/svg+xml" : append_svg,
991 "image/png" : append_png,
920 "image/png" : append_png,
992 "image/jpeg" : append_jpeg,
921 "image/jpeg" : append_jpeg,
993 "text/latex" : append_latex,
922 "text/latex" : append_latex,
994 "application/javascript" : append_javascript,
923 "application/javascript" : append_javascript,
995 "application/pdf" : append_pdf
924 "application/pdf" : append_pdf
996 };
925 };
997
926
998 // For backwards compatability.
927 // For backwards compatability.
999 IPython.OutputArea = OutputArea;
928 IPython.OutputArea = OutputArea;
1000
929
1001 return {'OutputArea': OutputArea};
930 return {'OutputArea': OutputArea};
1002 });
931 });
@@ -1,425 +1,345 b''
1 // Copyright (c) IPython Development Team.
1 // Copyright (c) IPython Development Team.
2 // Distributed under the terms of the Modified BSD License.
2 // Distributed under the terms of the Modified BSD License.
3
3
4 define([
4 define([
5 'base/js/namespace',
5 'base/js/namespace',
6 'base/js/utils',
6 'base/js/utils',
7 'jquery',
7 'jquery',
8 'notebook/js/cell',
8 'notebook/js/cell',
9 'base/js/security',
9 'base/js/security',
10 'notebook/js/mathjaxutils',
10 'notebook/js/mathjaxutils',
11 'notebook/js/celltoolbar',
11 'notebook/js/celltoolbar',
12 'components/marked/lib/marked',
12 'components/marked/lib/marked',
13 'codemirror/lib/codemirror',
13 'codemirror/lib/codemirror',
14 'codemirror/mode/gfm/gfm',
14 'codemirror/mode/gfm/gfm',
15 'notebook/js/codemirror-ipythongfm'
15 'notebook/js/codemirror-ipythongfm'
16 ], function(IPython,utils , $, cell, security, mathjaxutils, celltoolbar, marked, CodeMirror, gfm, ipgfm) {
16 ], function(IPython,utils , $, cell, security, mathjaxutils, celltoolbar, marked, CodeMirror, gfm, ipgfm) {
17 "use strict";
17 "use strict";
18 var Cell = cell.Cell;
18 var Cell = cell.Cell;
19
19
20 var TextCell = function (options) {
20 var TextCell = function (options) {
21 // Constructor
21 // Constructor
22 //
22 //
23 // Construct a new TextCell, codemirror mode is by default 'htmlmixed',
23 // Construct a new TextCell, codemirror mode is by default 'htmlmixed',
24 // and cell type is 'text' cell start as not redered.
24 // and cell type is 'text' cell start as not redered.
25 //
25 //
26 // Parameters:
26 // Parameters:
27 // options: dictionary
27 // options: dictionary
28 // Dictionary of keyword arguments.
28 // Dictionary of keyword arguments.
29 // events: $(Events) instance
29 // events: $(Events) instance
30 // config: dictionary
30 // config: dictionary
31 // keyboard_manager: KeyboardManager instance
31 // keyboard_manager: KeyboardManager instance
32 // notebook: Notebook instance
32 // notebook: Notebook instance
33 options = options || {};
33 options = options || {};
34
34
35 // in all TextCell/Cell subclasses
35 // in all TextCell/Cell subclasses
36 // do not assign most of members here, just pass it down
36 // do not assign most of members here, just pass it down
37 // in the options dict potentially overwriting what you wish.
37 // in the options dict potentially overwriting what you wish.
38 // they will be assigned in the base class.
38 // they will be assigned in the base class.
39 this.notebook = options.notebook;
39 this.notebook = options.notebook;
40 this.events = options.events;
40 this.events = options.events;
41 this.config = options.config;
41 this.config = options.config;
42
42
43 // we cannot put this as a class key as it has handle to "this".
43 // we cannot put this as a class key as it has handle to "this".
44 var cm_overwrite_options = {
44 var cm_overwrite_options = {
45 onKeyEvent: $.proxy(this.handle_keyevent,this)
45 onKeyEvent: $.proxy(this.handle_keyevent,this)
46 };
46 };
47 var config = utils.mergeopt(TextCell, this.config, {cm_config:cm_overwrite_options});
47 var config = utils.mergeopt(TextCell, this.config, {cm_config:cm_overwrite_options});
48 Cell.apply(this, [{
48 Cell.apply(this, [{
49 config: config,
49 config: config,
50 keyboard_manager: options.keyboard_manager,
50 keyboard_manager: options.keyboard_manager,
51 events: this.events}]);
51 events: this.events}]);
52
52
53 this.cell_type = this.cell_type || 'text';
53 this.cell_type = this.cell_type || 'text';
54 mathjaxutils = mathjaxutils;
54 mathjaxutils = mathjaxutils;
55 this.rendered = false;
55 this.rendered = false;
56 };
56 };
57
57
58 TextCell.prototype = Object.create(Cell.prototype);
58 TextCell.prototype = Object.create(Cell.prototype);
59
59
60 TextCell.options_default = {
60 TextCell.options_default = {
61 cm_config : {
61 cm_config : {
62 extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess"},
62 extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess"},
63 mode: 'htmlmixed',
63 mode: 'htmlmixed',
64 lineWrapping : true,
64 lineWrapping : true,
65 }
65 }
66 };
66 };
67
67
68
68
69 /**
69 /**
70 * Create the DOM element of the TextCell
70 * Create the DOM element of the TextCell
71 * @method create_element
71 * @method create_element
72 * @private
72 * @private
73 */
73 */
74 TextCell.prototype.create_element = function () {
74 TextCell.prototype.create_element = function () {
75 Cell.prototype.create_element.apply(this, arguments);
75 Cell.prototype.create_element.apply(this, arguments);
76
76
77 var cell = $("<div>").addClass('cell text_cell');
77 var cell = $("<div>").addClass('cell text_cell');
78 cell.attr('tabindex','2');
78 cell.attr('tabindex','2');
79
79
80 var prompt = $('<div/>').addClass('prompt input_prompt');
80 var prompt = $('<div/>').addClass('prompt input_prompt');
81 cell.append(prompt);
81 cell.append(prompt);
82 var inner_cell = $('<div/>').addClass('inner_cell');
82 var inner_cell = $('<div/>').addClass('inner_cell');
83 this.celltoolbar = new celltoolbar.CellToolbar({
83 this.celltoolbar = new celltoolbar.CellToolbar({
84 cell: this,
84 cell: this,
85 notebook: this.notebook});
85 notebook: this.notebook});
86 inner_cell.append(this.celltoolbar.element);
86 inner_cell.append(this.celltoolbar.element);
87 var input_area = $('<div/>').addClass('input_area');
87 var input_area = $('<div/>').addClass('input_area');
88 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
88 this.code_mirror = new CodeMirror(input_area.get(0), this.cm_config);
89 // The tabindex=-1 makes this div focusable.
89 // The tabindex=-1 makes this div focusable.
90 var render_area = $('<div/>').addClass('text_cell_render rendered_html')
90 var render_area = $('<div/>').addClass('text_cell_render rendered_html')
91 .attr('tabindex','-1');
91 .attr('tabindex','-1');
92 inner_cell.append(input_area).append(render_area);
92 inner_cell.append(input_area).append(render_area);
93 cell.append(inner_cell);
93 cell.append(inner_cell);
94 this.element = cell;
94 this.element = cell;
95 };
95 };
96
96
97
97
98 // Cell level actions
98 // Cell level actions
99
99
100 TextCell.prototype.select = function () {
100 TextCell.prototype.select = function () {
101 var cont = Cell.prototype.select.apply(this);
101 var cont = Cell.prototype.select.apply(this);
102 if (cont) {
102 if (cont) {
103 if (this.mode === 'edit') {
103 if (this.mode === 'edit') {
104 this.code_mirror.refresh();
104 this.code_mirror.refresh();
105 }
105 }
106 }
106 }
107 return cont;
107 return cont;
108 };
108 };
109
109
110 TextCell.prototype.unrender = function () {
110 TextCell.prototype.unrender = function () {
111 if (this.read_only) return;
111 if (this.read_only) return;
112 var cont = Cell.prototype.unrender.apply(this);
112 var cont = Cell.prototype.unrender.apply(this);
113 if (cont) {
113 if (cont) {
114 var text_cell = this.element;
114 var text_cell = this.element;
115 var output = text_cell.find("div.text_cell_render");
115 var output = text_cell.find("div.text_cell_render");
116 if (this.get_text() === this.placeholder) {
116 if (this.get_text() === this.placeholder) {
117 this.set_text('');
117 this.set_text('');
118 }
118 }
119 this.refresh();
119 this.refresh();
120 }
120 }
121 return cont;
121 return cont;
122 };
122 };
123
123
124 TextCell.prototype.execute = function () {
124 TextCell.prototype.execute = function () {
125 this.render();
125 this.render();
126 };
126 };
127
127
128 /**
128 /**
129 * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
129 * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
130 * @method get_text
130 * @method get_text
131 * @retrun {string} CodeMirror current text value
131 * @retrun {string} CodeMirror current text value
132 */
132 */
133 TextCell.prototype.get_text = function() {
133 TextCell.prototype.get_text = function() {
134 return this.code_mirror.getValue();
134 return this.code_mirror.getValue();
135 };
135 };
136
136
137 /**
137 /**
138 * @param {string} text - Codemiror text value
138 * @param {string} text - Codemiror text value
139 * @see TextCell#get_text
139 * @see TextCell#get_text
140 * @method set_text
140 * @method set_text
141 * */
141 * */
142 TextCell.prototype.set_text = function(text) {
142 TextCell.prototype.set_text = function(text) {
143 this.code_mirror.setValue(text);
143 this.code_mirror.setValue(text);
144 this.unrender();
144 this.unrender();
145 this.code_mirror.refresh();
145 this.code_mirror.refresh();
146 };
146 };
147
147
148 /**
148 /**
149 * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
149 * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
150 * @method get_rendered
150 * @method get_rendered
151 * */
151 * */
152 TextCell.prototype.get_rendered = function() {
152 TextCell.prototype.get_rendered = function() {
153 return this.element.find('div.text_cell_render').html();
153 return this.element.find('div.text_cell_render').html();
154 };
154 };
155
155
156 /**
156 /**
157 * @method set_rendered
157 * @method set_rendered
158 */
158 */
159 TextCell.prototype.set_rendered = function(text) {
159 TextCell.prototype.set_rendered = function(text) {
160 this.element.find('div.text_cell_render').html(text);
160 this.element.find('div.text_cell_render').html(text);
161 };
161 };
162
162
163
163
164 /**
164 /**
165 * Create Text cell from JSON
165 * Create Text cell from JSON
166 * @param {json} data - JSON serialized text-cell
166 * @param {json} data - JSON serialized text-cell
167 * @method fromJSON
167 * @method fromJSON
168 */
168 */
169 TextCell.prototype.fromJSON = function (data) {
169 TextCell.prototype.fromJSON = function (data) {
170 Cell.prototype.fromJSON.apply(this, arguments);
170 Cell.prototype.fromJSON.apply(this, arguments);
171 if (data.cell_type === this.cell_type) {
171 if (data.cell_type === this.cell_type) {
172 if (data.source !== undefined) {
172 if (data.source !== undefined) {
173 this.set_text(data.source);
173 this.set_text(data.source);
174 // make this value the starting point, so that we can only undo
174 // make this value the starting point, so that we can only undo
175 // to this state, instead of a blank cell
175 // to this state, instead of a blank cell
176 this.code_mirror.clearHistory();
176 this.code_mirror.clearHistory();
177 // TODO: This HTML needs to be treated as potentially dangerous
177 // TODO: This HTML needs to be treated as potentially dangerous
178 // user input and should be handled before set_rendered.
178 // user input and should be handled before set_rendered.
179 this.set_rendered(data.rendered || '');
179 this.set_rendered(data.rendered || '');
180 this.rendered = false;
180 this.rendered = false;
181 this.render();
181 this.render();
182 }
182 }
183 }
183 }
184 };
184 };
185
185
186 /** Generate JSON from cell
186 /** Generate JSON from cell
187 * @return {object} cell data serialised to json
187 * @return {object} cell data serialised to json
188 */
188 */
189 TextCell.prototype.toJSON = function () {
189 TextCell.prototype.toJSON = function () {
190 var data = Cell.prototype.toJSON.apply(this);
190 var data = Cell.prototype.toJSON.apply(this);
191 data.source = this.get_text();
191 data.source = this.get_text();
192 if (data.source == this.placeholder) {
192 if (data.source == this.placeholder) {
193 data.source = "";
193 data.source = "";
194 }
194 }
195 return data;
195 return data;
196 };
196 };
197
197
198
198
199 var MarkdownCell = function (options) {
199 var MarkdownCell = function (options) {
200 // Constructor
200 // Constructor
201 //
201 //
202 // Parameters:
202 // Parameters:
203 // options: dictionary
203 // options: dictionary
204 // Dictionary of keyword arguments.
204 // Dictionary of keyword arguments.
205 // events: $(Events) instance
205 // events: $(Events) instance
206 // config: dictionary
206 // config: dictionary
207 // keyboard_manager: KeyboardManager instance
207 // keyboard_manager: KeyboardManager instance
208 // notebook: Notebook instance
208 // notebook: Notebook instance
209 options = options || {};
209 options = options || {};
210 var config = utils.mergeopt(MarkdownCell, options.config);
210 var config = utils.mergeopt(MarkdownCell, options.config);
211 TextCell.apply(this, [$.extend({}, options, {config: config})]);
211 TextCell.apply(this, [$.extend({}, options, {config: config})]);
212
212
213 this.cell_type = 'markdown';
213 this.cell_type = 'markdown';
214 };
214 };
215
215
216 MarkdownCell.options_default = {
216 MarkdownCell.options_default = {
217 cm_config: {
217 cm_config: {
218 mode: 'ipythongfm'
218 mode: 'ipythongfm'
219 },
219 },
220 placeholder: "Type *Markdown* and LaTeX: $\\alpha^2$"
220 placeholder: "Type *Markdown* and LaTeX: $\\alpha^2$"
221 };
221 };
222
222
223 MarkdownCell.prototype = Object.create(TextCell.prototype);
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 * @method render
239 * @method render
227 */
240 */
228 MarkdownCell.prototype.render = function () {
241 MarkdownCell.prototype.render = function () {
229 var cont = TextCell.prototype.render.apply(this);
242 var cont = TextCell.prototype.render.apply(this);
230 if (cont) {
243 if (cont) {
231 var text = this.get_text();
244 var text = this.get_text();
232 var math = null;
245 var math = null;
233 if (text === "") { text = this.placeholder; }
246 if (text === "") { text = this.placeholder; }
234 var text_and_math = mathjaxutils.remove_math(text);
247 var text_and_math = mathjaxutils.remove_math(text);
235 text = text_and_math[0];
248 text = text_and_math[0];
236 math = text_and_math[1];
249 math = text_and_math[1];
237 var html = marked.parser(marked.lexer(text));
250 var html = marked.parser(marked.lexer(text));
238 html = mathjaxutils.replace_math(html, math);
251 html = mathjaxutils.replace_math(html, math);
239 html = security.sanitize_html(html);
252 html = security.sanitize_html(html);
240 html = $($.parseHTML(html));
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 // links in markdown cells should open in new tabs
267 // links in markdown cells should open in new tabs
242 html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
268 html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
243 this.set_rendered(html);
269 this.set_rendered(html);
244 this.typeset();
270 this.typeset();
245 this.events.trigger("rendered.MarkdownCell", {cell: this})
271 this.events.trigger("rendered.MarkdownCell", {cell: this})
246 }
272 }
247 return cont;
273 return cont;
248 };
274 };
249
275
250
276
251 var RawCell = function (options) {
277 var RawCell = function (options) {
252 // Constructor
278 // Constructor
253 //
279 //
254 // Parameters:
280 // Parameters:
255 // options: dictionary
281 // options: dictionary
256 // Dictionary of keyword arguments.
282 // Dictionary of keyword arguments.
257 // events: $(Events) instance
283 // events: $(Events) instance
258 // config: dictionary
284 // config: dictionary
259 // keyboard_manager: KeyboardManager instance
285 // keyboard_manager: KeyboardManager instance
260 // notebook: Notebook instance
286 // notebook: Notebook instance
261 options = options || {};
287 options = options || {};
262 var config = utils.mergeopt(RawCell, options.config);
288 var config = utils.mergeopt(RawCell, options.config);
263 TextCell.apply(this, [$.extend({}, options, {config: config})]);
289 TextCell.apply(this, [$.extend({}, options, {config: config})]);
264
290
265 this.cell_type = 'raw';
291 this.cell_type = 'raw';
266 };
292 };
267
293
268 RawCell.options_default = {
294 RawCell.options_default = {
269 placeholder : "Write raw LaTeX or other formats here, for use with nbconvert. " +
295 placeholder : "Write raw LaTeX or other formats here, for use with nbconvert. " +
270 "It will not be rendered in the notebook. " +
296 "It will not be rendered in the notebook. " +
271 "When passing through nbconvert, a Raw Cell's content is added to the output unmodified."
297 "When passing through nbconvert, a Raw Cell's content is added to the output unmodified."
272 };
298 };
273
299
274 RawCell.prototype = Object.create(TextCell.prototype);
300 RawCell.prototype = Object.create(TextCell.prototype);
275
301
276 /** @method bind_events **/
302 /** @method bind_events **/
277 RawCell.prototype.bind_events = function () {
303 RawCell.prototype.bind_events = function () {
278 TextCell.prototype.bind_events.apply(this);
304 TextCell.prototype.bind_events.apply(this);
279 var that = this;
305 var that = this;
280 this.element.focusout(function() {
306 this.element.focusout(function() {
281 that.auto_highlight();
307 that.auto_highlight();
282 that.render();
308 that.render();
283 });
309 });
284
310
285 this.code_mirror.on('focus', function() { that.unrender(); });
311 this.code_mirror.on('focus', function() { that.unrender(); });
286 };
312 };
287
313
288 /**
314 /**
289 * Trigger autodetection of highlight scheme for current cell
315 * Trigger autodetection of highlight scheme for current cell
290 * @method auto_highlight
316 * @method auto_highlight
291 */
317 */
292 RawCell.prototype.auto_highlight = function () {
318 RawCell.prototype.auto_highlight = function () {
293 this._auto_highlight(this.config.raw_cell_highlight);
319 this._auto_highlight(this.config.raw_cell_highlight);
294 };
320 };
295
321
296 /** @method render **/
322 /** @method render **/
297 RawCell.prototype.render = function () {
323 RawCell.prototype.render = function () {
298 var cont = TextCell.prototype.render.apply(this);
324 var cont = TextCell.prototype.render.apply(this);
299 if (cont){
325 if (cont){
300 var text = this.get_text();
326 var text = this.get_text();
301 if (text === "") { text = this.placeholder; }
327 if (text === "") { text = this.placeholder; }
302 this.set_text(text);
328 this.set_text(text);
303 this.element.removeClass('rendered');
329 this.element.removeClass('rendered');
304 }
330 }
305 return cont;
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 // Backwards compatability.
334 // Backwards compatability.
413 IPython.TextCell = TextCell;
335 IPython.TextCell = TextCell;
414 IPython.MarkdownCell = MarkdownCell;
336 IPython.MarkdownCell = MarkdownCell;
415 IPython.RawCell = RawCell;
337 IPython.RawCell = RawCell;
416 IPython.HeadingCell = HeadingCell;
417
338
418 var textcell = {
339 var textcell = {
419 'TextCell': TextCell,
340 TextCell: TextCell,
420 'MarkdownCell': MarkdownCell,
341 MarkdownCell: MarkdownCell,
421 'RawCell': RawCell,
342 RawCell: RawCell,
422 'HeadingCell': HeadingCell,
423 };
343 };
424 return textcell;
344 return textcell;
425 });
345 });
@@ -1,69 +1,68 b''
1 div.text_cell {
1 div.text_cell {
2 padding: 5px 5px 5px 0px;
2 padding: 5px 5px 5px 0px;
3 .hbox();
3 .hbox();
4 }
4 }
5 @media (max-width: 480px) {
5 @media (max-width: 480px) {
6 // remove prompt indentation on small screens
6 // remove prompt indentation on small screens
7 div.text_cell > div.prompt {
7 div.text_cell > div.prompt {
8 display: none;
8 display: none;
9 }
9 }
10 }
10 }
11
11
12 div.text_cell_render {
12 div.text_cell_render {
13 /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
13 /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
14 outline: none;
14 outline: none;
15 resize: none;
15 resize: none;
16 width: inherit;
16 width: inherit;
17 border-style: none;
17 border-style: none;
18 padding: 0.5em 0.5em 0.5em @code_padding;
18 padding: 0.5em 0.5em 0.5em @code_padding;
19 color: @text-color;
19 color: @text-color;
20 .border-box-sizing();
20 .border-box-sizing();
21 }
21 }
22
22
23 a.anchor-link:link {
23 a.anchor-link:link {
24 text-decoration: none;
24 text-decoration: none;
25 padding: 0px 20px;
25 padding: 0px 20px;
26 visibility: hidden;
26 visibility: hidden;
27 }
27 }
28
28
29 h1,h2,h3,h4,h5,h6 {
29 h1,h2,h3,h4,h5,h6 {
30 &:hover .anchor-link {
30 &:hover .anchor-link {
31 visibility: visible;
31 visibility: visible;
32 }
32 }
33 }
33 }
34
34
35 div.cell.text_cell.rendered {
35 div.cell.text_cell.rendered {
36 padding: 0px;
36 padding: 0px;
37 }
37 }
38
38
39
40 .text_cell.rendered .input_area {
39 .text_cell.rendered .input_area {
41 display: none;
40 display: none;
42 }
41 }
43
42
44 .text_cell.unrendered .text_cell_render {
43 .text_cell.unrendered .text_cell_render {
45 display:none;
44 display:none;
46 }
45 }
47
46
48 .cm-s-heading-1,
47 .cm-header-1,
49 .cm-s-heading-2,
48 .cm-header-2,
50 .cm-s-heading-3,
49 .cm-header-3,
51 .cm-s-heading-4,
50 .cm-header-4,
52 .cm-s-heading-5,
51 .cm-header-5,
53 .cm-s-heading-6 {
52 .cm-header-6 {
54 font-weight: bold;
53 font-weight: bold;
55 font-family: @font-family-sans-serif;
54 font-family: @font-family-sans-serif;
56 }
55 }
57
56
58 .cm-s-heading-1 { font-size:150%; }
57 .cm-header-1 { font-size: 185.7%; }
59 .cm-s-heading-2 { font-size: 130%; }
58 .cm-header-2 { font-size: 157.1%; }
60 .cm-s-heading-3 { font-size: 120%; }
59 .cm-header-3 { font-size: 128.6%; }
61 .cm-s-heading-4 { font-size: 110%; }
60 .cm-header-4 { font-size: 110%; }
62 .cm-s-heading-5 {
61 .cm-header-5 {
63 font-size: 100%;
62 font-size: 100%;
64 font-style: italic;
63 font-style: italic;
65 }
64 }
66 .cm-s-heading-6 {
65 .cm-header-6 {
67 font-size: 90%;
66 font-size: 100%;
68 font-style: italic;
67 font-style: italic;
69 }
68 }
@@ -1,1535 +1,1535 b''
1 /*!
1 /*!
2 *
2 *
3 * IPython base
3 * IPython base
4 *
4 *
5 */
5 */
6 .modal.fade .modal-dialog {
6 .modal.fade .modal-dialog {
7 -webkit-transform: translate(0, 0);
7 -webkit-transform: translate(0, 0);
8 -ms-transform: translate(0, 0);
8 -ms-transform: translate(0, 0);
9 transform: translate(0, 0);
9 transform: translate(0, 0);
10 }
10 }
11 code {
11 code {
12 color: #000000;
12 color: #000000;
13 }
13 }
14 pre {
14 pre {
15 font-size: inherit;
15 font-size: inherit;
16 line-height: inherit;
16 line-height: inherit;
17 }
17 }
18 label {
18 label {
19 font-weight: normal;
19 font-weight: normal;
20 }
20 }
21 .border-box-sizing {
21 .border-box-sizing {
22 box-sizing: border-box;
22 box-sizing: border-box;
23 -moz-box-sizing: border-box;
23 -moz-box-sizing: border-box;
24 -webkit-box-sizing: border-box;
24 -webkit-box-sizing: border-box;
25 }
25 }
26 .corner-all {
26 .corner-all {
27 border-radius: 4px;
27 border-radius: 4px;
28 }
28 }
29 .no-padding {
29 .no-padding {
30 padding: 0px;
30 padding: 0px;
31 }
31 }
32 /* Flexible box model classes */
32 /* Flexible box model classes */
33 /* Taken from Alex Russell http://infrequently.org/2009/08/css-3-progress/ */
33 /* Taken from Alex Russell http://infrequently.org/2009/08/css-3-progress/ */
34 /* This file is a compatability layer. It allows the usage of flexible box
34 /* This file is a compatability layer. It allows the usage of flexible box
35 model layouts accross multiple browsers, including older browsers. The newest,
35 model layouts accross multiple browsers, including older browsers. The newest,
36 universal implementation of the flexible box model is used when available (see
36 universal implementation of the flexible box model is used when available (see
37 `Modern browsers` comments below). Browsers that are known to implement this
37 `Modern browsers` comments below). Browsers that are known to implement this
38 new spec completely include:
38 new spec completely include:
39
39
40 Firefox 28.0+
40 Firefox 28.0+
41 Chrome 29.0+
41 Chrome 29.0+
42 Internet Explorer 11+
42 Internet Explorer 11+
43 Opera 17.0+
43 Opera 17.0+
44
44
45 Browsers not listed, including Safari, are supported via the styling under the
45 Browsers not listed, including Safari, are supported via the styling under the
46 `Old browsers` comments below.
46 `Old browsers` comments below.
47 */
47 */
48 .hbox {
48 .hbox {
49 /* Old browsers */
49 /* Old browsers */
50 display: -webkit-box;
50 display: -webkit-box;
51 -webkit-box-orient: horizontal;
51 -webkit-box-orient: horizontal;
52 -webkit-box-align: stretch;
52 -webkit-box-align: stretch;
53 display: -moz-box;
53 display: -moz-box;
54 -moz-box-orient: horizontal;
54 -moz-box-orient: horizontal;
55 -moz-box-align: stretch;
55 -moz-box-align: stretch;
56 display: box;
56 display: box;
57 box-orient: horizontal;
57 box-orient: horizontal;
58 box-align: stretch;
58 box-align: stretch;
59 /* Modern browsers */
59 /* Modern browsers */
60 display: flex;
60 display: flex;
61 flex-direction: row;
61 flex-direction: row;
62 align-items: stretch;
62 align-items: stretch;
63 }
63 }
64 .hbox > * {
64 .hbox > * {
65 /* Old browsers */
65 /* Old browsers */
66 -webkit-box-flex: 0;
66 -webkit-box-flex: 0;
67 -moz-box-flex: 0;
67 -moz-box-flex: 0;
68 box-flex: 0;
68 box-flex: 0;
69 /* Modern browsers */
69 /* Modern browsers */
70 flex: none;
70 flex: none;
71 }
71 }
72 .vbox {
72 .vbox {
73 /* Old browsers */
73 /* Old browsers */
74 display: -webkit-box;
74 display: -webkit-box;
75 -webkit-box-orient: vertical;
75 -webkit-box-orient: vertical;
76 -webkit-box-align: stretch;
76 -webkit-box-align: stretch;
77 display: -moz-box;
77 display: -moz-box;
78 -moz-box-orient: vertical;
78 -moz-box-orient: vertical;
79 -moz-box-align: stretch;
79 -moz-box-align: stretch;
80 display: box;
80 display: box;
81 box-orient: vertical;
81 box-orient: vertical;
82 box-align: stretch;
82 box-align: stretch;
83 /* Modern browsers */
83 /* Modern browsers */
84 display: flex;
84 display: flex;
85 flex-direction: column;
85 flex-direction: column;
86 align-items: stretch;
86 align-items: stretch;
87 }
87 }
88 .vbox > * {
88 .vbox > * {
89 /* Old browsers */
89 /* Old browsers */
90 -webkit-box-flex: 0;
90 -webkit-box-flex: 0;
91 -moz-box-flex: 0;
91 -moz-box-flex: 0;
92 box-flex: 0;
92 box-flex: 0;
93 /* Modern browsers */
93 /* Modern browsers */
94 flex: none;
94 flex: none;
95 }
95 }
96 .hbox.reverse,
96 .hbox.reverse,
97 .vbox.reverse,
97 .vbox.reverse,
98 .reverse {
98 .reverse {
99 /* Old browsers */
99 /* Old browsers */
100 -webkit-box-direction: reverse;
100 -webkit-box-direction: reverse;
101 -moz-box-direction: reverse;
101 -moz-box-direction: reverse;
102 box-direction: reverse;
102 box-direction: reverse;
103 /* Modern browsers */
103 /* Modern browsers */
104 flex-direction: row-reverse;
104 flex-direction: row-reverse;
105 }
105 }
106 .hbox.box-flex0,
106 .hbox.box-flex0,
107 .vbox.box-flex0,
107 .vbox.box-flex0,
108 .box-flex0 {
108 .box-flex0 {
109 /* Old browsers */
109 /* Old browsers */
110 -webkit-box-flex: 0;
110 -webkit-box-flex: 0;
111 -moz-box-flex: 0;
111 -moz-box-flex: 0;
112 box-flex: 0;
112 box-flex: 0;
113 /* Modern browsers */
113 /* Modern browsers */
114 flex: none;
114 flex: none;
115 width: auto;
115 width: auto;
116 }
116 }
117 .hbox.box-flex1,
117 .hbox.box-flex1,
118 .vbox.box-flex1,
118 .vbox.box-flex1,
119 .box-flex1 {
119 .box-flex1 {
120 /* Old browsers */
120 /* Old browsers */
121 -webkit-box-flex: 1;
121 -webkit-box-flex: 1;
122 -moz-box-flex: 1;
122 -moz-box-flex: 1;
123 box-flex: 1;
123 box-flex: 1;
124 /* Modern browsers */
124 /* Modern browsers */
125 flex: 1;
125 flex: 1;
126 }
126 }
127 .hbox.box-flex,
127 .hbox.box-flex,
128 .vbox.box-flex,
128 .vbox.box-flex,
129 .box-flex {
129 .box-flex {
130 /* Old browsers */
130 /* Old browsers */
131 /* Old browsers */
131 /* Old browsers */
132 -webkit-box-flex: 1;
132 -webkit-box-flex: 1;
133 -moz-box-flex: 1;
133 -moz-box-flex: 1;
134 box-flex: 1;
134 box-flex: 1;
135 /* Modern browsers */
135 /* Modern browsers */
136 flex: 1;
136 flex: 1;
137 }
137 }
138 .hbox.box-flex2,
138 .hbox.box-flex2,
139 .vbox.box-flex2,
139 .vbox.box-flex2,
140 .box-flex2 {
140 .box-flex2 {
141 /* Old browsers */
141 /* Old browsers */
142 -webkit-box-flex: 2;
142 -webkit-box-flex: 2;
143 -moz-box-flex: 2;
143 -moz-box-flex: 2;
144 box-flex: 2;
144 box-flex: 2;
145 /* Modern browsers */
145 /* Modern browsers */
146 flex: 2;
146 flex: 2;
147 }
147 }
148 .box-group1 {
148 .box-group1 {
149 /* Deprecated */
149 /* Deprecated */
150 -webkit-box-flex-group: 1;
150 -webkit-box-flex-group: 1;
151 -moz-box-flex-group: 1;
151 -moz-box-flex-group: 1;
152 box-flex-group: 1;
152 box-flex-group: 1;
153 }
153 }
154 .box-group2 {
154 .box-group2 {
155 /* Deprecated */
155 /* Deprecated */
156 -webkit-box-flex-group: 2;
156 -webkit-box-flex-group: 2;
157 -moz-box-flex-group: 2;
157 -moz-box-flex-group: 2;
158 box-flex-group: 2;
158 box-flex-group: 2;
159 }
159 }
160 .hbox.start,
160 .hbox.start,
161 .vbox.start,
161 .vbox.start,
162 .start {
162 .start {
163 /* Old browsers */
163 /* Old browsers */
164 -webkit-box-pack: start;
164 -webkit-box-pack: start;
165 -moz-box-pack: start;
165 -moz-box-pack: start;
166 box-pack: start;
166 box-pack: start;
167 /* Modern browsers */
167 /* Modern browsers */
168 justify-content: flex-start;
168 justify-content: flex-start;
169 }
169 }
170 .hbox.end,
170 .hbox.end,
171 .vbox.end,
171 .vbox.end,
172 .end {
172 .end {
173 /* Old browsers */
173 /* Old browsers */
174 -webkit-box-pack: end;
174 -webkit-box-pack: end;
175 -moz-box-pack: end;
175 -moz-box-pack: end;
176 box-pack: end;
176 box-pack: end;
177 /* Modern browsers */
177 /* Modern browsers */
178 justify-content: flex-end;
178 justify-content: flex-end;
179 }
179 }
180 .hbox.center,
180 .hbox.center,
181 .vbox.center,
181 .vbox.center,
182 .center {
182 .center {
183 /* Old browsers */
183 /* Old browsers */
184 -webkit-box-pack: center;
184 -webkit-box-pack: center;
185 -moz-box-pack: center;
185 -moz-box-pack: center;
186 box-pack: center;
186 box-pack: center;
187 /* Modern browsers */
187 /* Modern browsers */
188 justify-content: center;
188 justify-content: center;
189 }
189 }
190 .hbox.baseline,
190 .hbox.baseline,
191 .vbox.baseline,
191 .vbox.baseline,
192 .baseline {
192 .baseline {
193 /* Old browsers */
193 /* Old browsers */
194 -webkit-box-pack: baseline;
194 -webkit-box-pack: baseline;
195 -moz-box-pack: baseline;
195 -moz-box-pack: baseline;
196 box-pack: baseline;
196 box-pack: baseline;
197 /* Modern browsers */
197 /* Modern browsers */
198 justify-content: baseline;
198 justify-content: baseline;
199 }
199 }
200 .hbox.stretch,
200 .hbox.stretch,
201 .vbox.stretch,
201 .vbox.stretch,
202 .stretch {
202 .stretch {
203 /* Old browsers */
203 /* Old browsers */
204 -webkit-box-pack: stretch;
204 -webkit-box-pack: stretch;
205 -moz-box-pack: stretch;
205 -moz-box-pack: stretch;
206 box-pack: stretch;
206 box-pack: stretch;
207 /* Modern browsers */
207 /* Modern browsers */
208 justify-content: stretch;
208 justify-content: stretch;
209 }
209 }
210 .hbox.align-start,
210 .hbox.align-start,
211 .vbox.align-start,
211 .vbox.align-start,
212 .align-start {
212 .align-start {
213 /* Old browsers */
213 /* Old browsers */
214 -webkit-box-align: start;
214 -webkit-box-align: start;
215 -moz-box-align: start;
215 -moz-box-align: start;
216 box-align: start;
216 box-align: start;
217 /* Modern browsers */
217 /* Modern browsers */
218 align-items: flex-start;
218 align-items: flex-start;
219 }
219 }
220 .hbox.align-end,
220 .hbox.align-end,
221 .vbox.align-end,
221 .vbox.align-end,
222 .align-end {
222 .align-end {
223 /* Old browsers */
223 /* Old browsers */
224 -webkit-box-align: end;
224 -webkit-box-align: end;
225 -moz-box-align: end;
225 -moz-box-align: end;
226 box-align: end;
226 box-align: end;
227 /* Modern browsers */
227 /* Modern browsers */
228 align-items: flex-end;
228 align-items: flex-end;
229 }
229 }
230 .hbox.align-center,
230 .hbox.align-center,
231 .vbox.align-center,
231 .vbox.align-center,
232 .align-center {
232 .align-center {
233 /* Old browsers */
233 /* Old browsers */
234 -webkit-box-align: center;
234 -webkit-box-align: center;
235 -moz-box-align: center;
235 -moz-box-align: center;
236 box-align: center;
236 box-align: center;
237 /* Modern browsers */
237 /* Modern browsers */
238 align-items: center;
238 align-items: center;
239 }
239 }
240 .hbox.align-baseline,
240 .hbox.align-baseline,
241 .vbox.align-baseline,
241 .vbox.align-baseline,
242 .align-baseline {
242 .align-baseline {
243 /* Old browsers */
243 /* Old browsers */
244 -webkit-box-align: baseline;
244 -webkit-box-align: baseline;
245 -moz-box-align: baseline;
245 -moz-box-align: baseline;
246 box-align: baseline;
246 box-align: baseline;
247 /* Modern browsers */
247 /* Modern browsers */
248 align-items: baseline;
248 align-items: baseline;
249 }
249 }
250 .hbox.align-stretch,
250 .hbox.align-stretch,
251 .vbox.align-stretch,
251 .vbox.align-stretch,
252 .align-stretch {
252 .align-stretch {
253 /* Old browsers */
253 /* Old browsers */
254 -webkit-box-align: stretch;
254 -webkit-box-align: stretch;
255 -moz-box-align: stretch;
255 -moz-box-align: stretch;
256 box-align: stretch;
256 box-align: stretch;
257 /* Modern browsers */
257 /* Modern browsers */
258 align-items: stretch;
258 align-items: stretch;
259 }
259 }
260 div.error {
260 div.error {
261 margin: 2em;
261 margin: 2em;
262 text-align: center;
262 text-align: center;
263 }
263 }
264 div.error > h1 {
264 div.error > h1 {
265 font-size: 500%;
265 font-size: 500%;
266 line-height: normal;
266 line-height: normal;
267 }
267 }
268 div.error > p {
268 div.error > p {
269 font-size: 200%;
269 font-size: 200%;
270 line-height: normal;
270 line-height: normal;
271 }
271 }
272 div.traceback-wrapper {
272 div.traceback-wrapper {
273 text-align: left;
273 text-align: left;
274 max-width: 800px;
274 max-width: 800px;
275 margin: auto;
275 margin: auto;
276 }
276 }
277 /*!
277 /*!
278 *
278 *
279 * IPython notebook
279 * IPython notebook
280 *
280 *
281 */
281 */
282 /* CSS font colors for translated ANSI colors. */
282 /* CSS font colors for translated ANSI colors. */
283 .ansibold {
283 .ansibold {
284 font-weight: bold;
284 font-weight: bold;
285 }
285 }
286 /* use dark versions for foreground, to improve visibility */
286 /* use dark versions for foreground, to improve visibility */
287 .ansiblack {
287 .ansiblack {
288 color: black;
288 color: black;
289 }
289 }
290 .ansired {
290 .ansired {
291 color: darkred;
291 color: darkred;
292 }
292 }
293 .ansigreen {
293 .ansigreen {
294 color: darkgreen;
294 color: darkgreen;
295 }
295 }
296 .ansiyellow {
296 .ansiyellow {
297 color: #c4a000;
297 color: #c4a000;
298 }
298 }
299 .ansiblue {
299 .ansiblue {
300 color: darkblue;
300 color: darkblue;
301 }
301 }
302 .ansipurple {
302 .ansipurple {
303 color: darkviolet;
303 color: darkviolet;
304 }
304 }
305 .ansicyan {
305 .ansicyan {
306 color: steelblue;
306 color: steelblue;
307 }
307 }
308 .ansigray {
308 .ansigray {
309 color: gray;
309 color: gray;
310 }
310 }
311 /* and light for background, for the same reason */
311 /* and light for background, for the same reason */
312 .ansibgblack {
312 .ansibgblack {
313 background-color: black;
313 background-color: black;
314 }
314 }
315 .ansibgred {
315 .ansibgred {
316 background-color: red;
316 background-color: red;
317 }
317 }
318 .ansibggreen {
318 .ansibggreen {
319 background-color: green;
319 background-color: green;
320 }
320 }
321 .ansibgyellow {
321 .ansibgyellow {
322 background-color: yellow;
322 background-color: yellow;
323 }
323 }
324 .ansibgblue {
324 .ansibgblue {
325 background-color: blue;
325 background-color: blue;
326 }
326 }
327 .ansibgpurple {
327 .ansibgpurple {
328 background-color: magenta;
328 background-color: magenta;
329 }
329 }
330 .ansibgcyan {
330 .ansibgcyan {
331 background-color: cyan;
331 background-color: cyan;
332 }
332 }
333 .ansibggray {
333 .ansibggray {
334 background-color: gray;
334 background-color: gray;
335 }
335 }
336 div.cell {
336 div.cell {
337 border: 1px solid transparent;
337 border: 1px solid transparent;
338 /* Old browsers */
338 /* Old browsers */
339 display: -webkit-box;
339 display: -webkit-box;
340 -webkit-box-orient: vertical;
340 -webkit-box-orient: vertical;
341 -webkit-box-align: stretch;
341 -webkit-box-align: stretch;
342 display: -moz-box;
342 display: -moz-box;
343 -moz-box-orient: vertical;
343 -moz-box-orient: vertical;
344 -moz-box-align: stretch;
344 -moz-box-align: stretch;
345 display: box;
345 display: box;
346 box-orient: vertical;
346 box-orient: vertical;
347 box-align: stretch;
347 box-align: stretch;
348 /* Modern browsers */
348 /* Modern browsers */
349 display: flex;
349 display: flex;
350 flex-direction: column;
350 flex-direction: column;
351 align-items: stretch;
351 align-items: stretch;
352 border-radius: 4px;
352 border-radius: 4px;
353 box-sizing: border-box;
353 box-sizing: border-box;
354 -moz-box-sizing: border-box;
354 -moz-box-sizing: border-box;
355 -webkit-box-sizing: border-box;
355 -webkit-box-sizing: border-box;
356 border-width: thin;
356 border-width: thin;
357 border-style: solid;
357 border-style: solid;
358 width: 100%;
358 width: 100%;
359 padding: 5px 5px 5px 0px;
359 padding: 5px 5px 5px 0px;
360 /* This acts as a spacer between cells, that is outside the border */
360 /* This acts as a spacer between cells, that is outside the border */
361 margin: 0px;
361 margin: 0px;
362 outline: none;
362 outline: none;
363 }
363 }
364 div.cell.selected {
364 div.cell.selected {
365 border-color: #ababab;
365 border-color: #ababab;
366 }
366 }
367 div.cell.edit_mode {
367 div.cell.edit_mode {
368 border-color: green;
368 border-color: green;
369 }
369 }
370 div.prompt {
370 div.prompt {
371 /* This needs to be wide enough for 3 digit prompt numbers: In[100]: */
371 /* This needs to be wide enough for 3 digit prompt numbers: In[100]: */
372 min-width: 15ex;
372 min-width: 15ex;
373 /* This padding is tuned to match the padding on the CodeMirror editor. */
373 /* This padding is tuned to match the padding on the CodeMirror editor. */
374 padding: 0.4em;
374 padding: 0.4em;
375 margin: 0px;
375 margin: 0px;
376 font-family: monospace;
376 font-family: monospace;
377 text-align: right;
377 text-align: right;
378 /* This has to match that of the the CodeMirror class line-height below */
378 /* This has to match that of the the CodeMirror class line-height below */
379 line-height: 1.21429em;
379 line-height: 1.21429em;
380 }
380 }
381 @media (max-width: 480px) {
381 @media (max-width: 480px) {
382 div.prompt {
382 div.prompt {
383 text-align: left;
383 text-align: left;
384 }
384 }
385 }
385 }
386 div.inner_cell {
386 div.inner_cell {
387 /* Old browsers */
387 /* Old browsers */
388 display: -webkit-box;
388 display: -webkit-box;
389 -webkit-box-orient: vertical;
389 -webkit-box-orient: vertical;
390 -webkit-box-align: stretch;
390 -webkit-box-align: stretch;
391 display: -moz-box;
391 display: -moz-box;
392 -moz-box-orient: vertical;
392 -moz-box-orient: vertical;
393 -moz-box-align: stretch;
393 -moz-box-align: stretch;
394 display: box;
394 display: box;
395 box-orient: vertical;
395 box-orient: vertical;
396 box-align: stretch;
396 box-align: stretch;
397 /* Modern browsers */
397 /* Modern browsers */
398 display: flex;
398 display: flex;
399 flex-direction: column;
399 flex-direction: column;
400 align-items: stretch;
400 align-items: stretch;
401 /* Old browsers */
401 /* Old browsers */
402 -webkit-box-flex: 1;
402 -webkit-box-flex: 1;
403 -moz-box-flex: 1;
403 -moz-box-flex: 1;
404 box-flex: 1;
404 box-flex: 1;
405 /* Modern browsers */
405 /* Modern browsers */
406 flex: 1;
406 flex: 1;
407 }
407 }
408 /* input_area and input_prompt must match in top border and margin for alignment */
408 /* input_area and input_prompt must match in top border and margin for alignment */
409 div.input_area {
409 div.input_area {
410 border: 1px solid #cfcfcf;
410 border: 1px solid #cfcfcf;
411 border-radius: 4px;
411 border-radius: 4px;
412 background: #f7f7f7;
412 background: #f7f7f7;
413 line-height: 1.21429em;
413 line-height: 1.21429em;
414 }
414 }
415 /* This is needed so that empty prompt areas can collapse to zero height when there
415 /* This is needed so that empty prompt areas can collapse to zero height when there
416 is no content in the output_subarea and the prompt. The main purpose of this is
416 is no content in the output_subarea and the prompt. The main purpose of this is
417 to make sure that empty JavaScript output_subareas have no height. */
417 to make sure that empty JavaScript output_subareas have no height. */
418 div.prompt:empty {
418 div.prompt:empty {
419 padding-top: 0;
419 padding-top: 0;
420 padding-bottom: 0;
420 padding-bottom: 0;
421 }
421 }
422 /* any special styling for code cells that are currently running goes here */
422 /* any special styling for code cells that are currently running goes here */
423 div.input {
423 div.input {
424 page-break-inside: avoid;
424 page-break-inside: avoid;
425 /* Old browsers */
425 /* Old browsers */
426 display: -webkit-box;
426 display: -webkit-box;
427 -webkit-box-orient: horizontal;
427 -webkit-box-orient: horizontal;
428 -webkit-box-align: stretch;
428 -webkit-box-align: stretch;
429 display: -moz-box;
429 display: -moz-box;
430 -moz-box-orient: horizontal;
430 -moz-box-orient: horizontal;
431 -moz-box-align: stretch;
431 -moz-box-align: stretch;
432 display: box;
432 display: box;
433 box-orient: horizontal;
433 box-orient: horizontal;
434 box-align: stretch;
434 box-align: stretch;
435 /* Modern browsers */
435 /* Modern browsers */
436 display: flex;
436 display: flex;
437 flex-direction: row;
437 flex-direction: row;
438 align-items: stretch;
438 align-items: stretch;
439 }
439 }
440 @media (max-width: 480px) {
440 @media (max-width: 480px) {
441 div.input {
441 div.input {
442 /* Old browsers */
442 /* Old browsers */
443 display: -webkit-box;
443 display: -webkit-box;
444 -webkit-box-orient: vertical;
444 -webkit-box-orient: vertical;
445 -webkit-box-align: stretch;
445 -webkit-box-align: stretch;
446 display: -moz-box;
446 display: -moz-box;
447 -moz-box-orient: vertical;
447 -moz-box-orient: vertical;
448 -moz-box-align: stretch;
448 -moz-box-align: stretch;
449 display: box;
449 display: box;
450 box-orient: vertical;
450 box-orient: vertical;
451 box-align: stretch;
451 box-align: stretch;
452 /* Modern browsers */
452 /* Modern browsers */
453 display: flex;
453 display: flex;
454 flex-direction: column;
454 flex-direction: column;
455 align-items: stretch;
455 align-items: stretch;
456 }
456 }
457 }
457 }
458 /* input_area and input_prompt must match in top border and margin for alignment */
458 /* input_area and input_prompt must match in top border and margin for alignment */
459 div.input_prompt {
459 div.input_prompt {
460 color: #000080;
460 color: #000080;
461 border-top: 1px solid transparent;
461 border-top: 1px solid transparent;
462 }
462 }
463 div.input_area > div.highlight {
463 div.input_area > div.highlight {
464 margin: 0.4em;
464 margin: 0.4em;
465 border: none;
465 border: none;
466 padding: 0px;
466 padding: 0px;
467 background-color: transparent;
467 background-color: transparent;
468 }
468 }
469 div.input_area > div.highlight > pre {
469 div.input_area > div.highlight > pre {
470 margin: 0px;
470 margin: 0px;
471 border: none;
471 border: none;
472 padding: 0px;
472 padding: 0px;
473 background-color: transparent;
473 background-color: transparent;
474 }
474 }
475 /* The following gets added to the <head> if it is detected that the user has a
475 /* The following gets added to the <head> if it is detected that the user has a
476 * monospace font with inconsistent normal/bold/italic height. See
476 * monospace font with inconsistent normal/bold/italic height. See
477 * notebookmain.js. Such fonts will have keywords vertically offset with
477 * notebookmain.js. Such fonts will have keywords vertically offset with
478 * respect to the rest of the text. The user should select a better font.
478 * respect to the rest of the text. The user should select a better font.
479 * See: https://github.com/ipython/ipython/issues/1503
479 * See: https://github.com/ipython/ipython/issues/1503
480 *
480 *
481 * .CodeMirror span {
481 * .CodeMirror span {
482 * vertical-align: bottom;
482 * vertical-align: bottom;
483 * }
483 * }
484 */
484 */
485 .CodeMirror {
485 .CodeMirror {
486 line-height: 1.21429em;
486 line-height: 1.21429em;
487 /* Changed from 1em to our global default */
487 /* Changed from 1em to our global default */
488 height: auto;
488 height: auto;
489 /* Changed to auto to autogrow */
489 /* Changed to auto to autogrow */
490 background: none;
490 background: none;
491 /* Changed from white to allow our bg to show through */
491 /* Changed from white to allow our bg to show through */
492 }
492 }
493 .CodeMirror-scroll {
493 .CodeMirror-scroll {
494 /* The CodeMirror docs are a bit fuzzy on if overflow-y should be hidden or visible.*/
494 /* The CodeMirror docs are a bit fuzzy on if overflow-y should be hidden or visible.*/
495 /* We have found that if it is visible, vertical scrollbars appear with font size changes.*/
495 /* We have found that if it is visible, vertical scrollbars appear with font size changes.*/
496 overflow-y: hidden;
496 overflow-y: hidden;
497 overflow-x: auto;
497 overflow-x: auto;
498 }
498 }
499 .CodeMirror-lines {
499 .CodeMirror-lines {
500 /* In CM2, this used to be 0.4em, but in CM3 it went to 4px. We need the em value because */
500 /* In CM2, this used to be 0.4em, but in CM3 it went to 4px. We need the em value because */
501 /* we have set a different line-height and want this to scale with that. */
501 /* we have set a different line-height and want this to scale with that. */
502 padding: 0.4em;
502 padding: 0.4em;
503 }
503 }
504 .CodeMirror-linenumber {
504 .CodeMirror-linenumber {
505 padding: 0 8px 0 4px;
505 padding: 0 8px 0 4px;
506 }
506 }
507 .CodeMirror-gutters {
507 .CodeMirror-gutters {
508 border-bottom-left-radius: 4px;
508 border-bottom-left-radius: 4px;
509 border-top-left-radius: 4px;
509 border-top-left-radius: 4px;
510 }
510 }
511 .CodeMirror pre {
511 .CodeMirror pre {
512 /* In CM3 this went to 4px from 0 in CM2. We need the 0 value because of how we size */
512 /* In CM3 this went to 4px from 0 in CM2. We need the 0 value because of how we size */
513 /* .CodeMirror-lines */
513 /* .CodeMirror-lines */
514 padding: 0;
514 padding: 0;
515 border: 0;
515 border: 0;
516 border-radius: 0;
516 border-radius: 0;
517 }
517 }
518 .CodeMirror-vscrollbar,
518 .CodeMirror-vscrollbar,
519 .CodeMirror-hscrollbar {
519 .CodeMirror-hscrollbar {
520 display: none !important;
520 display: none !important;
521 }
521 }
522 /*
522 /*
523
523
524 Original style from softwaremaniacs.org (c) Ivan Sagalaev <Maniac@SoftwareManiacs.Org>
524 Original style from softwaremaniacs.org (c) Ivan Sagalaev <Maniac@SoftwareManiacs.Org>
525 Adapted from GitHub theme
525 Adapted from GitHub theme
526
526
527 */
527 */
528 pre code {
528 pre code {
529 display: block;
529 display: block;
530 padding: 0.5em;
530 padding: 0.5em;
531 }
531 }
532 .highlight-base,
532 .highlight-base,
533 pre code,
533 pre code,
534 pre .subst,
534 pre .subst,
535 pre .tag .title,
535 pre .tag .title,
536 pre .lisp .title,
536 pre .lisp .title,
537 pre .clojure .built_in,
537 pre .clojure .built_in,
538 pre .nginx .title {
538 pre .nginx .title {
539 color: black;
539 color: black;
540 }
540 }
541 .highlight-string,
541 .highlight-string,
542 pre .string,
542 pre .string,
543 pre .constant,
543 pre .constant,
544 pre .parent,
544 pre .parent,
545 pre .tag .value,
545 pre .tag .value,
546 pre .rules .value,
546 pre .rules .value,
547 pre .rules .value .number,
547 pre .rules .value .number,
548 pre .preprocessor,
548 pre .preprocessor,
549 pre .ruby .symbol,
549 pre .ruby .symbol,
550 pre .ruby .symbol .string,
550 pre .ruby .symbol .string,
551 pre .aggregate,
551 pre .aggregate,
552 pre .template_tag,
552 pre .template_tag,
553 pre .django .variable,
553 pre .django .variable,
554 pre .smalltalk .class,
554 pre .smalltalk .class,
555 pre .addition,
555 pre .addition,
556 pre .flow,
556 pre .flow,
557 pre .stream,
557 pre .stream,
558 pre .bash .variable,
558 pre .bash .variable,
559 pre .apache .tag,
559 pre .apache .tag,
560 pre .apache .cbracket,
560 pre .apache .cbracket,
561 pre .tex .command,
561 pre .tex .command,
562 pre .tex .special,
562 pre .tex .special,
563 pre .erlang_repl .function_or_atom,
563 pre .erlang_repl .function_or_atom,
564 pre .markdown .header {
564 pre .markdown .header {
565 color: #BA2121;
565 color: #BA2121;
566 }
566 }
567 .highlight-comment,
567 .highlight-comment,
568 pre .comment,
568 pre .comment,
569 pre .annotation,
569 pre .annotation,
570 pre .template_comment,
570 pre .template_comment,
571 pre .diff .header,
571 pre .diff .header,
572 pre .chunk,
572 pre .chunk,
573 pre .markdown .blockquote {
573 pre .markdown .blockquote {
574 color: #408080;
574 color: #408080;
575 font-style: italic;
575 font-style: italic;
576 }
576 }
577 .highlight-number,
577 .highlight-number,
578 pre .number,
578 pre .number,
579 pre .date,
579 pre .date,
580 pre .regexp,
580 pre .regexp,
581 pre .literal,
581 pre .literal,
582 pre .smalltalk .symbol,
582 pre .smalltalk .symbol,
583 pre .smalltalk .char,
583 pre .smalltalk .char,
584 pre .go .constant,
584 pre .go .constant,
585 pre .change,
585 pre .change,
586 pre .markdown .bullet,
586 pre .markdown .bullet,
587 pre .markdown .link_url {
587 pre .markdown .link_url {
588 color: #080;
588 color: #080;
589 }
589 }
590 pre .label,
590 pre .label,
591 pre .javadoc,
591 pre .javadoc,
592 pre .ruby .string,
592 pre .ruby .string,
593 pre .decorator,
593 pre .decorator,
594 pre .filter .argument,
594 pre .filter .argument,
595 pre .localvars,
595 pre .localvars,
596 pre .array,
596 pre .array,
597 pre .attr_selector,
597 pre .attr_selector,
598 pre .important,
598 pre .important,
599 pre .pseudo,
599 pre .pseudo,
600 pre .pi,
600 pre .pi,
601 pre .doctype,
601 pre .doctype,
602 pre .deletion,
602 pre .deletion,
603 pre .envvar,
603 pre .envvar,
604 pre .shebang,
604 pre .shebang,
605 pre .apache .sqbracket,
605 pre .apache .sqbracket,
606 pre .nginx .built_in,
606 pre .nginx .built_in,
607 pre .tex .formula,
607 pre .tex .formula,
608 pre .erlang_repl .reserved,
608 pre .erlang_repl .reserved,
609 pre .prompt,
609 pre .prompt,
610 pre .markdown .link_label,
610 pre .markdown .link_label,
611 pre .vhdl .attribute,
611 pre .vhdl .attribute,
612 pre .clojure .attribute,
612 pre .clojure .attribute,
613 pre .coffeescript .property {
613 pre .coffeescript .property {
614 color: #8888ff;
614 color: #8888ff;
615 }
615 }
616 .highlight-keyword,
616 .highlight-keyword,
617 pre .keyword,
617 pre .keyword,
618 pre .id,
618 pre .id,
619 pre .phpdoc,
619 pre .phpdoc,
620 pre .aggregate,
620 pre .aggregate,
621 pre .css .tag,
621 pre .css .tag,
622 pre .javadoctag,
622 pre .javadoctag,
623 pre .phpdoc,
623 pre .phpdoc,
624 pre .yardoctag,
624 pre .yardoctag,
625 pre .smalltalk .class,
625 pre .smalltalk .class,
626 pre .winutils,
626 pre .winutils,
627 pre .bash .variable,
627 pre .bash .variable,
628 pre .apache .tag,
628 pre .apache .tag,
629 pre .go .typename,
629 pre .go .typename,
630 pre .tex .command,
630 pre .tex .command,
631 pre .markdown .strong,
631 pre .markdown .strong,
632 pre .request,
632 pre .request,
633 pre .status {
633 pre .status {
634 color: #008000;
634 color: #008000;
635 font-weight: bold;
635 font-weight: bold;
636 }
636 }
637 .highlight-builtin,
637 .highlight-builtin,
638 pre .built_in {
638 pre .built_in {
639 color: #008000;
639 color: #008000;
640 }
640 }
641 pre .markdown .emphasis {
641 pre .markdown .emphasis {
642 font-style: italic;
642 font-style: italic;
643 }
643 }
644 pre .nginx .built_in {
644 pre .nginx .built_in {
645 font-weight: normal;
645 font-weight: normal;
646 }
646 }
647 pre .coffeescript .javascript,
647 pre .coffeescript .javascript,
648 pre .javascript .xml,
648 pre .javascript .xml,
649 pre .tex .formula,
649 pre .tex .formula,
650 pre .xml .javascript,
650 pre .xml .javascript,
651 pre .xml .vbscript,
651 pre .xml .vbscript,
652 pre .xml .css,
652 pre .xml .css,
653 pre .xml .cdata {
653 pre .xml .cdata {
654 opacity: 0.5;
654 opacity: 0.5;
655 }
655 }
656 /* apply the same style to codemirror */
656 /* apply the same style to codemirror */
657 .cm-s-ipython span.cm-variable {
657 .cm-s-ipython span.cm-variable {
658 color: black;
658 color: black;
659 }
659 }
660 .cm-s-ipython span.cm-keyword {
660 .cm-s-ipython span.cm-keyword {
661 color: #008000;
661 color: #008000;
662 font-weight: bold;
662 font-weight: bold;
663 }
663 }
664 .cm-s-ipython span.cm-number {
664 .cm-s-ipython span.cm-number {
665 color: #080;
665 color: #080;
666 }
666 }
667 .cm-s-ipython span.cm-comment {
667 .cm-s-ipython span.cm-comment {
668 color: #408080;
668 color: #408080;
669 font-style: italic;
669 font-style: italic;
670 }
670 }
671 .cm-s-ipython span.cm-string {
671 .cm-s-ipython span.cm-string {
672 color: #BA2121;
672 color: #BA2121;
673 }
673 }
674 .cm-s-ipython span.cm-builtin {
674 .cm-s-ipython span.cm-builtin {
675 color: #008000;
675 color: #008000;
676 }
676 }
677 .cm-s-ipython span.cm-error {
677 .cm-s-ipython span.cm-error {
678 color: #f00;
678 color: #f00;
679 }
679 }
680 .cm-s-ipython span.cm-operator {
680 .cm-s-ipython span.cm-operator {
681 color: #AA22FF;
681 color: #AA22FF;
682 font-weight: bold;
682 font-weight: bold;
683 }
683 }
684 .cm-s-ipython span.cm-meta {
684 .cm-s-ipython span.cm-meta {
685 color: #AA22FF;
685 color: #AA22FF;
686 }
686 }
687 .cm-s-ipython span.cm-tab {
687 .cm-s-ipython span.cm-tab {
688 background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
688 background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
689 background-position: right;
689 background-position: right;
690 background-repeat: no-repeat;
690 background-repeat: no-repeat;
691 }
691 }
692 div.output_wrapper {
692 div.output_wrapper {
693 /* this position must be relative to enable descendents to be absolute within it */
693 /* this position must be relative to enable descendents to be absolute within it */
694 position: relative;
694 position: relative;
695 /* Old browsers */
695 /* Old browsers */
696 display: -webkit-box;
696 display: -webkit-box;
697 -webkit-box-orient: vertical;
697 -webkit-box-orient: vertical;
698 -webkit-box-align: stretch;
698 -webkit-box-align: stretch;
699 display: -moz-box;
699 display: -moz-box;
700 -moz-box-orient: vertical;
700 -moz-box-orient: vertical;
701 -moz-box-align: stretch;
701 -moz-box-align: stretch;
702 display: box;
702 display: box;
703 box-orient: vertical;
703 box-orient: vertical;
704 box-align: stretch;
704 box-align: stretch;
705 /* Modern browsers */
705 /* Modern browsers */
706 display: flex;
706 display: flex;
707 flex-direction: column;
707 flex-direction: column;
708 align-items: stretch;
708 align-items: stretch;
709 }
709 }
710 /* class for the output area when it should be height-limited */
710 /* class for the output area when it should be height-limited */
711 div.output_scroll {
711 div.output_scroll {
712 /* ideally, this would be max-height, but FF barfs all over that */
712 /* ideally, this would be max-height, but FF barfs all over that */
713 height: 24em;
713 height: 24em;
714 /* FF needs this *and the wrapper* to specify full width, or it will shrinkwrap */
714 /* FF needs this *and the wrapper* to specify full width, or it will shrinkwrap */
715 width: 100%;
715 width: 100%;
716 overflow: auto;
716 overflow: auto;
717 border-radius: 4px;
717 border-radius: 4px;
718 -webkit-box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
718 -webkit-box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
719 box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
719 box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
720 display: block;
720 display: block;
721 }
721 }
722 /* output div while it is collapsed */
722 /* output div while it is collapsed */
723 div.output_collapsed {
723 div.output_collapsed {
724 margin: 0px;
724 margin: 0px;
725 padding: 0px;
725 padding: 0px;
726 /* Old browsers */
726 /* Old browsers */
727 display: -webkit-box;
727 display: -webkit-box;
728 -webkit-box-orient: vertical;
728 -webkit-box-orient: vertical;
729 -webkit-box-align: stretch;
729 -webkit-box-align: stretch;
730 display: -moz-box;
730 display: -moz-box;
731 -moz-box-orient: vertical;
731 -moz-box-orient: vertical;
732 -moz-box-align: stretch;
732 -moz-box-align: stretch;
733 display: box;
733 display: box;
734 box-orient: vertical;
734 box-orient: vertical;
735 box-align: stretch;
735 box-align: stretch;
736 /* Modern browsers */
736 /* Modern browsers */
737 display: flex;
737 display: flex;
738 flex-direction: column;
738 flex-direction: column;
739 align-items: stretch;
739 align-items: stretch;
740 }
740 }
741 div.out_prompt_overlay {
741 div.out_prompt_overlay {
742 height: 100%;
742 height: 100%;
743 padding: 0px 0.4em;
743 padding: 0px 0.4em;
744 position: absolute;
744 position: absolute;
745 border-radius: 4px;
745 border-radius: 4px;
746 }
746 }
747 div.out_prompt_overlay:hover {
747 div.out_prompt_overlay:hover {
748 /* use inner shadow to get border that is computed the same on WebKit/FF */
748 /* use inner shadow to get border that is computed the same on WebKit/FF */
749 -webkit-box-shadow: inset 0 0 1px #000000;
749 -webkit-box-shadow: inset 0 0 1px #000000;
750 box-shadow: inset 0 0 1px #000000;
750 box-shadow: inset 0 0 1px #000000;
751 background: rgba(240, 240, 240, 0.5);
751 background: rgba(240, 240, 240, 0.5);
752 }
752 }
753 div.output_prompt {
753 div.output_prompt {
754 color: #8b0000;
754 color: #8b0000;
755 }
755 }
756 /* This class is the outer container of all output sections. */
756 /* This class is the outer container of all output sections. */
757 div.output_area {
757 div.output_area {
758 padding: 0px;
758 padding: 0px;
759 page-break-inside: avoid;
759 page-break-inside: avoid;
760 /* Old browsers */
760 /* Old browsers */
761 display: -webkit-box;
761 display: -webkit-box;
762 -webkit-box-orient: horizontal;
762 -webkit-box-orient: horizontal;
763 -webkit-box-align: stretch;
763 -webkit-box-align: stretch;
764 display: -moz-box;
764 display: -moz-box;
765 -moz-box-orient: horizontal;
765 -moz-box-orient: horizontal;
766 -moz-box-align: stretch;
766 -moz-box-align: stretch;
767 display: box;
767 display: box;
768 box-orient: horizontal;
768 box-orient: horizontal;
769 box-align: stretch;
769 box-align: stretch;
770 /* Modern browsers */
770 /* Modern browsers */
771 display: flex;
771 display: flex;
772 flex-direction: row;
772 flex-direction: row;
773 align-items: stretch;
773 align-items: stretch;
774 }
774 }
775 div.output_area .MathJax_Display {
775 div.output_area .MathJax_Display {
776 text-align: left !important;
776 text-align: left !important;
777 }
777 }
778 div.output_area .rendered_html table {
778 div.output_area .rendered_html table {
779 margin-left: 0;
779 margin-left: 0;
780 margin-right: 0;
780 margin-right: 0;
781 }
781 }
782 div.output_area .rendered_html img {
782 div.output_area .rendered_html img {
783 margin-left: 0;
783 margin-left: 0;
784 margin-right: 0;
784 margin-right: 0;
785 }
785 }
786 /* This is needed to protect the pre formating from global settings such
786 /* This is needed to protect the pre formating from global settings such
787 as that of bootstrap */
787 as that of bootstrap */
788 .output {
788 .output {
789 /* Old browsers */
789 /* Old browsers */
790 display: -webkit-box;
790 display: -webkit-box;
791 -webkit-box-orient: vertical;
791 -webkit-box-orient: vertical;
792 -webkit-box-align: stretch;
792 -webkit-box-align: stretch;
793 display: -moz-box;
793 display: -moz-box;
794 -moz-box-orient: vertical;
794 -moz-box-orient: vertical;
795 -moz-box-align: stretch;
795 -moz-box-align: stretch;
796 display: box;
796 display: box;
797 box-orient: vertical;
797 box-orient: vertical;
798 box-align: stretch;
798 box-align: stretch;
799 /* Modern browsers */
799 /* Modern browsers */
800 display: flex;
800 display: flex;
801 flex-direction: column;
801 flex-direction: column;
802 align-items: stretch;
802 align-items: stretch;
803 }
803 }
804 @media (max-width: 480px) {
804 @media (max-width: 480px) {
805 div.output_area {
805 div.output_area {
806 /* Old browsers */
806 /* Old browsers */
807 display: -webkit-box;
807 display: -webkit-box;
808 -webkit-box-orient: vertical;
808 -webkit-box-orient: vertical;
809 -webkit-box-align: stretch;
809 -webkit-box-align: stretch;
810 display: -moz-box;
810 display: -moz-box;
811 -moz-box-orient: vertical;
811 -moz-box-orient: vertical;
812 -moz-box-align: stretch;
812 -moz-box-align: stretch;
813 display: box;
813 display: box;
814 box-orient: vertical;
814 box-orient: vertical;
815 box-align: stretch;
815 box-align: stretch;
816 /* Modern browsers */
816 /* Modern browsers */
817 display: flex;
817 display: flex;
818 flex-direction: column;
818 flex-direction: column;
819 align-items: stretch;
819 align-items: stretch;
820 }
820 }
821 }
821 }
822 div.output_area pre {
822 div.output_area pre {
823 margin: 0;
823 margin: 0;
824 padding: 0;
824 padding: 0;
825 border: 0;
825 border: 0;
826 vertical-align: baseline;
826 vertical-align: baseline;
827 color: #000000;
827 color: #000000;
828 background-color: transparent;
828 background-color: transparent;
829 border-radius: 0;
829 border-radius: 0;
830 }
830 }
831 /* This class is for the output subarea inside the output_area and after
831 /* This class is for the output subarea inside the output_area and after
832 the prompt div. */
832 the prompt div. */
833 div.output_subarea {
833 div.output_subarea {
834 padding: 0.4em 0.4em 0em 0.4em;
834 padding: 0.4em 0.4em 0em 0.4em;
835 /* Old browsers */
835 /* Old browsers */
836 -webkit-box-flex: 1;
836 -webkit-box-flex: 1;
837 -moz-box-flex: 1;
837 -moz-box-flex: 1;
838 box-flex: 1;
838 box-flex: 1;
839 /* Modern browsers */
839 /* Modern browsers */
840 flex: 1;
840 flex: 1;
841 }
841 }
842 /* The rest of the output_* classes are for special styling of the different
842 /* The rest of the output_* classes are for special styling of the different
843 output types */
843 output types */
844 /* all text output has this class: */
844 /* all text output has this class: */
845 div.output_text {
845 div.output_text {
846 text-align: left;
846 text-align: left;
847 color: #000000;
847 color: #000000;
848 /* This has to match that of the the CodeMirror class line-height below */
848 /* This has to match that of the the CodeMirror class line-height below */
849 line-height: 1.21429em;
849 line-height: 1.21429em;
850 }
850 }
851 /* stdout/stderr are 'text' as well as 'stream', but execute_result/error are *not* streams */
851 /* stdout/stderr are 'text' as well as 'stream', but execute_result/error are *not* streams */
852 div.output_stderr {
852 div.output_stderr {
853 background: #fdd;
853 background: #fdd;
854 /* very light red background for stderr */
854 /* very light red background for stderr */
855 }
855 }
856 div.output_latex {
856 div.output_latex {
857 text-align: left;
857 text-align: left;
858 }
858 }
859 /* Empty output_javascript divs should have no height */
859 /* Empty output_javascript divs should have no height */
860 div.output_javascript:empty {
860 div.output_javascript:empty {
861 padding: 0;
861 padding: 0;
862 }
862 }
863 .js-error {
863 .js-error {
864 color: darkred;
864 color: darkred;
865 }
865 }
866 /* raw_input styles */
866 /* raw_input styles */
867 div.raw_input_container {
867 div.raw_input_container {
868 font-family: monospace;
868 font-family: monospace;
869 padding-top: 5px;
869 padding-top: 5px;
870 }
870 }
871 span.raw_input_prompt {
871 span.raw_input_prompt {
872 /* nothing needed here */
872 /* nothing needed here */
873 }
873 }
874 input.raw_input {
874 input.raw_input {
875 font-family: inherit;
875 font-family: inherit;
876 font-size: inherit;
876 font-size: inherit;
877 color: inherit;
877 color: inherit;
878 width: auto;
878 width: auto;
879 /* make sure input baseline aligns with prompt */
879 /* make sure input baseline aligns with prompt */
880 vertical-align: baseline;
880 vertical-align: baseline;
881 /* padding + margin = 0.5em between prompt and cursor */
881 /* padding + margin = 0.5em between prompt and cursor */
882 padding: 0em 0.25em;
882 padding: 0em 0.25em;
883 margin: 0em 0.25em;
883 margin: 0em 0.25em;
884 }
884 }
885 input.raw_input:focus {
885 input.raw_input:focus {
886 box-shadow: none;
886 box-shadow: none;
887 }
887 }
888 p.p-space {
888 p.p-space {
889 margin-bottom: 10px;
889 margin-bottom: 10px;
890 }
890 }
891 .rendered_html {
891 .rendered_html {
892 color: #000000;
892 color: #000000;
893 /* any extras will just be numbers: */
893 /* any extras will just be numbers: */
894 }
894 }
895 .rendered_html em {
895 .rendered_html em {
896 font-style: italic;
896 font-style: italic;
897 }
897 }
898 .rendered_html strong {
898 .rendered_html strong {
899 font-weight: bold;
899 font-weight: bold;
900 }
900 }
901 .rendered_html u {
901 .rendered_html u {
902 text-decoration: underline;
902 text-decoration: underline;
903 }
903 }
904 .rendered_html :link {
904 .rendered_html :link {
905 text-decoration: underline;
905 text-decoration: underline;
906 }
906 }
907 .rendered_html :visited {
907 .rendered_html :visited {
908 text-decoration: underline;
908 text-decoration: underline;
909 }
909 }
910 .rendered_html h1 {
910 .rendered_html h1 {
911 font-size: 185.7%;
911 font-size: 185.7%;
912 margin: 1.08em 0 0 0;
912 margin: 1.08em 0 0 0;
913 font-weight: bold;
913 font-weight: bold;
914 line-height: 1.0;
914 line-height: 1.0;
915 }
915 }
916 .rendered_html h2 {
916 .rendered_html h2 {
917 font-size: 157.1%;
917 font-size: 157.1%;
918 margin: 1.27em 0 0 0;
918 margin: 1.27em 0 0 0;
919 font-weight: bold;
919 font-weight: bold;
920 line-height: 1.0;
920 line-height: 1.0;
921 }
921 }
922 .rendered_html h3 {
922 .rendered_html h3 {
923 font-size: 128.6%;
923 font-size: 128.6%;
924 margin: 1.55em 0 0 0;
924 margin: 1.55em 0 0 0;
925 font-weight: bold;
925 font-weight: bold;
926 line-height: 1.0;
926 line-height: 1.0;
927 }
927 }
928 .rendered_html h4 {
928 .rendered_html h4 {
929 font-size: 100%;
929 font-size: 100%;
930 margin: 2em 0 0 0;
930 margin: 2em 0 0 0;
931 font-weight: bold;
931 font-weight: bold;
932 line-height: 1.0;
932 line-height: 1.0;
933 }
933 }
934 .rendered_html h5 {
934 .rendered_html h5 {
935 font-size: 100%;
935 font-size: 100%;
936 margin: 2em 0 0 0;
936 margin: 2em 0 0 0;
937 font-weight: bold;
937 font-weight: bold;
938 line-height: 1.0;
938 line-height: 1.0;
939 font-style: italic;
939 font-style: italic;
940 }
940 }
941 .rendered_html h6 {
941 .rendered_html h6 {
942 font-size: 100%;
942 font-size: 100%;
943 margin: 2em 0 0 0;
943 margin: 2em 0 0 0;
944 font-weight: bold;
944 font-weight: bold;
945 line-height: 1.0;
945 line-height: 1.0;
946 font-style: italic;
946 font-style: italic;
947 }
947 }
948 .rendered_html h1:first-child {
948 .rendered_html h1:first-child {
949 margin-top: 0.538em;
949 margin-top: 0.538em;
950 }
950 }
951 .rendered_html h2:first-child {
951 .rendered_html h2:first-child {
952 margin-top: 0.636em;
952 margin-top: 0.636em;
953 }
953 }
954 .rendered_html h3:first-child {
954 .rendered_html h3:first-child {
955 margin-top: 0.777em;
955 margin-top: 0.777em;
956 }
956 }
957 .rendered_html h4:first-child {
957 .rendered_html h4:first-child {
958 margin-top: 1em;
958 margin-top: 1em;
959 }
959 }
960 .rendered_html h5:first-child {
960 .rendered_html h5:first-child {
961 margin-top: 1em;
961 margin-top: 1em;
962 }
962 }
963 .rendered_html h6:first-child {
963 .rendered_html h6:first-child {
964 margin-top: 1em;
964 margin-top: 1em;
965 }
965 }
966 .rendered_html ul {
966 .rendered_html ul {
967 list-style: disc;
967 list-style: disc;
968 margin: 0em 2em;
968 margin: 0em 2em;
969 padding-left: 0px;
969 padding-left: 0px;
970 }
970 }
971 .rendered_html ul ul {
971 .rendered_html ul ul {
972 list-style: square;
972 list-style: square;
973 margin: 0em 2em;
973 margin: 0em 2em;
974 }
974 }
975 .rendered_html ul ul ul {
975 .rendered_html ul ul ul {
976 list-style: circle;
976 list-style: circle;
977 margin: 0em 2em;
977 margin: 0em 2em;
978 }
978 }
979 .rendered_html ol {
979 .rendered_html ol {
980 list-style: decimal;
980 list-style: decimal;
981 margin: 0em 2em;
981 margin: 0em 2em;
982 padding-left: 0px;
982 padding-left: 0px;
983 }
983 }
984 .rendered_html ol ol {
984 .rendered_html ol ol {
985 list-style: upper-alpha;
985 list-style: upper-alpha;
986 margin: 0em 2em;
986 margin: 0em 2em;
987 }
987 }
988 .rendered_html ol ol ol {
988 .rendered_html ol ol ol {
989 list-style: lower-alpha;
989 list-style: lower-alpha;
990 margin: 0em 2em;
990 margin: 0em 2em;
991 }
991 }
992 .rendered_html ol ol ol ol {
992 .rendered_html ol ol ol ol {
993 list-style: lower-roman;
993 list-style: lower-roman;
994 margin: 0em 2em;
994 margin: 0em 2em;
995 }
995 }
996 .rendered_html ol ol ol ol ol {
996 .rendered_html ol ol ol ol ol {
997 list-style: decimal;
997 list-style: decimal;
998 margin: 0em 2em;
998 margin: 0em 2em;
999 }
999 }
1000 .rendered_html * + ul {
1000 .rendered_html * + ul {
1001 margin-top: 1em;
1001 margin-top: 1em;
1002 }
1002 }
1003 .rendered_html * + ol {
1003 .rendered_html * + ol {
1004 margin-top: 1em;
1004 margin-top: 1em;
1005 }
1005 }
1006 .rendered_html hr {
1006 .rendered_html hr {
1007 color: #000000;
1007 color: #000000;
1008 background-color: #000000;
1008 background-color: #000000;
1009 }
1009 }
1010 .rendered_html pre {
1010 .rendered_html pre {
1011 margin: 1em 2em;
1011 margin: 1em 2em;
1012 }
1012 }
1013 .rendered_html pre,
1013 .rendered_html pre,
1014 .rendered_html code {
1014 .rendered_html code {
1015 border: 0;
1015 border: 0;
1016 background-color: #ffffff;
1016 background-color: #ffffff;
1017 color: #000000;
1017 color: #000000;
1018 font-size: 100%;
1018 font-size: 100%;
1019 padding: 0px;
1019 padding: 0px;
1020 }
1020 }
1021 .rendered_html blockquote {
1021 .rendered_html blockquote {
1022 margin: 1em 2em;
1022 margin: 1em 2em;
1023 }
1023 }
1024 .rendered_html table {
1024 .rendered_html table {
1025 margin-left: auto;
1025 margin-left: auto;
1026 margin-right: auto;
1026 margin-right: auto;
1027 border: 1px solid #000000;
1027 border: 1px solid #000000;
1028 border-collapse: collapse;
1028 border-collapse: collapse;
1029 }
1029 }
1030 .rendered_html tr,
1030 .rendered_html tr,
1031 .rendered_html th,
1031 .rendered_html th,
1032 .rendered_html td {
1032 .rendered_html td {
1033 border: 1px solid #000000;
1033 border: 1px solid #000000;
1034 border-collapse: collapse;
1034 border-collapse: collapse;
1035 margin: 1em 2em;
1035 margin: 1em 2em;
1036 }
1036 }
1037 .rendered_html td,
1037 .rendered_html td,
1038 .rendered_html th {
1038 .rendered_html th {
1039 text-align: left;
1039 text-align: left;
1040 vertical-align: middle;
1040 vertical-align: middle;
1041 padding: 4px;
1041 padding: 4px;
1042 }
1042 }
1043 .rendered_html th {
1043 .rendered_html th {
1044 font-weight: bold;
1044 font-weight: bold;
1045 }
1045 }
1046 .rendered_html * + table {
1046 .rendered_html * + table {
1047 margin-top: 1em;
1047 margin-top: 1em;
1048 }
1048 }
1049 .rendered_html p {
1049 .rendered_html p {
1050 text-align: justify;
1050 text-align: justify;
1051 }
1051 }
1052 .rendered_html * + p {
1052 .rendered_html * + p {
1053 margin-top: 1em;
1053 margin-top: 1em;
1054 }
1054 }
1055 .rendered_html img {
1055 .rendered_html img {
1056 display: block;
1056 display: block;
1057 margin-left: auto;
1057 margin-left: auto;
1058 margin-right: auto;
1058 margin-right: auto;
1059 }
1059 }
1060 .rendered_html * + img {
1060 .rendered_html * + img {
1061 margin-top: 1em;
1061 margin-top: 1em;
1062 }
1062 }
1063 div.text_cell {
1063 div.text_cell {
1064 padding: 5px 5px 5px 0px;
1064 padding: 5px 5px 5px 0px;
1065 /* Old browsers */
1065 /* Old browsers */
1066 display: -webkit-box;
1066 display: -webkit-box;
1067 -webkit-box-orient: horizontal;
1067 -webkit-box-orient: horizontal;
1068 -webkit-box-align: stretch;
1068 -webkit-box-align: stretch;
1069 display: -moz-box;
1069 display: -moz-box;
1070 -moz-box-orient: horizontal;
1070 -moz-box-orient: horizontal;
1071 -moz-box-align: stretch;
1071 -moz-box-align: stretch;
1072 display: box;
1072 display: box;
1073 box-orient: horizontal;
1073 box-orient: horizontal;
1074 box-align: stretch;
1074 box-align: stretch;
1075 /* Modern browsers */
1075 /* Modern browsers */
1076 display: flex;
1076 display: flex;
1077 flex-direction: row;
1077 flex-direction: row;
1078 align-items: stretch;
1078 align-items: stretch;
1079 }
1079 }
1080 @media (max-width: 480px) {
1080 @media (max-width: 480px) {
1081 div.text_cell > div.prompt {
1081 div.text_cell > div.prompt {
1082 display: none;
1082 display: none;
1083 }
1083 }
1084 }
1084 }
1085 div.text_cell_render {
1085 div.text_cell_render {
1086 /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
1086 /*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
1087 outline: none;
1087 outline: none;
1088 resize: none;
1088 resize: none;
1089 width: inherit;
1089 width: inherit;
1090 border-style: none;
1090 border-style: none;
1091 padding: 0.5em 0.5em 0.5em 0.4em;
1091 padding: 0.5em 0.5em 0.5em 0.4em;
1092 color: #000000;
1092 color: #000000;
1093 box-sizing: border-box;
1093 box-sizing: border-box;
1094 -moz-box-sizing: border-box;
1094 -moz-box-sizing: border-box;
1095 -webkit-box-sizing: border-box;
1095 -webkit-box-sizing: border-box;
1096 }
1096 }
1097 a.anchor-link:link {
1097 a.anchor-link:link {
1098 text-decoration: none;
1098 text-decoration: none;
1099 padding: 0px 20px;
1099 padding: 0px 20px;
1100 visibility: hidden;
1100 visibility: hidden;
1101 }
1101 }
1102 h1:hover .anchor-link,
1102 h1:hover .anchor-link,
1103 h2:hover .anchor-link,
1103 h2:hover .anchor-link,
1104 h3:hover .anchor-link,
1104 h3:hover .anchor-link,
1105 h4:hover .anchor-link,
1105 h4:hover .anchor-link,
1106 h5:hover .anchor-link,
1106 h5:hover .anchor-link,
1107 h6:hover .anchor-link {
1107 h6:hover .anchor-link {
1108 visibility: visible;
1108 visibility: visible;
1109 }
1109 }
1110 div.cell.text_cell.rendered {
1110 div.cell.text_cell.rendered {
1111 padding: 0px;
1111 padding: 0px;
1112 }
1112 }
1113 .text_cell.rendered .input_area {
1113 .text_cell.rendered .input_area {
1114 display: none;
1114 display: none;
1115 }
1115 }
1116 .text_cell.unrendered .text_cell_render {
1116 .text_cell.unrendered .text_cell_render {
1117 display: none;
1117 display: none;
1118 }
1118 }
1119 .cm-s-heading-1,
1119 .cm-header-1,
1120 .cm-s-heading-2,
1120 .cm-header-2,
1121 .cm-s-heading-3,
1121 .cm-header-3,
1122 .cm-s-heading-4,
1122 .cm-header-4,
1123 .cm-s-heading-5,
1123 .cm-header-5,
1124 .cm-s-heading-6 {
1124 .cm-header-6 {
1125 font-weight: bold;
1125 font-weight: bold;
1126 font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
1126 font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
1127 }
1127 }
1128 .cm-s-heading-1 {
1128 .cm-header-1 {
1129 font-size: 150%;
1129 font-size: 185.7%;
1130 }
1130 }
1131 .cm-s-heading-2 {
1131 .cm-header-2 {
1132 font-size: 130%;
1132 font-size: 157.1%;
1133 }
1133 }
1134 .cm-s-heading-3 {
1134 .cm-header-3 {
1135 font-size: 120%;
1135 font-size: 128.6%;
1136 }
1136 }
1137 .cm-s-heading-4 {
1137 .cm-header-4 {
1138 font-size: 110%;
1138 font-size: 110%;
1139 }
1139 }
1140 .cm-s-heading-5 {
1140 .cm-header-5 {
1141 font-size: 100%;
1141 font-size: 100%;
1142 font-style: italic;
1142 font-style: italic;
1143 }
1143 }
1144 .cm-s-heading-6 {
1144 .cm-header-6 {
1145 font-size: 90%;
1145 font-size: 100%;
1146 font-style: italic;
1146 font-style: italic;
1147 }
1147 }
1148 .widget-area {
1148 .widget-area {
1149 /*
1149 /*
1150 LESS file that styles IPython notebook widgets and the area they sit in.
1150 LESS file that styles IPython notebook widgets and the area they sit in.
1151
1151
1152 The widget area typically looks something like this:
1152 The widget area typically looks something like this:
1153 +------------------------------------------+
1153 +------------------------------------------+
1154 | widget-area |
1154 | widget-area |
1155 | +--------+---------------------------+ |
1155 | +--------+---------------------------+ |
1156 | | prompt | widget-subarea | |
1156 | | prompt | widget-subarea | |
1157 | | | +--------+ +--------+ | |
1157 | | | +--------+ +--------+ | |
1158 | | | | widget | | widget | | |
1158 | | | | widget | | widget | | |
1159 | | | +--------+ +--------+ | |
1159 | | | +--------+ +--------+ | |
1160 | +--------+---------------------------+ |
1160 | +--------+---------------------------+ |
1161 +------------------------------------------+
1161 +------------------------------------------+
1162 */
1162 */
1163 page-break-inside: avoid;
1163 page-break-inside: avoid;
1164 /* Old browsers */
1164 /* Old browsers */
1165 display: -webkit-box;
1165 display: -webkit-box;
1166 -webkit-box-orient: horizontal;
1166 -webkit-box-orient: horizontal;
1167 -webkit-box-align: stretch;
1167 -webkit-box-align: stretch;
1168 display: -moz-box;
1168 display: -moz-box;
1169 -moz-box-orient: horizontal;
1169 -moz-box-orient: horizontal;
1170 -moz-box-align: stretch;
1170 -moz-box-align: stretch;
1171 display: box;
1171 display: box;
1172 box-orient: horizontal;
1172 box-orient: horizontal;
1173 box-align: stretch;
1173 box-align: stretch;
1174 /* Modern browsers */
1174 /* Modern browsers */
1175 display: flex;
1175 display: flex;
1176 flex-direction: row;
1176 flex-direction: row;
1177 align-items: stretch;
1177 align-items: stretch;
1178 }
1178 }
1179 .widget-area .widget-subarea {
1179 .widget-area .widget-subarea {
1180 padding: 0.44em 0.4em 0.4em 1px;
1180 padding: 0.44em 0.4em 0.4em 1px;
1181 margin-left: 6px;
1181 margin-left: 6px;
1182 box-sizing: border-box;
1182 box-sizing: border-box;
1183 -moz-box-sizing: border-box;
1183 -moz-box-sizing: border-box;
1184 -webkit-box-sizing: border-box;
1184 -webkit-box-sizing: border-box;
1185 /* Old browsers */
1185 /* Old browsers */
1186 display: -webkit-box;
1186 display: -webkit-box;
1187 -webkit-box-orient: vertical;
1187 -webkit-box-orient: vertical;
1188 -webkit-box-align: stretch;
1188 -webkit-box-align: stretch;
1189 display: -moz-box;
1189 display: -moz-box;
1190 -moz-box-orient: vertical;
1190 -moz-box-orient: vertical;
1191 -moz-box-align: stretch;
1191 -moz-box-align: stretch;
1192 display: box;
1192 display: box;
1193 box-orient: vertical;
1193 box-orient: vertical;
1194 box-align: stretch;
1194 box-align: stretch;
1195 /* Modern browsers */
1195 /* Modern browsers */
1196 display: flex;
1196 display: flex;
1197 flex-direction: column;
1197 flex-direction: column;
1198 align-items: stretch;
1198 align-items: stretch;
1199 /* Old browsers */
1199 /* Old browsers */
1200 -webkit-box-flex: 2;
1200 -webkit-box-flex: 2;
1201 -moz-box-flex: 2;
1201 -moz-box-flex: 2;
1202 box-flex: 2;
1202 box-flex: 2;
1203 /* Modern browsers */
1203 /* Modern browsers */
1204 flex: 2;
1204 flex: 2;
1205 /* Old browsers */
1205 /* Old browsers */
1206 -webkit-box-align: start;
1206 -webkit-box-align: start;
1207 -moz-box-align: start;
1207 -moz-box-align: start;
1208 box-align: start;
1208 box-align: start;
1209 /* Modern browsers */
1209 /* Modern browsers */
1210 align-items: flex-start;
1210 align-items: flex-start;
1211 }
1211 }
1212 /* THE CLASSES BELOW CAN APPEAR ANYWHERE IN THE DOM (POSSIBLEY OUTSIDE OF
1212 /* THE CLASSES BELOW CAN APPEAR ANYWHERE IN THE DOM (POSSIBLEY OUTSIDE OF
1213 THE WIDGET AREA). */
1213 THE WIDGET AREA). */
1214 .slide-track {
1214 .slide-track {
1215 /* Slider Track */
1215 /* Slider Track */
1216 border: 1px solid #CCCCCC;
1216 border: 1px solid #CCCCCC;
1217 background: #FFFFFF;
1217 background: #FFFFFF;
1218 border-radius: 4px;
1218 border-radius: 4px;
1219 /* Round the corners of the slide track */
1219 /* Round the corners of the slide track */
1220 }
1220 }
1221 .widget-hslider {
1221 .widget-hslider {
1222 /* Horizontal jQuery Slider
1222 /* Horizontal jQuery Slider
1223
1223
1224 Both the horizontal and vertical versions of the slider are characterized
1224 Both the horizontal and vertical versions of the slider are characterized
1225 by a styled div that contains an invisible jQuery slide div which
1225 by a styled div that contains an invisible jQuery slide div which
1226 contains a visible slider handle div. This is requred so we can control
1226 contains a visible slider handle div. This is requred so we can control
1227 how the slider is drawn and 'fix' the issue where the slide handle
1227 how the slider is drawn and 'fix' the issue where the slide handle
1228 doesn't stop at the end of the slide.
1228 doesn't stop at the end of the slide.
1229
1229
1230 Both horizontal and vertical sliders have this div nesting:
1230 Both horizontal and vertical sliders have this div nesting:
1231 +------------------------------------------+
1231 +------------------------------------------+
1232 | widget-(h/v)slider |
1232 | widget-(h/v)slider |
1233 | +--------+---------------------------+ |
1233 | +--------+---------------------------+ |
1234 | | ui-slider | |
1234 | | ui-slider | |
1235 | | +------------------+ | |
1235 | | +------------------+ | |
1236 | | | ui-slider-handle | | |
1236 | | | ui-slider-handle | | |
1237 | | +------------------+ | |
1237 | | +------------------+ | |
1238 | +--------+---------------------------+ |
1238 | +--------+---------------------------+ |
1239 +------------------------------------------+
1239 +------------------------------------------+
1240 */
1240 */
1241 /* Fix the padding of the slide track so the ui-slider is sized
1241 /* Fix the padding of the slide track so the ui-slider is sized
1242 correctly. */
1242 correctly. */
1243 padding-left: 8px;
1243 padding-left: 8px;
1244 padding-right: 5px;
1244 padding-right: 5px;
1245 overflow: visible;
1245 overflow: visible;
1246 /* Default size of the slider */
1246 /* Default size of the slider */
1247 width: 350px;
1247 width: 350px;
1248 height: 5px;
1248 height: 5px;
1249 max-height: 5px;
1249 max-height: 5px;
1250 margin-top: 13px;
1250 margin-top: 13px;
1251 margin-bottom: 10px;
1251 margin-bottom: 10px;
1252 /* Style the slider track */
1252 /* Style the slider track */
1253 /* Slider Track */
1253 /* Slider Track */
1254 border: 1px solid #CCCCCC;
1254 border: 1px solid #CCCCCC;
1255 background: #FFFFFF;
1255 background: #FFFFFF;
1256 border-radius: 4px;
1256 border-radius: 4px;
1257 /* Round the corners of the slide track */
1257 /* Round the corners of the slide track */
1258 /* Make the div a flex box (makes FF behave correctly). */
1258 /* Make the div a flex box (makes FF behave correctly). */
1259 /* Old browsers */
1259 /* Old browsers */
1260 display: -webkit-box;
1260 display: -webkit-box;
1261 -webkit-box-orient: horizontal;
1261 -webkit-box-orient: horizontal;
1262 -webkit-box-align: stretch;
1262 -webkit-box-align: stretch;
1263 display: -moz-box;
1263 display: -moz-box;
1264 -moz-box-orient: horizontal;
1264 -moz-box-orient: horizontal;
1265 -moz-box-align: stretch;
1265 -moz-box-align: stretch;
1266 display: box;
1266 display: box;
1267 box-orient: horizontal;
1267 box-orient: horizontal;
1268 box-align: stretch;
1268 box-align: stretch;
1269 /* Modern browsers */
1269 /* Modern browsers */
1270 display: flex;
1270 display: flex;
1271 flex-direction: row;
1271 flex-direction: row;
1272 align-items: stretch;
1272 align-items: stretch;
1273 }
1273 }
1274 .widget-hslider .ui-slider {
1274 .widget-hslider .ui-slider {
1275 /* Inner, invisible slide div */
1275 /* Inner, invisible slide div */
1276 border: 0px !important;
1276 border: 0px !important;
1277 background: none !important;
1277 background: none !important;
1278 /* Old browsers */
1278 /* Old browsers */
1279 display: -webkit-box;
1279 display: -webkit-box;
1280 -webkit-box-orient: horizontal;
1280 -webkit-box-orient: horizontal;
1281 -webkit-box-align: stretch;
1281 -webkit-box-align: stretch;
1282 display: -moz-box;
1282 display: -moz-box;
1283 -moz-box-orient: horizontal;
1283 -moz-box-orient: horizontal;
1284 -moz-box-align: stretch;
1284 -moz-box-align: stretch;
1285 display: box;
1285 display: box;
1286 box-orient: horizontal;
1286 box-orient: horizontal;
1287 box-align: stretch;
1287 box-align: stretch;
1288 /* Modern browsers */
1288 /* Modern browsers */
1289 display: flex;
1289 display: flex;
1290 flex-direction: row;
1290 flex-direction: row;
1291 align-items: stretch;
1291 align-items: stretch;
1292 /* Old browsers */
1292 /* Old browsers */
1293 -webkit-box-flex: 1;
1293 -webkit-box-flex: 1;
1294 -moz-box-flex: 1;
1294 -moz-box-flex: 1;
1295 box-flex: 1;
1295 box-flex: 1;
1296 /* Modern browsers */
1296 /* Modern browsers */
1297 flex: 1;
1297 flex: 1;
1298 }
1298 }
1299 .widget-hslider .ui-slider .ui-slider-handle {
1299 .widget-hslider .ui-slider .ui-slider-handle {
1300 width: 14px !important;
1300 width: 14px !important;
1301 height: 28px !important;
1301 height: 28px !important;
1302 margin-top: -8px !important;
1302 margin-top: -8px !important;
1303 }
1303 }
1304 .widget-hslider .ui-slider .ui-slider-range {
1304 .widget-hslider .ui-slider .ui-slider-range {
1305 height: 12px !important;
1305 height: 12px !important;
1306 margin-top: -4px !important;
1306 margin-top: -4px !important;
1307 }
1307 }
1308 .widget-vslider {
1308 .widget-vslider {
1309 /* Vertical jQuery Slider */
1309 /* Vertical jQuery Slider */
1310 /* Fix the padding of the slide track so the ui-slider is sized
1310 /* Fix the padding of the slide track so the ui-slider is sized
1311 correctly. */
1311 correctly. */
1312 padding-bottom: 8px;
1312 padding-bottom: 8px;
1313 overflow: visible;
1313 overflow: visible;
1314 /* Default size of the slider */
1314 /* Default size of the slider */
1315 width: 5px;
1315 width: 5px;
1316 max-width: 5px;
1316 max-width: 5px;
1317 height: 250px;
1317 height: 250px;
1318 margin-left: 12px;
1318 margin-left: 12px;
1319 /* Style the slider track */
1319 /* Style the slider track */
1320 /* Slider Track */
1320 /* Slider Track */
1321 border: 1px solid #CCCCCC;
1321 border: 1px solid #CCCCCC;
1322 background: #FFFFFF;
1322 background: #FFFFFF;
1323 border-radius: 4px;
1323 border-radius: 4px;
1324 /* Round the corners of the slide track */
1324 /* Round the corners of the slide track */
1325 /* Make the div a flex box (makes FF behave correctly). */
1325 /* Make the div a flex box (makes FF behave correctly). */
1326 /* Old browsers */
1326 /* Old browsers */
1327 display: -webkit-box;
1327 display: -webkit-box;
1328 -webkit-box-orient: vertical;
1328 -webkit-box-orient: vertical;
1329 -webkit-box-align: stretch;
1329 -webkit-box-align: stretch;
1330 display: -moz-box;
1330 display: -moz-box;
1331 -moz-box-orient: vertical;
1331 -moz-box-orient: vertical;
1332 -moz-box-align: stretch;
1332 -moz-box-align: stretch;
1333 display: box;
1333 display: box;
1334 box-orient: vertical;
1334 box-orient: vertical;
1335 box-align: stretch;
1335 box-align: stretch;
1336 /* Modern browsers */
1336 /* Modern browsers */
1337 display: flex;
1337 display: flex;
1338 flex-direction: column;
1338 flex-direction: column;
1339 align-items: stretch;
1339 align-items: stretch;
1340 }
1340 }
1341 .widget-vslider .ui-slider {
1341 .widget-vslider .ui-slider {
1342 /* Inner, invisible slide div */
1342 /* Inner, invisible slide div */
1343 border: 0px !important;
1343 border: 0px !important;
1344 background: none !important;
1344 background: none !important;
1345 margin-left: -4px;
1345 margin-left: -4px;
1346 margin-top: 5px;
1346 margin-top: 5px;
1347 /* Old browsers */
1347 /* Old browsers */
1348 display: -webkit-box;
1348 display: -webkit-box;
1349 -webkit-box-orient: vertical;
1349 -webkit-box-orient: vertical;
1350 -webkit-box-align: stretch;
1350 -webkit-box-align: stretch;
1351 display: -moz-box;
1351 display: -moz-box;
1352 -moz-box-orient: vertical;
1352 -moz-box-orient: vertical;
1353 -moz-box-align: stretch;
1353 -moz-box-align: stretch;
1354 display: box;
1354 display: box;
1355 box-orient: vertical;
1355 box-orient: vertical;
1356 box-align: stretch;
1356 box-align: stretch;
1357 /* Modern browsers */
1357 /* Modern browsers */
1358 display: flex;
1358 display: flex;
1359 flex-direction: column;
1359 flex-direction: column;
1360 align-items: stretch;
1360 align-items: stretch;
1361 /* Old browsers */
1361 /* Old browsers */
1362 -webkit-box-flex: 1;
1362 -webkit-box-flex: 1;
1363 -moz-box-flex: 1;
1363 -moz-box-flex: 1;
1364 box-flex: 1;
1364 box-flex: 1;
1365 /* Modern browsers */
1365 /* Modern browsers */
1366 flex: 1;
1366 flex: 1;
1367 }
1367 }
1368 .widget-vslider .ui-slider .ui-slider-handle {
1368 .widget-vslider .ui-slider .ui-slider-handle {
1369 width: 28px !important;
1369 width: 28px !important;
1370 height: 14px !important;
1370 height: 14px !important;
1371 margin-left: -9px;
1371 margin-left: -9px;
1372 }
1372 }
1373 .widget-vslider .ui-slider .ui-slider-range {
1373 .widget-vslider .ui-slider .ui-slider-range {
1374 width: 12px !important;
1374 width: 12px !important;
1375 margin-left: -1px !important;
1375 margin-left: -1px !important;
1376 }
1376 }
1377 .widget-text {
1377 .widget-text {
1378 /* String Textbox - used for TextBoxView and TextAreaView */
1378 /* String Textbox - used for TextBoxView and TextAreaView */
1379 width: 350px;
1379 width: 350px;
1380 margin: 0px !important;
1380 margin: 0px !important;
1381 }
1381 }
1382 .widget-listbox {
1382 .widget-listbox {
1383 /* Listbox */
1383 /* Listbox */
1384 width: 350px;
1384 width: 350px;
1385 margin-bottom: 0px;
1385 margin-bottom: 0px;
1386 }
1386 }
1387 .widget-numeric-text {
1387 .widget-numeric-text {
1388 /* Single Line Textbox - used for IntTextView and FloatTextView */
1388 /* Single Line Textbox - used for IntTextView and FloatTextView */
1389 width: 150px;
1389 width: 150px;
1390 margin: 0px !important;
1390 margin: 0px !important;
1391 }
1391 }
1392 .widget-progress {
1392 .widget-progress {
1393 /* Progress Bar */
1393 /* Progress Bar */
1394 margin-top: 6px;
1394 margin-top: 6px;
1395 width: 350px;
1395 width: 350px;
1396 }
1396 }
1397 .widget-progress .progress-bar {
1397 .widget-progress .progress-bar {
1398 /* Disable progress bar animation */
1398 /* Disable progress bar animation */
1399 -webkit-transition: none;
1399 -webkit-transition: none;
1400 -moz-transition: none;
1400 -moz-transition: none;
1401 -ms-transition: none;
1401 -ms-transition: none;
1402 -o-transition: none;
1402 -o-transition: none;
1403 transition: none;
1403 transition: none;
1404 }
1404 }
1405 .widget-combo-btn {
1405 .widget-combo-btn {
1406 /* ComboBox Main Button */
1406 /* ComboBox Main Button */
1407 min-width: 125px;
1407 min-width: 125px;
1408 }
1408 }
1409 .widget_item .dropdown-menu li a {
1409 .widget_item .dropdown-menu li a {
1410 color: inherit;
1410 color: inherit;
1411 }
1411 }
1412 .widget-hbox {
1412 .widget-hbox {
1413 /* Horizontal widgets */
1413 /* Horizontal widgets */
1414 /* Old browsers */
1414 /* Old browsers */
1415 display: -webkit-box;
1415 display: -webkit-box;
1416 -webkit-box-orient: horizontal;
1416 -webkit-box-orient: horizontal;
1417 -webkit-box-align: stretch;
1417 -webkit-box-align: stretch;
1418 display: -moz-box;
1418 display: -moz-box;
1419 -moz-box-orient: horizontal;
1419 -moz-box-orient: horizontal;
1420 -moz-box-align: stretch;
1420 -moz-box-align: stretch;
1421 display: box;
1421 display: box;
1422 box-orient: horizontal;
1422 box-orient: horizontal;
1423 box-align: stretch;
1423 box-align: stretch;
1424 /* Modern browsers */
1424 /* Modern browsers */
1425 display: flex;
1425 display: flex;
1426 flex-direction: row;
1426 flex-direction: row;
1427 align-items: stretch;
1427 align-items: stretch;
1428 margin-top: 0px !important;
1428 margin-top: 0px !important;
1429 margin-bottom: 0px !important;
1429 margin-bottom: 0px !important;
1430 margin-right: 5px;
1430 margin-right: 5px;
1431 margin-left: 5px;
1431 margin-left: 5px;
1432 }
1432 }
1433 .widget-hbox input[type="checkbox"] {
1433 .widget-hbox input[type="checkbox"] {
1434 margin-top: 9px;
1434 margin-top: 9px;
1435 }
1435 }
1436 .widget-hbox .widget-label {
1436 .widget-hbox .widget-label {
1437 /* Horizontal Label */
1437 /* Horizontal Label */
1438 min-width: 10ex;
1438 min-width: 10ex;
1439 padding-right: 8px;
1439 padding-right: 8px;
1440 padding-top: 5px;
1440 padding-top: 5px;
1441 text-align: right;
1441 text-align: right;
1442 vertical-align: text-top;
1442 vertical-align: text-top;
1443 }
1443 }
1444 .widget-hbox .widget-readout {
1444 .widget-hbox .widget-readout {
1445 padding-left: 8px;
1445 padding-left: 8px;
1446 padding-top: 5px;
1446 padding-top: 5px;
1447 text-align: left;
1447 text-align: left;
1448 vertical-align: text-top;
1448 vertical-align: text-top;
1449 }
1449 }
1450 .widget-vbox {
1450 .widget-vbox {
1451 /* Vertical widgets */
1451 /* Vertical widgets */
1452 /* Old browsers */
1452 /* Old browsers */
1453 display: -webkit-box;
1453 display: -webkit-box;
1454 -webkit-box-orient: vertical;
1454 -webkit-box-orient: vertical;
1455 -webkit-box-align: stretch;
1455 -webkit-box-align: stretch;
1456 display: -moz-box;
1456 display: -moz-box;
1457 -moz-box-orient: vertical;
1457 -moz-box-orient: vertical;
1458 -moz-box-align: stretch;
1458 -moz-box-align: stretch;
1459 display: box;
1459 display: box;
1460 box-orient: vertical;
1460 box-orient: vertical;
1461 box-align: stretch;
1461 box-align: stretch;
1462 /* Modern browsers */
1462 /* Modern browsers */
1463 display: flex;
1463 display: flex;
1464 flex-direction: column;
1464 flex-direction: column;
1465 align-items: stretch;
1465 align-items: stretch;
1466 }
1466 }
1467 .widget-vbox .widget-label {
1467 .widget-vbox .widget-label {
1468 /* Vertical Label */
1468 /* Vertical Label */
1469 padding-bottom: 5px;
1469 padding-bottom: 5px;
1470 text-align: center;
1470 text-align: center;
1471 vertical-align: text-bottom;
1471 vertical-align: text-bottom;
1472 }
1472 }
1473 .widget-vbox .widget-readout {
1473 .widget-vbox .widget-readout {
1474 /* Vertical Label */
1474 /* Vertical Label */
1475 padding-top: 5px;
1475 padding-top: 5px;
1476 text-align: center;
1476 text-align: center;
1477 vertical-align: text-top;
1477 vertical-align: text-top;
1478 }
1478 }
1479 .widget-modal {
1479 .widget-modal {
1480 /* Box - ModalView */
1480 /* Box - ModalView */
1481 overflow: hidden;
1481 overflow: hidden;
1482 position: absolute !important;
1482 position: absolute !important;
1483 top: 0px;
1483 top: 0px;
1484 left: 0px;
1484 left: 0px;
1485 margin-left: 0px !important;
1485 margin-left: 0px !important;
1486 }
1486 }
1487 .widget-modal-body {
1487 .widget-modal-body {
1488 /* Box - ModalView Body */
1488 /* Box - ModalView Body */
1489 max-height: none !important;
1489 max-height: none !important;
1490 }
1490 }
1491 .widget-box {
1491 .widget-box {
1492 /* Box */
1492 /* Box */
1493 box-sizing: border-box;
1493 box-sizing: border-box;
1494 -moz-box-sizing: border-box;
1494 -moz-box-sizing: border-box;
1495 -webkit-box-sizing: border-box;
1495 -webkit-box-sizing: border-box;
1496 /* Old browsers */
1496 /* Old browsers */
1497 -webkit-box-align: start;
1497 -webkit-box-align: start;
1498 -moz-box-align: start;
1498 -moz-box-align: start;
1499 box-align: start;
1499 box-align: start;
1500 /* Modern browsers */
1500 /* Modern browsers */
1501 align-items: flex-start;
1501 align-items: flex-start;
1502 }
1502 }
1503 .widget-radio-box {
1503 .widget-radio-box {
1504 /* Contains RadioButtonsWidget */
1504 /* Contains RadioButtonsWidget */
1505 /* Old browsers */
1505 /* Old browsers */
1506 display: -webkit-box;
1506 display: -webkit-box;
1507 -webkit-box-orient: vertical;
1507 -webkit-box-orient: vertical;
1508 -webkit-box-align: stretch;
1508 -webkit-box-align: stretch;
1509 display: -moz-box;
1509 display: -moz-box;
1510 -moz-box-orient: vertical;
1510 -moz-box-orient: vertical;
1511 -moz-box-align: stretch;
1511 -moz-box-align: stretch;
1512 display: box;
1512 display: box;
1513 box-orient: vertical;
1513 box-orient: vertical;
1514 box-align: stretch;
1514 box-align: stretch;
1515 /* Modern browsers */
1515 /* Modern browsers */
1516 display: flex;
1516 display: flex;
1517 flex-direction: column;
1517 flex-direction: column;
1518 align-items: stretch;
1518 align-items: stretch;
1519 box-sizing: border-box;
1519 box-sizing: border-box;
1520 -moz-box-sizing: border-box;
1520 -moz-box-sizing: border-box;
1521 -webkit-box-sizing: border-box;
1521 -webkit-box-sizing: border-box;
1522 padding-top: 4px;
1522 padding-top: 4px;
1523 }
1523 }
1524 .widget-radio-box label {
1524 .widget-radio-box label {
1525 margin-top: 0px;
1525 margin-top: 0px;
1526 }
1526 }
1527 .docked-widget-modal {
1527 .docked-widget-modal {
1528 /* Horizontal Label */
1528 /* Horizontal Label */
1529 overflow: hidden;
1529 overflow: hidden;
1530 position: relative !important;
1530 position: relative !important;
1531 top: 0px !important;
1531 top: 0px !important;
1532 left: 0px !important;
1532 left: 0px !important;
1533 margin-left: 0px !important;
1533 margin-left: 0px !important;
1534 }
1534 }
1535 /*# sourceMappingURL=../style/ipython.min.css.map */ No newline at end of file
1535 /*# sourceMappingURL=../style/ipython.min.css.map */
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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
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
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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
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
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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
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