5555
5656# These are used for syntax hilighting.
5757from pygments import format
58+ from pygments .formatters import TerminalFormatter
5859from pygments .lexers import PythonLexer
5960from pygments .token import Token
6061from bpython .formatter import BPythonFormatter , Parenthesis
@@ -422,6 +423,7 @@ def __init__(self, scr, interp, statusbar=None, idle=None):
422423 self .matches = []
423424 self .matches_iter = MatchesIterator ()
424425 self .argspec = None
426+ self .current_func = None
425427 self .s = ''
426428 self .inside_string = False
427429 self .highlighted_paren = None
@@ -523,6 +525,12 @@ def cw(self):
523525 i += 1
524526 return self .s [- i + 1 :]
525527
528+ def get_object (self , name ):
529+ if name in self .interp .locals :
530+ return self .interp .locals [name ]
531+ else :
532+ return eval (name , self .interp .locals )
533+
526534 def get_args (self ):
527535 """Check if an unclosed parenthesis exists, then attempt to get the
528536 argspec() for it. On success, update self.argspec and return True,
@@ -533,7 +541,8 @@ def get_args(self):
533541 if not OPTS .arg_spec :
534542 return False
535543
536- # Find the name of the current function
544+ # Get the name of the current function and where we are in
545+ # the arguments
537546 stack = [['' , 0 , '' ]]
538547 try :
539548 for (token , value ) in PythonLexer ().get_tokens (self .s ):
@@ -560,19 +569,14 @@ def get_args(self):
560569 func , _ , _ = stack .pop ()
561570 except IndexError :
562571 return False
572+ if not func :
573+ return False
563574
564- # We found a name, now get a function object
565575 try :
566- if func in self .interp .locals :
567- f = self .interp .locals [func ]
568- except TypeError :
569- return None
570- else :
571- try :
572- f = eval (func , self .interp .locals )
573- except Exception :
574- # Same deal with the exceptions :(
575- return None
576+ f = self .get_object (func )
577+ except (AttributeError , NameError ):
578+ return False
579+
576580 if inspect .isclass (f ):
577581 try :
578582 f = f .__init__
@@ -1565,6 +1569,22 @@ def p_key(self, key):
15651569 page (self .stdout_hist [self .prev_block_finished :- 4 ])
15661570 return ''
15671571
1572+ elif key in key_dispatch [OPTS .show_source_key ]:
1573+ try :
1574+ obj = self .current_func
1575+ if obj is None and inspection .is_eval_safe_name (self .s ):
1576+ obj = self .get_object (self .s )
1577+ source = inspect .getsource (obj )
1578+ except (AttributeError , NameError , TypeError ):
1579+ self .statusbar .message ("Cannot show source." )
1580+ return ''
1581+ else :
1582+ if OPTS .highlight_show_source :
1583+ source = format (PythonLexer ().get_tokens (source ),
1584+ TerminalFormatter ())
1585+ page (source )
1586+ return ''
1587+
15681588 elif key == '\n ' :
15691589 self .lf ()
15701590 return None
0 commit comments