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