Show More
@@ -1,625 +1,623 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-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 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 __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | from contextlib import nested |
|
19 | from contextlib import nested | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 | import sys |
|
22 | import sys | |
23 |
|
23 | |||
24 | from IPython.core.error import TryNext |
|
24 | from IPython.core.error import TryNext | |
25 | from IPython.core.usage import interactive_usage, default_banner |
|
25 | from IPython.core.usage import interactive_usage, default_banner | |
26 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
26 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC | |
27 | from IPython.lib.inputhook import enable_gui |
|
27 | from IPython.lib.inputhook import enable_gui | |
28 | from IPython.lib.pylabtools import pylab_activate |
|
28 | from IPython.lib.pylabtools import pylab_activate | |
|
29 | from IPython.testing import decorators as testdec | |||
29 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title | |
30 | from IPython.utils.process import abbrev_cwd |
|
31 | from IPython.utils.process import abbrev_cwd | |
31 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
32 | from IPython.utils.text import num_ini_spaces |
|
33 | from IPython.utils.text import num_ini_spaces | |
33 | from IPython.utils.traitlets import Int, Str, CBool |
|
34 | from IPython.utils.traitlets import Int, Str, CBool | |
34 |
|
35 | |||
35 |
|
||||
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 | # Utilities |
|
37 | # Utilities | |
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 |
|
||||
41 | def get_default_editor(): |
|
40 | def get_default_editor(): | |
42 | try: |
|
41 | try: | |
43 | ed = os.environ['EDITOR'] |
|
42 | ed = os.environ['EDITOR'] | |
44 | except KeyError: |
|
43 | except KeyError: | |
45 | if os.name == 'posix': |
|
44 | if os.name == 'posix': | |
46 | ed = 'vi' # the only one guaranteed to be there! |
|
45 | ed = 'vi' # the only one guaranteed to be there! | |
47 | else: |
|
46 | else: | |
48 | ed = 'notepad' # same in Windows! |
|
47 | ed = 'notepad' # same in Windows! | |
49 | return ed |
|
48 | return ed | |
50 |
|
49 | |||
51 |
|
50 | |||
52 | # store the builtin raw_input globally, and use this always, in case user code |
|
51 | # store the builtin raw_input globally, and use this always, in case user code | |
53 | # overwrites it (like wx.py.PyShell does) |
|
52 | # overwrites it (like wx.py.PyShell does) | |
54 | raw_input_original = raw_input |
|
53 | raw_input_original = raw_input | |
55 |
|
54 | |||
56 |
|
||||
57 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
58 | # Main class |
|
56 | # Main class | |
59 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
60 |
|
58 | |||
61 |
|
||||
62 | class TerminalInteractiveShell(InteractiveShell): |
|
59 | class TerminalInteractiveShell(InteractiveShell): | |
63 |
|
60 | |||
64 | autoedit_syntax = CBool(False, config=True) |
|
61 | autoedit_syntax = CBool(False, config=True) | |
65 | banner = Str('') |
|
62 | banner = Str('') | |
66 | banner1 = Str(default_banner, config=True) |
|
63 | banner1 = Str(default_banner, config=True) | |
67 | banner2 = Str('', config=True) |
|
64 | banner2 = Str('', config=True) | |
68 | confirm_exit = CBool(True, config=True) |
|
65 | confirm_exit = CBool(True, config=True) | |
69 | # This display_banner only controls whether or not self.show_banner() |
|
66 | # This display_banner only controls whether or not self.show_banner() | |
70 | # is called when mainloop/interact are called. The default is False |
|
67 | # is called when mainloop/interact are called. The default is False | |
71 | # because for the terminal based application, the banner behavior |
|
68 | # because for the terminal based application, the banner behavior | |
72 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
69 | # is controlled by Global.display_banner, which IPythonApp looks at | |
73 | # to determine if *it* should call show_banner() by hand or not. |
|
70 | # to determine if *it* should call show_banner() by hand or not. | |
74 | display_banner = CBool(False) # This isn't configurable! |
|
71 | display_banner = CBool(False) # This isn't configurable! | |
75 | embedded = CBool(False) |
|
72 | embedded = CBool(False) | |
76 | embedded_active = CBool(False) |
|
73 | embedded_active = CBool(False) | |
77 | editor = Str(get_default_editor(), config=True) |
|
74 | editor = Str(get_default_editor(), config=True) | |
78 | pager = Str('less', config=True) |
|
75 | pager = Str('less', config=True) | |
79 |
|
76 | |||
80 | screen_length = Int(0, config=True) |
|
77 | screen_length = Int(0, config=True) | |
81 | term_title = CBool(False, config=True) |
|
78 | term_title = CBool(False, config=True) | |
82 |
|
79 | |||
83 | def __init__(self, config=None, ipython_dir=None, user_ns=None, |
|
80 | def __init__(self, config=None, ipython_dir=None, user_ns=None, | |
84 | user_global_ns=None, custom_exceptions=((),None), |
|
81 | user_global_ns=None, custom_exceptions=((),None), | |
85 | usage=None, banner1=None, banner2=None, |
|
82 | usage=None, banner1=None, banner2=None, | |
86 | display_banner=None): |
|
83 | display_banner=None): | |
87 |
|
84 | |||
88 | super(TerminalInteractiveShell, self).__init__( |
|
85 | super(TerminalInteractiveShell, self).__init__( | |
89 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, |
|
86 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, | |
90 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions |
|
87 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions | |
91 | ) |
|
88 | ) | |
92 | self.init_term_title() |
|
89 | self.init_term_title() | |
93 | self.init_usage(usage) |
|
90 | self.init_usage(usage) | |
94 | self.init_banner(banner1, banner2, display_banner) |
|
91 | self.init_banner(banner1, banner2, display_banner) | |
95 |
|
92 | |||
96 | #------------------------------------------------------------------------- |
|
93 | #------------------------------------------------------------------------- | |
97 | # Things related to the terminal |
|
94 | # Things related to the terminal | |
98 | #------------------------------------------------------------------------- |
|
95 | #------------------------------------------------------------------------- | |
99 |
|
96 | |||
100 | @property |
|
97 | @property | |
101 | def usable_screen_length(self): |
|
98 | def usable_screen_length(self): | |
102 | if self.screen_length == 0: |
|
99 | if self.screen_length == 0: | |
103 | return 0 |
|
100 | return 0 | |
104 | else: |
|
101 | else: | |
105 | num_lines_bot = self.separate_in.count('\n')+1 |
|
102 | num_lines_bot = self.separate_in.count('\n')+1 | |
106 | return self.screen_length - num_lines_bot |
|
103 | return self.screen_length - num_lines_bot | |
107 |
|
104 | |||
108 | def init_term_title(self): |
|
105 | def init_term_title(self): | |
109 | # Enable or disable the terminal title. |
|
106 | # Enable or disable the terminal title. | |
110 | if self.term_title: |
|
107 | if self.term_title: | |
111 | toggle_set_term_title(True) |
|
108 | toggle_set_term_title(True) | |
112 | set_term_title('IPython: ' + abbrev_cwd()) |
|
109 | set_term_title('IPython: ' + abbrev_cwd()) | |
113 | else: |
|
110 | else: | |
114 | toggle_set_term_title(False) |
|
111 | toggle_set_term_title(False) | |
115 |
|
112 | |||
116 | #------------------------------------------------------------------------- |
|
113 | #------------------------------------------------------------------------- | |
117 | # Things related to aliases |
|
114 | # Things related to aliases | |
118 | #------------------------------------------------------------------------- |
|
115 | #------------------------------------------------------------------------- | |
119 |
|
116 | |||
120 | def init_alias(self): |
|
117 | def init_alias(self): | |
121 | # The parent class defines aliases that can be safely used with any |
|
118 | # The parent class defines aliases that can be safely used with any | |
122 | # frontend. |
|
119 | # frontend. | |
123 | super(TerminalInteractiveShell, self).init_alias() |
|
120 | super(TerminalInteractiveShell, self).init_alias() | |
124 |
|
121 | |||
125 | # Now define aliases that only make sense on the terminal, because they |
|
122 | # Now define aliases that only make sense on the terminal, because they | |
126 | # need direct access to the console in a way that we can't emulate in |
|
123 | # need direct access to the console in a way that we can't emulate in | |
127 | # GUI or web frontend |
|
124 | # GUI or web frontend | |
128 | if os.name == 'posix': |
|
125 | if os.name == 'posix': | |
129 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), |
|
126 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), | |
130 | ('man', 'man')] |
|
127 | ('man', 'man')] | |
131 | elif os.name == 'nt': |
|
128 | elif os.name == 'nt': | |
132 | aliases = [('cls', 'cls')] |
|
129 | aliases = [('cls', 'cls')] | |
133 |
|
130 | |||
134 |
|
131 | |||
135 | for name, cmd in aliases: |
|
132 | for name, cmd in aliases: | |
136 | self.alias_manager.define_alias(name, cmd) |
|
133 | self.alias_manager.define_alias(name, cmd) | |
137 |
|
134 | |||
138 | #------------------------------------------------------------------------- |
|
135 | #------------------------------------------------------------------------- | |
139 | # Things related to the banner and usage |
|
136 | # Things related to the banner and usage | |
140 | #------------------------------------------------------------------------- |
|
137 | #------------------------------------------------------------------------- | |
141 |
|
138 | |||
142 | def _banner1_changed(self): |
|
139 | def _banner1_changed(self): | |
143 | self.compute_banner() |
|
140 | self.compute_banner() | |
144 |
|
141 | |||
145 | def _banner2_changed(self): |
|
142 | def _banner2_changed(self): | |
146 | self.compute_banner() |
|
143 | self.compute_banner() | |
147 |
|
144 | |||
148 | def _term_title_changed(self, name, new_value): |
|
145 | def _term_title_changed(self, name, new_value): | |
149 | self.init_term_title() |
|
146 | self.init_term_title() | |
150 |
|
147 | |||
151 | def init_banner(self, banner1, banner2, display_banner): |
|
148 | def init_banner(self, banner1, banner2, display_banner): | |
152 | if banner1 is not None: |
|
149 | if banner1 is not None: | |
153 | self.banner1 = banner1 |
|
150 | self.banner1 = banner1 | |
154 | if banner2 is not None: |
|
151 | if banner2 is not None: | |
155 | self.banner2 = banner2 |
|
152 | self.banner2 = banner2 | |
156 | if display_banner is not None: |
|
153 | if display_banner is not None: | |
157 | self.display_banner = display_banner |
|
154 | self.display_banner = display_banner | |
158 | self.compute_banner() |
|
155 | self.compute_banner() | |
159 |
|
156 | |||
160 | def show_banner(self, banner=None): |
|
157 | def show_banner(self, banner=None): | |
161 | if banner is None: |
|
158 | if banner is None: | |
162 | banner = self.banner |
|
159 | banner = self.banner | |
163 | self.write(banner) |
|
160 | self.write(banner) | |
164 |
|
161 | |||
165 | def compute_banner(self): |
|
162 | def compute_banner(self): | |
166 | self.banner = self.banner1 |
|
163 | self.banner = self.banner1 | |
167 | if self.profile: |
|
164 | if self.profile: | |
168 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
165 | self.banner += '\nIPython profile: %s\n' % self.profile | |
169 | if self.banner2: |
|
166 | if self.banner2: | |
170 | self.banner += '\n' + self.banner2 |
|
167 | self.banner += '\n' + self.banner2 | |
171 |
|
168 | |||
172 | def init_usage(self, usage=None): |
|
169 | def init_usage(self, usage=None): | |
173 | if usage is None: |
|
170 | if usage is None: | |
174 | self.usage = interactive_usage |
|
171 | self.usage = interactive_usage | |
175 | else: |
|
172 | else: | |
176 | self.usage = usage |
|
173 | self.usage = usage | |
177 |
|
174 | |||
178 | #------------------------------------------------------------------------- |
|
175 | #------------------------------------------------------------------------- | |
179 | # Mainloop and code execution logic |
|
176 | # Mainloop and code execution logic | |
180 | #------------------------------------------------------------------------- |
|
177 | #------------------------------------------------------------------------- | |
181 |
|
178 | |||
182 | def mainloop(self, display_banner=None): |
|
179 | def mainloop(self, display_banner=None): | |
183 | """Start the mainloop. |
|
180 | """Start the mainloop. | |
184 |
|
181 | |||
185 | If an optional banner argument is given, it will override the |
|
182 | If an optional banner argument is given, it will override the | |
186 | internally created default banner. |
|
183 | internally created default banner. | |
187 | """ |
|
184 | """ | |
188 |
|
185 | |||
189 | with nested(self.builtin_trap, self.display_trap): |
|
186 | with nested(self.builtin_trap, self.display_trap): | |
190 |
|
187 | |||
191 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
188 | # if you run stuff with -c <cmd>, raw hist is not updated | |
192 | # ensure that it's in sync |
|
189 | # ensure that it's in sync | |
193 | self.history_manager.sync_inputs() |
|
190 | self.history_manager.sync_inputs() | |
194 |
|
191 | |||
195 | while 1: |
|
192 | while 1: | |
196 | try: |
|
193 | try: | |
197 | self.interact(display_banner=display_banner) |
|
194 | self.interact(display_banner=display_banner) | |
198 | #self.interact_with_readline() |
|
195 | #self.interact_with_readline() | |
199 | # XXX for testing of a readline-decoupled repl loop, call |
|
196 | # XXX for testing of a readline-decoupled repl loop, call | |
200 | # interact_with_readline above |
|
197 | # interact_with_readline above | |
201 | break |
|
198 | break | |
202 | except KeyboardInterrupt: |
|
199 | except KeyboardInterrupt: | |
203 | # this should not be necessary, but KeyboardInterrupt |
|
200 | # this should not be necessary, but KeyboardInterrupt | |
204 | # handling seems rather unpredictable... |
|
201 | # handling seems rather unpredictable... | |
205 | self.write("\nKeyboardInterrupt in interact()\n") |
|
202 | self.write("\nKeyboardInterrupt in interact()\n") | |
206 |
|
203 | |||
207 | def interact(self, display_banner=None): |
|
204 | def interact(self, display_banner=None): | |
208 | """Closely emulate the interactive Python console.""" |
|
205 | """Closely emulate the interactive Python console.""" | |
209 |
|
206 | |||
210 | # batch run -> do not interact |
|
207 | # batch run -> do not interact | |
211 | if self.exit_now: |
|
208 | if self.exit_now: | |
212 | return |
|
209 | return | |
213 |
|
210 | |||
214 | if display_banner is None: |
|
211 | if display_banner is None: | |
215 | display_banner = self.display_banner |
|
212 | display_banner = self.display_banner | |
216 | if display_banner: |
|
213 | if display_banner: | |
217 | self.show_banner() |
|
214 | self.show_banner() | |
218 |
|
215 | |||
219 | more = False |
|
216 | more = False | |
220 |
|
217 | |||
221 | # Mark activity in the builtins |
|
218 | # Mark activity in the builtins | |
222 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
219 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
223 |
|
220 | |||
224 | if self.has_readline: |
|
221 | if self.has_readline: | |
225 | self.readline_startup_hook(self.pre_readline) |
|
222 | self.readline_startup_hook(self.pre_readline) | |
226 | # exit_now is set by a call to %Exit or %Quit, through the |
|
223 | # exit_now is set by a call to %Exit or %Quit, through the | |
227 | # ask_exit callback. |
|
224 | # ask_exit callback. | |
228 |
|
225 | |||
229 | while not self.exit_now: |
|
226 | while not self.exit_now: | |
230 | self.hooks.pre_prompt_hook() |
|
227 | self.hooks.pre_prompt_hook() | |
231 | if more: |
|
228 | if more: | |
232 | try: |
|
229 | try: | |
233 | prompt = self.hooks.generate_prompt(True) |
|
230 | prompt = self.hooks.generate_prompt(True) | |
234 | except: |
|
231 | except: | |
235 | self.showtraceback() |
|
232 | self.showtraceback() | |
236 | if self.autoindent: |
|
233 | if self.autoindent: | |
237 | self.rl_do_indent = True |
|
234 | self.rl_do_indent = True | |
238 |
|
235 | |||
239 | else: |
|
236 | else: | |
240 | try: |
|
237 | try: | |
241 | prompt = self.hooks.generate_prompt(False) |
|
238 | prompt = self.hooks.generate_prompt(False) | |
242 | except: |
|
239 | except: | |
243 | self.showtraceback() |
|
240 | self.showtraceback() | |
244 | try: |
|
241 | try: | |
245 | line = self.raw_input(prompt) |
|
242 | line = self.raw_input(prompt) | |
246 | if self.exit_now: |
|
243 | if self.exit_now: | |
247 | # quick exit on sys.std[in|out] close |
|
244 | # quick exit on sys.std[in|out] close | |
248 | break |
|
245 | break | |
249 | if self.autoindent: |
|
246 | if self.autoindent: | |
250 | self.rl_do_indent = False |
|
247 | self.rl_do_indent = False | |
251 |
|
248 | |||
252 | except KeyboardInterrupt: |
|
249 | except KeyboardInterrupt: | |
253 | #double-guard against keyboardinterrupts during kbdint handling |
|
250 | #double-guard against keyboardinterrupts during kbdint handling | |
254 | try: |
|
251 | try: | |
255 | self.write('\nKeyboardInterrupt\n') |
|
252 | self.write('\nKeyboardInterrupt\n') | |
256 | self.resetbuffer() |
|
253 | self.resetbuffer() | |
257 | more = False |
|
254 | more = False | |
258 | except KeyboardInterrupt: |
|
255 | except KeyboardInterrupt: | |
259 | pass |
|
256 | pass | |
260 | except EOFError: |
|
257 | except EOFError: | |
261 | if self.autoindent: |
|
258 | if self.autoindent: | |
262 | self.rl_do_indent = False |
|
259 | self.rl_do_indent = False | |
263 | if self.has_readline: |
|
260 | if self.has_readline: | |
264 | self.readline_startup_hook(None) |
|
261 | self.readline_startup_hook(None) | |
265 | self.write('\n') |
|
262 | self.write('\n') | |
266 | self.exit() |
|
263 | self.exit() | |
267 | except bdb.BdbQuit: |
|
264 | except bdb.BdbQuit: | |
268 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
265 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
269 | 'Because of how pdb handles the stack, it is impossible\n' |
|
266 | 'Because of how pdb handles the stack, it is impossible\n' | |
270 | 'for IPython to properly format this particular exception.\n' |
|
267 | 'for IPython to properly format this particular exception.\n' | |
271 | 'IPython will resume normal operation.') |
|
268 | 'IPython will resume normal operation.') | |
272 | except: |
|
269 | except: | |
273 | # exceptions here are VERY RARE, but they can be triggered |
|
270 | # exceptions here are VERY RARE, but they can be triggered | |
274 | # asynchronously by signal handlers, for example. |
|
271 | # asynchronously by signal handlers, for example. | |
275 | self.showtraceback() |
|
272 | self.showtraceback() | |
276 | else: |
|
273 | else: | |
277 | self.input_splitter.push(line) |
|
274 | self.input_splitter.push(line) | |
278 | more = self.input_splitter.push_accepts_more() |
|
275 | more = self.input_splitter.push_accepts_more() | |
279 | if (self.SyntaxTB.last_syntax_error and |
|
276 | if (self.SyntaxTB.last_syntax_error and | |
280 | self.autoedit_syntax): |
|
277 | self.autoedit_syntax): | |
281 | self.edit_syntax_error() |
|
278 | self.edit_syntax_error() | |
282 | if not more: |
|
279 | if not more: | |
283 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
280 | source_raw = self.input_splitter.source_raw_reset()[1] | |
284 | self.run_cell(source_raw) |
|
281 | self.run_cell(source_raw) | |
285 |
|
282 | |||
286 | # We are off again... |
|
283 | # We are off again... | |
287 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
284 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
288 |
|
285 | |||
289 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
286 | # Turn off the exit flag, so the mainloop can be restarted if desired | |
290 | self.exit_now = False |
|
287 | self.exit_now = False | |
291 |
|
288 | |||
292 | def raw_input(self, prompt='', continue_prompt=False): |
|
289 | def raw_input(self, prompt='', continue_prompt=False): | |
293 | """Write a prompt and read a line. |
|
290 | """Write a prompt and read a line. | |
294 |
|
291 | |||
295 | The returned line does not include the trailing newline. |
|
292 | The returned line does not include the trailing newline. | |
296 | When the user enters the EOF key sequence, EOFError is raised. |
|
293 | When the user enters the EOF key sequence, EOFError is raised. | |
297 |
|
294 | |||
298 | Optional inputs: |
|
295 | Optional inputs: | |
299 |
|
296 | |||
300 | - prompt(''): a string to be printed to prompt the user. |
|
297 | - prompt(''): a string to be printed to prompt the user. | |
301 |
|
298 | |||
302 | - continue_prompt(False): whether this line is the first one or a |
|
299 | - continue_prompt(False): whether this line is the first one or a | |
303 | continuation in a sequence of inputs. |
|
300 | continuation in a sequence of inputs. | |
304 | """ |
|
301 | """ | |
305 | # Code run by the user may have modified the readline completer state. |
|
302 | # Code run by the user may have modified the readline completer state. | |
306 | # We must ensure that our completer is back in place. |
|
303 | # We must ensure that our completer is back in place. | |
307 |
|
304 | |||
308 | if self.has_readline: |
|
305 | if self.has_readline: | |
309 | self.set_readline_completer() |
|
306 | self.set_readline_completer() | |
310 |
|
307 | |||
311 | try: |
|
308 | try: | |
312 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
309 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
313 | except ValueError: |
|
310 | except ValueError: | |
314 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
311 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
315 | " or sys.stdout.close()!\nExiting IPython!") |
|
312 | " or sys.stdout.close()!\nExiting IPython!") | |
316 | self.ask_exit() |
|
313 | self.ask_exit() | |
317 | return "" |
|
314 | return "" | |
318 |
|
315 | |||
319 | # Try to be reasonably smart about not re-indenting pasted input more |
|
316 | # Try to be reasonably smart about not re-indenting pasted input more | |
320 | # than necessary. We do this by trimming out the auto-indent initial |
|
317 | # than necessary. We do this by trimming out the auto-indent initial | |
321 | # spaces, if the user's actual input started itself with whitespace. |
|
318 | # spaces, if the user's actual input started itself with whitespace. | |
322 | if self.autoindent: |
|
319 | if self.autoindent: | |
323 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
320 | if num_ini_spaces(line) > self.indent_current_nsp: | |
324 | line = line[self.indent_current_nsp:] |
|
321 | line = line[self.indent_current_nsp:] | |
325 | self.indent_current_nsp = 0 |
|
322 | self.indent_current_nsp = 0 | |
326 |
|
323 | |||
327 | # store the unfiltered input before the user has any chance to modify |
|
324 | # store the unfiltered input before the user has any chance to modify | |
328 | # it. |
|
325 | # it. | |
329 | if line.strip(): |
|
326 | if line.strip(): | |
330 | if continue_prompt: |
|
327 | if continue_prompt: | |
331 | if self.has_readline and self.readline_use: |
|
328 | if self.has_readline and self.readline_use: | |
332 | histlen = self.readline.get_current_history_length() |
|
329 | histlen = self.readline.get_current_history_length() | |
333 | if histlen > 1: |
|
330 | if histlen > 1: | |
334 | newhist = self.history_manager.input_hist_raw[-1].rstrip() |
|
331 | newhist = self.history_manager.input_hist_raw[-1].rstrip() | |
335 | self.readline.remove_history_item(histlen-1) |
|
332 | self.readline.remove_history_item(histlen-1) | |
336 | self.readline.replace_history_item(histlen-2, |
|
333 | self.readline.replace_history_item(histlen-2, | |
337 | newhist.encode(self.stdin_encoding)) |
|
334 | newhist.encode(self.stdin_encoding)) | |
338 | else: |
|
335 | else: | |
339 | self.history_manager.input_hist_raw.append('%s\n' % line) |
|
336 | self.history_manager.input_hist_raw.append('%s\n' % line) | |
340 | elif not continue_prompt: |
|
337 | elif not continue_prompt: | |
341 | self.history_manager.input_hist_raw.append('\n') |
|
338 | self.history_manager.input_hist_raw.append('\n') | |
342 | try: |
|
339 | try: | |
343 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
340 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
344 | except: |
|
341 | except: | |
345 | # blanket except, in case a user-defined prefilter crashes, so it |
|
342 | # blanket except, in case a user-defined prefilter crashes, so it | |
346 | # can't take all of ipython with it. |
|
343 | # can't take all of ipython with it. | |
347 | self.showtraceback() |
|
344 | self.showtraceback() | |
348 | return '' |
|
345 | return '' | |
349 | else: |
|
346 | else: | |
350 | return lineout |
|
347 | return lineout | |
351 |
|
348 | |||
352 |
|
349 | |||
353 | def raw_input(self, prompt=''): |
|
350 | def raw_input(self, prompt=''): | |
354 | """Write a prompt and read a line. |
|
351 | """Write a prompt and read a line. | |
355 |
|
352 | |||
356 | The returned line does not include the trailing newline. |
|
353 | The returned line does not include the trailing newline. | |
357 | When the user enters the EOF key sequence, EOFError is raised. |
|
354 | When the user enters the EOF key sequence, EOFError is raised. | |
358 |
|
355 | |||
359 | Optional inputs: |
|
356 | Optional inputs: | |
360 |
|
357 | |||
361 | - prompt(''): a string to be printed to prompt the user. |
|
358 | - prompt(''): a string to be printed to prompt the user. | |
362 |
|
359 | |||
363 | - continue_prompt(False): whether this line is the first one or a |
|
360 | - continue_prompt(False): whether this line is the first one or a | |
364 | continuation in a sequence of inputs. |
|
361 | continuation in a sequence of inputs. | |
365 | """ |
|
362 | """ | |
366 | # Code run by the user may have modified the readline completer state. |
|
363 | # Code run by the user may have modified the readline completer state. | |
367 | # We must ensure that our completer is back in place. |
|
364 | # We must ensure that our completer is back in place. | |
368 |
|
365 | |||
369 | if self.has_readline: |
|
366 | if self.has_readline: | |
370 | self.set_readline_completer() |
|
367 | self.set_readline_completer() | |
371 |
|
368 | |||
372 | try: |
|
369 | try: | |
373 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
370 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
374 | except ValueError: |
|
371 | except ValueError: | |
375 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
372 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
376 | " or sys.stdout.close()!\nExiting IPython!") |
|
373 | " or sys.stdout.close()!\nExiting IPython!") | |
377 | self.ask_exit() |
|
374 | self.ask_exit() | |
378 | return "" |
|
375 | return "" | |
379 |
|
376 | |||
380 | # Try to be reasonably smart about not re-indenting pasted input more |
|
377 | # Try to be reasonably smart about not re-indenting pasted input more | |
381 | # than necessary. We do this by trimming out the auto-indent initial |
|
378 | # than necessary. We do this by trimming out the auto-indent initial | |
382 | # spaces, if the user's actual input started itself with whitespace. |
|
379 | # spaces, if the user's actual input started itself with whitespace. | |
383 | if self.autoindent: |
|
380 | if self.autoindent: | |
384 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
381 | if num_ini_spaces(line) > self.indent_current_nsp: | |
385 | line = line[self.indent_current_nsp:] |
|
382 | line = line[self.indent_current_nsp:] | |
386 | self.indent_current_nsp = 0 |
|
383 | self.indent_current_nsp = 0 | |
387 |
|
384 | |||
388 | return line |
|
385 | return line | |
389 |
|
386 | |||
390 | #------------------------------------------------------------------------- |
|
387 | #------------------------------------------------------------------------- | |
391 | # Methods to support auto-editing of SyntaxErrors. |
|
388 | # Methods to support auto-editing of SyntaxErrors. | |
392 | #------------------------------------------------------------------------- |
|
389 | #------------------------------------------------------------------------- | |
393 |
|
390 | |||
394 | def edit_syntax_error(self): |
|
391 | def edit_syntax_error(self): | |
395 | """The bottom half of the syntax error handler called in the main loop. |
|
392 | """The bottom half of the syntax error handler called in the main loop. | |
396 |
|
393 | |||
397 | Loop until syntax error is fixed or user cancels. |
|
394 | Loop until syntax error is fixed or user cancels. | |
398 | """ |
|
395 | """ | |
399 |
|
396 | |||
400 | while self.SyntaxTB.last_syntax_error: |
|
397 | while self.SyntaxTB.last_syntax_error: | |
401 | # copy and clear last_syntax_error |
|
398 | # copy and clear last_syntax_error | |
402 | err = self.SyntaxTB.clear_err_state() |
|
399 | err = self.SyntaxTB.clear_err_state() | |
403 | if not self._should_recompile(err): |
|
400 | if not self._should_recompile(err): | |
404 | return |
|
401 | return | |
405 | try: |
|
402 | try: | |
406 | # may set last_syntax_error again if a SyntaxError is raised |
|
403 | # may set last_syntax_error again if a SyntaxError is raised | |
407 | self.safe_execfile(err.filename,self.user_ns) |
|
404 | self.safe_execfile(err.filename,self.user_ns) | |
408 | except: |
|
405 | except: | |
409 | self.showtraceback() |
|
406 | self.showtraceback() | |
410 | else: |
|
407 | else: | |
411 | try: |
|
408 | try: | |
412 | f = file(err.filename) |
|
409 | f = file(err.filename) | |
413 | try: |
|
410 | try: | |
414 | # This should be inside a display_trap block and I |
|
411 | # This should be inside a display_trap block and I | |
415 | # think it is. |
|
412 | # think it is. | |
416 | sys.displayhook(f.read()) |
|
413 | sys.displayhook(f.read()) | |
417 | finally: |
|
414 | finally: | |
418 | f.close() |
|
415 | f.close() | |
419 | except: |
|
416 | except: | |
420 | self.showtraceback() |
|
417 | self.showtraceback() | |
421 |
|
418 | |||
422 | def _should_recompile(self,e): |
|
419 | def _should_recompile(self,e): | |
423 | """Utility routine for edit_syntax_error""" |
|
420 | """Utility routine for edit_syntax_error""" | |
424 |
|
421 | |||
425 | if e.filename in ('<ipython console>','<input>','<string>', |
|
422 | if e.filename in ('<ipython console>','<input>','<string>', | |
426 | '<console>','<BackgroundJob compilation>', |
|
423 | '<console>','<BackgroundJob compilation>', | |
427 | None): |
|
424 | None): | |
428 |
|
425 | |||
429 | return False |
|
426 | return False | |
430 | try: |
|
427 | try: | |
431 | if (self.autoedit_syntax and |
|
428 | if (self.autoedit_syntax and | |
432 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
429 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
433 | '[Y/n] ','y')): |
|
430 | '[Y/n] ','y')): | |
434 | return False |
|
431 | return False | |
435 | except EOFError: |
|
432 | except EOFError: | |
436 | return False |
|
433 | return False | |
437 |
|
434 | |||
438 | def int0(x): |
|
435 | def int0(x): | |
439 | try: |
|
436 | try: | |
440 | return int(x) |
|
437 | return int(x) | |
441 | except TypeError: |
|
438 | except TypeError: | |
442 | return 0 |
|
439 | return 0 | |
443 | # always pass integer line and offset values to editor hook |
|
440 | # always pass integer line and offset values to editor hook | |
444 | try: |
|
441 | try: | |
445 | self.hooks.fix_error_editor(e.filename, |
|
442 | self.hooks.fix_error_editor(e.filename, | |
446 | int0(e.lineno),int0(e.offset),e.msg) |
|
443 | int0(e.lineno),int0(e.offset),e.msg) | |
447 | except TryNext: |
|
444 | except TryNext: | |
448 | warn('Could not open editor') |
|
445 | warn('Could not open editor') | |
449 | return False |
|
446 | return False | |
450 | return True |
|
447 | return True | |
451 |
|
448 | |||
452 | #------------------------------------------------------------------------- |
|
449 | #------------------------------------------------------------------------- | |
453 | # Things related to GUI support and pylab |
|
450 | # Things related to GUI support and pylab | |
454 | #------------------------------------------------------------------------- |
|
451 | #------------------------------------------------------------------------- | |
455 |
|
452 | |||
456 | def enable_pylab(self, gui=None): |
|
453 | def enable_pylab(self, gui=None): | |
457 | """Activate pylab support at runtime. |
|
454 | """Activate pylab support at runtime. | |
458 |
|
455 | |||
459 | This turns on support for matplotlib, preloads into the interactive |
|
456 | This turns on support for matplotlib, preloads into the interactive | |
460 | namespace all of numpy and pylab, and configures IPython to correcdtly |
|
457 | namespace all of numpy and pylab, and configures IPython to correcdtly | |
461 | interact with the GUI event loop. The GUI backend to be used can be |
|
458 | interact with the GUI event loop. The GUI backend to be used can be | |
462 | optionally selected with the optional :param:`gui` argument. |
|
459 | optionally selected with the optional :param:`gui` argument. | |
463 |
|
460 | |||
464 | Parameters |
|
461 | Parameters | |
465 | ---------- |
|
462 | ---------- | |
466 | gui : optional, string |
|
463 | gui : optional, string | |
467 |
|
464 | |||
468 | If given, dictates the choice of matplotlib GUI backend to use |
|
465 | If given, dictates the choice of matplotlib GUI backend to use | |
469 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or |
|
466 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |
470 | 'gtk'), otherwise we use the default chosen by matplotlib (as |
|
467 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |
471 | dictated by the matplotlib build-time options plus the user's |
|
468 | dictated by the matplotlib build-time options plus the user's | |
472 | matplotlibrc configuration file). |
|
469 | matplotlibrc configuration file). | |
473 | """ |
|
470 | """ | |
474 | # We want to prevent the loading of pylab to pollute the user's |
|
471 | # We want to prevent the loading of pylab to pollute the user's | |
475 | # namespace as shown by the %who* magics, so we execute the activation |
|
472 | # namespace as shown by the %who* magics, so we execute the activation | |
476 | # code in an empty namespace, and we update *both* user_ns and |
|
473 | # code in an empty namespace, and we update *both* user_ns and | |
477 | # user_ns_hidden with this information. |
|
474 | # user_ns_hidden with this information. | |
478 | ns = {} |
|
475 | ns = {} | |
479 | gui = pylab_activate(ns, gui) |
|
476 | gui = pylab_activate(ns, gui) | |
480 | self.user_ns.update(ns) |
|
477 | self.user_ns.update(ns) | |
481 | self.user_ns_hidden.update(ns) |
|
478 | self.user_ns_hidden.update(ns) | |
482 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
479 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
483 | # plot updates into account |
|
480 | # plot updates into account | |
484 | enable_gui(gui) |
|
481 | enable_gui(gui) | |
485 | self.magic_run = self._pylab_magic_run |
|
482 | self.magic_run = self._pylab_magic_run | |
486 |
|
483 | |||
487 | #------------------------------------------------------------------------- |
|
484 | #------------------------------------------------------------------------- | |
488 | # Things related to exiting |
|
485 | # Things related to exiting | |
489 | #------------------------------------------------------------------------- |
|
486 | #------------------------------------------------------------------------- | |
490 |
|
487 | |||
491 | def ask_exit(self): |
|
488 | def ask_exit(self): | |
492 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
489 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
493 | self.exit_now = True |
|
490 | self.exit_now = True | |
494 |
|
491 | |||
495 | def exit(self): |
|
492 | def exit(self): | |
496 | """Handle interactive exit. |
|
493 | """Handle interactive exit. | |
497 |
|
494 | |||
498 | This method calls the ask_exit callback.""" |
|
495 | This method calls the ask_exit callback.""" | |
499 | if self.confirm_exit: |
|
496 | if self.confirm_exit: | |
500 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
497 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
501 | self.ask_exit() |
|
498 | self.ask_exit() | |
502 | else: |
|
499 | else: | |
503 | self.ask_exit() |
|
500 | self.ask_exit() | |
504 |
|
501 | |||
505 | #------------------------------------------------------------------------ |
|
502 | #------------------------------------------------------------------------ | |
506 | # Magic overrides |
|
503 | # Magic overrides | |
507 | #------------------------------------------------------------------------ |
|
504 | #------------------------------------------------------------------------ | |
508 | # Once the base class stops inheriting from magic, this code needs to be |
|
505 | # Once the base class stops inheriting from magic, this code needs to be | |
509 | # moved into a separate machinery as well. For now, at least isolate here |
|
506 | # moved into a separate machinery as well. For now, at least isolate here | |
510 | # the magics which this class needs to implement differently from the base |
|
507 | # the magics which this class needs to implement differently from the base | |
511 | # class, or that are unique to it. |
|
508 | # class, or that are unique to it. | |
512 |
|
509 | |||
513 | def magic_autoindent(self, parameter_s = ''): |
|
510 | def magic_autoindent(self, parameter_s = ''): | |
514 | """Toggle autoindent on/off (if available).""" |
|
511 | """Toggle autoindent on/off (if available).""" | |
515 |
|
512 | |||
516 | self.shell.set_autoindent() |
|
513 | self.shell.set_autoindent() | |
517 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
514 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
518 |
|
515 | |||
|
516 | @testdec.skip_doctest | |||
519 | def magic_cpaste(self, parameter_s=''): |
|
517 | def magic_cpaste(self, parameter_s=''): | |
520 | """Paste & execute a pre-formatted code block from clipboard. |
|
518 | """Paste & execute a pre-formatted code block from clipboard. | |
521 |
|
519 | |||
522 | You must terminate the block with '--' (two minus-signs) alone on the |
|
520 | You must terminate the block with '--' (two minus-signs) alone on the | |
523 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
521 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
524 | is the new sentinel for this operation) |
|
522 | is the new sentinel for this operation) | |
525 |
|
523 | |||
526 | The block is dedented prior to execution to enable execution of method |
|
524 | The block is dedented prior to execution to enable execution of method | |
527 | definitions. '>' and '+' characters at the beginning of a line are |
|
525 | definitions. '>' and '+' characters at the beginning of a line are | |
528 | ignored, to allow pasting directly from e-mails, diff files and |
|
526 | ignored, to allow pasting directly from e-mails, diff files and | |
529 | doctests (the '...' continuation prompt is also stripped). The |
|
527 | doctests (the '...' continuation prompt is also stripped). The | |
530 | executed block is also assigned to variable named 'pasted_block' for |
|
528 | executed block is also assigned to variable named 'pasted_block' for | |
531 | later editing with '%edit pasted_block'. |
|
529 | later editing with '%edit pasted_block'. | |
532 |
|
530 | |||
533 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
531 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
534 | This assigns the pasted block to variable 'foo' as string, without |
|
532 | This assigns the pasted block to variable 'foo' as string, without | |
535 | dedenting or executing it (preceding >>> and + is still stripped) |
|
533 | dedenting or executing it (preceding >>> and + is still stripped) | |
536 |
|
534 | |||
537 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
535 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
538 |
|
536 | |||
539 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
537 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
540 | Just press enter and type -- (and press enter again) and the block |
|
538 | Just press enter and type -- (and press enter again) and the block | |
541 | will be what was just pasted. |
|
539 | will be what was just pasted. | |
542 |
|
540 | |||
543 | IPython statements (magics, shell escapes) are not supported (yet). |
|
541 | IPython statements (magics, shell escapes) are not supported (yet). | |
544 |
|
542 | |||
545 | See also |
|
543 | See also | |
546 | -------- |
|
544 | -------- | |
547 | paste: automatically pull code from clipboard. |
|
545 | paste: automatically pull code from clipboard. | |
548 |
|
546 | |||
549 | Examples |
|
547 | Examples | |
550 | -------- |
|
548 | -------- | |
551 | :: |
|
549 | :: | |
552 |
|
550 | |||
553 | In [8]: %cpaste |
|
551 | In [8]: %cpaste | |
554 | Pasting code; enter '--' alone on the line to stop. |
|
552 | Pasting code; enter '--' alone on the line to stop. | |
555 | :>>> a = ["world!", "Hello"] |
|
553 | :>>> a = ["world!", "Hello"] | |
556 | :>>> print " ".join(sorted(a)) |
|
554 | :>>> print " ".join(sorted(a)) | |
557 | :-- |
|
555 | :-- | |
558 | Hello world! |
|
556 | Hello world! | |
559 | """ |
|
557 | """ | |
560 |
|
558 | |||
561 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
559 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
562 | par = args.strip() |
|
560 | par = args.strip() | |
563 | if opts.has_key('r'): |
|
561 | if opts.has_key('r'): | |
564 | self._rerun_pasted() |
|
562 | self._rerun_pasted() | |
565 | return |
|
563 | return | |
566 |
|
564 | |||
567 | sentinel = opts.get('s','--') |
|
565 | sentinel = opts.get('s','--') | |
568 |
|
566 | |||
569 | block = self._strip_pasted_lines_for_code( |
|
567 | block = self._strip_pasted_lines_for_code( | |
570 | self._get_pasted_lines(sentinel)) |
|
568 | self._get_pasted_lines(sentinel)) | |
571 |
|
569 | |||
572 | self._execute_block(block, par) |
|
570 | self._execute_block(block, par) | |
573 |
|
571 | |||
574 | def magic_paste(self, parameter_s=''): |
|
572 | def magic_paste(self, parameter_s=''): | |
575 | """Paste & execute a pre-formatted code block from clipboard. |
|
573 | """Paste & execute a pre-formatted code block from clipboard. | |
576 |
|
574 | |||
577 | The text is pulled directly from the clipboard without user |
|
575 | The text is pulled directly from the clipboard without user | |
578 | intervention and printed back on the screen before execution (unless |
|
576 | intervention and printed back on the screen before execution (unless | |
579 | the -q flag is given to force quiet mode). |
|
577 | the -q flag is given to force quiet mode). | |
580 |
|
578 | |||
581 | The block is dedented prior to execution to enable execution of method |
|
579 | The block is dedented prior to execution to enable execution of method | |
582 | definitions. '>' and '+' characters at the beginning of a line are |
|
580 | definitions. '>' and '+' characters at the beginning of a line are | |
583 | ignored, to allow pasting directly from e-mails, diff files and |
|
581 | ignored, to allow pasting directly from e-mails, diff files and | |
584 | doctests (the '...' continuation prompt is also stripped). The |
|
582 | doctests (the '...' continuation prompt is also stripped). The | |
585 | executed block is also assigned to variable named 'pasted_block' for |
|
583 | executed block is also assigned to variable named 'pasted_block' for | |
586 | later editing with '%edit pasted_block'. |
|
584 | later editing with '%edit pasted_block'. | |
587 |
|
585 | |||
588 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
586 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
589 | This assigns the pasted block to variable 'foo' as string, without |
|
587 | This assigns the pasted block to variable 'foo' as string, without | |
590 | dedenting or executing it (preceding >>> and + is still stripped) |
|
588 | dedenting or executing it (preceding >>> and + is still stripped) | |
591 |
|
589 | |||
592 | Options |
|
590 | Options | |
593 | ------- |
|
591 | ------- | |
594 |
|
592 | |||
595 | -r: re-executes the block previously entered by cpaste. |
|
593 | -r: re-executes the block previously entered by cpaste. | |
596 |
|
594 | |||
597 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
595 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
598 |
|
596 | |||
599 | IPython statements (magics, shell escapes) are not supported (yet). |
|
597 | IPython statements (magics, shell escapes) are not supported (yet). | |
600 |
|
598 | |||
601 | See also |
|
599 | See also | |
602 | -------- |
|
600 | -------- | |
603 | cpaste: manually paste code into terminal until you mark its end. |
|
601 | cpaste: manually paste code into terminal until you mark its end. | |
604 | """ |
|
602 | """ | |
605 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
603 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
606 | par = args.strip() |
|
604 | par = args.strip() | |
607 | if opts.has_key('r'): |
|
605 | if opts.has_key('r'): | |
608 | self._rerun_pasted() |
|
606 | self._rerun_pasted() | |
609 | return |
|
607 | return | |
610 |
|
608 | |||
611 | text = self.shell.hooks.clipboard_get() |
|
609 | text = self.shell.hooks.clipboard_get() | |
612 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
610 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
613 |
|
611 | |||
614 | # By default, echo back to terminal unless quiet mode is requested |
|
612 | # By default, echo back to terminal unless quiet mode is requested | |
615 | if not opts.has_key('q'): |
|
613 | if not opts.has_key('q'): | |
616 | write = self.shell.write |
|
614 | write = self.shell.write | |
617 | write(self.shell.pycolorize(block)) |
|
615 | write(self.shell.pycolorize(block)) | |
618 | if not block.endswith('\n'): |
|
616 | if not block.endswith('\n'): | |
619 | write('\n') |
|
617 | write('\n') | |
620 | write("## -- End pasted text --\n") |
|
618 | write("## -- End pasted text --\n") | |
621 |
|
619 | |||
622 | self._execute_block(block, par) |
|
620 | self._execute_block(block, par) | |
623 |
|
621 | |||
624 |
|
622 | |||
625 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
623 | InteractiveShellABC.register(TerminalInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now