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