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