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