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