##// END OF EJS Templates
Merge branch 'paste-errmsg'
Thomas Kluyver -
r5369:6c203584 merge
parent child Browse files
Show More
@@ -1,235 +1,235 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your profile's ipython_config.py configuration.
16 from within your profile's ipython_config.py configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 import os, bisect
44 import os, bisect
45 import sys
45 import sys
46
46
47 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48
48
49 # List here all the default hooks. For now it's just the editor functions
49 # List here all the default hooks. For now it's just the editor functions
50 # but over time we'll move here all the public API for user-accessible things.
50 # but over time we'll move here all the public API for user-accessible things.
51
51
52 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
52 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
53 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
53 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
54 'generate_prompt', 'show_in_pager','pre_prompt_hook',
54 'generate_prompt', 'show_in_pager','pre_prompt_hook',
55 'pre_run_code_hook', 'clipboard_get']
55 'pre_run_code_hook', 'clipboard_get']
56
56
57 def editor(self,filename, linenum=None):
57 def editor(self,filename, linenum=None):
58 """Open the default editor at the given filename and linenumber.
58 """Open the default editor at the given filename and linenumber.
59
59
60 This is IPython's default editor hook, you can use it as an example to
60 This is IPython's default editor hook, you can use it as an example to
61 write your own modified one. To set your own editor function as the
61 write your own modified one. To set your own editor function as the
62 new editor hook, call ip.set_hook('editor',yourfunc)."""
62 new editor hook, call ip.set_hook('editor',yourfunc)."""
63
63
64 # IPython configures a default editor at startup by reading $EDITOR from
64 # IPython configures a default editor at startup by reading $EDITOR from
65 # the environment, and falling back on vi (unix) or notepad (win32).
65 # the environment, and falling back on vi (unix) or notepad (win32).
66 editor = self.editor
66 editor = self.editor
67
67
68 # marker for at which line to open the file (for existing objects)
68 # marker for at which line to open the file (for existing objects)
69 if linenum is None or editor=='notepad':
69 if linenum is None or editor=='notepad':
70 linemark = ''
70 linemark = ''
71 else:
71 else:
72 linemark = '+%d' % int(linenum)
72 linemark = '+%d' % int(linenum)
73
73
74 # Enclose in quotes if necessary and legal
74 # Enclose in quotes if necessary and legal
75 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
75 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
76 editor = '"%s"' % editor
76 editor = '"%s"' % editor
77
77
78 # Call the actual editor
78 # Call the actual editor
79 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
79 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
80 raise TryNext()
80 raise TryNext()
81
81
82 import tempfile
82 import tempfile
83 def fix_error_editor(self,filename,linenum,column,msg):
83 def fix_error_editor(self,filename,linenum,column,msg):
84 """Open the editor at the given filename, linenumber, column and
84 """Open the editor at the given filename, linenumber, column and
85 show an error message. This is used for correcting syntax errors.
85 show an error message. This is used for correcting syntax errors.
86 The current implementation only has special support for the VIM editor,
86 The current implementation only has special support for the VIM editor,
87 and falls back on the 'editor' hook if VIM is not used.
87 and falls back on the 'editor' hook if VIM is not used.
88
88
89 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
89 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
90 """
90 """
91 def vim_quickfix_file():
91 def vim_quickfix_file():
92 t = tempfile.NamedTemporaryFile()
92 t = tempfile.NamedTemporaryFile()
93 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
93 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
94 t.flush()
94 t.flush()
95 return t
95 return t
96 if os.path.basename(self.editor) != 'vim':
96 if os.path.basename(self.editor) != 'vim':
97 self.hooks.editor(filename,linenum)
97 self.hooks.editor(filename,linenum)
98 return
98 return
99 t = vim_quickfix_file()
99 t = vim_quickfix_file()
100 try:
100 try:
101 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
101 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
102 raise TryNext()
102 raise TryNext()
103 finally:
103 finally:
104 t.close()
104 t.close()
105
105
106
106
107 def synchronize_with_editor(self, filename, linenum, column):
107 def synchronize_with_editor(self, filename, linenum, column):
108 pass
108 pass
109
109
110
110
111 class CommandChainDispatcher:
111 class CommandChainDispatcher:
112 """ Dispatch calls to a chain of commands until some func can handle it
112 """ Dispatch calls to a chain of commands until some func can handle it
113
113
114 Usage: instantiate, execute "add" to add commands (with optional
114 Usage: instantiate, execute "add" to add commands (with optional
115 priority), execute normally via f() calling mechanism.
115 priority), execute normally via f() calling mechanism.
116
116
117 """
117 """
118 def __init__(self,commands=None):
118 def __init__(self,commands=None):
119 if commands is None:
119 if commands is None:
120 self.chain = []
120 self.chain = []
121 else:
121 else:
122 self.chain = commands
122 self.chain = commands
123
123
124
124
125 def __call__(self,*args, **kw):
125 def __call__(self,*args, **kw):
126 """ Command chain is called just like normal func.
126 """ Command chain is called just like normal func.
127
127
128 This will call all funcs in chain with the same args as were given to this
128 This will call all funcs in chain with the same args as were given to this
129 function, and return the result of first func that didn't raise
129 function, and return the result of first func that didn't raise
130 TryNext """
130 TryNext """
131
131
132 for prio,cmd in self.chain:
132 for prio,cmd in self.chain:
133 #print "prio",prio,"cmd",cmd #dbg
133 #print "prio",prio,"cmd",cmd #dbg
134 try:
134 try:
135 return cmd(*args, **kw)
135 return cmd(*args, **kw)
136 except TryNext, exc:
136 except TryNext, exc:
137 if exc.args or exc.kwargs:
137 if exc.args or exc.kwargs:
138 args = exc.args
138 args = exc.args
139 kw = exc.kwargs
139 kw = exc.kwargs
140 # if no function will accept it, raise TryNext up to the caller
140 # if no function will accept it, raise TryNext up to the caller
141 raise TryNext
141 raise TryNext(*args, **kw)
142
142
143 def __str__(self):
143 def __str__(self):
144 return str(self.chain)
144 return str(self.chain)
145
145
146 def add(self, func, priority=0):
146 def add(self, func, priority=0):
147 """ Add a func to the cmd chain with given priority """
147 """ Add a func to the cmd chain with given priority """
148 bisect.insort(self.chain,(priority,func))
148 bisect.insort(self.chain,(priority,func))
149
149
150 def __iter__(self):
150 def __iter__(self):
151 """ Return all objects in chain.
151 """ Return all objects in chain.
152
152
153 Handy if the objects are not callable.
153 Handy if the objects are not callable.
154 """
154 """
155 return iter(self.chain)
155 return iter(self.chain)
156
156
157
157
158 def input_prefilter(self,line):
158 def input_prefilter(self,line):
159 """ Default input prefilter
159 """ Default input prefilter
160
160
161 This returns the line as unchanged, so that the interpreter
161 This returns the line as unchanged, so that the interpreter
162 knows that nothing was done and proceeds with "classic" prefiltering
162 knows that nothing was done and proceeds with "classic" prefiltering
163 (%magics, !shell commands etc.).
163 (%magics, !shell commands etc.).
164
164
165 Note that leading whitespace is not passed to this hook. Prefilter
165 Note that leading whitespace is not passed to this hook. Prefilter
166 can't alter indentation.
166 can't alter indentation.
167
167
168 """
168 """
169 #print "attempt to rewrite",line #dbg
169 #print "attempt to rewrite",line #dbg
170 return line
170 return line
171
171
172
172
173 def shutdown_hook(self):
173 def shutdown_hook(self):
174 """ default shutdown hook
174 """ default shutdown hook
175
175
176 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
176 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
177 """
177 """
178
178
179 #print "default shutdown hook ok" # dbg
179 #print "default shutdown hook ok" # dbg
180 return
180 return
181
181
182
182
183 def late_startup_hook(self):
183 def late_startup_hook(self):
184 """ Executed after ipython has been constructed and configured
184 """ Executed after ipython has been constructed and configured
185
185
186 """
186 """
187 #print "default startup hook ok" # dbg
187 #print "default startup hook ok" # dbg
188
188
189
189
190 def generate_prompt(self, is_continuation):
190 def generate_prompt(self, is_continuation):
191 """ calculate and return a string with the prompt to display """
191 """ calculate and return a string with the prompt to display """
192 if is_continuation:
192 if is_continuation:
193 return str(self.displayhook.prompt2)
193 return str(self.displayhook.prompt2)
194 return str(self.displayhook.prompt1)
194 return str(self.displayhook.prompt1)
195
195
196
196
197 def show_in_pager(self,s):
197 def show_in_pager(self,s):
198 """ Run a string through pager """
198 """ Run a string through pager """
199 # raising TryNext here will use the default paging functionality
199 # raising TryNext here will use the default paging functionality
200 raise TryNext
200 raise TryNext
201
201
202
202
203 def pre_prompt_hook(self):
203 def pre_prompt_hook(self):
204 """ Run before displaying the next prompt
204 """ Run before displaying the next prompt
205
205
206 Use this e.g. to display output from asynchronous operations (in order
206 Use this e.g. to display output from asynchronous operations (in order
207 to not mess up text entry)
207 to not mess up text entry)
208 """
208 """
209
209
210 return None
210 return None
211
211
212
212
213 def pre_run_code_hook(self):
213 def pre_run_code_hook(self):
214 """ Executed before running the (prefiltered) code in IPython """
214 """ Executed before running the (prefiltered) code in IPython """
215 return None
215 return None
216
216
217
217
218 def clipboard_get(self):
218 def clipboard_get(self):
219 """ Get text from the clipboard.
219 """ Get text from the clipboard.
220 """
220 """
221 from IPython.lib.clipboard import (
221 from IPython.lib.clipboard import (
222 osx_clipboard_get, tkinter_clipboard_get,
222 osx_clipboard_get, tkinter_clipboard_get,
223 win32_clipboard_get
223 win32_clipboard_get
224 )
224 )
225 if sys.platform == 'win32':
225 if sys.platform == 'win32':
226 chain = [win32_clipboard_get, tkinter_clipboard_get]
226 chain = [win32_clipboard_get, tkinter_clipboard_get]
227 elif sys.platform == 'darwin':
227 elif sys.platform == 'darwin':
228 chain = [osx_clipboard_get, tkinter_clipboard_get]
228 chain = [osx_clipboard_get, tkinter_clipboard_get]
229 else:
229 else:
230 chain = [tkinter_clipboard_get]
230 chain = [tkinter_clipboard_get]
231 dispatcher = CommandChainDispatcher()
231 dispatcher = CommandChainDispatcher()
232 for func in chain:
232 for func in chain:
233 dispatcher.add(func)
233 dispatcher.add(func)
234 text = dispatcher()
234 text = dispatcher()
235 return text
235 return text
@@ -1,639 +1,646 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 import os
19 import os
20 import re
20 import re
21 import sys
21 import sys
22
22
23 try:
23 try:
24 from contextlib import nested
24 from contextlib import nested
25 except:
25 except:
26 from IPython.utils.nested_context import nested
26 from IPython.utils.nested_context import nested
27
27
28 from IPython.core.error import TryNext
28 from IPython.core.error import TryNext
29 from IPython.core.usage import interactive_usage, default_banner
29 from IPython.core.usage import interactive_usage, default_banner
30 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
30 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
31 from IPython.lib.inputhook import enable_gui
31 from IPython.lib.inputhook import enable_gui
32 from IPython.lib.pylabtools import pylab_activate
32 from IPython.lib.pylabtools import pylab_activate
33 from IPython.testing.skipdoctest import skip_doctest
33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils import py3compat
34 from IPython.utils import py3compat
35 from IPython.utils.terminal import toggle_set_term_title, set_term_title
35 from IPython.utils.terminal import toggle_set_term_title, set_term_title
36 from IPython.utils.process import abbrev_cwd
36 from IPython.utils.process import abbrev_cwd
37 from IPython.utils.warn import warn
37 from IPython.utils.warn import warn, error
38 from IPython.utils.text import num_ini_spaces
38 from IPython.utils.text import num_ini_spaces
39 from IPython.utils.traitlets import Integer, CBool, Unicode
39 from IPython.utils.traitlets import Integer, CBool, Unicode
40
40
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Utilities
42 # Utilities
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45 def get_default_editor():
45 def get_default_editor():
46 try:
46 try:
47 ed = os.environ['EDITOR']
47 ed = os.environ['EDITOR']
48 except KeyError:
48 except KeyError:
49 if os.name == 'posix':
49 if os.name == 'posix':
50 ed = 'vi' # the only one guaranteed to be there!
50 ed = 'vi' # the only one guaranteed to be there!
51 else:
51 else:
52 ed = 'notepad' # same in Windows!
52 ed = 'notepad' # same in Windows!
53 return ed
53 return ed
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Main class
56 # Main class
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 class TerminalInteractiveShell(InteractiveShell):
59 class TerminalInteractiveShell(InteractiveShell):
60
60
61 autoedit_syntax = CBool(False, config=True,
61 autoedit_syntax = CBool(False, config=True,
62 help="auto editing of files with syntax errors.")
62 help="auto editing of files with syntax errors.")
63 banner = Unicode('')
63 banner = Unicode('')
64 banner1 = Unicode(default_banner, config=True,
64 banner1 = Unicode(default_banner, config=True,
65 help="""The part of the banner to be printed before the profile"""
65 help="""The part of the banner to be printed before the profile"""
66 )
66 )
67 banner2 = Unicode('', config=True,
67 banner2 = Unicode('', config=True,
68 help="""The part of the banner to be printed after the profile"""
68 help="""The part of the banner to be printed after the profile"""
69 )
69 )
70 confirm_exit = CBool(True, config=True,
70 confirm_exit = CBool(True, config=True,
71 help="""
71 help="""
72 Set to confirm when you try to exit IPython with an EOF (Control-D
72 Set to confirm when you try to exit IPython with an EOF (Control-D
73 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
73 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
74 you can force a direct exit without any confirmation.""",
74 you can force a direct exit without any confirmation.""",
75 )
75 )
76 # This display_banner only controls whether or not self.show_banner()
76 # This display_banner only controls whether or not self.show_banner()
77 # is called when mainloop/interact are called. The default is False
77 # is called when mainloop/interact are called. The default is False
78 # because for the terminal based application, the banner behavior
78 # because for the terminal based application, the banner behavior
79 # is controlled by Global.display_banner, which IPythonApp looks at
79 # is controlled by Global.display_banner, which IPythonApp looks at
80 # to determine if *it* should call show_banner() by hand or not.
80 # to determine if *it* should call show_banner() by hand or not.
81 display_banner = CBool(False) # This isn't configurable!
81 display_banner = CBool(False) # This isn't configurable!
82 embedded = CBool(False)
82 embedded = CBool(False)
83 embedded_active = CBool(False)
83 embedded_active = CBool(False)
84 editor = Unicode(get_default_editor(), config=True,
84 editor = Unicode(get_default_editor(), config=True,
85 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
85 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
86 )
86 )
87 pager = Unicode('less', config=True,
87 pager = Unicode('less', config=True,
88 help="The shell program to be used for paging.")
88 help="The shell program to be used for paging.")
89
89
90 screen_length = Integer(0, config=True,
90 screen_length = Integer(0, config=True,
91 help=
91 help=
92 """Number of lines of your screen, used to control printing of very
92 """Number of lines of your screen, used to control printing of very
93 long strings. Strings longer than this number of lines will be sent
93 long strings. Strings longer than this number of lines will be sent
94 through a pager instead of directly printed. The default value for
94 through a pager instead of directly printed. The default value for
95 this is 0, which means IPython will auto-detect your screen size every
95 this is 0, which means IPython will auto-detect your screen size every
96 time it needs to print certain potentially long strings (this doesn't
96 time it needs to print certain potentially long strings (this doesn't
97 change the behavior of the 'print' keyword, it's only triggered
97 change the behavior of the 'print' keyword, it's only triggered
98 internally). If for some reason this isn't working well (it needs
98 internally). If for some reason this isn't working well (it needs
99 curses support), specify it yourself. Otherwise don't change the
99 curses support), specify it yourself. Otherwise don't change the
100 default.""",
100 default.""",
101 )
101 )
102 term_title = CBool(False, config=True,
102 term_title = CBool(False, config=True,
103 help="Enable auto setting the terminal title."
103 help="Enable auto setting the terminal title."
104 )
104 )
105
105
106 def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None,
106 def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None,
107 user_global_ns=None, custom_exceptions=((),None),
107 user_global_ns=None, custom_exceptions=((),None),
108 usage=None, banner1=None, banner2=None,
108 usage=None, banner1=None, banner2=None,
109 display_banner=None):
109 display_banner=None):
110
110
111 super(TerminalInteractiveShell, self).__init__(
111 super(TerminalInteractiveShell, self).__init__(
112 config=config, profile_dir=profile_dir, user_ns=user_ns,
112 config=config, profile_dir=profile_dir, user_ns=user_ns,
113 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
113 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
114 )
114 )
115 # use os.system instead of utils.process.system by default,
115 # use os.system instead of utils.process.system by default,
116 # because piped system doesn't make sense in the Terminal:
116 # because piped system doesn't make sense in the Terminal:
117 self.system = self.system_raw
117 self.system = self.system_raw
118
118
119 self.init_term_title()
119 self.init_term_title()
120 self.init_usage(usage)
120 self.init_usage(usage)
121 self.init_banner(banner1, banner2, display_banner)
121 self.init_banner(banner1, banner2, display_banner)
122
122
123 #-------------------------------------------------------------------------
123 #-------------------------------------------------------------------------
124 # Things related to the terminal
124 # Things related to the terminal
125 #-------------------------------------------------------------------------
125 #-------------------------------------------------------------------------
126
126
127 @property
127 @property
128 def usable_screen_length(self):
128 def usable_screen_length(self):
129 if self.screen_length == 0:
129 if self.screen_length == 0:
130 return 0
130 return 0
131 else:
131 else:
132 num_lines_bot = self.separate_in.count('\n')+1
132 num_lines_bot = self.separate_in.count('\n')+1
133 return self.screen_length - num_lines_bot
133 return self.screen_length - num_lines_bot
134
134
135 def init_term_title(self):
135 def init_term_title(self):
136 # Enable or disable the terminal title.
136 # Enable or disable the terminal title.
137 if self.term_title:
137 if self.term_title:
138 toggle_set_term_title(True)
138 toggle_set_term_title(True)
139 set_term_title('IPython: ' + abbrev_cwd())
139 set_term_title('IPython: ' + abbrev_cwd())
140 else:
140 else:
141 toggle_set_term_title(False)
141 toggle_set_term_title(False)
142
142
143 #-------------------------------------------------------------------------
143 #-------------------------------------------------------------------------
144 # Things related to aliases
144 # Things related to aliases
145 #-------------------------------------------------------------------------
145 #-------------------------------------------------------------------------
146
146
147 def init_alias(self):
147 def init_alias(self):
148 # The parent class defines aliases that can be safely used with any
148 # The parent class defines aliases that can be safely used with any
149 # frontend.
149 # frontend.
150 super(TerminalInteractiveShell, self).init_alias()
150 super(TerminalInteractiveShell, self).init_alias()
151
151
152 # Now define aliases that only make sense on the terminal, because they
152 # Now define aliases that only make sense on the terminal, because they
153 # need direct access to the console in a way that we can't emulate in
153 # need direct access to the console in a way that we can't emulate in
154 # GUI or web frontend
154 # GUI or web frontend
155 if os.name == 'posix':
155 if os.name == 'posix':
156 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
156 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
157 ('man', 'man')]
157 ('man', 'man')]
158 elif os.name == 'nt':
158 elif os.name == 'nt':
159 aliases = [('cls', 'cls')]
159 aliases = [('cls', 'cls')]
160
160
161
161
162 for name, cmd in aliases:
162 for name, cmd in aliases:
163 self.alias_manager.define_alias(name, cmd)
163 self.alias_manager.define_alias(name, cmd)
164
164
165 #-------------------------------------------------------------------------
165 #-------------------------------------------------------------------------
166 # Things related to the banner and usage
166 # Things related to the banner and usage
167 #-------------------------------------------------------------------------
167 #-------------------------------------------------------------------------
168
168
169 def _banner1_changed(self):
169 def _banner1_changed(self):
170 self.compute_banner()
170 self.compute_banner()
171
171
172 def _banner2_changed(self):
172 def _banner2_changed(self):
173 self.compute_banner()
173 self.compute_banner()
174
174
175 def _term_title_changed(self, name, new_value):
175 def _term_title_changed(self, name, new_value):
176 self.init_term_title()
176 self.init_term_title()
177
177
178 def init_banner(self, banner1, banner2, display_banner):
178 def init_banner(self, banner1, banner2, display_banner):
179 if banner1 is not None:
179 if banner1 is not None:
180 self.banner1 = banner1
180 self.banner1 = banner1
181 if banner2 is not None:
181 if banner2 is not None:
182 self.banner2 = banner2
182 self.banner2 = banner2
183 if display_banner is not None:
183 if display_banner is not None:
184 self.display_banner = display_banner
184 self.display_banner = display_banner
185 self.compute_banner()
185 self.compute_banner()
186
186
187 def show_banner(self, banner=None):
187 def show_banner(self, banner=None):
188 if banner is None:
188 if banner is None:
189 banner = self.banner
189 banner = self.banner
190 self.write(banner)
190 self.write(banner)
191
191
192 def compute_banner(self):
192 def compute_banner(self):
193 self.banner = self.banner1
193 self.banner = self.banner1
194 if self.profile and self.profile != 'default':
194 if self.profile and self.profile != 'default':
195 self.banner += '\nIPython profile: %s\n' % self.profile
195 self.banner += '\nIPython profile: %s\n' % self.profile
196 if self.banner2:
196 if self.banner2:
197 self.banner += '\n' + self.banner2
197 self.banner += '\n' + self.banner2
198
198
199 def init_usage(self, usage=None):
199 def init_usage(self, usage=None):
200 if usage is None:
200 if usage is None:
201 self.usage = interactive_usage
201 self.usage = interactive_usage
202 else:
202 else:
203 self.usage = usage
203 self.usage = usage
204
204
205 #-------------------------------------------------------------------------
205 #-------------------------------------------------------------------------
206 # Mainloop and code execution logic
206 # Mainloop and code execution logic
207 #-------------------------------------------------------------------------
207 #-------------------------------------------------------------------------
208
208
209 def mainloop(self, display_banner=None):
209 def mainloop(self, display_banner=None):
210 """Start the mainloop.
210 """Start the mainloop.
211
211
212 If an optional banner argument is given, it will override the
212 If an optional banner argument is given, it will override the
213 internally created default banner.
213 internally created default banner.
214 """
214 """
215
215
216 with nested(self.builtin_trap, self.display_trap):
216 with nested(self.builtin_trap, self.display_trap):
217
217
218 while 1:
218 while 1:
219 try:
219 try:
220 self.interact(display_banner=display_banner)
220 self.interact(display_banner=display_banner)
221 #self.interact_with_readline()
221 #self.interact_with_readline()
222 # XXX for testing of a readline-decoupled repl loop, call
222 # XXX for testing of a readline-decoupled repl loop, call
223 # interact_with_readline above
223 # interact_with_readline above
224 break
224 break
225 except KeyboardInterrupt:
225 except KeyboardInterrupt:
226 # this should not be necessary, but KeyboardInterrupt
226 # this should not be necessary, but KeyboardInterrupt
227 # handling seems rather unpredictable...
227 # handling seems rather unpredictable...
228 self.write("\nKeyboardInterrupt in interact()\n")
228 self.write("\nKeyboardInterrupt in interact()\n")
229
229
230 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
230 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
231 """Store multiple lines as a single entry in history"""
231 """Store multiple lines as a single entry in history"""
232
232
233 # do nothing without readline or disabled multiline
233 # do nothing without readline or disabled multiline
234 if not self.has_readline or not self.multiline_history:
234 if not self.has_readline or not self.multiline_history:
235 return hlen_before_cell
235 return hlen_before_cell
236
236
237 # windows rl has no remove_history_item
237 # windows rl has no remove_history_item
238 if not hasattr(self.readline, "remove_history_item"):
238 if not hasattr(self.readline, "remove_history_item"):
239 return hlen_before_cell
239 return hlen_before_cell
240
240
241 # skip empty cells
241 # skip empty cells
242 if not source_raw.rstrip():
242 if not source_raw.rstrip():
243 return hlen_before_cell
243 return hlen_before_cell
244
244
245 # nothing changed do nothing, e.g. when rl removes consecutive dups
245 # nothing changed do nothing, e.g. when rl removes consecutive dups
246 hlen = self.readline.get_current_history_length()
246 hlen = self.readline.get_current_history_length()
247 if hlen == hlen_before_cell:
247 if hlen == hlen_before_cell:
248 return hlen_before_cell
248 return hlen_before_cell
249
249
250 for i in range(hlen - hlen_before_cell):
250 for i in range(hlen - hlen_before_cell):
251 self.readline.remove_history_item(hlen - i - 1)
251 self.readline.remove_history_item(hlen - i - 1)
252 stdin_encoding = sys.stdin.encoding or "utf-8"
252 stdin_encoding = sys.stdin.encoding or "utf-8"
253 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
253 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
254 stdin_encoding))
254 stdin_encoding))
255 return self.readline.get_current_history_length()
255 return self.readline.get_current_history_length()
256
256
257 def interact(self, display_banner=None):
257 def interact(self, display_banner=None):
258 """Closely emulate the interactive Python console."""
258 """Closely emulate the interactive Python console."""
259
259
260 # batch run -> do not interact
260 # batch run -> do not interact
261 if self.exit_now:
261 if self.exit_now:
262 return
262 return
263
263
264 if display_banner is None:
264 if display_banner is None:
265 display_banner = self.display_banner
265 display_banner = self.display_banner
266
266
267 if isinstance(display_banner, basestring):
267 if isinstance(display_banner, basestring):
268 self.show_banner(display_banner)
268 self.show_banner(display_banner)
269 elif display_banner:
269 elif display_banner:
270 self.show_banner()
270 self.show_banner()
271
271
272 more = False
272 more = False
273
273
274 # Mark activity in the builtins
274 # Mark activity in the builtins
275 __builtin__.__dict__['__IPYTHON__active'] += 1
275 __builtin__.__dict__['__IPYTHON__active'] += 1
276
276
277 if self.has_readline:
277 if self.has_readline:
278 self.readline_startup_hook(self.pre_readline)
278 self.readline_startup_hook(self.pre_readline)
279 hlen_b4_cell = self.readline.get_current_history_length()
279 hlen_b4_cell = self.readline.get_current_history_length()
280 else:
280 else:
281 hlen_b4_cell = 0
281 hlen_b4_cell = 0
282 # exit_now is set by a call to %Exit or %Quit, through the
282 # exit_now is set by a call to %Exit or %Quit, through the
283 # ask_exit callback.
283 # ask_exit callback.
284
284
285 while not self.exit_now:
285 while not self.exit_now:
286 self.hooks.pre_prompt_hook()
286 self.hooks.pre_prompt_hook()
287 if more:
287 if more:
288 try:
288 try:
289 prompt = self.hooks.generate_prompt(True)
289 prompt = self.hooks.generate_prompt(True)
290 except:
290 except:
291 self.showtraceback()
291 self.showtraceback()
292 if self.autoindent:
292 if self.autoindent:
293 self.rl_do_indent = True
293 self.rl_do_indent = True
294
294
295 else:
295 else:
296 try:
296 try:
297 prompt = self.hooks.generate_prompt(False)
297 prompt = self.hooks.generate_prompt(False)
298 except:
298 except:
299 self.showtraceback()
299 self.showtraceback()
300 try:
300 try:
301 line = self.raw_input(prompt)
301 line = self.raw_input(prompt)
302 if self.exit_now:
302 if self.exit_now:
303 # quick exit on sys.std[in|out] close
303 # quick exit on sys.std[in|out] close
304 break
304 break
305 if self.autoindent:
305 if self.autoindent:
306 self.rl_do_indent = False
306 self.rl_do_indent = False
307
307
308 except KeyboardInterrupt:
308 except KeyboardInterrupt:
309 #double-guard against keyboardinterrupts during kbdint handling
309 #double-guard against keyboardinterrupts during kbdint handling
310 try:
310 try:
311 self.write('\nKeyboardInterrupt\n')
311 self.write('\nKeyboardInterrupt\n')
312 source_raw = self.input_splitter.source_raw_reset()[1]
312 source_raw = self.input_splitter.source_raw_reset()[1]
313 hlen_b4_cell = \
313 hlen_b4_cell = \
314 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
314 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
315 more = False
315 more = False
316 except KeyboardInterrupt:
316 except KeyboardInterrupt:
317 pass
317 pass
318 except EOFError:
318 except EOFError:
319 if self.autoindent:
319 if self.autoindent:
320 self.rl_do_indent = False
320 self.rl_do_indent = False
321 if self.has_readline:
321 if self.has_readline:
322 self.readline_startup_hook(None)
322 self.readline_startup_hook(None)
323 self.write('\n')
323 self.write('\n')
324 self.exit()
324 self.exit()
325 except bdb.BdbQuit:
325 except bdb.BdbQuit:
326 warn('The Python debugger has exited with a BdbQuit exception.\n'
326 warn('The Python debugger has exited with a BdbQuit exception.\n'
327 'Because of how pdb handles the stack, it is impossible\n'
327 'Because of how pdb handles the stack, it is impossible\n'
328 'for IPython to properly format this particular exception.\n'
328 'for IPython to properly format this particular exception.\n'
329 'IPython will resume normal operation.')
329 'IPython will resume normal operation.')
330 except:
330 except:
331 # exceptions here are VERY RARE, but they can be triggered
331 # exceptions here are VERY RARE, but they can be triggered
332 # asynchronously by signal handlers, for example.
332 # asynchronously by signal handlers, for example.
333 self.showtraceback()
333 self.showtraceback()
334 else:
334 else:
335 self.input_splitter.push(line)
335 self.input_splitter.push(line)
336 more = self.input_splitter.push_accepts_more()
336 more = self.input_splitter.push_accepts_more()
337 if (self.SyntaxTB.last_syntax_error and
337 if (self.SyntaxTB.last_syntax_error and
338 self.autoedit_syntax):
338 self.autoedit_syntax):
339 self.edit_syntax_error()
339 self.edit_syntax_error()
340 if not more:
340 if not more:
341 source_raw = self.input_splitter.source_raw_reset()[1]
341 source_raw = self.input_splitter.source_raw_reset()[1]
342 self.run_cell(source_raw, store_history=True)
342 self.run_cell(source_raw, store_history=True)
343 hlen_b4_cell = \
343 hlen_b4_cell = \
344 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
344 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
345
345
346 # We are off again...
346 # We are off again...
347 __builtin__.__dict__['__IPYTHON__active'] -= 1
347 __builtin__.__dict__['__IPYTHON__active'] -= 1
348
348
349 # Turn off the exit flag, so the mainloop can be restarted if desired
349 # Turn off the exit flag, so the mainloop can be restarted if desired
350 self.exit_now = False
350 self.exit_now = False
351
351
352 def raw_input(self, prompt=''):
352 def raw_input(self, prompt=''):
353 """Write a prompt and read a line.
353 """Write a prompt and read a line.
354
354
355 The returned line does not include the trailing newline.
355 The returned line does not include the trailing newline.
356 When the user enters the EOF key sequence, EOFError is raised.
356 When the user enters the EOF key sequence, EOFError is raised.
357
357
358 Optional inputs:
358 Optional inputs:
359
359
360 - prompt(''): a string to be printed to prompt the user.
360 - prompt(''): a string to be printed to prompt the user.
361
361
362 - continue_prompt(False): whether this line is the first one or a
362 - continue_prompt(False): whether this line is the first one or a
363 continuation in a sequence of inputs.
363 continuation in a sequence of inputs.
364 """
364 """
365 # Code run by the user may have modified the readline completer state.
365 # Code run by the user may have modified the readline completer state.
366 # We must ensure that our completer is back in place.
366 # We must ensure that our completer is back in place.
367
367
368 if self.has_readline:
368 if self.has_readline:
369 self.set_readline_completer()
369 self.set_readline_completer()
370
370
371 try:
371 try:
372 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
372 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
373 except ValueError:
373 except ValueError:
374 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
374 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
375 " or sys.stdout.close()!\nExiting IPython!")
375 " or sys.stdout.close()!\nExiting IPython!")
376 self.ask_exit()
376 self.ask_exit()
377 return ""
377 return ""
378
378
379 # Try to be reasonably smart about not re-indenting pasted input more
379 # Try to be reasonably smart about not re-indenting pasted input more
380 # than necessary. We do this by trimming out the auto-indent initial
380 # than necessary. We do this by trimming out the auto-indent initial
381 # spaces, if the user's actual input started itself with whitespace.
381 # spaces, if the user's actual input started itself with whitespace.
382 if self.autoindent:
382 if self.autoindent:
383 if num_ini_spaces(line) > self.indent_current_nsp:
383 if num_ini_spaces(line) > self.indent_current_nsp:
384 line = line[self.indent_current_nsp:]
384 line = line[self.indent_current_nsp:]
385 self.indent_current_nsp = 0
385 self.indent_current_nsp = 0
386
386
387 return line
387 return line
388
388
389 #-------------------------------------------------------------------------
389 #-------------------------------------------------------------------------
390 # Methods to support auto-editing of SyntaxErrors.
390 # Methods to support auto-editing of SyntaxErrors.
391 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
392
392
393 def edit_syntax_error(self):
393 def edit_syntax_error(self):
394 """The bottom half of the syntax error handler called in the main loop.
394 """The bottom half of the syntax error handler called in the main loop.
395
395
396 Loop until syntax error is fixed or user cancels.
396 Loop until syntax error is fixed or user cancels.
397 """
397 """
398
398
399 while self.SyntaxTB.last_syntax_error:
399 while self.SyntaxTB.last_syntax_error:
400 # copy and clear last_syntax_error
400 # copy and clear last_syntax_error
401 err = self.SyntaxTB.clear_err_state()
401 err = self.SyntaxTB.clear_err_state()
402 if not self._should_recompile(err):
402 if not self._should_recompile(err):
403 return
403 return
404 try:
404 try:
405 # may set last_syntax_error again if a SyntaxError is raised
405 # may set last_syntax_error again if a SyntaxError is raised
406 self.safe_execfile(err.filename,self.user_ns)
406 self.safe_execfile(err.filename,self.user_ns)
407 except:
407 except:
408 self.showtraceback()
408 self.showtraceback()
409 else:
409 else:
410 try:
410 try:
411 f = file(err.filename)
411 f = file(err.filename)
412 try:
412 try:
413 # This should be inside a display_trap block and I
413 # This should be inside a display_trap block and I
414 # think it is.
414 # think it is.
415 sys.displayhook(f.read())
415 sys.displayhook(f.read())
416 finally:
416 finally:
417 f.close()
417 f.close()
418 except:
418 except:
419 self.showtraceback()
419 self.showtraceback()
420
420
421 def _should_recompile(self,e):
421 def _should_recompile(self,e):
422 """Utility routine for edit_syntax_error"""
422 """Utility routine for edit_syntax_error"""
423
423
424 if e.filename in ('<ipython console>','<input>','<string>',
424 if e.filename in ('<ipython console>','<input>','<string>',
425 '<console>','<BackgroundJob compilation>',
425 '<console>','<BackgroundJob compilation>',
426 None):
426 None):
427
427
428 return False
428 return False
429 try:
429 try:
430 if (self.autoedit_syntax and
430 if (self.autoedit_syntax and
431 not self.ask_yes_no('Return to editor to correct syntax error? '
431 not self.ask_yes_no('Return to editor to correct syntax error? '
432 '[Y/n] ','y')):
432 '[Y/n] ','y')):
433 return False
433 return False
434 except EOFError:
434 except EOFError:
435 return False
435 return False
436
436
437 def int0(x):
437 def int0(x):
438 try:
438 try:
439 return int(x)
439 return int(x)
440 except TypeError:
440 except TypeError:
441 return 0
441 return 0
442 # always pass integer line and offset values to editor hook
442 # always pass integer line and offset values to editor hook
443 try:
443 try:
444 self.hooks.fix_error_editor(e.filename,
444 self.hooks.fix_error_editor(e.filename,
445 int0(e.lineno),int0(e.offset),e.msg)
445 int0(e.lineno),int0(e.offset),e.msg)
446 except TryNext:
446 except TryNext:
447 warn('Could not open editor')
447 warn('Could not open editor')
448 return False
448 return False
449 return True
449 return True
450
450
451 #-------------------------------------------------------------------------
451 #-------------------------------------------------------------------------
452 # Things related to GUI support and pylab
452 # Things related to GUI support and pylab
453 #-------------------------------------------------------------------------
453 #-------------------------------------------------------------------------
454
454
455 def enable_pylab(self, gui=None, import_all=True):
455 def enable_pylab(self, gui=None, import_all=True):
456 """Activate pylab support at runtime.
456 """Activate pylab support at runtime.
457
457
458 This turns on support for matplotlib, preloads into the interactive
458 This turns on support for matplotlib, preloads into the interactive
459 namespace all of numpy and pylab, and configures IPython to correcdtly
459 namespace all of numpy and pylab, and configures IPython to correcdtly
460 interact with the GUI event loop. The GUI backend to be used can be
460 interact with the GUI event loop. The GUI backend to be used can be
461 optionally selected with the optional :param:`gui` argument.
461 optionally selected with the optional :param:`gui` argument.
462
462
463 Parameters
463 Parameters
464 ----------
464 ----------
465 gui : optional, string
465 gui : optional, string
466
466
467 If given, dictates the choice of matplotlib GUI backend to use
467 If given, dictates the choice of matplotlib GUI backend to use
468 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
468 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
469 'gtk'), otherwise we use the default chosen by matplotlib (as
469 'gtk'), otherwise we use the default chosen by matplotlib (as
470 dictated by the matplotlib build-time options plus the user's
470 dictated by the matplotlib build-time options plus the user's
471 matplotlibrc configuration file).
471 matplotlibrc configuration file).
472 """
472 """
473 # We want to prevent the loading of pylab to pollute the user's
473 # We want to prevent the loading of pylab to pollute the user's
474 # namespace as shown by the %who* magics, so we execute the activation
474 # namespace as shown by the %who* magics, so we execute the activation
475 # code in an empty namespace, and we update *both* user_ns and
475 # code in an empty namespace, and we update *both* user_ns and
476 # user_ns_hidden with this information.
476 # user_ns_hidden with this information.
477 ns = {}
477 ns = {}
478 try:
478 try:
479 gui = pylab_activate(ns, gui, import_all)
479 gui = pylab_activate(ns, gui, import_all)
480 except KeyError:
480 except KeyError:
481 error("Backend %r not supported" % gui)
481 error("Backend %r not supported" % gui)
482 return
482 return
483 self.user_ns.update(ns)
483 self.user_ns.update(ns)
484 self.user_ns_hidden.update(ns)
484 self.user_ns_hidden.update(ns)
485 # Now we must activate the gui pylab wants to use, and fix %run to take
485 # Now we must activate the gui pylab wants to use, and fix %run to take
486 # plot updates into account
486 # plot updates into account
487 enable_gui(gui)
487 enable_gui(gui)
488 self.magic_run = self._pylab_magic_run
488 self.magic_run = self._pylab_magic_run
489
489
490 #-------------------------------------------------------------------------
490 #-------------------------------------------------------------------------
491 # Things related to exiting
491 # Things related to exiting
492 #-------------------------------------------------------------------------
492 #-------------------------------------------------------------------------
493
493
494 def ask_exit(self):
494 def ask_exit(self):
495 """ Ask the shell to exit. Can be overiden and used as a callback. """
495 """ Ask the shell to exit. Can be overiden and used as a callback. """
496 self.exit_now = True
496 self.exit_now = True
497
497
498 def exit(self):
498 def exit(self):
499 """Handle interactive exit.
499 """Handle interactive exit.
500
500
501 This method calls the ask_exit callback."""
501 This method calls the ask_exit callback."""
502 if self.confirm_exit:
502 if self.confirm_exit:
503 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
503 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
504 self.ask_exit()
504 self.ask_exit()
505 else:
505 else:
506 self.ask_exit()
506 self.ask_exit()
507
507
508 #------------------------------------------------------------------------
508 #------------------------------------------------------------------------
509 # Magic overrides
509 # Magic overrides
510 #------------------------------------------------------------------------
510 #------------------------------------------------------------------------
511 # Once the base class stops inheriting from magic, this code needs to be
511 # Once the base class stops inheriting from magic, this code needs to be
512 # moved into a separate machinery as well. For now, at least isolate here
512 # moved into a separate machinery as well. For now, at least isolate here
513 # the magics which this class needs to implement differently from the base
513 # the magics which this class needs to implement differently from the base
514 # class, or that are unique to it.
514 # class, or that are unique to it.
515
515
516 def magic_autoindent(self, parameter_s = ''):
516 def magic_autoindent(self, parameter_s = ''):
517 """Toggle autoindent on/off (if available)."""
517 """Toggle autoindent on/off (if available)."""
518
518
519 self.shell.set_autoindent()
519 self.shell.set_autoindent()
520 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
520 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
521
521
522 @skip_doctest
522 @skip_doctest
523 def magic_cpaste(self, parameter_s=''):
523 def magic_cpaste(self, parameter_s=''):
524 """Paste & execute a pre-formatted code block from clipboard.
524 """Paste & execute a pre-formatted code block from clipboard.
525
525
526 You must terminate the block with '--' (two minus-signs) or Ctrl-D alone on the
526 You must terminate the block with '--' (two minus-signs) or Ctrl-D alone on the
527 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
527 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
528 is the new sentinel for this operation)
528 is the new sentinel for this operation)
529
529
530 The block is dedented prior to execution to enable execution of method
530 The block is dedented prior to execution to enable execution of method
531 definitions. '>' and '+' characters at the beginning of a line are
531 definitions. '>' and '+' characters at the beginning of a line are
532 ignored, to allow pasting directly from e-mails, diff files and
532 ignored, to allow pasting directly from e-mails, diff files and
533 doctests (the '...' continuation prompt is also stripped). The
533 doctests (the '...' continuation prompt is also stripped). The
534 executed block is also assigned to variable named 'pasted_block' for
534 executed block is also assigned to variable named 'pasted_block' for
535 later editing with '%edit pasted_block'.
535 later editing with '%edit pasted_block'.
536
536
537 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
537 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
538 This assigns the pasted block to variable 'foo' as string, without
538 This assigns the pasted block to variable 'foo' as string, without
539 dedenting or executing it (preceding >>> and + is still stripped)
539 dedenting or executing it (preceding >>> and + is still stripped)
540
540
541 '%cpaste -r' re-executes the block previously entered by cpaste.
541 '%cpaste -r' re-executes the block previously entered by cpaste.
542
542
543 Do not be alarmed by garbled output on Windows (it's a readline bug).
543 Do not be alarmed by garbled output on Windows (it's a readline bug).
544 Just press enter and type -- (and press enter again) and the block
544 Just press enter and type -- (and press enter again) and the block
545 will be what was just pasted.
545 will be what was just pasted.
546
546
547 IPython statements (magics, shell escapes) are not supported (yet).
547 IPython statements (magics, shell escapes) are not supported (yet).
548
548
549 See also
549 See also
550 --------
550 --------
551 paste: automatically pull code from clipboard.
551 paste: automatically pull code from clipboard.
552
552
553 Examples
553 Examples
554 --------
554 --------
555 ::
555 ::
556
556
557 In [8]: %cpaste
557 In [8]: %cpaste
558 Pasting code; enter '--' alone on the line to stop.
558 Pasting code; enter '--' alone on the line to stop.
559 :>>> a = ["world!", "Hello"]
559 :>>> a = ["world!", "Hello"]
560 :>>> print " ".join(sorted(a))
560 :>>> print " ".join(sorted(a))
561 :--
561 :--
562 Hello world!
562 Hello world!
563 """
563 """
564
564
565 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
565 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
566 par = args.strip()
566 par = args.strip()
567 if opts.has_key('r'):
567 if opts.has_key('r'):
568 self._rerun_pasted()
568 self._rerun_pasted()
569 return
569 return
570
570
571 sentinel = opts.get('s','--')
571 sentinel = opts.get('s','--')
572
572
573 block = self._strip_pasted_lines_for_code(
573 block = self._strip_pasted_lines_for_code(
574 self._get_pasted_lines(sentinel))
574 self._get_pasted_lines(sentinel))
575
575
576 self._execute_block(block, par)
576 self._execute_block(block, par)
577
577
578 def magic_paste(self, parameter_s=''):
578 def magic_paste(self, parameter_s=''):
579 """Paste & execute a pre-formatted code block from clipboard.
579 """Paste & execute a pre-formatted code block from clipboard.
580
580
581 The text is pulled directly from the clipboard without user
581 The text is pulled directly from the clipboard without user
582 intervention and printed back on the screen before execution (unless
582 intervention and printed back on the screen before execution (unless
583 the -q flag is given to force quiet mode).
583 the -q flag is given to force quiet mode).
584
584
585 The block is dedented prior to execution to enable execution of method
585 The block is dedented prior to execution to enable execution of method
586 definitions. '>' and '+' characters at the beginning of a line are
586 definitions. '>' and '+' characters at the beginning of a line are
587 ignored, to allow pasting directly from e-mails, diff files and
587 ignored, to allow pasting directly from e-mails, diff files and
588 doctests (the '...' continuation prompt is also stripped). The
588 doctests (the '...' continuation prompt is also stripped). The
589 executed block is also assigned to variable named 'pasted_block' for
589 executed block is also assigned to variable named 'pasted_block' for
590 later editing with '%edit pasted_block'.
590 later editing with '%edit pasted_block'.
591
591
592 You can also pass a variable name as an argument, e.g. '%paste foo'.
592 You can also pass a variable name as an argument, e.g. '%paste foo'.
593 This assigns the pasted block to variable 'foo' as string, without
593 This assigns the pasted block to variable 'foo' as string, without
594 dedenting or executing it (preceding >>> and + is still stripped)
594 dedenting or executing it (preceding >>> and + is still stripped)
595
595
596 Options
596 Options
597 -------
597 -------
598
598
599 -r: re-executes the block previously entered by cpaste.
599 -r: re-executes the block previously entered by cpaste.
600
600
601 -q: quiet mode: do not echo the pasted text back to the terminal.
601 -q: quiet mode: do not echo the pasted text back to the terminal.
602
602
603 IPython statements (magics, shell escapes) are not supported (yet).
603 IPython statements (magics, shell escapes) are not supported (yet).
604
604
605 See also
605 See also
606 --------
606 --------
607 cpaste: manually paste code into terminal until you mark its end.
607 cpaste: manually paste code into terminal until you mark its end.
608 """
608 """
609 opts,args = self.parse_options(parameter_s,'rq',mode='string')
609 opts,args = self.parse_options(parameter_s,'rq',mode='string')
610 par = args.strip()
610 par = args.strip()
611 if opts.has_key('r'):
611 if opts.has_key('r'):
612 self._rerun_pasted()
612 self._rerun_pasted()
613 return
613 return
614
614 try:
615 text = self.shell.hooks.clipboard_get()
615 text = self.shell.hooks.clipboard_get()
616 block = self._strip_pasted_lines_for_code(text.splitlines())
616 block = self._strip_pasted_lines_for_code(text.splitlines())
617 except TryNext as clipboard_exc:
618 message = getattr(clipboard_exc, 'args')
619 if message:
620 error(message[0])
621 else:
622 error('Could not get text from the clipboard.')
623 return
617
624
618 # By default, echo back to terminal unless quiet mode is requested
625 # By default, echo back to terminal unless quiet mode is requested
619 if not opts.has_key('q'):
626 if not opts.has_key('q'):
620 write = self.shell.write
627 write = self.shell.write
621 write(self.shell.pycolorize(block))
628 write(self.shell.pycolorize(block))
622 if not block.endswith('\n'):
629 if not block.endswith('\n'):
623 write('\n')
630 write('\n')
624 write("## -- End pasted text --\n")
631 write("## -- End pasted text --\n")
625
632
626 self._execute_block(block, par)
633 self._execute_block(block, par)
627
634
628 if sys.platform == 'win32':
635 if sys.platform == 'win32':
629 def magic_cls(self, s):
636 def magic_cls(self, s):
630 """Clear screen.
637 """Clear screen.
631 """
638 """
632 os.system("cls")
639 os.system("cls")
633
640
634 def showindentationerror(self):
641 def showindentationerror(self):
635 super(TerminalInteractiveShell, self).showindentationerror()
642 super(TerminalInteractiveShell, self).showindentationerror()
636 print("If you want to paste code into IPython, try the %paste magic function.")
643 print("If you want to paste code into IPython, try the %paste magic function.")
637
644
638
645
639 InteractiveShellABC.register(TerminalInteractiveShell)
646 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now