##// END OF EJS Templates
Fix bug with autocall and multiline input recalled from readline buffer....
Fernando Perez -
Show More
@@ -1,1044 +1,1052 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import keyword
30 import keyword
31 import os
31 import os
32 import re
32 import re
33 import sys
33 import sys
34
34
35 from IPython.core.alias import AliasManager
35 from IPython.core.alias import AliasManager
36 from IPython.core.autocall import IPyAutocall
36 from IPython.core.autocall import IPyAutocall
37 from IPython.core.component import Component
37 from IPython.core.component import Component
38 from IPython.core.splitinput import split_user_input
38 from IPython.core.splitinput import split_user_input
39 from IPython.core.page import page
39 from IPython.core.page import page
40
40
41 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
41 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
42 from IPython.utils.genutils import make_quoted_expr, Term
42 from IPython.utils.genutils import make_quoted_expr, Term
43 from IPython.utils.autoattr import auto_attr
43 from IPython.utils.autoattr import auto_attr
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # Global utilities, errors and constants
46 # Global utilities, errors and constants
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49 # Warning, these cannot be changed unless various regular expressions
49 # Warning, these cannot be changed unless various regular expressions
50 # are updated in a number of places. Not great, but at least we told you.
50 # are updated in a number of places. Not great, but at least we told you.
51 ESC_SHELL = '!'
51 ESC_SHELL = '!'
52 ESC_SH_CAP = '!!'
52 ESC_SH_CAP = '!!'
53 ESC_HELP = '?'
53 ESC_HELP = '?'
54 ESC_MAGIC = '%'
54 ESC_MAGIC = '%'
55 ESC_QUOTE = ','
55 ESC_QUOTE = ','
56 ESC_QUOTE2 = ';'
56 ESC_QUOTE2 = ';'
57 ESC_PAREN = '/'
57 ESC_PAREN = '/'
58
58
59
59
60 class PrefilterError(Exception):
60 class PrefilterError(Exception):
61 pass
61 pass
62
62
63
63
64 # RegExp to identify potential function names
64 # RegExp to identify potential function names
65 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
65 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
66
66
67 # RegExp to exclude strings with this start from autocalling. In
67 # RegExp to exclude strings with this start from autocalling. In
68 # particular, all binary operators should be excluded, so that if foo is
68 # particular, all binary operators should be excluded, so that if foo is
69 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
69 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
70 # characters '!=()' don't need to be checked for, as the checkPythonChars
70 # characters '!=()' don't need to be checked for, as the checkPythonChars
71 # routine explicitely does so, to catch direct calls and rebindings of
71 # routine explicitely does so, to catch direct calls and rebindings of
72 # existing names.
72 # existing names.
73
73
74 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
74 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
75 # it affects the rest of the group in square brackets.
75 # it affects the rest of the group in square brackets.
76 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
76 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
77 r'|^is |^not |^in |^and |^or ')
77 r'|^is |^not |^in |^and |^or ')
78
78
79 # try to catch also methods for stuff in lists/tuples/dicts: off
79 # try to catch also methods for stuff in lists/tuples/dicts: off
80 # (experimental). For this to work, the line_split regexp would need
80 # (experimental). For this to work, the line_split regexp would need
81 # to be modified so it wouldn't break things at '['. That line is
81 # to be modified so it wouldn't break things at '['. That line is
82 # nasty enough that I shouldn't change it until I can test it _well_.
82 # nasty enough that I shouldn't change it until I can test it _well_.
83 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
83 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
84
84
85
85
86 # Handler Check Utilities
86 # Handler Check Utilities
87 def is_shadowed(identifier, ip):
87 def is_shadowed(identifier, ip):
88 """Is the given identifier defined in one of the namespaces which shadow
88 """Is the given identifier defined in one of the namespaces which shadow
89 the alias and magic namespaces? Note that an identifier is different
89 the alias and magic namespaces? Note that an identifier is different
90 than ifun, because it can not contain a '.' character."""
90 than ifun, because it can not contain a '.' character."""
91 # This is much safer than calling ofind, which can change state
91 # This is much safer than calling ofind, which can change state
92 return (identifier in ip.user_ns \
92 return (identifier in ip.user_ns \
93 or identifier in ip.internal_ns \
93 or identifier in ip.internal_ns \
94 or identifier in ip.ns_table['builtin'])
94 or identifier in ip.ns_table['builtin'])
95
95
96
96
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98 # The LineInfo class used throughout
98 # The LineInfo class used throughout
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100
100
101
101
102 class LineInfo(object):
102 class LineInfo(object):
103 """A single line of input and associated info.
103 """A single line of input and associated info.
104
104
105 Includes the following as properties:
105 Includes the following as properties:
106
106
107 line
107 line
108 The original, raw line
108 The original, raw line
109
109
110 continue_prompt
110 continue_prompt
111 Is this line a continuation in a sequence of multiline input?
111 Is this line a continuation in a sequence of multiline input?
112
112
113 pre
113 pre
114 The initial esc character or whitespace.
114 The initial esc character or whitespace.
115
115
116 pre_char
116 pre_char
117 The escape character(s) in pre or the empty string if there isn't one.
117 The escape character(s) in pre or the empty string if there isn't one.
118 Note that '!!' is a possible value for pre_char. Otherwise it will
118 Note that '!!' is a possible value for pre_char. Otherwise it will
119 always be a single character.
119 always be a single character.
120
120
121 pre_whitespace
121 pre_whitespace
122 The leading whitespace from pre if it exists. If there is a pre_char,
122 The leading whitespace from pre if it exists. If there is a pre_char,
123 this is just ''.
123 this is just ''.
124
124
125 ifun
125 ifun
126 The 'function part', which is basically the maximal initial sequence
126 The 'function part', which is basically the maximal initial sequence
127 of valid python identifiers and the '.' character. This is what is
127 of valid python identifiers and the '.' character. This is what is
128 checked for alias and magic transformations, used for auto-calling,
128 checked for alias and magic transformations, used for auto-calling,
129 etc.
129 etc.
130
130
131 the_rest
131 the_rest
132 Everything else on the line.
132 Everything else on the line.
133 """
133 """
134 def __init__(self, line, continue_prompt):
134 def __init__(self, line, continue_prompt):
135 self.line = line
135 self.line = line
136 self.continue_prompt = continue_prompt
136 self.continue_prompt = continue_prompt
137 self.pre, self.ifun, self.the_rest = split_user_input(line)
137 self.pre, self.ifun, self.the_rest = split_user_input(line)
138
138
139 self.pre_char = self.pre.strip()
139 self.pre_char = self.pre.strip()
140 if self.pre_char:
140 if self.pre_char:
141 self.pre_whitespace = '' # No whitespace allowd before esc chars
141 self.pre_whitespace = '' # No whitespace allowd before esc chars
142 else:
142 else:
143 self.pre_whitespace = self.pre
143 self.pre_whitespace = self.pre
144
144
145 self._oinfo = None
145 self._oinfo = None
146
146
147 def ofind(self, ip):
147 def ofind(self, ip):
148 """Do a full, attribute-walking lookup of the ifun in the various
148 """Do a full, attribute-walking lookup of the ifun in the various
149 namespaces for the given IPython InteractiveShell instance.
149 namespaces for the given IPython InteractiveShell instance.
150
150
151 Return a dict with keys: found,obj,ospace,ismagic
151 Return a dict with keys: found,obj,ospace,ismagic
152
152
153 Note: can cause state changes because of calling getattr, but should
153 Note: can cause state changes because of calling getattr, but should
154 only be run if autocall is on and if the line hasn't matched any
154 only be run if autocall is on and if the line hasn't matched any
155 other, less dangerous handlers.
155 other, less dangerous handlers.
156
156
157 Does cache the results of the call, so can be called multiple times
157 Does cache the results of the call, so can be called multiple times
158 without worrying about *further* damaging state.
158 without worrying about *further* damaging state.
159 """
159 """
160 if not self._oinfo:
160 if not self._oinfo:
161 self._oinfo = ip.shell._ofind(self.ifun)
161 self._oinfo = ip.shell._ofind(self.ifun)
162 return self._oinfo
162 return self._oinfo
163
163
164 def __str__(self):
164 def __str__(self):
165 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
165 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
166
166
167
167
168 #-----------------------------------------------------------------------------
168 #-----------------------------------------------------------------------------
169 # Main Prefilter manager
169 # Main Prefilter manager
170 #-----------------------------------------------------------------------------
170 #-----------------------------------------------------------------------------
171
171
172
172
173 class PrefilterManager(Component):
173 class PrefilterManager(Component):
174 """Main prefilter component.
174 """Main prefilter component.
175
175
176 The IPython prefilter is run on all user input before it is run. The
176 The IPython prefilter is run on all user input before it is run. The
177 prefilter consumes lines of input and produces transformed lines of
177 prefilter consumes lines of input and produces transformed lines of
178 input.
178 input.
179
179
180 The iplementation consists of two phases:
180 The iplementation consists of two phases:
181
181
182 1. Transformers
182 1. Transformers
183 2. Checkers and handlers
183 2. Checkers and handlers
184
184
185 Over time, we plan on deprecating the checkers and handlers and doing
185 Over time, we plan on deprecating the checkers and handlers and doing
186 everything in the transformers.
186 everything in the transformers.
187
187
188 The transformers are instances of :class:`PrefilterTransformer` and have
188 The transformers are instances of :class:`PrefilterTransformer` and have
189 a single method :meth:`transform` that takes a line and returns a
189 a single method :meth:`transform` that takes a line and returns a
190 transformed line. The transformation can be accomplished using any
190 transformed line. The transformation can be accomplished using any
191 tool, but our current ones use regular expressions for speed. We also
191 tool, but our current ones use regular expressions for speed. We also
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
193
193
194 After all the transformers have been run, the line is fed to the checkers,
194 After all the transformers have been run, the line is fed to the checkers,
195 which are instances of :class:`PrefilterChecker`. The line is passed to
195 which are instances of :class:`PrefilterChecker`. The line is passed to
196 the :meth:`check` method, which either returns `None` or a
196 the :meth:`check` method, which either returns `None` or a
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
199 the line is passed to the :meth:`handle` method of the returned
199 the line is passed to the :meth:`handle` method of the returned
200 handler and no further checkers are tried.
200 handler and no further checkers are tried.
201
201
202 Both transformers and checkers have a `priority` attribute, that determines
202 Both transformers and checkers have a `priority` attribute, that determines
203 the order in which they are called. Smaller priorities are tried first.
203 the order in which they are called. Smaller priorities are tried first.
204
204
205 Both transformers and checkers also have `enabled` attribute, which is
205 Both transformers and checkers also have `enabled` attribute, which is
206 a boolean that determines if the instance is used.
206 a boolean that determines if the instance is used.
207
207
208 Users or developers can change the priority or enabled attribute of
208 Users or developers can change the priority or enabled attribute of
209 transformers or checkers, but they must call the :meth:`sort_checkers`
209 transformers or checkers, but they must call the :meth:`sort_checkers`
210 or :meth:`sort_transformers` method after changing the priority.
210 or :meth:`sort_transformers` method after changing the priority.
211 """
211 """
212
212
213 multi_line_specials = CBool(True, config=True)
213 multi_line_specials = CBool(True, config=True)
214
214
215 def __init__(self, parent, config=None):
215 def __init__(self, parent, config=None):
216 super(PrefilterManager, self).__init__(parent, config=config)
216 super(PrefilterManager, self).__init__(parent, config=config)
217 self.init_transformers()
217 self.init_transformers()
218 self.init_handlers()
218 self.init_handlers()
219 self.init_checkers()
219 self.init_checkers()
220
220
221 @auto_attr
221 @auto_attr
222 def shell(self):
222 def shell(self):
223 return Component.get_instances(
223 return Component.get_instances(
224 root=self.root,
224 root=self.root,
225 klass='IPython.core.iplib.InteractiveShell')[0]
225 klass='IPython.core.iplib.InteractiveShell')[0]
226
226
227 #-------------------------------------------------------------------------
227 #-------------------------------------------------------------------------
228 # API for managing transformers
228 # API for managing transformers
229 #-------------------------------------------------------------------------
229 #-------------------------------------------------------------------------
230
230
231 def init_transformers(self):
231 def init_transformers(self):
232 """Create the default transformers."""
232 """Create the default transformers."""
233 self._transformers = []
233 self._transformers = []
234 for transformer_cls in _default_transformers:
234 for transformer_cls in _default_transformers:
235 transformer_cls(self, config=self.config)
235 transformer_cls(self, config=self.config)
236
236
237 def sort_transformers(self):
237 def sort_transformers(self):
238 """Sort the transformers by priority.
238 """Sort the transformers by priority.
239
239
240 This must be called after the priority of a transformer is changed.
240 This must be called after the priority of a transformer is changed.
241 The :meth:`register_transformer` method calls this automatically.
241 The :meth:`register_transformer` method calls this automatically.
242 """
242 """
243 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
243 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
244
244
245 @property
245 @property
246 def transformers(self):
246 def transformers(self):
247 """Return a list of checkers, sorted by priority."""
247 """Return a list of checkers, sorted by priority."""
248 return self._transformers
248 return self._transformers
249
249
250 def register_transformer(self, transformer):
250 def register_transformer(self, transformer):
251 """Register a transformer instance."""
251 """Register a transformer instance."""
252 if transformer not in self._transformers:
252 if transformer not in self._transformers:
253 self._transformers.append(transformer)
253 self._transformers.append(transformer)
254 self.sort_transformers()
254 self.sort_transformers()
255
255
256 def unregister_transformer(self, transformer):
256 def unregister_transformer(self, transformer):
257 """Unregister a transformer instance."""
257 """Unregister a transformer instance."""
258 if transformer in self._transformers:
258 if transformer in self._transformers:
259 self._transformers.remove(transformer)
259 self._transformers.remove(transformer)
260
260
261 #-------------------------------------------------------------------------
261 #-------------------------------------------------------------------------
262 # API for managing checkers
262 # API for managing checkers
263 #-------------------------------------------------------------------------
263 #-------------------------------------------------------------------------
264
264
265 def init_checkers(self):
265 def init_checkers(self):
266 """Create the default checkers."""
266 """Create the default checkers."""
267 self._checkers = []
267 self._checkers = []
268 for checker in _default_checkers:
268 for checker in _default_checkers:
269 checker(self, config=self.config)
269 checker(self, config=self.config)
270
270
271 def sort_checkers(self):
271 def sort_checkers(self):
272 """Sort the checkers by priority.
272 """Sort the checkers by priority.
273
273
274 This must be called after the priority of a checker is changed.
274 This must be called after the priority of a checker is changed.
275 The :meth:`register_checker` method calls this automatically.
275 The :meth:`register_checker` method calls this automatically.
276 """
276 """
277 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
278
278
279 @property
279 @property
280 def checkers(self):
280 def checkers(self):
281 """Return a list of checkers, sorted by priority."""
281 """Return a list of checkers, sorted by priority."""
282 return self._checkers
282 return self._checkers
283
283
284 def register_checker(self, checker):
284 def register_checker(self, checker):
285 """Register a checker instance."""
285 """Register a checker instance."""
286 if checker not in self._checkers:
286 if checker not in self._checkers:
287 self._checkers.append(checker)
287 self._checkers.append(checker)
288 self.sort_checkers()
288 self.sort_checkers()
289
289
290 def unregister_checker(self, checker):
290 def unregister_checker(self, checker):
291 """Unregister a checker instance."""
291 """Unregister a checker instance."""
292 if checker in self._checkers:
292 if checker in self._checkers:
293 self._checkers.remove(checker)
293 self._checkers.remove(checker)
294
294
295 #-------------------------------------------------------------------------
295 #-------------------------------------------------------------------------
296 # API for managing checkers
296 # API for managing checkers
297 #-------------------------------------------------------------------------
297 #-------------------------------------------------------------------------
298
298
299 def init_handlers(self):
299 def init_handlers(self):
300 """Create the default handlers."""
300 """Create the default handlers."""
301 self._handlers = {}
301 self._handlers = {}
302 self._esc_handlers = {}
302 self._esc_handlers = {}
303 for handler in _default_handlers:
303 for handler in _default_handlers:
304 handler(self, config=self.config)
304 handler(self, config=self.config)
305
305
306 @property
306 @property
307 def handlers(self):
307 def handlers(self):
308 """Return a dict of all the handlers."""
308 """Return a dict of all the handlers."""
309 return self._handlers
309 return self._handlers
310
310
311 def register_handler(self, name, handler, esc_strings):
311 def register_handler(self, name, handler, esc_strings):
312 """Register a handler instance by name with esc_strings."""
312 """Register a handler instance by name with esc_strings."""
313 self._handlers[name] = handler
313 self._handlers[name] = handler
314 for esc_str in esc_strings:
314 for esc_str in esc_strings:
315 self._esc_handlers[esc_str] = handler
315 self._esc_handlers[esc_str] = handler
316
316
317 def unregister_handler(self, name, handler, esc_strings):
317 def unregister_handler(self, name, handler, esc_strings):
318 """Unregister a handler instance by name with esc_strings."""
318 """Unregister a handler instance by name with esc_strings."""
319 try:
319 try:
320 del self._handlers[name]
320 del self._handlers[name]
321 except KeyError:
321 except KeyError:
322 pass
322 pass
323 for esc_str in esc_strings:
323 for esc_str in esc_strings:
324 h = self._esc_handlers.get(esc_str)
324 h = self._esc_handlers.get(esc_str)
325 if h is handler:
325 if h is handler:
326 del self._esc_handlers[esc_str]
326 del self._esc_handlers[esc_str]
327
327
328 def get_handler_by_name(self, name):
328 def get_handler_by_name(self, name):
329 """Get a handler by its name."""
329 """Get a handler by its name."""
330 return self._handlers.get(name)
330 return self._handlers.get(name)
331
331
332 def get_handler_by_esc(self, esc_str):
332 def get_handler_by_esc(self, esc_str):
333 """Get a handler by its escape string."""
333 """Get a handler by its escape string."""
334 return self._esc_handlers.get(esc_str)
334 return self._esc_handlers.get(esc_str)
335
335
336 #-------------------------------------------------------------------------
336 #-------------------------------------------------------------------------
337 # Main prefiltering API
337 # Main prefiltering API
338 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
339
339
340 def prefilter_line_info(self, line_info):
340 def prefilter_line_info(self, line_info):
341 """Prefilter a line that has been converted to a LineInfo object.
341 """Prefilter a line that has been converted to a LineInfo object.
342
342
343 This implements the checker/handler part of the prefilter pipe.
343 This implements the checker/handler part of the prefilter pipe.
344 """
344 """
345 # print "prefilter_line_info: ", line_info
345 # print "prefilter_line_info: ", line_info
346 handler = self.find_handler(line_info)
346 handler = self.find_handler(line_info)
347 return handler.handle(line_info)
347 return handler.handle(line_info)
348
348
349 def find_handler(self, line_info):
349 def find_handler(self, line_info):
350 """Find a handler for the line_info by trying checkers."""
350 """Find a handler for the line_info by trying checkers."""
351 for checker in self.checkers:
351 for checker in self.checkers:
352 if checker.enabled:
352 if checker.enabled:
353 handler = checker.check(line_info)
353 handler = checker.check(line_info)
354 if handler:
354 if handler:
355 return handler
355 return handler
356 return self.get_handler_by_name('normal')
356 return self.get_handler_by_name('normal')
357
357
358 def transform_line(self, line, continue_prompt):
358 def transform_line(self, line, continue_prompt):
359 """Calls the enabled transformers in order of increasing priority."""
359 """Calls the enabled transformers in order of increasing priority."""
360 for transformer in self.transformers:
360 for transformer in self.transformers:
361 if transformer.enabled:
361 if transformer.enabled:
362 line = transformer.transform(line, continue_prompt)
362 line = transformer.transform(line, continue_prompt)
363 return line
363 return line
364
364
365 def prefilter_line(self, line, continue_prompt=False):
365 def prefilter_line(self, line, continue_prompt=False):
366 """Prefilter a single input line as text.
366 """Prefilter a single input line as text.
367
367
368 This method prefilters a single line of text by calling the
368 This method prefilters a single line of text by calling the
369 transformers and then the checkers/handlers.
369 transformers and then the checkers/handlers.
370 """
370 """
371
371
372 # print "prefilter_line: ", line, continue_prompt
372 # print "prefilter_line: ", line, continue_prompt
373 # All handlers *must* return a value, even if it's blank ('').
373 # All handlers *must* return a value, even if it's blank ('').
374
374
375 # Lines are NOT logged here. Handlers should process the line as
375 # Lines are NOT logged here. Handlers should process the line as
376 # needed, update the cache AND log it (so that the input cache array
376 # needed, update the cache AND log it (so that the input cache array
377 # stays synced).
377 # stays synced).
378
378
379 # save the line away in case we crash, so the post-mortem handler can
379 # save the line away in case we crash, so the post-mortem handler can
380 # record it
380 # record it
381 self.shell._last_input_line = line
381 self.shell._last_input_line = line
382
382
383 if not line:
383 if not line:
384 # Return immediately on purely empty lines, so that if the user
384 # Return immediately on purely empty lines, so that if the user
385 # previously typed some whitespace that started a continuation
385 # previously typed some whitespace that started a continuation
386 # prompt, he can break out of that loop with just an empty line.
386 # prompt, he can break out of that loop with just an empty line.
387 # This is how the default python prompt works.
387 # This is how the default python prompt works.
388
388
389 # Only return if the accumulated input buffer was just whitespace!
389 # Only return if the accumulated input buffer was just whitespace!
390 if ''.join(self.shell.buffer).isspace():
390 if ''.join(self.shell.buffer).isspace():
391 self.shell.buffer[:] = []
391 self.shell.buffer[:] = []
392 return ''
392 return ''
393
393
394 # At this point, we invoke our transformers.
394 # At this point, we invoke our transformers.
395 if not continue_prompt or (continue_prompt and self.multi_line_specials):
395 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 line = self.transform_line(line, continue_prompt)
396 line = self.transform_line(line, continue_prompt)
397
397
398 # Now we compute line_info for the checkers and handlers
398 # Now we compute line_info for the checkers and handlers
399 line_info = LineInfo(line, continue_prompt)
399 line_info = LineInfo(line, continue_prompt)
400
400
401 # the input history needs to track even empty lines
401 # the input history needs to track even empty lines
402 stripped = line.strip()
402 stripped = line.strip()
403
403
404 normal_handler = self.get_handler_by_name('normal')
404 normal_handler = self.get_handler_by_name('normal')
405 if not stripped:
405 if not stripped:
406 if not continue_prompt:
406 if not continue_prompt:
407 self.shell.outputcache.prompt_count -= 1
407 self.shell.outputcache.prompt_count -= 1
408
408
409 return normal_handler.handle(line_info)
409 return normal_handler.handle(line_info)
410
410
411 # special handlers are only allowed for single line statements
411 # special handlers are only allowed for single line statements
412 if continue_prompt and not self.multi_line_specials:
412 if continue_prompt and not self.multi_line_specials:
413 return normal_handler.handle(line_info)
413 return normal_handler.handle(line_info)
414
414
415 prefiltered = self.prefilter_line_info(line_info)
415 prefiltered = self.prefilter_line_info(line_info)
416 # print "prefiltered line: %r" % prefiltered
416 # print "prefiltered line: %r" % prefiltered
417 return prefiltered
417 return prefiltered
418
418
419 def prefilter_lines(self, lines, continue_prompt=False):
419 def prefilter_lines(self, lines, continue_prompt=False):
420 """Prefilter multiple input lines of text.
420 """Prefilter multiple input lines of text.
421
421
422 This is the main entry point for prefiltering multiple lines of
422 This is the main entry point for prefiltering multiple lines of
423 input. This simply calls :meth:`prefilter_line` for each line of
423 input. This simply calls :meth:`prefilter_line` for each line of
424 input.
424 input.
425
425
426 This covers cases where there are multiple lines in the user entry,
426 This covers cases where there are multiple lines in the user entry,
427 which is the case when the user goes back to a multiline history
427 which is the case when the user goes back to a multiline history
428 entry and presses enter.
428 entry and presses enter.
429 """
429 """
430 out = []
430 llines = lines.rstrip('\n').split('\n')
431 for line in lines.rstrip('\n').split('\n'):
431 # We can get multiple lines in one shot, where multiline input 'blends'
432 out.append(self.prefilter_line(line, continue_prompt))
432 # into one line, in cases like recalling from the readline history
433 return '\n'.join(out)
433 # buffer. We need to make sure that in such cases, we correctly
434
434 # communicate downstream which line is first and which are continuation
435 # ones.
436 if len(llines) > 1:
437 out = '\n'.join([self.prefilter_line(line, lnum>0)
438 for lnum, line in enumerate(llines) ])
439 else:
440 out = self.prefilter_line(llines[0], continue_prompt)
441
442 return out
435
443
436 #-----------------------------------------------------------------------------
444 #-----------------------------------------------------------------------------
437 # Prefilter transformers
445 # Prefilter transformers
438 #-----------------------------------------------------------------------------
446 #-----------------------------------------------------------------------------
439
447
440
448
441 class PrefilterTransformer(Component):
449 class PrefilterTransformer(Component):
442 """Transform a line of user input."""
450 """Transform a line of user input."""
443
451
444 priority = Int(100, config=True)
452 priority = Int(100, config=True)
445 shell = Any
453 shell = Any
446 prefilter_manager = Any
454 prefilter_manager = Any
447 enabled = Bool(True, config=True)
455 enabled = Bool(True, config=True)
448
456
449 def __init__(self, parent, config=None):
457 def __init__(self, parent, config=None):
450 super(PrefilterTransformer, self).__init__(parent, config=config)
458 super(PrefilterTransformer, self).__init__(parent, config=config)
451 self.prefilter_manager.register_transformer(self)
459 self.prefilter_manager.register_transformer(self)
452
460
453 @auto_attr
461 @auto_attr
454 def shell(self):
462 def shell(self):
455 return Component.get_instances(
463 return Component.get_instances(
456 root=self.root,
464 root=self.root,
457 klass='IPython.core.iplib.InteractiveShell')[0]
465 klass='IPython.core.iplib.InteractiveShell')[0]
458
466
459 @auto_attr
467 @auto_attr
460 def prefilter_manager(self):
468 def prefilter_manager(self):
461 return PrefilterManager.get_instances(root=self.root)[0]
469 return PrefilterManager.get_instances(root=self.root)[0]
462
470
463 def transform(self, line, continue_prompt):
471 def transform(self, line, continue_prompt):
464 """Transform a line, returning the new one."""
472 """Transform a line, returning the new one."""
465 return None
473 return None
466
474
467 def __repr__(self):
475 def __repr__(self):
468 return "<%s(priority=%r, enabled=%r)>" % (
476 return "<%s(priority=%r, enabled=%r)>" % (
469 self.__class__.__name__, self.priority, self.enabled)
477 self.__class__.__name__, self.priority, self.enabled)
470
478
471
479
472 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
480 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
473 r'\s*=\s*!(?P<cmd>.*)')
481 r'\s*=\s*!(?P<cmd>.*)')
474
482
475
483
476 class AssignSystemTransformer(PrefilterTransformer):
484 class AssignSystemTransformer(PrefilterTransformer):
477 """Handle the `files = !ls` syntax."""
485 """Handle the `files = !ls` syntax."""
478
486
479 priority = Int(100, config=True)
487 priority = Int(100, config=True)
480
488
481 def transform(self, line, continue_prompt):
489 def transform(self, line, continue_prompt):
482 m = _assign_system_re.match(line)
490 m = _assign_system_re.match(line)
483 if m is not None:
491 if m is not None:
484 cmd = m.group('cmd')
492 cmd = m.group('cmd')
485 lhs = m.group('lhs')
493 lhs = m.group('lhs')
486 expr = make_quoted_expr("sc -l =%s" % cmd)
494 expr = make_quoted_expr("sc -l =%s" % cmd)
487 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
495 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
488 return new_line
496 return new_line
489 return line
497 return line
490
498
491
499
492 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
500 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
493 r'\s*=\s*%(?P<cmd>.*)')
501 r'\s*=\s*%(?P<cmd>.*)')
494
502
495 class AssignMagicTransformer(PrefilterTransformer):
503 class AssignMagicTransformer(PrefilterTransformer):
496 """Handle the `a = %who` syntax."""
504 """Handle the `a = %who` syntax."""
497
505
498 priority = Int(200, config=True)
506 priority = Int(200, config=True)
499
507
500 def transform(self, line, continue_prompt):
508 def transform(self, line, continue_prompt):
501 m = _assign_magic_re.match(line)
509 m = _assign_magic_re.match(line)
502 if m is not None:
510 if m is not None:
503 cmd = m.group('cmd')
511 cmd = m.group('cmd')
504 lhs = m.group('lhs')
512 lhs = m.group('lhs')
505 expr = make_quoted_expr(cmd)
513 expr = make_quoted_expr(cmd)
506 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
514 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
507 return new_line
515 return new_line
508 return line
516 return line
509
517
510
518
511 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
519 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
512
520
513 class PyPromptTransformer(PrefilterTransformer):
521 class PyPromptTransformer(PrefilterTransformer):
514 """Handle inputs that start with '>>> ' syntax."""
522 """Handle inputs that start with '>>> ' syntax."""
515
523
516 priority = Int(50, config=True)
524 priority = Int(50, config=True)
517
525
518 def transform(self, line, continue_prompt):
526 def transform(self, line, continue_prompt):
519
527
520 if not line or line.isspace() or line.strip() == '...':
528 if not line or line.isspace() or line.strip() == '...':
521 # This allows us to recognize multiple input prompts separated by
529 # This allows us to recognize multiple input prompts separated by
522 # blank lines and pasted in a single chunk, very common when
530 # blank lines and pasted in a single chunk, very common when
523 # pasting doctests or long tutorial passages.
531 # pasting doctests or long tutorial passages.
524 return ''
532 return ''
525 m = _classic_prompt_re.match(line)
533 m = _classic_prompt_re.match(line)
526 if m:
534 if m:
527 return line[len(m.group(0)):]
535 return line[len(m.group(0)):]
528 else:
536 else:
529 return line
537 return line
530
538
531
539
532 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
540 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
533
541
534 class IPyPromptTransformer(PrefilterTransformer):
542 class IPyPromptTransformer(PrefilterTransformer):
535 """Handle inputs that start classic IPython prompt syntax."""
543 """Handle inputs that start classic IPython prompt syntax."""
536
544
537 priority = Int(50, config=True)
545 priority = Int(50, config=True)
538
546
539 def transform(self, line, continue_prompt):
547 def transform(self, line, continue_prompt):
540
548
541 if not line or line.isspace() or line.strip() == '...':
549 if not line or line.isspace() or line.strip() == '...':
542 # This allows us to recognize multiple input prompts separated by
550 # This allows us to recognize multiple input prompts separated by
543 # blank lines and pasted in a single chunk, very common when
551 # blank lines and pasted in a single chunk, very common when
544 # pasting doctests or long tutorial passages.
552 # pasting doctests or long tutorial passages.
545 return ''
553 return ''
546 m = _ipy_prompt_re.match(line)
554 m = _ipy_prompt_re.match(line)
547 if m:
555 if m:
548 return line[len(m.group(0)):]
556 return line[len(m.group(0)):]
549 else:
557 else:
550 return line
558 return line
551
559
552 #-----------------------------------------------------------------------------
560 #-----------------------------------------------------------------------------
553 # Prefilter checkers
561 # Prefilter checkers
554 #-----------------------------------------------------------------------------
562 #-----------------------------------------------------------------------------
555
563
556
564
557 class PrefilterChecker(Component):
565 class PrefilterChecker(Component):
558 """Inspect an input line and return a handler for that line."""
566 """Inspect an input line and return a handler for that line."""
559
567
560 priority = Int(100, config=True)
568 priority = Int(100, config=True)
561 shell = Any
569 shell = Any
562 prefilter_manager = Any
570 prefilter_manager = Any
563 enabled = Bool(True, config=True)
571 enabled = Bool(True, config=True)
564
572
565 def __init__(self, parent, config=None):
573 def __init__(self, parent, config=None):
566 super(PrefilterChecker, self).__init__(parent, config=config)
574 super(PrefilterChecker, self).__init__(parent, config=config)
567 self.prefilter_manager.register_checker(self)
575 self.prefilter_manager.register_checker(self)
568
576
569 @auto_attr
577 @auto_attr
570 def shell(self):
578 def shell(self):
571 return Component.get_instances(
579 return Component.get_instances(
572 root=self.root,
580 root=self.root,
573 klass='IPython.core.iplib.InteractiveShell')[0]
581 klass='IPython.core.iplib.InteractiveShell')[0]
574
582
575 @auto_attr
583 @auto_attr
576 def prefilter_manager(self):
584 def prefilter_manager(self):
577 return PrefilterManager.get_instances(root=self.root)[0]
585 return PrefilterManager.get_instances(root=self.root)[0]
578
586
579 def check(self, line_info):
587 def check(self, line_info):
580 """Inspect line_info and return a handler instance or None."""
588 """Inspect line_info and return a handler instance or None."""
581 return None
589 return None
582
590
583 def __repr__(self):
591 def __repr__(self):
584 return "<%s(priority=%r, enabled=%r)>" % (
592 return "<%s(priority=%r, enabled=%r)>" % (
585 self.__class__.__name__, self.priority, self.enabled)
593 self.__class__.__name__, self.priority, self.enabled)
586
594
587
595
588 class EmacsChecker(PrefilterChecker):
596 class EmacsChecker(PrefilterChecker):
589
597
590 priority = Int(100, config=True)
598 priority = Int(100, config=True)
591 enabled = Bool(False, config=True)
599 enabled = Bool(False, config=True)
592
600
593 def check(self, line_info):
601 def check(self, line_info):
594 "Emacs ipython-mode tags certain input lines."
602 "Emacs ipython-mode tags certain input lines."
595 if line_info.line.endswith('# PYTHON-MODE'):
603 if line_info.line.endswith('# PYTHON-MODE'):
596 return self.prefilter_manager.get_handler_by_name('emacs')
604 return self.prefilter_manager.get_handler_by_name('emacs')
597 else:
605 else:
598 return None
606 return None
599
607
600
608
601 class ShellEscapeChecker(PrefilterChecker):
609 class ShellEscapeChecker(PrefilterChecker):
602
610
603 priority = Int(200, config=True)
611 priority = Int(200, config=True)
604
612
605 def check(self, line_info):
613 def check(self, line_info):
606 if line_info.line.lstrip().startswith(ESC_SHELL):
614 if line_info.line.lstrip().startswith(ESC_SHELL):
607 return self.prefilter_manager.get_handler_by_name('shell')
615 return self.prefilter_manager.get_handler_by_name('shell')
608
616
609
617
610 class IPyAutocallChecker(PrefilterChecker):
618 class IPyAutocallChecker(PrefilterChecker):
611
619
612 priority = Int(300, config=True)
620 priority = Int(300, config=True)
613
621
614 def check(self, line_info):
622 def check(self, line_info):
615 "Instances of IPyAutocall in user_ns get autocalled immediately"
623 "Instances of IPyAutocall in user_ns get autocalled immediately"
616 obj = self.shell.user_ns.get(line_info.ifun, None)
624 obj = self.shell.user_ns.get(line_info.ifun, None)
617 if isinstance(obj, IPyAutocall):
625 if isinstance(obj, IPyAutocall):
618 obj.set_ip(self.shell)
626 obj.set_ip(self.shell)
619 return self.prefilter_manager.get_handler_by_name('auto')
627 return self.prefilter_manager.get_handler_by_name('auto')
620 else:
628 else:
621 return None
629 return None
622
630
623
631
624 class MultiLineMagicChecker(PrefilterChecker):
632 class MultiLineMagicChecker(PrefilterChecker):
625
633
626 priority = Int(400, config=True)
634 priority = Int(400, config=True)
627
635
628 def check(self, line_info):
636 def check(self, line_info):
629 "Allow ! and !! in multi-line statements if multi_line_specials is on"
637 "Allow ! and !! in multi-line statements if multi_line_specials is on"
630 # Note that this one of the only places we check the first character of
638 # Note that this one of the only places we check the first character of
631 # ifun and *not* the pre_char. Also note that the below test matches
639 # ifun and *not* the pre_char. Also note that the below test matches
632 # both ! and !!.
640 # both ! and !!.
633 if line_info.continue_prompt \
641 if line_info.continue_prompt \
634 and self.prefilter_manager.multi_line_specials:
642 and self.prefilter_manager.multi_line_specials:
635 if line_info.ifun.startswith(ESC_MAGIC):
643 if line_info.ifun.startswith(ESC_MAGIC):
636 return self.prefilter_manager.get_handler_by_name('magic')
644 return self.prefilter_manager.get_handler_by_name('magic')
637 else:
645 else:
638 return None
646 return None
639
647
640
648
641 class EscCharsChecker(PrefilterChecker):
649 class EscCharsChecker(PrefilterChecker):
642
650
643 priority = Int(500, config=True)
651 priority = Int(500, config=True)
644
652
645 def check(self, line_info):
653 def check(self, line_info):
646 """Check for escape character and return either a handler to handle it,
654 """Check for escape character and return either a handler to handle it,
647 or None if there is no escape char."""
655 or None if there is no escape char."""
648 if line_info.line[-1] == ESC_HELP \
656 if line_info.line[-1] == ESC_HELP \
649 and line_info.pre_char != ESC_SHELL \
657 and line_info.pre_char != ESC_SHELL \
650 and line_info.pre_char != ESC_SH_CAP:
658 and line_info.pre_char != ESC_SH_CAP:
651 # the ? can be at the end, but *not* for either kind of shell escape,
659 # the ? can be at the end, but *not* for either kind of shell escape,
652 # because a ? can be a vaild final char in a shell cmd
660 # because a ? can be a vaild final char in a shell cmd
653 return self.prefilter_manager.get_handler_by_name('help')
661 return self.prefilter_manager.get_handler_by_name('help')
654 else:
662 else:
655 # This returns None like it should if no handler exists
663 # This returns None like it should if no handler exists
656 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
664 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
657
665
658
666
659 class AssignmentChecker(PrefilterChecker):
667 class AssignmentChecker(PrefilterChecker):
660
668
661 priority = Int(600, config=True)
669 priority = Int(600, config=True)
662
670
663 def check(self, line_info):
671 def check(self, line_info):
664 """Check to see if user is assigning to a var for the first time, in
672 """Check to see if user is assigning to a var for the first time, in
665 which case we want to avoid any sort of automagic / autocall games.
673 which case we want to avoid any sort of automagic / autocall games.
666
674
667 This allows users to assign to either alias or magic names true python
675 This allows users to assign to either alias or magic names true python
668 variables (the magic/alias systems always take second seat to true
676 variables (the magic/alias systems always take second seat to true
669 python code). E.g. ls='hi', or ls,that=1,2"""
677 python code). E.g. ls='hi', or ls,that=1,2"""
670 if line_info.the_rest:
678 if line_info.the_rest:
671 if line_info.the_rest[0] in '=,':
679 if line_info.the_rest[0] in '=,':
672 return self.prefilter_manager.get_handler_by_name('normal')
680 return self.prefilter_manager.get_handler_by_name('normal')
673 else:
681 else:
674 return None
682 return None
675
683
676
684
677 class AutoMagicChecker(PrefilterChecker):
685 class AutoMagicChecker(PrefilterChecker):
678
686
679 priority = Int(700, config=True)
687 priority = Int(700, config=True)
680
688
681 def check(self, line_info):
689 def check(self, line_info):
682 """If the ifun is magic, and automagic is on, run it. Note: normal,
690 """If the ifun is magic, and automagic is on, run it. Note: normal,
683 non-auto magic would already have been triggered via '%' in
691 non-auto magic would already have been triggered via '%' in
684 check_esc_chars. This just checks for automagic. Also, before
692 check_esc_chars. This just checks for automagic. Also, before
685 triggering the magic handler, make sure that there is nothing in the
693 triggering the magic handler, make sure that there is nothing in the
686 user namespace which could shadow it."""
694 user namespace which could shadow it."""
687 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
695 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
688 return None
696 return None
689
697
690 # We have a likely magic method. Make sure we should actually call it.
698 # We have a likely magic method. Make sure we should actually call it.
691 if line_info.continue_prompt and not self.shell.multi_line_specials:
699 if line_info.continue_prompt and not self.shell.multi_line_specials:
692 return None
700 return None
693
701
694 head = line_info.ifun.split('.',1)[0]
702 head = line_info.ifun.split('.',1)[0]
695 if is_shadowed(head, self.shell):
703 if is_shadowed(head, self.shell):
696 return None
704 return None
697
705
698 return self.prefilter_manager.get_handler_by_name('magic')
706 return self.prefilter_manager.get_handler_by_name('magic')
699
707
700
708
701 class AliasChecker(PrefilterChecker):
709 class AliasChecker(PrefilterChecker):
702
710
703 priority = Int(800, config=True)
711 priority = Int(800, config=True)
704
712
705 @auto_attr
713 @auto_attr
706 def alias_manager(self):
714 def alias_manager(self):
707 return AliasManager.get_instances(root=self.root)[0]
715 return AliasManager.get_instances(root=self.root)[0]
708
716
709 def check(self, line_info):
717 def check(self, line_info):
710 "Check if the initital identifier on the line is an alias."
718 "Check if the initital identifier on the line is an alias."
711 # Note: aliases can not contain '.'
719 # Note: aliases can not contain '.'
712 head = line_info.ifun.split('.',1)[0]
720 head = line_info.ifun.split('.',1)[0]
713 if line_info.ifun not in self.alias_manager \
721 if line_info.ifun not in self.alias_manager \
714 or head not in self.alias_manager \
722 or head not in self.alias_manager \
715 or is_shadowed(head, self.shell):
723 or is_shadowed(head, self.shell):
716 return None
724 return None
717
725
718 return self.prefilter_manager.get_handler_by_name('alias')
726 return self.prefilter_manager.get_handler_by_name('alias')
719
727
720
728
721 class PythonOpsChecker(PrefilterChecker):
729 class PythonOpsChecker(PrefilterChecker):
722
730
723 priority = Int(900, config=True)
731 priority = Int(900, config=True)
724
732
725 def check(self, line_info):
733 def check(self, line_info):
726 """If the 'rest' of the line begins with a function call or pretty much
734 """If the 'rest' of the line begins with a function call or pretty much
727 any python operator, we should simply execute the line (regardless of
735 any python operator, we should simply execute the line (regardless of
728 whether or not there's a possible autocall expansion). This avoids
736 whether or not there's a possible autocall expansion). This avoids
729 spurious (and very confusing) geattr() accesses."""
737 spurious (and very confusing) geattr() accesses."""
730 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
738 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
731 return self.prefilter_manager.get_handler_by_name('normal')
739 return self.prefilter_manager.get_handler_by_name('normal')
732 else:
740 else:
733 return None
741 return None
734
742
735
743
736 class AutocallChecker(PrefilterChecker):
744 class AutocallChecker(PrefilterChecker):
737
745
738 priority = Int(1000, config=True)
746 priority = Int(1000, config=True)
739
747
740 def check(self, line_info):
748 def check(self, line_info):
741 "Check if the initial word/function is callable and autocall is on."
749 "Check if the initial word/function is callable and autocall is on."
742 if not self.shell.autocall:
750 if not self.shell.autocall:
743 return None
751 return None
744
752
745 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
753 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
746 if not oinfo['found']:
754 if not oinfo['found']:
747 return None
755 return None
748
756
749 if callable(oinfo['obj']) \
757 if callable(oinfo['obj']) \
750 and (not re_exclude_auto.match(line_info.the_rest)) \
758 and (not re_exclude_auto.match(line_info.the_rest)) \
751 and re_fun_name.match(line_info.ifun):
759 and re_fun_name.match(line_info.ifun):
752 return self.prefilter_manager.get_handler_by_name('auto')
760 return self.prefilter_manager.get_handler_by_name('auto')
753 else:
761 else:
754 return None
762 return None
755
763
756
764
757 #-----------------------------------------------------------------------------
765 #-----------------------------------------------------------------------------
758 # Prefilter handlers
766 # Prefilter handlers
759 #-----------------------------------------------------------------------------
767 #-----------------------------------------------------------------------------
760
768
761
769
762 class PrefilterHandler(Component):
770 class PrefilterHandler(Component):
763
771
764 handler_name = Str('normal')
772 handler_name = Str('normal')
765 esc_strings = List([])
773 esc_strings = List([])
766 shell = Any
774 shell = Any
767 prefilter_manager = Any
775 prefilter_manager = Any
768
776
769 def __init__(self, parent, config=None):
777 def __init__(self, parent, config=None):
770 super(PrefilterHandler, self).__init__(parent, config=config)
778 super(PrefilterHandler, self).__init__(parent, config=config)
771 self.prefilter_manager.register_handler(
779 self.prefilter_manager.register_handler(
772 self.handler_name,
780 self.handler_name,
773 self,
781 self,
774 self.esc_strings
782 self.esc_strings
775 )
783 )
776
784
777 @auto_attr
785 @auto_attr
778 def shell(self):
786 def shell(self):
779 return Component.get_instances(
787 return Component.get_instances(
780 root=self.root,
788 root=self.root,
781 klass='IPython.core.iplib.InteractiveShell')[0]
789 klass='IPython.core.iplib.InteractiveShell')[0]
782
790
783 @auto_attr
791 @auto_attr
784 def prefilter_manager(self):
792 def prefilter_manager(self):
785 return PrefilterManager.get_instances(root=self.root)[0]
793 return PrefilterManager.get_instances(root=self.root)[0]
786
794
787 def handle(self, line_info):
795 def handle(self, line_info):
788 # print "normal: ", line_info
796 # print "normal: ", line_info
789 """Handle normal input lines. Use as a template for handlers."""
797 """Handle normal input lines. Use as a template for handlers."""
790
798
791 # With autoindent on, we need some way to exit the input loop, and I
799 # With autoindent on, we need some way to exit the input loop, and I
792 # don't want to force the user to have to backspace all the way to
800 # don't want to force the user to have to backspace all the way to
793 # clear the line. The rule will be in this case, that either two
801 # clear the line. The rule will be in this case, that either two
794 # lines of pure whitespace in a row, or a line of pure whitespace but
802 # lines of pure whitespace in a row, or a line of pure whitespace but
795 # of a size different to the indent level, will exit the input loop.
803 # of a size different to the indent level, will exit the input loop.
796 line = line_info.line
804 line = line_info.line
797 continue_prompt = line_info.continue_prompt
805 continue_prompt = line_info.continue_prompt
798
806
799 if (continue_prompt and
807 if (continue_prompt and
800 self.shell.autoindent and
808 self.shell.autoindent and
801 line.isspace() and
809 line.isspace() and
802
810
803 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
811 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
804 or
812 or
805 not self.shell.buffer
813 not self.shell.buffer
806 or
814 or
807 (self.shell.buffer[-1]).isspace()
815 (self.shell.buffer[-1]).isspace()
808 )
816 )
809 ):
817 ):
810 line = ''
818 line = ''
811
819
812 self.shell.log(line, line, continue_prompt)
820 self.shell.log(line, line, continue_prompt)
813 return line
821 return line
814
822
815 def __str__(self):
823 def __str__(self):
816 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
824 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
817
825
818
826
819 class AliasHandler(PrefilterHandler):
827 class AliasHandler(PrefilterHandler):
820
828
821 handler_name = Str('alias')
829 handler_name = Str('alias')
822
830
823 @auto_attr
831 @auto_attr
824 def alias_manager(self):
832 def alias_manager(self):
825 return AliasManager.get_instances(root=self.root)[0]
833 return AliasManager.get_instances(root=self.root)[0]
826
834
827 def handle(self, line_info):
835 def handle(self, line_info):
828 """Handle alias input lines. """
836 """Handle alias input lines. """
829 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
837 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
830 # pre is needed, because it carries the leading whitespace. Otherwise
838 # pre is needed, because it carries the leading whitespace. Otherwise
831 # aliases won't work in indented sections.
839 # aliases won't work in indented sections.
832 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
840 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
833 make_quoted_expr(transformed))
841 make_quoted_expr(transformed))
834
842
835 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
843 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
836 return line_out
844 return line_out
837
845
838
846
839 class ShellEscapeHandler(PrefilterHandler):
847 class ShellEscapeHandler(PrefilterHandler):
840
848
841 handler_name = Str('shell')
849 handler_name = Str('shell')
842 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
850 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
843
851
844 def handle(self, line_info):
852 def handle(self, line_info):
845 """Execute the line in a shell, empty return value"""
853 """Execute the line in a shell, empty return value"""
846 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
854 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
847
855
848 line = line_info.line
856 line = line_info.line
849 if line.lstrip().startswith(ESC_SH_CAP):
857 if line.lstrip().startswith(ESC_SH_CAP):
850 # rewrite LineInfo's line, ifun and the_rest to properly hold the
858 # rewrite LineInfo's line, ifun and the_rest to properly hold the
851 # call to %sx and the actual command to be executed, so
859 # call to %sx and the actual command to be executed, so
852 # handle_magic can work correctly. Note that this works even if
860 # handle_magic can work correctly. Note that this works even if
853 # the line is indented, so it handles multi_line_specials
861 # the line is indented, so it handles multi_line_specials
854 # properly.
862 # properly.
855 new_rest = line.lstrip()[2:]
863 new_rest = line.lstrip()[2:]
856 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
864 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
857 line_info.ifun = 'sx'
865 line_info.ifun = 'sx'
858 line_info.the_rest = new_rest
866 line_info.the_rest = new_rest
859 return magic_handler.handle(line_info)
867 return magic_handler.handle(line_info)
860 else:
868 else:
861 cmd = line.lstrip().lstrip(ESC_SHELL)
869 cmd = line.lstrip().lstrip(ESC_SHELL)
862 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
870 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
863 make_quoted_expr(cmd))
871 make_quoted_expr(cmd))
864 # update cache/log and return
872 # update cache/log and return
865 self.shell.log(line, line_out, line_info.continue_prompt)
873 self.shell.log(line, line_out, line_info.continue_prompt)
866 return line_out
874 return line_out
867
875
868
876
869 class MagicHandler(PrefilterHandler):
877 class MagicHandler(PrefilterHandler):
870
878
871 handler_name = Str('magic')
879 handler_name = Str('magic')
872 esc_strings = List([ESC_MAGIC])
880 esc_strings = List([ESC_MAGIC])
873
881
874 def handle(self, line_info):
882 def handle(self, line_info):
875 """Execute magic functions."""
883 """Execute magic functions."""
876 ifun = line_info.ifun
884 ifun = line_info.ifun
877 the_rest = line_info.the_rest
885 the_rest = line_info.the_rest
878 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
886 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
879 make_quoted_expr(ifun + " " + the_rest))
887 make_quoted_expr(ifun + " " + the_rest))
880 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
888 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
881 return cmd
889 return cmd
882
890
883
891
884 class AutoHandler(PrefilterHandler):
892 class AutoHandler(PrefilterHandler):
885
893
886 handler_name = Str('auto')
894 handler_name = Str('auto')
887 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
895 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
888
896
889 def handle(self, line_info):
897 def handle(self, line_info):
890 """Hande lines which can be auto-executed, quoting if requested."""
898 """Hande lines which can be auto-executed, quoting if requested."""
891 line = line_info.line
899 line = line_info.line
892 ifun = line_info.ifun
900 ifun = line_info.ifun
893 the_rest = line_info.the_rest
901 the_rest = line_info.the_rest
894 pre = line_info.pre
902 pre = line_info.pre
895 continue_prompt = line_info.continue_prompt
903 continue_prompt = line_info.continue_prompt
896 obj = line_info.ofind(self)['obj']
904 obj = line_info.ofind(self)['obj']
897 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
905 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
898
906
899 # This should only be active for single-line input!
907 # This should only be active for single-line input!
900 if continue_prompt:
908 if continue_prompt:
901 self.shell.log(line,line,continue_prompt)
909 self.shell.log(line,line,continue_prompt)
902 return line
910 return line
903
911
904 force_auto = isinstance(obj, IPyAutocall)
912 force_auto = isinstance(obj, IPyAutocall)
905 auto_rewrite = True
913 auto_rewrite = True
906
914
907 if pre == ESC_QUOTE:
915 if pre == ESC_QUOTE:
908 # Auto-quote splitting on whitespace
916 # Auto-quote splitting on whitespace
909 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
917 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
910 elif pre == ESC_QUOTE2:
918 elif pre == ESC_QUOTE2:
911 # Auto-quote whole string
919 # Auto-quote whole string
912 newcmd = '%s("%s")' % (ifun,the_rest)
920 newcmd = '%s("%s")' % (ifun,the_rest)
913 elif pre == ESC_PAREN:
921 elif pre == ESC_PAREN:
914 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
922 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
915 else:
923 else:
916 # Auto-paren.
924 # Auto-paren.
917 # We only apply it to argument-less calls if the autocall
925 # We only apply it to argument-less calls if the autocall
918 # parameter is set to 2. We only need to check that autocall is <
926 # parameter is set to 2. We only need to check that autocall is <
919 # 2, since this function isn't called unless it's at least 1.
927 # 2, since this function isn't called unless it's at least 1.
920 if not the_rest and (self.shell.autocall < 2) and not force_auto:
928 if not the_rest and (self.shell.autocall < 2) and not force_auto:
921 newcmd = '%s %s' % (ifun,the_rest)
929 newcmd = '%s %s' % (ifun,the_rest)
922 auto_rewrite = False
930 auto_rewrite = False
923 else:
931 else:
924 if not force_auto and the_rest.startswith('['):
932 if not force_auto and the_rest.startswith('['):
925 if hasattr(obj,'__getitem__'):
933 if hasattr(obj,'__getitem__'):
926 # Don't autocall in this case: item access for an object
934 # Don't autocall in this case: item access for an object
927 # which is BOTH callable and implements __getitem__.
935 # which is BOTH callable and implements __getitem__.
928 newcmd = '%s %s' % (ifun,the_rest)
936 newcmd = '%s %s' % (ifun,the_rest)
929 auto_rewrite = False
937 auto_rewrite = False
930 else:
938 else:
931 # if the object doesn't support [] access, go ahead and
939 # if the object doesn't support [] access, go ahead and
932 # autocall
940 # autocall
933 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
941 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
934 elif the_rest.endswith(';'):
942 elif the_rest.endswith(';'):
935 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
943 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
936 else:
944 else:
937 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
945 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
938
946
939 if auto_rewrite:
947 if auto_rewrite:
940 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
948 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
941
949
942 try:
950 try:
943 # plain ascii works better w/ pyreadline, on some machines, so
951 # plain ascii works better w/ pyreadline, on some machines, so
944 # we use it and only print uncolored rewrite if we have unicode
952 # we use it and only print uncolored rewrite if we have unicode
945 rw = str(rw)
953 rw = str(rw)
946 print >>Term.cout, rw
954 print >>Term.cout, rw
947 except UnicodeEncodeError:
955 except UnicodeEncodeError:
948 print "-------------->" + newcmd
956 print "-------------->" + newcmd
949
957
950 # log what is now valid Python, not the actual user input (without the
958 # log what is now valid Python, not the actual user input (without the
951 # final newline)
959 # final newline)
952 self.shell.log(line,newcmd,continue_prompt)
960 self.shell.log(line,newcmd,continue_prompt)
953 return newcmd
961 return newcmd
954
962
955
963
956 class HelpHandler(PrefilterHandler):
964 class HelpHandler(PrefilterHandler):
957
965
958 handler_name = Str('help')
966 handler_name = Str('help')
959 esc_strings = List([ESC_HELP])
967 esc_strings = List([ESC_HELP])
960
968
961 def handle(self, line_info):
969 def handle(self, line_info):
962 """Try to get some help for the object.
970 """Try to get some help for the object.
963
971
964 obj? or ?obj -> basic information.
972 obj? or ?obj -> basic information.
965 obj?? or ??obj -> more details.
973 obj?? or ??obj -> more details.
966 """
974 """
967 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
975 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
968 line = line_info.line
976 line = line_info.line
969 # We need to make sure that we don't process lines which would be
977 # We need to make sure that we don't process lines which would be
970 # otherwise valid python, such as "x=1 # what?"
978 # otherwise valid python, such as "x=1 # what?"
971 try:
979 try:
972 codeop.compile_command(line)
980 codeop.compile_command(line)
973 except SyntaxError:
981 except SyntaxError:
974 # We should only handle as help stuff which is NOT valid syntax
982 # We should only handle as help stuff which is NOT valid syntax
975 if line[0]==ESC_HELP:
983 if line[0]==ESC_HELP:
976 line = line[1:]
984 line = line[1:]
977 elif line[-1]==ESC_HELP:
985 elif line[-1]==ESC_HELP:
978 line = line[:-1]
986 line = line[:-1]
979 self.shell.log(line, '#?'+line, line_info.continue_prompt)
987 self.shell.log(line, '#?'+line, line_info.continue_prompt)
980 if line:
988 if line:
981 #print 'line:<%r>' % line # dbg
989 #print 'line:<%r>' % line # dbg
982 self.shell.magic_pinfo(line)
990 self.shell.magic_pinfo(line)
983 else:
991 else:
984 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
992 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
985 return '' # Empty string is needed here!
993 return '' # Empty string is needed here!
986 except:
994 except:
987 raise
995 raise
988 # Pass any other exceptions through to the normal handler
996 # Pass any other exceptions through to the normal handler
989 return normal_handler.handle(line_info)
997 return normal_handler.handle(line_info)
990 else:
998 else:
991 raise
999 raise
992 # If the code compiles ok, we should handle it normally
1000 # If the code compiles ok, we should handle it normally
993 return normal_handler.handle(line_info)
1001 return normal_handler.handle(line_info)
994
1002
995
1003
996 class EmacsHandler(PrefilterHandler):
1004 class EmacsHandler(PrefilterHandler):
997
1005
998 handler_name = Str('emacs')
1006 handler_name = Str('emacs')
999 esc_strings = List([])
1007 esc_strings = List([])
1000
1008
1001 def handle(self, line_info):
1009 def handle(self, line_info):
1002 """Handle input lines marked by python-mode."""
1010 """Handle input lines marked by python-mode."""
1003
1011
1004 # Currently, nothing is done. Later more functionality can be added
1012 # Currently, nothing is done. Later more functionality can be added
1005 # here if needed.
1013 # here if needed.
1006
1014
1007 # The input cache shouldn't be updated
1015 # The input cache shouldn't be updated
1008 return line_info.line
1016 return line_info.line
1009
1017
1010
1018
1011 #-----------------------------------------------------------------------------
1019 #-----------------------------------------------------------------------------
1012 # Defaults
1020 # Defaults
1013 #-----------------------------------------------------------------------------
1021 #-----------------------------------------------------------------------------
1014
1022
1015
1023
1016 _default_transformers = [
1024 _default_transformers = [
1017 AssignSystemTransformer,
1025 AssignSystemTransformer,
1018 AssignMagicTransformer,
1026 AssignMagicTransformer,
1019 PyPromptTransformer,
1027 PyPromptTransformer,
1020 IPyPromptTransformer,
1028 IPyPromptTransformer,
1021 ]
1029 ]
1022
1030
1023 _default_checkers = [
1031 _default_checkers = [
1024 EmacsChecker,
1032 EmacsChecker,
1025 ShellEscapeChecker,
1033 ShellEscapeChecker,
1026 IPyAutocallChecker,
1034 IPyAutocallChecker,
1027 MultiLineMagicChecker,
1035 MultiLineMagicChecker,
1028 EscCharsChecker,
1036 EscCharsChecker,
1029 AssignmentChecker,
1037 AssignmentChecker,
1030 AutoMagicChecker,
1038 AutoMagicChecker,
1031 AliasChecker,
1039 AliasChecker,
1032 PythonOpsChecker,
1040 PythonOpsChecker,
1033 AutocallChecker
1041 AutocallChecker
1034 ]
1042 ]
1035
1043
1036 _default_handlers = [
1044 _default_handlers = [
1037 PrefilterHandler,
1045 PrefilterHandler,
1038 AliasHandler,
1046 AliasHandler,
1039 ShellEscapeHandler,
1047 ShellEscapeHandler,
1040 MagicHandler,
1048 MagicHandler,
1041 AutoHandler,
1049 AutoHandler,
1042 HelpHandler,
1050 HelpHandler,
1043 EmacsHandler
1051 EmacsHandler
1044 ]
1052 ]
General Comments 0
You need to be logged in to leave comments. Login now