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