##// END OF EJS Templates
Fall back to default editor if $EDITOR is non-ASCII....
Thomas Kluyver -
Show More
@@ -1,691 +1,697 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
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 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 import bdb
18 import bdb
19 import os
19 import os
20 import sys
20 import sys
21
21
22 from IPython.core.error import TryNext, UsageError
22 from IPython.core.error import TryNext, UsageError
23 from IPython.core.usage import interactive_usage, default_banner
23 from IPython.core.usage import interactive_usage, default_banner
24 from IPython.core.inputsplitter import IPythonInputSplitter
24 from IPython.core.inputsplitter import IPythonInputSplitter
25 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
25 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
26 from IPython.core.magic import Magics, magics_class, line_magic
26 from IPython.core.magic import Magics, magics_class, line_magic
27 from IPython.lib.clipboard import ClipboardEmpty
27 from IPython.lib.clipboard import ClipboardEmpty
28 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.utils.encoding import get_stream_enc
29 from IPython.utils.encoding import get_stream_enc
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.terminal import toggle_set_term_title, set_term_title
32 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.process import abbrev_cwd
33 from IPython.utils.warn import warn, error
33 from IPython.utils.warn import warn, error
34 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
34 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
35 from IPython.utils.traitlets import Integer, CBool, Unicode
35 from IPython.utils.traitlets import Integer, CBool, Unicode
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Utilities
38 # Utilities
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 def get_default_editor():
41 def get_default_editor():
42 try:
42 try:
43 ed = os.environ['EDITOR']
43 ed = os.environ['EDITOR']
44 if not py3compat.PY3:
45 ed = ed.decode()
46 return ed
44 except KeyError:
47 except KeyError:
45 if os.name == 'posix':
48 pass
46 ed = 'vi' # the only one guaranteed to be there!
49 except UnicodeError:
47 else:
50 warn("$EDITOR environment variable is not pure ASCII. Using platform "
48 ed = 'notepad' # same in Windows!
51 "default editor.")
49 return ed
52
50
53 if os.name == 'posix':
54 return 'vi' # the only one guaranteed to be there!
55 else:
56 return 'notepad' # same in Windows!
51
57
52 def get_pasted_lines(sentinel, l_input=py3compat.input):
58 def get_pasted_lines(sentinel, l_input=py3compat.input):
53 """ Yield pasted lines until the user enters the given sentinel value.
59 """ Yield pasted lines until the user enters the given sentinel value.
54 """
60 """
55 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
61 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
56 % sentinel)
62 % sentinel)
57 while True:
63 while True:
58 try:
64 try:
59 l = l_input(':')
65 l = l_input(':')
60 if l == sentinel:
66 if l == sentinel:
61 return
67 return
62 else:
68 else:
63 yield l
69 yield l
64 except EOFError:
70 except EOFError:
65 print('<EOF>')
71 print('<EOF>')
66 return
72 return
67
73
68
74
69 #------------------------------------------------------------------------
75 #------------------------------------------------------------------------
70 # Terminal-specific magics
76 # Terminal-specific magics
71 #------------------------------------------------------------------------
77 #------------------------------------------------------------------------
72
78
73 @magics_class
79 @magics_class
74 class TerminalMagics(Magics):
80 class TerminalMagics(Magics):
75 def __init__(self, shell):
81 def __init__(self, shell):
76 super(TerminalMagics, self).__init__(shell)
82 super(TerminalMagics, self).__init__(shell)
77 self.input_splitter = IPythonInputSplitter()
83 self.input_splitter = IPythonInputSplitter()
78
84
79 def store_or_execute(self, block, name):
85 def store_or_execute(self, block, name):
80 """ Execute a block, or store it in a variable, per the user's request.
86 """ Execute a block, or store it in a variable, per the user's request.
81 """
87 """
82 if name:
88 if name:
83 # If storing it for further editing
89 # If storing it for further editing
84 self.shell.user_ns[name] = SList(block.splitlines())
90 self.shell.user_ns[name] = SList(block.splitlines())
85 print("Block assigned to '%s'" % name)
91 print("Block assigned to '%s'" % name)
86 else:
92 else:
87 b = self.preclean_input(block)
93 b = self.preclean_input(block)
88 self.shell.user_ns['pasted_block'] = b
94 self.shell.user_ns['pasted_block'] = b
89 self.shell.using_paste_magics = True
95 self.shell.using_paste_magics = True
90 try:
96 try:
91 self.shell.run_cell(b)
97 self.shell.run_cell(b)
92 finally:
98 finally:
93 self.shell.using_paste_magics = False
99 self.shell.using_paste_magics = False
94
100
95 def preclean_input(self, block):
101 def preclean_input(self, block):
96 lines = block.splitlines()
102 lines = block.splitlines()
97 while lines and not lines[0].strip():
103 while lines and not lines[0].strip():
98 lines = lines[1:]
104 lines = lines[1:]
99 return strip_email_quotes('\n'.join(lines))
105 return strip_email_quotes('\n'.join(lines))
100
106
101 def rerun_pasted(self, name='pasted_block'):
107 def rerun_pasted(self, name='pasted_block'):
102 """ Rerun a previously pasted command.
108 """ Rerun a previously pasted command.
103 """
109 """
104 b = self.shell.user_ns.get(name)
110 b = self.shell.user_ns.get(name)
105
111
106 # Sanity checks
112 # Sanity checks
107 if b is None:
113 if b is None:
108 raise UsageError('No previous pasted block available')
114 raise UsageError('No previous pasted block available')
109 if not isinstance(b, py3compat.string_types):
115 if not isinstance(b, py3compat.string_types):
110 raise UsageError(
116 raise UsageError(
111 "Variable 'pasted_block' is not a string, can't execute")
117 "Variable 'pasted_block' is not a string, can't execute")
112
118
113 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
119 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
114 self.shell.run_cell(b)
120 self.shell.run_cell(b)
115
121
116 @line_magic
122 @line_magic
117 def autoindent(self, parameter_s = ''):
123 def autoindent(self, parameter_s = ''):
118 """Toggle autoindent on/off (if available)."""
124 """Toggle autoindent on/off (if available)."""
119
125
120 self.shell.set_autoindent()
126 self.shell.set_autoindent()
121 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
127 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
122
128
123 @skip_doctest
129 @skip_doctest
124 @line_magic
130 @line_magic
125 def cpaste(self, parameter_s=''):
131 def cpaste(self, parameter_s=''):
126 """Paste & execute a pre-formatted code block from clipboard.
132 """Paste & execute a pre-formatted code block from clipboard.
127
133
128 You must terminate the block with '--' (two minus-signs) or Ctrl-D
134 You must terminate the block with '--' (two minus-signs) or Ctrl-D
129 alone on the line. You can also provide your own sentinel with '%paste
135 alone on the line. You can also provide your own sentinel with '%paste
130 -s %%' ('%%' is the new sentinel for this operation)
136 -s %%' ('%%' is the new sentinel for this operation)
131
137
132 The block is dedented prior to execution to enable execution of method
138 The block is dedented prior to execution to enable execution of method
133 definitions. '>' and '+' characters at the beginning of a line are
139 definitions. '>' and '+' characters at the beginning of a line are
134 ignored, to allow pasting directly from e-mails, diff files and
140 ignored, to allow pasting directly from e-mails, diff files and
135 doctests (the '...' continuation prompt is also stripped). The
141 doctests (the '...' continuation prompt is also stripped). The
136 executed block is also assigned to variable named 'pasted_block' for
142 executed block is also assigned to variable named 'pasted_block' for
137 later editing with '%edit pasted_block'.
143 later editing with '%edit pasted_block'.
138
144
139 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
145 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
140 This assigns the pasted block to variable 'foo' as string, without
146 This assigns the pasted block to variable 'foo' as string, without
141 dedenting or executing it (preceding >>> and + is still stripped)
147 dedenting or executing it (preceding >>> and + is still stripped)
142
148
143 '%cpaste -r' re-executes the block previously entered by cpaste.
149 '%cpaste -r' re-executes the block previously entered by cpaste.
144
150
145 Do not be alarmed by garbled output on Windows (it's a readline bug).
151 Do not be alarmed by garbled output on Windows (it's a readline bug).
146 Just press enter and type -- (and press enter again) and the block
152 Just press enter and type -- (and press enter again) and the block
147 will be what was just pasted.
153 will be what was just pasted.
148
154
149 IPython statements (magics, shell escapes) are not supported (yet).
155 IPython statements (magics, shell escapes) are not supported (yet).
150
156
151 See also
157 See also
152 --------
158 --------
153 paste: automatically pull code from clipboard.
159 paste: automatically pull code from clipboard.
154
160
155 Examples
161 Examples
156 --------
162 --------
157 ::
163 ::
158
164
159 In [8]: %cpaste
165 In [8]: %cpaste
160 Pasting code; enter '--' alone on the line to stop.
166 Pasting code; enter '--' alone on the line to stop.
161 :>>> a = ["world!", "Hello"]
167 :>>> a = ["world!", "Hello"]
162 :>>> print " ".join(sorted(a))
168 :>>> print " ".join(sorted(a))
163 :--
169 :--
164 Hello world!
170 Hello world!
165 """
171 """
166 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
172 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
167 if 'r' in opts:
173 if 'r' in opts:
168 self.rerun_pasted()
174 self.rerun_pasted()
169 return
175 return
170
176
171 sentinel = opts.get('s', '--')
177 sentinel = opts.get('s', '--')
172 block = '\n'.join(get_pasted_lines(sentinel))
178 block = '\n'.join(get_pasted_lines(sentinel))
173 self.store_or_execute(block, name)
179 self.store_or_execute(block, name)
174
180
175 @line_magic
181 @line_magic
176 def paste(self, parameter_s=''):
182 def paste(self, parameter_s=''):
177 """Paste & execute a pre-formatted code block from clipboard.
183 """Paste & execute a pre-formatted code block from clipboard.
178
184
179 The text is pulled directly from the clipboard without user
185 The text is pulled directly from the clipboard without user
180 intervention and printed back on the screen before execution (unless
186 intervention and printed back on the screen before execution (unless
181 the -q flag is given to force quiet mode).
187 the -q flag is given to force quiet mode).
182
188
183 The block is dedented prior to execution to enable execution of method
189 The block is dedented prior to execution to enable execution of method
184 definitions. '>' and '+' characters at the beginning of a line are
190 definitions. '>' and '+' characters at the beginning of a line are
185 ignored, to allow pasting directly from e-mails, diff files and
191 ignored, to allow pasting directly from e-mails, diff files and
186 doctests (the '...' continuation prompt is also stripped). The
192 doctests (the '...' continuation prompt is also stripped). The
187 executed block is also assigned to variable named 'pasted_block' for
193 executed block is also assigned to variable named 'pasted_block' for
188 later editing with '%edit pasted_block'.
194 later editing with '%edit pasted_block'.
189
195
190 You can also pass a variable name as an argument, e.g. '%paste foo'.
196 You can also pass a variable name as an argument, e.g. '%paste foo'.
191 This assigns the pasted block to variable 'foo' as string, without
197 This assigns the pasted block to variable 'foo' as string, without
192 executing it (preceding >>> and + is still stripped).
198 executing it (preceding >>> and + is still stripped).
193
199
194 Options:
200 Options:
195
201
196 -r: re-executes the block previously entered by cpaste.
202 -r: re-executes the block previously entered by cpaste.
197
203
198 -q: quiet mode: do not echo the pasted text back to the terminal.
204 -q: quiet mode: do not echo the pasted text back to the terminal.
199
205
200 IPython statements (magics, shell escapes) are not supported (yet).
206 IPython statements (magics, shell escapes) are not supported (yet).
201
207
202 See also
208 See also
203 --------
209 --------
204 cpaste: manually paste code into terminal until you mark its end.
210 cpaste: manually paste code into terminal until you mark its end.
205 """
211 """
206 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
212 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
207 if 'r' in opts:
213 if 'r' in opts:
208 self.rerun_pasted()
214 self.rerun_pasted()
209 return
215 return
210 try:
216 try:
211 block = self.shell.hooks.clipboard_get()
217 block = self.shell.hooks.clipboard_get()
212 except TryNext as clipboard_exc:
218 except TryNext as clipboard_exc:
213 message = getattr(clipboard_exc, 'args')
219 message = getattr(clipboard_exc, 'args')
214 if message:
220 if message:
215 error(message[0])
221 error(message[0])
216 else:
222 else:
217 error('Could not get text from the clipboard.')
223 error('Could not get text from the clipboard.')
218 return
224 return
219 except ClipboardEmpty:
225 except ClipboardEmpty:
220 raise UsageError("The clipboard appears to be empty")
226 raise UsageError("The clipboard appears to be empty")
221
227
222 # By default, echo back to terminal unless quiet mode is requested
228 # By default, echo back to terminal unless quiet mode is requested
223 if 'q' not in opts:
229 if 'q' not in opts:
224 write = self.shell.write
230 write = self.shell.write
225 write(self.shell.pycolorize(block))
231 write(self.shell.pycolorize(block))
226 if not block.endswith('\n'):
232 if not block.endswith('\n'):
227 write('\n')
233 write('\n')
228 write("## -- End pasted text --\n")
234 write("## -- End pasted text --\n")
229
235
230 self.store_or_execute(block, name)
236 self.store_or_execute(block, name)
231
237
232 # Class-level: add a '%cls' magic only on Windows
238 # Class-level: add a '%cls' magic only on Windows
233 if sys.platform == 'win32':
239 if sys.platform == 'win32':
234 @line_magic
240 @line_magic
235 def cls(self, s):
241 def cls(self, s):
236 """Clear screen.
242 """Clear screen.
237 """
243 """
238 os.system("cls")
244 os.system("cls")
239
245
240 #-----------------------------------------------------------------------------
246 #-----------------------------------------------------------------------------
241 # Main class
247 # Main class
242 #-----------------------------------------------------------------------------
248 #-----------------------------------------------------------------------------
243
249
244 class TerminalInteractiveShell(InteractiveShell):
250 class TerminalInteractiveShell(InteractiveShell):
245
251
246 autoedit_syntax = CBool(False, config=True,
252 autoedit_syntax = CBool(False, config=True,
247 help="auto editing of files with syntax errors.")
253 help="auto editing of files with syntax errors.")
248 banner = Unicode('')
254 banner = Unicode('')
249 banner1 = Unicode(default_banner, config=True,
255 banner1 = Unicode(default_banner, config=True,
250 help="""The part of the banner to be printed before the profile"""
256 help="""The part of the banner to be printed before the profile"""
251 )
257 )
252 banner2 = Unicode('', config=True,
258 banner2 = Unicode('', config=True,
253 help="""The part of the banner to be printed after the profile"""
259 help="""The part of the banner to be printed after the profile"""
254 )
260 )
255 confirm_exit = CBool(True, config=True,
261 confirm_exit = CBool(True, config=True,
256 help="""
262 help="""
257 Set to confirm when you try to exit IPython with an EOF (Control-D
263 Set to confirm when you try to exit IPython with an EOF (Control-D
258 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
264 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
259 you can force a direct exit without any confirmation.""",
265 you can force a direct exit without any confirmation.""",
260 )
266 )
261 # This display_banner only controls whether or not self.show_banner()
267 # This display_banner only controls whether or not self.show_banner()
262 # is called when mainloop/interact are called. The default is False
268 # is called when mainloop/interact are called. The default is False
263 # because for the terminal based application, the banner behavior
269 # because for the terminal based application, the banner behavior
264 # is controlled by Global.display_banner, which IPythonApp looks at
270 # is controlled by Global.display_banner, which IPythonApp looks at
265 # to determine if *it* should call show_banner() by hand or not.
271 # to determine if *it* should call show_banner() by hand or not.
266 display_banner = CBool(False) # This isn't configurable!
272 display_banner = CBool(False) # This isn't configurable!
267 embedded = CBool(False)
273 embedded = CBool(False)
268 embedded_active = CBool(False)
274 embedded_active = CBool(False)
269 editor = Unicode(get_default_editor(), config=True,
275 editor = Unicode(get_default_editor(), config=True,
270 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
276 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
271 )
277 )
272 pager = Unicode('less', config=True,
278 pager = Unicode('less', config=True,
273 help="The shell program to be used for paging.")
279 help="The shell program to be used for paging.")
274
280
275 screen_length = Integer(0, config=True,
281 screen_length = Integer(0, config=True,
276 help=
282 help=
277 """Number of lines of your screen, used to control printing of very
283 """Number of lines of your screen, used to control printing of very
278 long strings. Strings longer than this number of lines will be sent
284 long strings. Strings longer than this number of lines will be sent
279 through a pager instead of directly printed. The default value for
285 through a pager instead of directly printed. The default value for
280 this is 0, which means IPython will auto-detect your screen size every
286 this is 0, which means IPython will auto-detect your screen size every
281 time it needs to print certain potentially long strings (this doesn't
287 time it needs to print certain potentially long strings (this doesn't
282 change the behavior of the 'print' keyword, it's only triggered
288 change the behavior of the 'print' keyword, it's only triggered
283 internally). If for some reason this isn't working well (it needs
289 internally). If for some reason this isn't working well (it needs
284 curses support), specify it yourself. Otherwise don't change the
290 curses support), specify it yourself. Otherwise don't change the
285 default.""",
291 default.""",
286 )
292 )
287 term_title = CBool(False, config=True,
293 term_title = CBool(False, config=True,
288 help="Enable auto setting the terminal title."
294 help="Enable auto setting the terminal title."
289 )
295 )
290
296
291 # This `using_paste_magics` is used to detect whether the code is being
297 # This `using_paste_magics` is used to detect whether the code is being
292 # executed via paste magics functions
298 # executed via paste magics functions
293 using_paste_magics = CBool(False)
299 using_paste_magics = CBool(False)
294
300
295 # In the terminal, GUI control is done via PyOS_InputHook
301 # In the terminal, GUI control is done via PyOS_InputHook
296 @staticmethod
302 @staticmethod
297 def enable_gui(gui=None, app=None):
303 def enable_gui(gui=None, app=None):
298 """Switch amongst GUI input hooks by name.
304 """Switch amongst GUI input hooks by name.
299 """
305 """
300 # Deferred import
306 # Deferred import
301 from IPython.lib.inputhook import enable_gui as real_enable_gui
307 from IPython.lib.inputhook import enable_gui as real_enable_gui
302 try:
308 try:
303 return real_enable_gui(gui, app)
309 return real_enable_gui(gui, app)
304 except ValueError as e:
310 except ValueError as e:
305 raise UsageError("%s" % e)
311 raise UsageError("%s" % e)
306
312
307 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
313 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
308 user_ns=None, user_module=None, custom_exceptions=((),None),
314 user_ns=None, user_module=None, custom_exceptions=((),None),
309 usage=None, banner1=None, banner2=None, display_banner=None,
315 usage=None, banner1=None, banner2=None, display_banner=None,
310 **kwargs):
316 **kwargs):
311
317
312 super(TerminalInteractiveShell, self).__init__(
318 super(TerminalInteractiveShell, self).__init__(
313 config=config, ipython_dir=ipython_dir, profile_dir=profile_dir, user_ns=user_ns,
319 config=config, ipython_dir=ipython_dir, profile_dir=profile_dir, user_ns=user_ns,
314 user_module=user_module, custom_exceptions=custom_exceptions,
320 user_module=user_module, custom_exceptions=custom_exceptions,
315 **kwargs
321 **kwargs
316 )
322 )
317 # use os.system instead of utils.process.system by default,
323 # use os.system instead of utils.process.system by default,
318 # because piped system doesn't make sense in the Terminal:
324 # because piped system doesn't make sense in the Terminal:
319 self.system = self.system_raw
325 self.system = self.system_raw
320
326
321 self.init_term_title()
327 self.init_term_title()
322 self.init_usage(usage)
328 self.init_usage(usage)
323 self.init_banner(banner1, banner2, display_banner)
329 self.init_banner(banner1, banner2, display_banner)
324
330
325 #-------------------------------------------------------------------------
331 #-------------------------------------------------------------------------
326 # Overrides of init stages
332 # Overrides of init stages
327 #-------------------------------------------------------------------------
333 #-------------------------------------------------------------------------
328
334
329 def init_display_formatter(self):
335 def init_display_formatter(self):
330 super(TerminalInteractiveShell, self).init_display_formatter()
336 super(TerminalInteractiveShell, self).init_display_formatter()
331 # terminal only supports plaintext
337 # terminal only supports plaintext
332 self.display_formatter.active_types = ['text/plain']
338 self.display_formatter.active_types = ['text/plain']
333
339
334 #-------------------------------------------------------------------------
340 #-------------------------------------------------------------------------
335 # Things related to the terminal
341 # Things related to the terminal
336 #-------------------------------------------------------------------------
342 #-------------------------------------------------------------------------
337
343
338 @property
344 @property
339 def usable_screen_length(self):
345 def usable_screen_length(self):
340 if self.screen_length == 0:
346 if self.screen_length == 0:
341 return 0
347 return 0
342 else:
348 else:
343 num_lines_bot = self.separate_in.count('\n')+1
349 num_lines_bot = self.separate_in.count('\n')+1
344 return self.screen_length - num_lines_bot
350 return self.screen_length - num_lines_bot
345
351
346 def init_term_title(self):
352 def init_term_title(self):
347 # Enable or disable the terminal title.
353 # Enable or disable the terminal title.
348 if self.term_title:
354 if self.term_title:
349 toggle_set_term_title(True)
355 toggle_set_term_title(True)
350 set_term_title('IPython: ' + abbrev_cwd())
356 set_term_title('IPython: ' + abbrev_cwd())
351 else:
357 else:
352 toggle_set_term_title(False)
358 toggle_set_term_title(False)
353
359
354 #-------------------------------------------------------------------------
360 #-------------------------------------------------------------------------
355 # Things related to aliases
361 # Things related to aliases
356 #-------------------------------------------------------------------------
362 #-------------------------------------------------------------------------
357
363
358 def init_alias(self):
364 def init_alias(self):
359 # The parent class defines aliases that can be safely used with any
365 # The parent class defines aliases that can be safely used with any
360 # frontend.
366 # frontend.
361 super(TerminalInteractiveShell, self).init_alias()
367 super(TerminalInteractiveShell, self).init_alias()
362
368
363 # Now define aliases that only make sense on the terminal, because they
369 # Now define aliases that only make sense on the terminal, because they
364 # need direct access to the console in a way that we can't emulate in
370 # need direct access to the console in a way that we can't emulate in
365 # GUI or web frontend
371 # GUI or web frontend
366 if os.name == 'posix':
372 if os.name == 'posix':
367 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
373 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
368 ('man', 'man')]
374 ('man', 'man')]
369 elif os.name == 'nt':
375 elif os.name == 'nt':
370 aliases = [('cls', 'cls')]
376 aliases = [('cls', 'cls')]
371
377
372
378
373 for name, cmd in aliases:
379 for name, cmd in aliases:
374 self.alias_manager.soft_define_alias(name, cmd)
380 self.alias_manager.soft_define_alias(name, cmd)
375
381
376 #-------------------------------------------------------------------------
382 #-------------------------------------------------------------------------
377 # Things related to the banner and usage
383 # Things related to the banner and usage
378 #-------------------------------------------------------------------------
384 #-------------------------------------------------------------------------
379
385
380 def _banner1_changed(self):
386 def _banner1_changed(self):
381 self.compute_banner()
387 self.compute_banner()
382
388
383 def _banner2_changed(self):
389 def _banner2_changed(self):
384 self.compute_banner()
390 self.compute_banner()
385
391
386 def _term_title_changed(self, name, new_value):
392 def _term_title_changed(self, name, new_value):
387 self.init_term_title()
393 self.init_term_title()
388
394
389 def init_banner(self, banner1, banner2, display_banner):
395 def init_banner(self, banner1, banner2, display_banner):
390 if banner1 is not None:
396 if banner1 is not None:
391 self.banner1 = banner1
397 self.banner1 = banner1
392 if banner2 is not None:
398 if banner2 is not None:
393 self.banner2 = banner2
399 self.banner2 = banner2
394 if display_banner is not None:
400 if display_banner is not None:
395 self.display_banner = display_banner
401 self.display_banner = display_banner
396 self.compute_banner()
402 self.compute_banner()
397
403
398 def show_banner(self, banner=None):
404 def show_banner(self, banner=None):
399 if banner is None:
405 if banner is None:
400 banner = self.banner
406 banner = self.banner
401 self.write(banner)
407 self.write(banner)
402
408
403 def compute_banner(self):
409 def compute_banner(self):
404 self.banner = self.banner1
410 self.banner = self.banner1
405 if self.profile and self.profile != 'default':
411 if self.profile and self.profile != 'default':
406 self.banner += '\nIPython profile: %s\n' % self.profile
412 self.banner += '\nIPython profile: %s\n' % self.profile
407 if self.banner2:
413 if self.banner2:
408 self.banner += '\n' + self.banner2
414 self.banner += '\n' + self.banner2
409
415
410 def init_usage(self, usage=None):
416 def init_usage(self, usage=None):
411 if usage is None:
417 if usage is None:
412 self.usage = interactive_usage
418 self.usage = interactive_usage
413 else:
419 else:
414 self.usage = usage
420 self.usage = usage
415
421
416 #-------------------------------------------------------------------------
422 #-------------------------------------------------------------------------
417 # Mainloop and code execution logic
423 # Mainloop and code execution logic
418 #-------------------------------------------------------------------------
424 #-------------------------------------------------------------------------
419
425
420 def mainloop(self, display_banner=None):
426 def mainloop(self, display_banner=None):
421 """Start the mainloop.
427 """Start the mainloop.
422
428
423 If an optional banner argument is given, it will override the
429 If an optional banner argument is given, it will override the
424 internally created default banner.
430 internally created default banner.
425 """
431 """
426
432
427 with self.builtin_trap, self.display_trap:
433 with self.builtin_trap, self.display_trap:
428
434
429 while 1:
435 while 1:
430 try:
436 try:
431 self.interact(display_banner=display_banner)
437 self.interact(display_banner=display_banner)
432 #self.interact_with_readline()
438 #self.interact_with_readline()
433 # XXX for testing of a readline-decoupled repl loop, call
439 # XXX for testing of a readline-decoupled repl loop, call
434 # interact_with_readline above
440 # interact_with_readline above
435 break
441 break
436 except KeyboardInterrupt:
442 except KeyboardInterrupt:
437 # this should not be necessary, but KeyboardInterrupt
443 # this should not be necessary, but KeyboardInterrupt
438 # handling seems rather unpredictable...
444 # handling seems rather unpredictable...
439 self.write("\nKeyboardInterrupt in interact()\n")
445 self.write("\nKeyboardInterrupt in interact()\n")
440
446
441 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
447 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
442 """Store multiple lines as a single entry in history"""
448 """Store multiple lines as a single entry in history"""
443
449
444 # do nothing without readline or disabled multiline
450 # do nothing without readline or disabled multiline
445 if not self.has_readline or not self.multiline_history:
451 if not self.has_readline or not self.multiline_history:
446 return hlen_before_cell
452 return hlen_before_cell
447
453
448 # windows rl has no remove_history_item
454 # windows rl has no remove_history_item
449 if not hasattr(self.readline, "remove_history_item"):
455 if not hasattr(self.readline, "remove_history_item"):
450 return hlen_before_cell
456 return hlen_before_cell
451
457
452 # skip empty cells
458 # skip empty cells
453 if not source_raw.rstrip():
459 if not source_raw.rstrip():
454 return hlen_before_cell
460 return hlen_before_cell
455
461
456 # nothing changed do nothing, e.g. when rl removes consecutive dups
462 # nothing changed do nothing, e.g. when rl removes consecutive dups
457 hlen = self.readline.get_current_history_length()
463 hlen = self.readline.get_current_history_length()
458 if hlen == hlen_before_cell:
464 if hlen == hlen_before_cell:
459 return hlen_before_cell
465 return hlen_before_cell
460
466
461 for i in range(hlen - hlen_before_cell):
467 for i in range(hlen - hlen_before_cell):
462 self.readline.remove_history_item(hlen - i - 1)
468 self.readline.remove_history_item(hlen - i - 1)
463 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
469 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
464 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
470 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
465 stdin_encoding))
471 stdin_encoding))
466 return self.readline.get_current_history_length()
472 return self.readline.get_current_history_length()
467
473
468 def interact(self, display_banner=None):
474 def interact(self, display_banner=None):
469 """Closely emulate the interactive Python console."""
475 """Closely emulate the interactive Python console."""
470
476
471 # batch run -> do not interact
477 # batch run -> do not interact
472 if self.exit_now:
478 if self.exit_now:
473 return
479 return
474
480
475 if display_banner is None:
481 if display_banner is None:
476 display_banner = self.display_banner
482 display_banner = self.display_banner
477
483
478 if isinstance(display_banner, py3compat.string_types):
484 if isinstance(display_banner, py3compat.string_types):
479 self.show_banner(display_banner)
485 self.show_banner(display_banner)
480 elif display_banner:
486 elif display_banner:
481 self.show_banner()
487 self.show_banner()
482
488
483 more = False
489 more = False
484
490
485 if self.has_readline:
491 if self.has_readline:
486 self.readline_startup_hook(self.pre_readline)
492 self.readline_startup_hook(self.pre_readline)
487 hlen_b4_cell = self.readline.get_current_history_length()
493 hlen_b4_cell = self.readline.get_current_history_length()
488 else:
494 else:
489 hlen_b4_cell = 0
495 hlen_b4_cell = 0
490 # exit_now is set by a call to %Exit or %Quit, through the
496 # exit_now is set by a call to %Exit or %Quit, through the
491 # ask_exit callback.
497 # ask_exit callback.
492
498
493 while not self.exit_now:
499 while not self.exit_now:
494 self.hooks.pre_prompt_hook()
500 self.hooks.pre_prompt_hook()
495 if more:
501 if more:
496 try:
502 try:
497 prompt = self.prompt_manager.render('in2')
503 prompt = self.prompt_manager.render('in2')
498 except:
504 except:
499 self.showtraceback()
505 self.showtraceback()
500 if self.autoindent:
506 if self.autoindent:
501 self.rl_do_indent = True
507 self.rl_do_indent = True
502
508
503 else:
509 else:
504 try:
510 try:
505 prompt = self.separate_in + self.prompt_manager.render('in')
511 prompt = self.separate_in + self.prompt_manager.render('in')
506 except:
512 except:
507 self.showtraceback()
513 self.showtraceback()
508 try:
514 try:
509 line = self.raw_input(prompt)
515 line = self.raw_input(prompt)
510 if self.exit_now:
516 if self.exit_now:
511 # quick exit on sys.std[in|out] close
517 # quick exit on sys.std[in|out] close
512 break
518 break
513 if self.autoindent:
519 if self.autoindent:
514 self.rl_do_indent = False
520 self.rl_do_indent = False
515
521
516 except KeyboardInterrupt:
522 except KeyboardInterrupt:
517 #double-guard against keyboardinterrupts during kbdint handling
523 #double-guard against keyboardinterrupts during kbdint handling
518 try:
524 try:
519 self.write('\nKeyboardInterrupt\n')
525 self.write('\nKeyboardInterrupt\n')
520 source_raw = self.input_splitter.source_raw_reset()[1]
526 source_raw = self.input_splitter.source_raw_reset()[1]
521 hlen_b4_cell = \
527 hlen_b4_cell = \
522 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
528 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
523 more = False
529 more = False
524 except KeyboardInterrupt:
530 except KeyboardInterrupt:
525 pass
531 pass
526 except EOFError:
532 except EOFError:
527 if self.autoindent:
533 if self.autoindent:
528 self.rl_do_indent = False
534 self.rl_do_indent = False
529 if self.has_readline:
535 if self.has_readline:
530 self.readline_startup_hook(None)
536 self.readline_startup_hook(None)
531 self.write('\n')
537 self.write('\n')
532 self.exit()
538 self.exit()
533 except bdb.BdbQuit:
539 except bdb.BdbQuit:
534 warn('The Python debugger has exited with a BdbQuit exception.\n'
540 warn('The Python debugger has exited with a BdbQuit exception.\n'
535 'Because of how pdb handles the stack, it is impossible\n'
541 'Because of how pdb handles the stack, it is impossible\n'
536 'for IPython to properly format this particular exception.\n'
542 'for IPython to properly format this particular exception.\n'
537 'IPython will resume normal operation.')
543 'IPython will resume normal operation.')
538 except:
544 except:
539 # exceptions here are VERY RARE, but they can be triggered
545 # exceptions here are VERY RARE, but they can be triggered
540 # asynchronously by signal handlers, for example.
546 # asynchronously by signal handlers, for example.
541 self.showtraceback()
547 self.showtraceback()
542 else:
548 else:
543 self.input_splitter.push(line)
549 self.input_splitter.push(line)
544 more = self.input_splitter.push_accepts_more()
550 more = self.input_splitter.push_accepts_more()
545 if (self.SyntaxTB.last_syntax_error and
551 if (self.SyntaxTB.last_syntax_error and
546 self.autoedit_syntax):
552 self.autoedit_syntax):
547 self.edit_syntax_error()
553 self.edit_syntax_error()
548 if not more:
554 if not more:
549 source_raw = self.input_splitter.source_raw_reset()[1]
555 source_raw = self.input_splitter.source_raw_reset()[1]
550 self.run_cell(source_raw, store_history=True)
556 self.run_cell(source_raw, store_history=True)
551 hlen_b4_cell = \
557 hlen_b4_cell = \
552 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
558 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
553
559
554 # Turn off the exit flag, so the mainloop can be restarted if desired
560 # Turn off the exit flag, so the mainloop can be restarted if desired
555 self.exit_now = False
561 self.exit_now = False
556
562
557 def raw_input(self, prompt=''):
563 def raw_input(self, prompt=''):
558 """Write a prompt and read a line.
564 """Write a prompt and read a line.
559
565
560 The returned line does not include the trailing newline.
566 The returned line does not include the trailing newline.
561 When the user enters the EOF key sequence, EOFError is raised.
567 When the user enters the EOF key sequence, EOFError is raised.
562
568
563 Parameters
569 Parameters
564 ----------
570 ----------
565
571
566 prompt : str, optional
572 prompt : str, optional
567 A string to be printed to prompt the user.
573 A string to be printed to prompt the user.
568 """
574 """
569 # Code run by the user may have modified the readline completer state.
575 # Code run by the user may have modified the readline completer state.
570 # We must ensure that our completer is back in place.
576 # We must ensure that our completer is back in place.
571
577
572 if self.has_readline:
578 if self.has_readline:
573 self.set_readline_completer()
579 self.set_readline_completer()
574
580
575 # raw_input expects str, but we pass it unicode sometimes
581 # raw_input expects str, but we pass it unicode sometimes
576 prompt = py3compat.cast_bytes_py2(prompt)
582 prompt = py3compat.cast_bytes_py2(prompt)
577
583
578 try:
584 try:
579 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
585 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
580 except ValueError:
586 except ValueError:
581 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
587 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
582 " or sys.stdout.close()!\nExiting IPython!\n")
588 " or sys.stdout.close()!\nExiting IPython!\n")
583 self.ask_exit()
589 self.ask_exit()
584 return ""
590 return ""
585
591
586 # Try to be reasonably smart about not re-indenting pasted input more
592 # Try to be reasonably smart about not re-indenting pasted input more
587 # than necessary. We do this by trimming out the auto-indent initial
593 # than necessary. We do this by trimming out the auto-indent initial
588 # spaces, if the user's actual input started itself with whitespace.
594 # spaces, if the user's actual input started itself with whitespace.
589 if self.autoindent:
595 if self.autoindent:
590 if num_ini_spaces(line) > self.indent_current_nsp:
596 if num_ini_spaces(line) > self.indent_current_nsp:
591 line = line[self.indent_current_nsp:]
597 line = line[self.indent_current_nsp:]
592 self.indent_current_nsp = 0
598 self.indent_current_nsp = 0
593
599
594 return line
600 return line
595
601
596 #-------------------------------------------------------------------------
602 #-------------------------------------------------------------------------
597 # Methods to support auto-editing of SyntaxErrors.
603 # Methods to support auto-editing of SyntaxErrors.
598 #-------------------------------------------------------------------------
604 #-------------------------------------------------------------------------
599
605
600 def edit_syntax_error(self):
606 def edit_syntax_error(self):
601 """The bottom half of the syntax error handler called in the main loop.
607 """The bottom half of the syntax error handler called in the main loop.
602
608
603 Loop until syntax error is fixed or user cancels.
609 Loop until syntax error is fixed or user cancels.
604 """
610 """
605
611
606 while self.SyntaxTB.last_syntax_error:
612 while self.SyntaxTB.last_syntax_error:
607 # copy and clear last_syntax_error
613 # copy and clear last_syntax_error
608 err = self.SyntaxTB.clear_err_state()
614 err = self.SyntaxTB.clear_err_state()
609 if not self._should_recompile(err):
615 if not self._should_recompile(err):
610 return
616 return
611 try:
617 try:
612 # may set last_syntax_error again if a SyntaxError is raised
618 # may set last_syntax_error again if a SyntaxError is raised
613 self.safe_execfile(err.filename,self.user_ns)
619 self.safe_execfile(err.filename,self.user_ns)
614 except:
620 except:
615 self.showtraceback()
621 self.showtraceback()
616 else:
622 else:
617 try:
623 try:
618 f = open(err.filename)
624 f = open(err.filename)
619 try:
625 try:
620 # This should be inside a display_trap block and I
626 # This should be inside a display_trap block and I
621 # think it is.
627 # think it is.
622 sys.displayhook(f.read())
628 sys.displayhook(f.read())
623 finally:
629 finally:
624 f.close()
630 f.close()
625 except:
631 except:
626 self.showtraceback()
632 self.showtraceback()
627
633
628 def _should_recompile(self,e):
634 def _should_recompile(self,e):
629 """Utility routine for edit_syntax_error"""
635 """Utility routine for edit_syntax_error"""
630
636
631 if e.filename in ('<ipython console>','<input>','<string>',
637 if e.filename in ('<ipython console>','<input>','<string>',
632 '<console>','<BackgroundJob compilation>',
638 '<console>','<BackgroundJob compilation>',
633 None):
639 None):
634
640
635 return False
641 return False
636 try:
642 try:
637 if (self.autoedit_syntax and
643 if (self.autoedit_syntax and
638 not self.ask_yes_no('Return to editor to correct syntax error? '
644 not self.ask_yes_no('Return to editor to correct syntax error? '
639 '[Y/n] ','y')):
645 '[Y/n] ','y')):
640 return False
646 return False
641 except EOFError:
647 except EOFError:
642 return False
648 return False
643
649
644 def int0(x):
650 def int0(x):
645 try:
651 try:
646 return int(x)
652 return int(x)
647 except TypeError:
653 except TypeError:
648 return 0
654 return 0
649 # always pass integer line and offset values to editor hook
655 # always pass integer line and offset values to editor hook
650 try:
656 try:
651 self.hooks.fix_error_editor(e.filename,
657 self.hooks.fix_error_editor(e.filename,
652 int0(e.lineno),int0(e.offset),e.msg)
658 int0(e.lineno),int0(e.offset),e.msg)
653 except TryNext:
659 except TryNext:
654 warn('Could not open editor')
660 warn('Could not open editor')
655 return False
661 return False
656 return True
662 return True
657
663
658 #-------------------------------------------------------------------------
664 #-------------------------------------------------------------------------
659 # Things related to exiting
665 # Things related to exiting
660 #-------------------------------------------------------------------------
666 #-------------------------------------------------------------------------
661
667
662 def ask_exit(self):
668 def ask_exit(self):
663 """ Ask the shell to exit. Can be overiden and used as a callback. """
669 """ Ask the shell to exit. Can be overiden and used as a callback. """
664 self.exit_now = True
670 self.exit_now = True
665
671
666 def exit(self):
672 def exit(self):
667 """Handle interactive exit.
673 """Handle interactive exit.
668
674
669 This method calls the ask_exit callback."""
675 This method calls the ask_exit callback."""
670 if self.confirm_exit:
676 if self.confirm_exit:
671 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
677 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
672 self.ask_exit()
678 self.ask_exit()
673 else:
679 else:
674 self.ask_exit()
680 self.ask_exit()
675
681
676 #-------------------------------------------------------------------------
682 #-------------------------------------------------------------------------
677 # Things related to magics
683 # Things related to magics
678 #-------------------------------------------------------------------------
684 #-------------------------------------------------------------------------
679
685
680 def init_magics(self):
686 def init_magics(self):
681 super(TerminalInteractiveShell, self).init_magics()
687 super(TerminalInteractiveShell, self).init_magics()
682 self.register_magics(TerminalMagics)
688 self.register_magics(TerminalMagics)
683
689
684 def showindentationerror(self):
690 def showindentationerror(self):
685 super(TerminalInteractiveShell, self).showindentationerror()
691 super(TerminalInteractiveShell, self).showindentationerror()
686 if not self.using_paste_magics:
692 if not self.using_paste_magics:
687 print("If you want to paste code into IPython, try the "
693 print("If you want to paste code into IPython, try the "
688 "%paste and %cpaste magic functions.")
694 "%paste and %cpaste magic functions.")
689
695
690
696
691 InteractiveShellABC.register(TerminalInteractiveShell)
697 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now