1 # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
2 # Author: Dave Love <fx@gnu.org>
4 # This file is part of GNU Emacs.
6 # GNU Emacs is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # GNU Emacs is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
19 import os
, sys
, traceback
, inspect
, imp
, __main__
24 from sets
import Set
as set
26 __all__
= ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
28 def format_exception (filename
, should_remove_self
):
29 type, value
, tb
= sys
.exc_info ()
31 sys
.last_value
= value
32 sys
.last_traceback
= tb
33 if type is SyntaxError:
34 try: # parse the error message
35 msg
, (dummy_filename
, lineno
, offset
, line
) = value
37 pass # Not the format we expect; leave it alone
39 # Stuff in the right filename
40 value
= SyntaxError(msg
, (filename
, lineno
, offset
, line
))
41 sys
.last_value
= value
42 res
= traceback
.format_exception_only (type, value
)
43 # There are some compilation errors which do not provide traceback so we
44 # should not massage it.
45 if should_remove_self
:
46 tblist
= traceback
.extract_tb (tb
)
48 res
= traceback
.format_list (tblist
)
50 res
.insert(0, "Traceback (most recent call last):\n")
51 res
[len(res
):] = traceback
.format_exception_only (type, value
)
52 # traceback.print_exception(type, value, tb)
53 for line
in res
: print(line
, end
=' ')
56 """Execute FILE and then remove it.
57 Execute the file within the __main__ namespace.
58 If we get an exception, print a traceback with the top frame
59 (ourselves) excluded."""
60 # We cannot use real execfile since it has a bug where the file stays
61 # locked forever (under w32) if SyntaxError occurs.
62 # --- code based on code.py and PyShell.py.
65 source
= open (file, "r").read()
66 code
= compile (source
, file, "exec")
67 # Other exceptions (shouldn't be any...) will (correctly) fall
69 except (OverflowError, SyntaxError, ValueError):
70 # FIXME: When can compile() raise anything else than
72 format_exception (file, False)
75 exec(code
, __main__
.__dict
__)
77 format_exception (file, True)
81 def eargs (name
, imports
):
82 "Get arglist of NAME for Eldoc &c."
84 if imports
: exec(imports
)
85 parts
= name
.split ('.')
87 exec('import ' + parts
[0]) # might fail
89 if inspect
.isbuiltin (func
) or type(func
) is type:
91 if doc
.find (' ->') != -1:
92 print('_emacs_out', doc
.split (' ->')[0])
94 print('_emacs_out', doc
.split ('\n')[0])
96 if inspect
.ismethod (func
):
98 if not inspect
.isfunction (func
):
101 (args
, varargs
, varkw
, defaults
) = inspect
.getargspec (func
)
102 # No space between name and arglist for consistency with builtins.
103 print('_emacs_out', \
104 func
.__name
__ + inspect
.formatargspec (args
, varargs
, varkw
,
109 def all_names (object):
110 """Return (an approximation to) a list of all possible attribute
111 names reachable via the attributes of OBJECT, i.e. roughly the
112 leaves of the dictionary tree under it."""
114 def do_object (object, names
):
115 if inspect
.ismodule (object):
116 do_module (object, names
)
117 elif inspect
.isclass (object):
118 do_class (object, names
)
119 # Might have an object without its class in scope.
120 elif hasattr (object, '__class__'):
121 names
.add ('__class__')
122 do_class (object.__class
__, names
)
123 # Probably not a good idea to try to enumerate arbitrary
127 def do_module (module
, names
):
128 if hasattr (module
, '__all__'): # limited export list
129 names
.update(module
.__all
__)
130 for i
in module
.__all
__:
131 do_object (getattr (module
, i
), names
)
132 else: # use all names
133 names
.update(dir (module
))
134 for i
in dir (module
):
135 do_object (getattr (module
, i
), names
)
138 def do_class (object, names
):
141 if hasattr (object, '__bases__'): # superclasses
142 for i
in object.__bases
__: do_object (i
, names
)
145 return do_object (object, set([]))
147 def complete (name
, imports
):
148 """Complete TEXT in NAMESPACE and print a Lisp list of completions.
149 Exec IMPORTS first."""
150 import __main__
, keyword
152 def class_members(object):
154 if hasattr (object, '__bases__'):
155 for super in object.__bases
__:
156 names
= class_members (super)
162 dict = __main__
.__dict
__.copy()
163 if imports
: exec(imports
, dict)
166 for src
in [dir (__builtins__
), keyword
.kwlist
, list(dict.keys())]:
168 if elt
[:l
] == name
: names
.add(elt
)
170 base
= name
[:name
.rfind ('.')]
171 name
= name
[name
.rfind('.')+1:]
173 object = eval (base
, dict)
174 names
= set(dir (object))
175 if hasattr (object, '__class__'):
176 names
.add('__class__')
177 names
.update(class_members (object))
178 except: names
= all_names (dict)
180 print(sys
.exc_info())
184 print('_emacs_out (', end
=' ')
187 if base
: print('"%s.%s"' % (base
, n
), end
=' ')
188 else: print('"%s"' % n
, end
=' ')
191 def ehelp (name
, imports
):
192 """Get help on string NAME.
193 First try to eval name for, e.g. user definitions where we need
194 the object. Otherwise try the string form."""
197 try: exec(imports
, locls
)
199 try: help (eval (name
, globals(), locls
))
202 def eimport (mod
, dir):
203 """Import module MOD with directory DIR at the head of the search path.
204 NB doesn't load from DIR if MOD shadows a system module."""
205 from __main__
import __dict__
211 if mod
in __dict__
and inspect
.ismodule (__dict__
[mod
]):
212 imp
.reload (__dict__
[mod
])
214 __dict__
[mod
] = __import__ (mod
)
216 (type, value
, tb
) = sys
.exc_info ()
217 print("Traceback (most recent call last):")
218 traceback
.print_exception (type, value
, tb
.tb_next
)
222 def modpath (module
):
223 """Return the source file for the given MODULE (or None).
224 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
226 path
= __import__ (module
).__file
__
227 if path
[-4:] == '.pyc' and os
.path
.exists (path
[0:-1]):
229 print("_emacs_out", path
)
231 print("_emacs_out ()")
233 # print '_emacs_ok' # ready for input and can call continuation
235 # arch-tag: 37bfed38-5f4a-4027-a2bf-d5f41819dd89