##// END OF EJS Templates
Aliases fixes: ls alias improvements and frontend-dependent fixes....
Fernando Perez -
Show More
@@ -1,258 +1,264 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 System command aliases.
4 System command aliases.
5
5
6 Authors:
6 Authors:
7
7
8 * Fernando Perez
8 * Fernando Perez
9 * Brian Granger
9 * Brian Granger
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2010 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License.
16 # the file COPYING, distributed as part of this software.
16 #
17 # The full license is in the file COPYING.txt, distributed with this software.
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18
19
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20 # Imports
21 # Imports
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22
23
23 import __builtin__
24 import __builtin__
24 import keyword
25 import keyword
25 import os
26 import os
26 import re
27 import re
27 import sys
28 import sys
28
29
29 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
30 from IPython.core.splitinput import split_user_input
31 from IPython.core.splitinput import split_user_input
31
32
32 from IPython.utils.traitlets import List, Instance
33 from IPython.utils.traitlets import List, Instance
33 from IPython.utils.autoattr import auto_attr
34 from IPython.utils.autoattr import auto_attr
34 from IPython.utils.warn import warn, error
35 from IPython.utils.warn import warn, error
35
36
36 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
37 # Utilities
38 # Utilities
38 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
39
40
40 # This is used as the pattern for calls to split_user_input.
41 # This is used as the pattern for calls to split_user_input.
41 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
42 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
42
43
43 def default_aliases():
44 def default_aliases():
44 # Make some aliases automatically
45 """Return list of shell aliases to auto-define.
45 # Prepare list of shell aliases to auto-define
46 """
47 # Note: the aliases defined here should be safe to use on a kernel
48 # regardless of what frontend it is attached to. Frontends that use a
49 # kernel in-process can define additional aliases that will only work in
50 # their case. For example, things like 'less' or 'clear' that manipulate
51 # the terminal should NOT be declared here, as they will only work if the
52 # kernel is running inside a true terminal, and not over the network.
53
46 if os.name == 'posix':
54 if os.name == 'posix':
47 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
55 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
48 'mv mv -i','rm rm -i','cp cp -i',
56 ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'),
49 'cat cat','less less','clear clear',
57 ('cat', 'cat'),
50 # a better ls
58 ]
51 'ls ls -F',
59 # Useful set of ls aliases. The GNU and BSD options are a little
52 # long ls
60 # different, so we make aliases that provide as similar as possible
53 'll ls -lF')
61 # behavior in ipython, by passing the right flags for each platform
54 # Extra ls aliases with color, which need special treatment on BSD
62 if sys.platform.startswith('linux'):
55 # variants
63 ls_aliases = [('ls', 'ls -F --color'),
56 ls_extra = ( # color ls
64 # long ls
57 'lc ls -F -o --color',
65 ('ll', 'ls -F -o --color'),
58 # ls normal files only
66 # ls normal files only
59 'lf ls -F -o --color %l | grep ^-',
67 ('lf', 'ls -F -o --color %l | grep ^-'),
60 # ls symbolic links
68 # ls symbolic links
61 'lk ls -F -o --color %l | grep ^l',
69 ('lk', 'ls -F -o --color %l | grep ^l'),
62 # directories or links to directories,
70 # directories or links to directories,
63 'ldir ls -F -o --color %l | grep /$',
71 ('ldir', 'ls -F -o --color %l | grep /$'),
64 # things which are executable
72 # things which are executable
65 'lx ls -F -o --color %l | grep ^-..x',
73 ('lx', 'ls -F -o --color %l | grep ^-..x'),
66 )
74 ]
67 # The BSDs don't ship GNU ls, so they don't understand the
75 else:
68 # --color switch out of the box
76 # BSD, OSX, etc.
69 if 'bsd' in sys.platform:
77 ls_aliases = [('ls', 'ls -F'),
70 ls_extra = ( # ls normal files only
78 # long ls
71 'lf ls -lF | grep ^-',
79 ('ll', 'ls -F -l'),
72 # ls symbolic links
80 # ls normal files only
73 'lk ls -lF | grep ^l',
81 ('lf', 'ls -F -l %l | grep ^-'),
74 # directories or links to directories,
82 # ls symbolic links
75 'ldir ls -lF | grep /$',
83 ('lk', 'ls -F -l %l | grep ^l'),
76 # things which are executable
84 # directories or links to directories,
77 'lx ls -lF | grep ^-..x',
85 ('ldir', 'ls -F -l %l | grep /$'),
78 )
86 # things which are executable
79 default_aliases = default_aliases + ls_extra
87 ('lx', 'ls -F -l %l | grep ^-..x'),
80 elif os.name in ['nt','dos']:
88 ]
81 default_aliases = ('ls dir /on',
89 default_aliases = default_aliases + ls_aliases
82 'ddir dir /ad /on', 'ldir dir /ad /on',
90 elif os.name in ['nt', 'dos']:
83 'mkdir mkdir','rmdir rmdir','echo echo',
91 default_aliases = [('ls', 'dir /on'),
84 'ren ren','cls cls','copy copy')
92 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
93 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
94 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
95 ]
85 else:
96 else:
86 default_aliases = ()
97 default_aliases = []
87 return [s.split(None,1) for s in default_aliases]
98
99 return default_aliases
88
100
89
101
90 class AliasError(Exception):
102 class AliasError(Exception):
91 pass
103 pass
92
104
93
105
94 class InvalidAliasError(AliasError):
106 class InvalidAliasError(AliasError):
95 pass
107 pass
96
108
97
98 #-----------------------------------------------------------------------------
109 #-----------------------------------------------------------------------------
99 # Main AliasManager class
110 # Main AliasManager class
100 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
101
112
102
103 class AliasManager(Configurable):
113 class AliasManager(Configurable):
104
114
105 default_aliases = List(default_aliases(), config=True)
115 default_aliases = List(default_aliases(), config=True)
106 user_aliases = List(default_value=[], config=True)
116 user_aliases = List(default_value=[], config=True)
107 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
117 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
108
118
109 def __init__(self, shell=None, config=None):
119 def __init__(self, shell=None, config=None):
110 super(AliasManager, self).__init__(shell=shell, config=config)
120 super(AliasManager, self).__init__(shell=shell, config=config)
111 self.alias_table = {}
121 self.alias_table = {}
112 self.exclude_aliases()
122 self.exclude_aliases()
113 self.init_aliases()
123 self.init_aliases()
114
124
115 def __contains__(self, name):
125 def __contains__(self, name):
116 if name in self.alias_table:
126 return name in self.alias_table
117 return True
118 else:
119 return False
120
127
121 @property
128 @property
122 def aliases(self):
129 def aliases(self):
123 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
130 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
124
131
125 def exclude_aliases(self):
132 def exclude_aliases(self):
126 # set of things NOT to alias (keywords, builtins and some magics)
133 # set of things NOT to alias (keywords, builtins and some magics)
127 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
134 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
128 no_alias.update(set(keyword.kwlist))
135 no_alias.update(set(keyword.kwlist))
129 no_alias.update(set(__builtin__.__dict__.keys()))
136 no_alias.update(set(__builtin__.__dict__.keys()))
130 self.no_alias = no_alias
137 self.no_alias = no_alias
131
138
132 def init_aliases(self):
139 def init_aliases(self):
133 # Load default aliases
140 # Load default aliases
134 for name, cmd in self.default_aliases:
141 for name, cmd in self.default_aliases:
135 self.soft_define_alias(name, cmd)
142 self.soft_define_alias(name, cmd)
136
143
137 # Load user aliases
144 # Load user aliases
138 for name, cmd in self.user_aliases:
145 for name, cmd in self.user_aliases:
139 self.soft_define_alias(name, cmd)
146 self.soft_define_alias(name, cmd)
140
147
141 def clear_aliases(self):
148 def clear_aliases(self):
142 self.alias_table.clear()
149 self.alias_table.clear()
143
150
144 def soft_define_alias(self, name, cmd):
151 def soft_define_alias(self, name, cmd):
145 """Define an alias, but don't raise on an AliasError."""
152 """Define an alias, but don't raise on an AliasError."""
146 try:
153 try:
147 self.define_alias(name, cmd)
154 self.define_alias(name, cmd)
148 except AliasError, e:
155 except AliasError, e:
149 error("Invalid alias: %s" % e)
156 error("Invalid alias: %s" % e)
150
157
151 def define_alias(self, name, cmd):
158 def define_alias(self, name, cmd):
152 """Define a new alias after validating it.
159 """Define a new alias after validating it.
153
160
154 This will raise an :exc:`AliasError` if there are validation
161 This will raise an :exc:`AliasError` if there are validation
155 problems.
162 problems.
156 """
163 """
157 nargs = self.validate_alias(name, cmd)
164 nargs = self.validate_alias(name, cmd)
158 self.alias_table[name] = (nargs, cmd)
165 self.alias_table[name] = (nargs, cmd)
159
166
160 def undefine_alias(self, name):
167 def undefine_alias(self, name):
161 if self.alias_table.has_key(name):
168 if self.alias_table.has_key(name):
162 del self.alias_table[name]
169 del self.alias_table[name]
163
170
164 def validate_alias(self, name, cmd):
171 def validate_alias(self, name, cmd):
165 """Validate an alias and return the its number of arguments."""
172 """Validate an alias and return the its number of arguments."""
166 if name in self.no_alias:
173 if name in self.no_alias:
167 raise InvalidAliasError("The name %s can't be aliased "
174 raise InvalidAliasError("The name %s can't be aliased "
168 "because it is a keyword or builtin." % name)
175 "because it is a keyword or builtin." % name)
169 if not (isinstance(cmd, basestring)):
176 if not (isinstance(cmd, basestring)):
170 raise InvalidAliasError("An alias command must be a string, "
177 raise InvalidAliasError("An alias command must be a string, "
171 "got: %r" % name)
178 "got: %r" % name)
172 nargs = cmd.count('%s')
179 nargs = cmd.count('%s')
173 if nargs>0 and cmd.find('%l')>=0:
180 if nargs>0 and cmd.find('%l')>=0:
174 raise InvalidAliasError('The %s and %l specifiers are mutually '
181 raise InvalidAliasError('The %s and %l specifiers are mutually '
175 'exclusive in alias definitions.')
182 'exclusive in alias definitions.')
176 return nargs
183 return nargs
177
184
178 def call_alias(self, alias, rest=''):
185 def call_alias(self, alias, rest=''):
179 """Call an alias given its name and the rest of the line."""
186 """Call an alias given its name and the rest of the line."""
180 cmd = self.transform_alias(alias, rest)
187 cmd = self.transform_alias(alias, rest)
181 try:
188 try:
182 self.shell.system(cmd)
189 self.shell.system(cmd)
183 except:
190 except:
184 self.shell.showtraceback()
191 self.shell.showtraceback()
185
192
186 def transform_alias(self, alias,rest=''):
193 def transform_alias(self, alias,rest=''):
187 """Transform alias to system command string."""
194 """Transform alias to system command string."""
188 nargs, cmd = self.alias_table[alias]
195 nargs, cmd = self.alias_table[alias]
189
196
190 if ' ' in cmd and os.path.isfile(cmd):
197 if ' ' in cmd and os.path.isfile(cmd):
191 cmd = '"%s"' % cmd
198 cmd = '"%s"' % cmd
192
199
193 # Expand the %l special to be the user's input line
200 # Expand the %l special to be the user's input line
194 if cmd.find('%l') >= 0:
201 if cmd.find('%l') >= 0:
195 cmd = cmd.replace('%l', rest)
202 cmd = cmd.replace('%l', rest)
196 rest = ''
203 rest = ''
197 if nargs==0:
204 if nargs==0:
198 # Simple, argument-less aliases
205 # Simple, argument-less aliases
199 cmd = '%s %s' % (cmd, rest)
206 cmd = '%s %s' % (cmd, rest)
200 else:
207 else:
201 # Handle aliases with positional arguments
208 # Handle aliases with positional arguments
202 args = rest.split(None, nargs)
209 args = rest.split(None, nargs)
203 if len(args) < nargs:
210 if len(args) < nargs:
204 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
211 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
205 (alias, nargs, len(args)))
212 (alias, nargs, len(args)))
206 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
213 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
207 return cmd
214 return cmd
208
215
209 def expand_alias(self, line):
216 def expand_alias(self, line):
210 """ Expand an alias in the command line
217 """ Expand an alias in the command line
211
218
212 Returns the provided command line, possibly with the first word
219 Returns the provided command line, possibly with the first word
213 (command) translated according to alias expansion rules.
220 (command) translated according to alias expansion rules.
214
221
215 [ipython]|16> _ip.expand_aliases("np myfile.txt")
222 [ipython]|16> _ip.expand_aliases("np myfile.txt")
216 <16> 'q:/opt/np/notepad++.exe myfile.txt'
223 <16> 'q:/opt/np/notepad++.exe myfile.txt'
217 """
224 """
218
225
219 pre,fn,rest = split_user_input(line)
226 pre,fn,rest = split_user_input(line)
220 res = pre + self.expand_aliases(fn, rest)
227 res = pre + self.expand_aliases(fn, rest)
221 return res
228 return res
222
229
223 def expand_aliases(self, fn, rest):
230 def expand_aliases(self, fn, rest):
224 """Expand multiple levels of aliases:
231 """Expand multiple levels of aliases:
225
232
226 if:
233 if:
227
234
228 alias foo bar /tmp
235 alias foo bar /tmp
229 alias baz foo
236 alias baz foo
230
237
231 then:
238 then:
232
239
233 baz huhhahhei -> bar /tmp huhhahhei
240 baz huhhahhei -> bar /tmp huhhahhei
234
235 """
241 """
236 line = fn + " " + rest
242 line = fn + " " + rest
237
243
238 done = set()
244 done = set()
239 while 1:
245 while 1:
240 pre,fn,rest = split_user_input(line, shell_line_split)
246 pre,fn,rest = split_user_input(line, shell_line_split)
241 if fn in self.alias_table:
247 if fn in self.alias_table:
242 if fn in done:
248 if fn in done:
243 warn("Cyclic alias definition, repeated '%s'" % fn)
249 warn("Cyclic alias definition, repeated '%s'" % fn)
244 return ""
250 return ""
245 done.add(fn)
251 done.add(fn)
246
252
247 l2 = self.transform_alias(fn, rest)
253 l2 = self.transform_alias(fn, rest)
248 if l2 == line:
254 if l2 == line:
249 break
255 break
250 # ls -> ls -F should not recurse forever
256 # ls -> ls -F should not recurse forever
251 if l2.split(None,1)[0] == line.split(None,1)[0]:
257 if l2.split(None,1)[0] == line.split(None,1)[0]:
252 line = l2
258 line = l2
253 break
259 break
254 line=l2
260 line=l2
255 else:
261 else:
256 break
262 break
257
263
258 return line
264 return line
@@ -1,630 +1,652 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.inputlist import InputList
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
29 from IPython.lib.pylabtools import pylab_activate
30 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
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
34 from IPython.utils.traitlets import Int, Str, CBool
35
35
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Utilities
38 # Utilities
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 def get_default_editor():
42 def get_default_editor():
43 try:
43 try:
44 ed = os.environ['EDITOR']
44 ed = os.environ['EDITOR']
45 except KeyError:
45 except KeyError:
46 if os.name == 'posix':
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
48 else:
49 ed = 'notepad' # same in Windows!
49 ed = 'notepad' # same in Windows!
50 return ed
50 return ed
51
51
52
52
53 # store the builtin raw_input globally, and use this always, in case user code
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
55 raw_input_original = raw_input
56
56
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # Main class
59 # Main class
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62
62
63 class TerminalInteractiveShell(InteractiveShell):
63 class TerminalInteractiveShell(InteractiveShell):
64
64
65 autoedit_syntax = CBool(False, config=True)
65 autoedit_syntax = CBool(False, config=True)
66 banner = Str('')
66 banner = Str('')
67 banner1 = Str(default_banner, config=True)
67 banner1 = Str(default_banner, config=True)
68 banner2 = Str('', config=True)
68 banner2 = Str('', config=True)
69 confirm_exit = CBool(True, config=True)
69 confirm_exit = CBool(True, config=True)
70 # This display_banner only controls whether or not self.show_banner()
70 # This display_banner only controls whether or not self.show_banner()
71 # is called when mainloop/interact are called. The default is False
71 # is called when mainloop/interact are called. The default is False
72 # because for the terminal based application, the banner behavior
72 # because for the terminal based application, the banner behavior
73 # is controlled by Global.display_banner, which IPythonApp looks at
73 # is controlled by Global.display_banner, which IPythonApp looks at
74 # to determine if *it* should call show_banner() by hand or not.
74 # to determine if *it* should call show_banner() by hand or not.
75 display_banner = CBool(False) # This isn't configurable!
75 display_banner = CBool(False) # This isn't configurable!
76 embedded = CBool(False)
76 embedded = CBool(False)
77 embedded_active = CBool(False)
77 embedded_active = CBool(False)
78 editor = Str(get_default_editor(), config=True)
78 editor = Str(get_default_editor(), config=True)
79 pager = Str('less', config=True)
79 pager = Str('less', config=True)
80
80
81 screen_length = Int(0, config=True)
81 screen_length = Int(0, config=True)
82 term_title = CBool(False, config=True)
82 term_title = CBool(False, config=True)
83
83
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 user_global_ns=None, custom_exceptions=((),None),
85 user_global_ns=None, custom_exceptions=((),None),
86 usage=None, banner1=None, banner2=None,
86 usage=None, banner1=None, banner2=None,
87 display_banner=None):
87 display_banner=None):
88
88
89 super(TerminalInteractiveShell, self).__init__(
89 super(TerminalInteractiveShell, self).__init__(
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 )
92 )
93 self.init_term_title()
93 self.init_term_title()
94 self.init_usage(usage)
94 self.init_usage(usage)
95 self.init_banner(banner1, banner2, display_banner)
95 self.init_banner(banner1, banner2, display_banner)
96
96
97 #-------------------------------------------------------------------------
97 #-------------------------------------------------------------------------
98 # Things related to the terminal
98 # Things related to the terminal
99 #-------------------------------------------------------------------------
99 #-------------------------------------------------------------------------
100
100
101 @property
101 @property
102 def usable_screen_length(self):
102 def usable_screen_length(self):
103 if self.screen_length == 0:
103 if self.screen_length == 0:
104 return 0
104 return 0
105 else:
105 else:
106 num_lines_bot = self.separate_in.count('\n')+1
106 num_lines_bot = self.separate_in.count('\n')+1
107 return self.screen_length - num_lines_bot
107 return self.screen_length - num_lines_bot
108
108
109 def init_term_title(self):
109 def init_term_title(self):
110 # Enable or disable the terminal title.
110 # Enable or disable the terminal title.
111 if self.term_title:
111 if self.term_title:
112 toggle_set_term_title(True)
112 toggle_set_term_title(True)
113 set_term_title('IPython: ' + abbrev_cwd())
113 set_term_title('IPython: ' + abbrev_cwd())
114 else:
114 else:
115 toggle_set_term_title(False)
115 toggle_set_term_title(False)
116
116
117 #-------------------------------------------------------------------------
117 #-------------------------------------------------------------------------
118 # Things related to aliases
119 #-------------------------------------------------------------------------
120
121 def init_alias(self):
122 # The parent class defines aliases that can be safely used with any
123 # frontend.
124 super(TerminalInteractiveShell, self).init_alias()
125
126 # Now define aliases that only make sense on the terminal, because they
127 # need direct access to the console in a way that we can't emulate in
128 # GUI or web frontend
129 if os.name == 'posix':
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
131 ('man', 'man')]
132 elif os.name == 'nt':
133 aliases = [('cls', 'cls')]
134
135
136 for name, cmd in aliases:
137 self.alias_manager.define_alias(name, cmd)
138
139 #-------------------------------------------------------------------------
118 # Things related to the banner and usage
140 # Things related to the banner and usage
119 #-------------------------------------------------------------------------
141 #-------------------------------------------------------------------------
120
142
121 def _banner1_changed(self):
143 def _banner1_changed(self):
122 self.compute_banner()
144 self.compute_banner()
123
145
124 def _banner2_changed(self):
146 def _banner2_changed(self):
125 self.compute_banner()
147 self.compute_banner()
126
148
127 def _term_title_changed(self, name, new_value):
149 def _term_title_changed(self, name, new_value):
128 self.init_term_title()
150 self.init_term_title()
129
151
130 def init_banner(self, banner1, banner2, display_banner):
152 def init_banner(self, banner1, banner2, display_banner):
131 if banner1 is not None:
153 if banner1 is not None:
132 self.banner1 = banner1
154 self.banner1 = banner1
133 if banner2 is not None:
155 if banner2 is not None:
134 self.banner2 = banner2
156 self.banner2 = banner2
135 if display_banner is not None:
157 if display_banner is not None:
136 self.display_banner = display_banner
158 self.display_banner = display_banner
137 self.compute_banner()
159 self.compute_banner()
138
160
139 def show_banner(self, banner=None):
161 def show_banner(self, banner=None):
140 if banner is None:
162 if banner is None:
141 banner = self.banner
163 banner = self.banner
142 self.write(banner)
164 self.write(banner)
143
165
144 def compute_banner(self):
166 def compute_banner(self):
145 self.banner = self.banner1 + '\n'
167 self.banner = self.banner1 + '\n'
146 if self.profile:
168 if self.profile:
147 self.banner += '\nIPython profile: %s\n' % self.profile
169 self.banner += '\nIPython profile: %s\n' % self.profile
148 if self.banner2:
170 if self.banner2:
149 self.banner += '\n' + self.banner2 + '\n'
171 self.banner += '\n' + self.banner2 + '\n'
150
172
151 def init_usage(self, usage=None):
173 def init_usage(self, usage=None):
152 if usage is None:
174 if usage is None:
153 self.usage = interactive_usage
175 self.usage = interactive_usage
154 else:
176 else:
155 self.usage = usage
177 self.usage = usage
156
178
157 #-------------------------------------------------------------------------
179 #-------------------------------------------------------------------------
158 # Mainloop and code execution logic
180 # Mainloop and code execution logic
159 #-------------------------------------------------------------------------
181 #-------------------------------------------------------------------------
160
182
161 def mainloop(self, display_banner=None):
183 def mainloop(self, display_banner=None):
162 """Start the mainloop.
184 """Start the mainloop.
163
185
164 If an optional banner argument is given, it will override the
186 If an optional banner argument is given, it will override the
165 internally created default banner.
187 internally created default banner.
166 """
188 """
167
189
168 with nested(self.builtin_trap, self.display_trap):
190 with nested(self.builtin_trap, self.display_trap):
169
191
170 # if you run stuff with -c <cmd>, raw hist is not updated
192 # if you run stuff with -c <cmd>, raw hist is not updated
171 # ensure that it's in sync
193 # ensure that it's in sync
172 if len(self.input_hist) != len (self.input_hist_raw):
194 if len(self.input_hist) != len (self.input_hist_raw):
173 self.input_hist_raw = InputList(self.input_hist)
195 self.input_hist_raw = InputList(self.input_hist)
174
196
175 while 1:
197 while 1:
176 try:
198 try:
177 self.interact(display_banner=display_banner)
199 self.interact(display_banner=display_banner)
178 #self.interact_with_readline()
200 #self.interact_with_readline()
179 # XXX for testing of a readline-decoupled repl loop, call
201 # XXX for testing of a readline-decoupled repl loop, call
180 # interact_with_readline above
202 # interact_with_readline above
181 break
203 break
182 except KeyboardInterrupt:
204 except KeyboardInterrupt:
183 # this should not be necessary, but KeyboardInterrupt
205 # this should not be necessary, but KeyboardInterrupt
184 # handling seems rather unpredictable...
206 # handling seems rather unpredictable...
185 self.write("\nKeyboardInterrupt in interact()\n")
207 self.write("\nKeyboardInterrupt in interact()\n")
186
208
187 def interact(self, display_banner=None):
209 def interact(self, display_banner=None):
188 """Closely emulate the interactive Python console."""
210 """Closely emulate the interactive Python console."""
189
211
190 # batch run -> do not interact
212 # batch run -> do not interact
191 if self.exit_now:
213 if self.exit_now:
192 return
214 return
193
215
194 if display_banner is None:
216 if display_banner is None:
195 display_banner = self.display_banner
217 display_banner = self.display_banner
196 if display_banner:
218 if display_banner:
197 self.show_banner()
219 self.show_banner()
198
220
199 more = 0
221 more = 0
200
222
201 # Mark activity in the builtins
223 # Mark activity in the builtins
202 __builtin__.__dict__['__IPYTHON__active'] += 1
224 __builtin__.__dict__['__IPYTHON__active'] += 1
203
225
204 if self.has_readline:
226 if self.has_readline:
205 self.readline_startup_hook(self.pre_readline)
227 self.readline_startup_hook(self.pre_readline)
206 # exit_now is set by a call to %Exit or %Quit, through the
228 # exit_now is set by a call to %Exit or %Quit, through the
207 # ask_exit callback.
229 # ask_exit callback.
208
230
209 while not self.exit_now:
231 while not self.exit_now:
210 self.hooks.pre_prompt_hook()
232 self.hooks.pre_prompt_hook()
211 if more:
233 if more:
212 try:
234 try:
213 prompt = self.hooks.generate_prompt(True)
235 prompt = self.hooks.generate_prompt(True)
214 except:
236 except:
215 self.showtraceback()
237 self.showtraceback()
216 if self.autoindent:
238 if self.autoindent:
217 self.rl_do_indent = True
239 self.rl_do_indent = True
218
240
219 else:
241 else:
220 try:
242 try:
221 prompt = self.hooks.generate_prompt(False)
243 prompt = self.hooks.generate_prompt(False)
222 except:
244 except:
223 self.showtraceback()
245 self.showtraceback()
224 try:
246 try:
225 line = self.raw_input(prompt, more)
247 line = self.raw_input(prompt, more)
226 if self.exit_now:
248 if self.exit_now:
227 # quick exit on sys.std[in|out] close
249 # quick exit on sys.std[in|out] close
228 break
250 break
229 if self.autoindent:
251 if self.autoindent:
230 self.rl_do_indent = False
252 self.rl_do_indent = False
231
253
232 except KeyboardInterrupt:
254 except KeyboardInterrupt:
233 #double-guard against keyboardinterrupts during kbdint handling
255 #double-guard against keyboardinterrupts during kbdint handling
234 try:
256 try:
235 self.write('\nKeyboardInterrupt\n')
257 self.write('\nKeyboardInterrupt\n')
236 self.resetbuffer()
258 self.resetbuffer()
237 # keep cache in sync with the prompt counter:
259 # keep cache in sync with the prompt counter:
238 self.displayhook.prompt_count -= 1
260 self.displayhook.prompt_count -= 1
239
261
240 if self.autoindent:
262 if self.autoindent:
241 self.indent_current_nsp = 0
263 self.indent_current_nsp = 0
242 more = 0
264 more = 0
243 except KeyboardInterrupt:
265 except KeyboardInterrupt:
244 pass
266 pass
245 except EOFError:
267 except EOFError:
246 if self.autoindent:
268 if self.autoindent:
247 self.rl_do_indent = False
269 self.rl_do_indent = False
248 if self.has_readline:
270 if self.has_readline:
249 self.readline_startup_hook(None)
271 self.readline_startup_hook(None)
250 self.write('\n')
272 self.write('\n')
251 self.exit()
273 self.exit()
252 except bdb.BdbQuit:
274 except bdb.BdbQuit:
253 warn('The Python debugger has exited with a BdbQuit exception.\n'
275 warn('The Python debugger has exited with a BdbQuit exception.\n'
254 'Because of how pdb handles the stack, it is impossible\n'
276 'Because of how pdb handles the stack, it is impossible\n'
255 'for IPython to properly format this particular exception.\n'
277 'for IPython to properly format this particular exception.\n'
256 'IPython will resume normal operation.')
278 'IPython will resume normal operation.')
257 except:
279 except:
258 # exceptions here are VERY RARE, but they can be triggered
280 # exceptions here are VERY RARE, but they can be triggered
259 # asynchronously by signal handlers, for example.
281 # asynchronously by signal handlers, for example.
260 self.showtraceback()
282 self.showtraceback()
261 else:
283 else:
262 more = self.push_line(line)
284 more = self.push_line(line)
263 if (self.SyntaxTB.last_syntax_error and
285 if (self.SyntaxTB.last_syntax_error and
264 self.autoedit_syntax):
286 self.autoedit_syntax):
265 self.edit_syntax_error()
287 self.edit_syntax_error()
266
288
267 # We are off again...
289 # We are off again...
268 __builtin__.__dict__['__IPYTHON__active'] -= 1
290 __builtin__.__dict__['__IPYTHON__active'] -= 1
269
291
270 # Turn off the exit flag, so the mainloop can be restarted if desired
292 # Turn off the exit flag, so the mainloop can be restarted if desired
271 self.exit_now = False
293 self.exit_now = False
272
294
273 def raw_input(self,prompt='',continue_prompt=False):
295 def raw_input(self,prompt='',continue_prompt=False):
274 """Write a prompt and read a line.
296 """Write a prompt and read a line.
275
297
276 The returned line does not include the trailing newline.
298 The returned line does not include the trailing newline.
277 When the user enters the EOF key sequence, EOFError is raised.
299 When the user enters the EOF key sequence, EOFError is raised.
278
300
279 Optional inputs:
301 Optional inputs:
280
302
281 - prompt(''): a string to be printed to prompt the user.
303 - prompt(''): a string to be printed to prompt the user.
282
304
283 - continue_prompt(False): whether this line is the first one or a
305 - continue_prompt(False): whether this line is the first one or a
284 continuation in a sequence of inputs.
306 continuation in a sequence of inputs.
285 """
307 """
286 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
308 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
287
309
288 # Code run by the user may have modified the readline completer state.
310 # Code run by the user may have modified the readline completer state.
289 # We must ensure that our completer is back in place.
311 # We must ensure that our completer is back in place.
290
312
291 if self.has_readline:
313 if self.has_readline:
292 self.set_readline_completer()
314 self.set_readline_completer()
293
315
294 try:
316 try:
295 line = raw_input_original(prompt).decode(self.stdin_encoding)
317 line = raw_input_original(prompt).decode(self.stdin_encoding)
296 except ValueError:
318 except ValueError:
297 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
319 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
298 " or sys.stdout.close()!\nExiting IPython!")
320 " or sys.stdout.close()!\nExiting IPython!")
299 self.ask_exit()
321 self.ask_exit()
300 return ""
322 return ""
301
323
302 # Try to be reasonably smart about not re-indenting pasted input more
324 # Try to be reasonably smart about not re-indenting pasted input more
303 # than necessary. We do this by trimming out the auto-indent initial
325 # than necessary. We do this by trimming out the auto-indent initial
304 # spaces, if the user's actual input started itself with whitespace.
326 # spaces, if the user's actual input started itself with whitespace.
305 #debugx('self.buffer[-1]')
327 #debugx('self.buffer[-1]')
306
328
307 if self.autoindent:
329 if self.autoindent:
308 if num_ini_spaces(line) > self.indent_current_nsp:
330 if num_ini_spaces(line) > self.indent_current_nsp:
309 line = line[self.indent_current_nsp:]
331 line = line[self.indent_current_nsp:]
310 self.indent_current_nsp = 0
332 self.indent_current_nsp = 0
311
333
312 # store the unfiltered input before the user has any chance to modify
334 # store the unfiltered input before the user has any chance to modify
313 # it.
335 # it.
314 if line.strip():
336 if line.strip():
315 if continue_prompt:
337 if continue_prompt:
316 self.input_hist_raw[-1] += '%s\n' % line
338 self.input_hist_raw[-1] += '%s\n' % line
317 if self.has_readline and self.readline_use:
339 if self.has_readline and self.readline_use:
318 try:
340 try:
319 histlen = self.readline.get_current_history_length()
341 histlen = self.readline.get_current_history_length()
320 if histlen > 1:
342 if histlen > 1:
321 newhist = self.input_hist_raw[-1].rstrip()
343 newhist = self.input_hist_raw[-1].rstrip()
322 self.readline.remove_history_item(histlen-1)
344 self.readline.remove_history_item(histlen-1)
323 self.readline.replace_history_item(histlen-2,
345 self.readline.replace_history_item(histlen-2,
324 newhist.encode(self.stdin_encoding))
346 newhist.encode(self.stdin_encoding))
325 except AttributeError:
347 except AttributeError:
326 pass # re{move,place}_history_item are new in 2.4.
348 pass # re{move,place}_history_item are new in 2.4.
327 else:
349 else:
328 self.input_hist_raw.append('%s\n' % line)
350 self.input_hist_raw.append('%s\n' % line)
329 # only entries starting at first column go to shadow history
351 # only entries starting at first column go to shadow history
330 if line.lstrip() == line:
352 if line.lstrip() == line:
331 self.shadowhist.add(line.strip())
353 self.shadowhist.add(line.strip())
332 elif not continue_prompt:
354 elif not continue_prompt:
333 self.input_hist_raw.append('\n')
355 self.input_hist_raw.append('\n')
334 try:
356 try:
335 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
357 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
336 except:
358 except:
337 # blanket except, in case a user-defined prefilter crashes, so it
359 # blanket except, in case a user-defined prefilter crashes, so it
338 # can't take all of ipython with it.
360 # can't take all of ipython with it.
339 self.showtraceback()
361 self.showtraceback()
340 return ''
362 return ''
341 else:
363 else:
342 return lineout
364 return lineout
343
365
344 # TODO: The following three methods are an early attempt to refactor
366 # TODO: The following three methods are an early attempt to refactor
345 # the main code execution logic. We don't use them, but they may be
367 # the main code execution logic. We don't use them, but they may be
346 # helpful when we refactor the code execution logic further.
368 # helpful when we refactor the code execution logic further.
347 # def interact_prompt(self):
369 # def interact_prompt(self):
348 # """ Print the prompt (in read-eval-print loop)
370 # """ Print the prompt (in read-eval-print loop)
349 #
371 #
350 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
351 # used in standard IPython flow.
373 # used in standard IPython flow.
352 # """
374 # """
353 # if self.more:
375 # if self.more:
354 # try:
376 # try:
355 # prompt = self.hooks.generate_prompt(True)
377 # prompt = self.hooks.generate_prompt(True)
356 # except:
378 # except:
357 # self.showtraceback()
379 # self.showtraceback()
358 # if self.autoindent:
380 # if self.autoindent:
359 # self.rl_do_indent = True
381 # self.rl_do_indent = True
360 #
382 #
361 # else:
383 # else:
362 # try:
384 # try:
363 # prompt = self.hooks.generate_prompt(False)
385 # prompt = self.hooks.generate_prompt(False)
364 # except:
386 # except:
365 # self.showtraceback()
387 # self.showtraceback()
366 # self.write(prompt)
388 # self.write(prompt)
367 #
389 #
368 # def interact_handle_input(self,line):
390 # def interact_handle_input(self,line):
369 # """ Handle the input line (in read-eval-print loop)
391 # """ Handle the input line (in read-eval-print loop)
370 #
392 #
371 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
393 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
372 # used in standard IPython flow.
394 # used in standard IPython flow.
373 # """
395 # """
374 # if line.lstrip() == line:
396 # if line.lstrip() == line:
375 # self.shadowhist.add(line.strip())
397 # self.shadowhist.add(line.strip())
376 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
398 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
377 #
399 #
378 # if line.strip():
400 # if line.strip():
379 # if self.more:
401 # if self.more:
380 # self.input_hist_raw[-1] += '%s\n' % line
402 # self.input_hist_raw[-1] += '%s\n' % line
381 # else:
403 # else:
382 # self.input_hist_raw.append('%s\n' % line)
404 # self.input_hist_raw.append('%s\n' % line)
383 #
405 #
384 #
406 #
385 # self.more = self.push_line(lineout)
407 # self.more = self.push_line(lineout)
386 # if (self.SyntaxTB.last_syntax_error and
408 # if (self.SyntaxTB.last_syntax_error and
387 # self.autoedit_syntax):
409 # self.autoedit_syntax):
388 # self.edit_syntax_error()
410 # self.edit_syntax_error()
389 #
411 #
390 # def interact_with_readline(self):
412 # def interact_with_readline(self):
391 # """ Demo of using interact_handle_input, interact_prompt
413 # """ Demo of using interact_handle_input, interact_prompt
392 #
414 #
393 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
415 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
394 # it should work like this.
416 # it should work like this.
395 # """
417 # """
396 # self.readline_startup_hook(self.pre_readline)
418 # self.readline_startup_hook(self.pre_readline)
397 # while not self.exit_now:
419 # while not self.exit_now:
398 # self.interact_prompt()
420 # self.interact_prompt()
399 # if self.more:
421 # if self.more:
400 # self.rl_do_indent = True
422 # self.rl_do_indent = True
401 # else:
423 # else:
402 # self.rl_do_indent = False
424 # self.rl_do_indent = False
403 # line = raw_input_original().decode(self.stdin_encoding)
425 # line = raw_input_original().decode(self.stdin_encoding)
404 # self.interact_handle_input(line)
426 # self.interact_handle_input(line)
405
427
406 #-------------------------------------------------------------------------
428 #-------------------------------------------------------------------------
407 # Methods to support auto-editing of SyntaxErrors.
429 # Methods to support auto-editing of SyntaxErrors.
408 #-------------------------------------------------------------------------
430 #-------------------------------------------------------------------------
409
431
410 def edit_syntax_error(self):
432 def edit_syntax_error(self):
411 """The bottom half of the syntax error handler called in the main loop.
433 """The bottom half of the syntax error handler called in the main loop.
412
434
413 Loop until syntax error is fixed or user cancels.
435 Loop until syntax error is fixed or user cancels.
414 """
436 """
415
437
416 while self.SyntaxTB.last_syntax_error:
438 while self.SyntaxTB.last_syntax_error:
417 # copy and clear last_syntax_error
439 # copy and clear last_syntax_error
418 err = self.SyntaxTB.clear_err_state()
440 err = self.SyntaxTB.clear_err_state()
419 if not self._should_recompile(err):
441 if not self._should_recompile(err):
420 return
442 return
421 try:
443 try:
422 # may set last_syntax_error again if a SyntaxError is raised
444 # may set last_syntax_error again if a SyntaxError is raised
423 self.safe_execfile(err.filename,self.user_ns)
445 self.safe_execfile(err.filename,self.user_ns)
424 except:
446 except:
425 self.showtraceback()
447 self.showtraceback()
426 else:
448 else:
427 try:
449 try:
428 f = file(err.filename)
450 f = file(err.filename)
429 try:
451 try:
430 # This should be inside a display_trap block and I
452 # This should be inside a display_trap block and I
431 # think it is.
453 # think it is.
432 sys.displayhook(f.read())
454 sys.displayhook(f.read())
433 finally:
455 finally:
434 f.close()
456 f.close()
435 except:
457 except:
436 self.showtraceback()
458 self.showtraceback()
437
459
438 def _should_recompile(self,e):
460 def _should_recompile(self,e):
439 """Utility routine for edit_syntax_error"""
461 """Utility routine for edit_syntax_error"""
440
462
441 if e.filename in ('<ipython console>','<input>','<string>',
463 if e.filename in ('<ipython console>','<input>','<string>',
442 '<console>','<BackgroundJob compilation>',
464 '<console>','<BackgroundJob compilation>',
443 None):
465 None):
444
466
445 return False
467 return False
446 try:
468 try:
447 if (self.autoedit_syntax and
469 if (self.autoedit_syntax and
448 not self.ask_yes_no('Return to editor to correct syntax error? '
470 not self.ask_yes_no('Return to editor to correct syntax error? '
449 '[Y/n] ','y')):
471 '[Y/n] ','y')):
450 return False
472 return False
451 except EOFError:
473 except EOFError:
452 return False
474 return False
453
475
454 def int0(x):
476 def int0(x):
455 try:
477 try:
456 return int(x)
478 return int(x)
457 except TypeError:
479 except TypeError:
458 return 0
480 return 0
459 # always pass integer line and offset values to editor hook
481 # always pass integer line and offset values to editor hook
460 try:
482 try:
461 self.hooks.fix_error_editor(e.filename,
483 self.hooks.fix_error_editor(e.filename,
462 int0(e.lineno),int0(e.offset),e.msg)
484 int0(e.lineno),int0(e.offset),e.msg)
463 except TryNext:
485 except TryNext:
464 warn('Could not open editor')
486 warn('Could not open editor')
465 return False
487 return False
466 return True
488 return True
467
489
468 #-------------------------------------------------------------------------
490 #-------------------------------------------------------------------------
469 # Things related to GUI support and pylab
491 # Things related to GUI support and pylab
470 #-------------------------------------------------------------------------
492 #-------------------------------------------------------------------------
471
493
472 def enable_pylab(self, gui=None):
494 def enable_pylab(self, gui=None):
473 """Activate pylab support at runtime.
495 """Activate pylab support at runtime.
474
496
475 This turns on support for matplotlib, preloads into the interactive
497 This turns on support for matplotlib, preloads into the interactive
476 namespace all of numpy and pylab, and configures IPython to correcdtly
498 namespace all of numpy and pylab, and configures IPython to correcdtly
477 interact with the GUI event loop. The GUI backend to be used can be
499 interact with the GUI event loop. The GUI backend to be used can be
478 optionally selected with the optional :param:`gui` argument.
500 optionally selected with the optional :param:`gui` argument.
479
501
480 Parameters
502 Parameters
481 ----------
503 ----------
482 gui : optional, string
504 gui : optional, string
483
505
484 If given, dictates the choice of matplotlib GUI backend to use
506 If given, dictates the choice of matplotlib GUI backend to use
485 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
507 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
486 'gtk'), otherwise we use the default chosen by matplotlib (as
508 'gtk'), otherwise we use the default chosen by matplotlib (as
487 dictated by the matplotlib build-time options plus the user's
509 dictated by the matplotlib build-time options plus the user's
488 matplotlibrc configuration file).
510 matplotlibrc configuration file).
489 """
511 """
490 # We want to prevent the loading of pylab to pollute the user's
512 # We want to prevent the loading of pylab to pollute the user's
491 # namespace as shown by the %who* magics, so we execute the activation
513 # namespace as shown by the %who* magics, so we execute the activation
492 # code in an empty namespace, and we update *both* user_ns and
514 # code in an empty namespace, and we update *both* user_ns and
493 # user_ns_hidden with this information.
515 # user_ns_hidden with this information.
494 ns = {}
516 ns = {}
495 gui = pylab_activate(ns, gui)
517 gui = pylab_activate(ns, gui)
496 self.user_ns.update(ns)
518 self.user_ns.update(ns)
497 self.user_ns_hidden.update(ns)
519 self.user_ns_hidden.update(ns)
498 # Now we must activate the gui pylab wants to use, and fix %run to take
520 # Now we must activate the gui pylab wants to use, and fix %run to take
499 # plot updates into account
521 # plot updates into account
500 enable_gui(gui)
522 enable_gui(gui)
501 self.magic_run = self._pylab_magic_run
523 self.magic_run = self._pylab_magic_run
502
524
503 #-------------------------------------------------------------------------
525 #-------------------------------------------------------------------------
504 # Things related to exiting
526 # Things related to exiting
505 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
506
528
507 def ask_exit(self):
529 def ask_exit(self):
508 """ Ask the shell to exit. Can be overiden and used as a callback. """
530 """ Ask the shell to exit. Can be overiden and used as a callback. """
509 self.exit_now = True
531 self.exit_now = True
510
532
511 def exit(self):
533 def exit(self):
512 """Handle interactive exit.
534 """Handle interactive exit.
513
535
514 This method calls the ask_exit callback."""
536 This method calls the ask_exit callback."""
515 if self.confirm_exit:
537 if self.confirm_exit:
516 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
538 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
517 self.ask_exit()
539 self.ask_exit()
518 else:
540 else:
519 self.ask_exit()
541 self.ask_exit()
520
542
521 #------------------------------------------------------------------------
543 #------------------------------------------------------------------------
522 # Magic overrides
544 # Magic overrides
523 #------------------------------------------------------------------------
545 #------------------------------------------------------------------------
524 # Once the base class stops inheriting from magic, this code needs to be
546 # Once the base class stops inheriting from magic, this code needs to be
525 # moved into a separate machinery as well. For now, at least isolate here
547 # moved into a separate machinery as well. For now, at least isolate here
526 # the magics which this class needs to implement differently from the base
548 # the magics which this class needs to implement differently from the base
527 # class, or that are unique to it.
549 # class, or that are unique to it.
528
550
529 def magic_autoindent(self, parameter_s = ''):
551 def magic_autoindent(self, parameter_s = ''):
530 """Toggle autoindent on/off (if available)."""
552 """Toggle autoindent on/off (if available)."""
531
553
532 self.shell.set_autoindent()
554 self.shell.set_autoindent()
533 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
555 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
534
556
535 def magic_cpaste(self, parameter_s=''):
557 def magic_cpaste(self, parameter_s=''):
536 """Paste & execute a pre-formatted code block from clipboard.
558 """Paste & execute a pre-formatted code block from clipboard.
537
559
538 You must terminate the block with '--' (two minus-signs) alone on the
560 You must terminate the block with '--' (two minus-signs) alone on the
539 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
561 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
540 is the new sentinel for this operation)
562 is the new sentinel for this operation)
541
563
542 The block is dedented prior to execution to enable execution of method
564 The block is dedented prior to execution to enable execution of method
543 definitions. '>' and '+' characters at the beginning of a line are
565 definitions. '>' and '+' characters at the beginning of a line are
544 ignored, to allow pasting directly from e-mails, diff files and
566 ignored, to allow pasting directly from e-mails, diff files and
545 doctests (the '...' continuation prompt is also stripped). The
567 doctests (the '...' continuation prompt is also stripped). The
546 executed block is also assigned to variable named 'pasted_block' for
568 executed block is also assigned to variable named 'pasted_block' for
547 later editing with '%edit pasted_block'.
569 later editing with '%edit pasted_block'.
548
570
549 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
571 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
550 This assigns the pasted block to variable 'foo' as string, without
572 This assigns the pasted block to variable 'foo' as string, without
551 dedenting or executing it (preceding >>> and + is still stripped)
573 dedenting or executing it (preceding >>> and + is still stripped)
552
574
553 '%cpaste -r' re-executes the block previously entered by cpaste.
575 '%cpaste -r' re-executes the block previously entered by cpaste.
554
576
555 Do not be alarmed by garbled output on Windows (it's a readline bug).
577 Do not be alarmed by garbled output on Windows (it's a readline bug).
556 Just press enter and type -- (and press enter again) and the block
578 Just press enter and type -- (and press enter again) and the block
557 will be what was just pasted.
579 will be what was just pasted.
558
580
559 IPython statements (magics, shell escapes) are not supported (yet).
581 IPython statements (magics, shell escapes) are not supported (yet).
560
582
561 See also
583 See also
562 --------
584 --------
563 paste: automatically pull code from clipboard.
585 paste: automatically pull code from clipboard.
564 """
586 """
565
587
566 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
588 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
567 par = args.strip()
589 par = args.strip()
568 if opts.has_key('r'):
590 if opts.has_key('r'):
569 self._rerun_pasted()
591 self._rerun_pasted()
570 return
592 return
571
593
572 sentinel = opts.get('s','--')
594 sentinel = opts.get('s','--')
573
595
574 block = self._strip_pasted_lines_for_code(
596 block = self._strip_pasted_lines_for_code(
575 self._get_pasted_lines(sentinel))
597 self._get_pasted_lines(sentinel))
576
598
577 self._execute_block(block, par)
599 self._execute_block(block, par)
578
600
579 def magic_paste(self, parameter_s=''):
601 def magic_paste(self, parameter_s=''):
580 """Paste & execute a pre-formatted code block from clipboard.
602 """Paste & execute a pre-formatted code block from clipboard.
581
603
582 The text is pulled directly from the clipboard without user
604 The text is pulled directly from the clipboard without user
583 intervention and printed back on the screen before execution (unless
605 intervention and printed back on the screen before execution (unless
584 the -q flag is given to force quiet mode).
606 the -q flag is given to force quiet mode).
585
607
586 The block is dedented prior to execution to enable execution of method
608 The block is dedented prior to execution to enable execution of method
587 definitions. '>' and '+' characters at the beginning of a line are
609 definitions. '>' and '+' characters at the beginning of a line are
588 ignored, to allow pasting directly from e-mails, diff files and
610 ignored, to allow pasting directly from e-mails, diff files and
589 doctests (the '...' continuation prompt is also stripped). The
611 doctests (the '...' continuation prompt is also stripped). The
590 executed block is also assigned to variable named 'pasted_block' for
612 executed block is also assigned to variable named 'pasted_block' for
591 later editing with '%edit pasted_block'.
613 later editing with '%edit pasted_block'.
592
614
593 You can also pass a variable name as an argument, e.g. '%paste foo'.
615 You can also pass a variable name as an argument, e.g. '%paste foo'.
594 This assigns the pasted block to variable 'foo' as string, without
616 This assigns the pasted block to variable 'foo' as string, without
595 dedenting or executing it (preceding >>> and + is still stripped)
617 dedenting or executing it (preceding >>> and + is still stripped)
596
618
597 Options
619 Options
598 -------
620 -------
599
621
600 -r: re-executes the block previously entered by cpaste.
622 -r: re-executes the block previously entered by cpaste.
601
623
602 -q: quiet mode: do not echo the pasted text back to the terminal.
624 -q: quiet mode: do not echo the pasted text back to the terminal.
603
625
604 IPython statements (magics, shell escapes) are not supported (yet).
626 IPython statements (magics, shell escapes) are not supported (yet).
605
627
606 See also
628 See also
607 --------
629 --------
608 cpaste: manually paste code into terminal until you mark its end.
630 cpaste: manually paste code into terminal until you mark its end.
609 """
631 """
610 opts,args = self.parse_options(parameter_s,'rq',mode='string')
632 opts,args = self.parse_options(parameter_s,'rq',mode='string')
611 par = args.strip()
633 par = args.strip()
612 if opts.has_key('r'):
634 if opts.has_key('r'):
613 self._rerun_pasted()
635 self._rerun_pasted()
614 return
636 return
615
637
616 text = self.shell.hooks.clipboard_get()
638 text = self.shell.hooks.clipboard_get()
617 block = self._strip_pasted_lines_for_code(text.splitlines())
639 block = self._strip_pasted_lines_for_code(text.splitlines())
618
640
619 # By default, echo back to terminal unless quiet mode is requested
641 # By default, echo back to terminal unless quiet mode is requested
620 if not opts.has_key('q'):
642 if not opts.has_key('q'):
621 write = self.shell.write
643 write = self.shell.write
622 write(self.shell.pycolorize(block))
644 write(self.shell.pycolorize(block))
623 if not block.endswith('\n'):
645 if not block.endswith('\n'):
624 write('\n')
646 write('\n')
625 write("## -- End pasted text --\n")
647 write("## -- End pasted text --\n")
626
648
627 self._execute_block(block, par)
649 self._execute_block(block, par)
628
650
629
651
630 InteractiveShellABC.register(TerminalInteractiveShell)
652 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now