* lisp/minibuffer.el (read-file-name-function, read-file-name-predicate)
[emacs.git] / etc / emacs2.py
blob7f0e44e3af2a9ae3b74cfe180c4216181bd82a54
1 """Definitions used by commands sent to inferior Python in python.el."""
3 # Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 # Author: Dave Love <fx@gnu.org>
6 # This file is part of GNU Emacs.
8 # GNU Emacs is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3, or (at your option)
11 # any later version.
13 # GNU Emacs is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with GNU Emacs; see the file COPYING. If not, write to the
20 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 # Boston, MA 02110-1301, USA.
23 import os, sys, traceback, inspect, __main__
25 try:
26 set
27 except:
28 from sets import Set as set
30 __all__ = ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
32 def format_exception (filename, should_remove_self):
33 type, value, tb = sys.exc_info ()
34 sys.last_type = type
35 sys.last_value = value
36 sys.last_traceback = tb
37 if type is SyntaxError:
38 try: # parse the error message
39 msg, (dummy_filename, lineno, offset, line) = value
40 except:
41 pass # Not the format we expect; leave it alone
42 else:
43 # Stuff in the right filename
44 value = SyntaxError(msg, (filename, lineno, offset, line))
45 sys.last_value = value
46 res = traceback.format_exception_only (type, value)
47 # There are some compilation errors which do not provide traceback so we
48 # should not massage it.
49 if should_remove_self:
50 tblist = traceback.extract_tb (tb)
51 del tblist[:1]
52 res = traceback.format_list (tblist)
53 if res:
54 res.insert(0, "Traceback (most recent call last):\n")
55 res[len(res):] = traceback.format_exception_only (type, value)
56 # traceback.print_exception(type, value, tb)
57 for line in res: print line,
59 def eexecfile (file):
60 """Execute FILE and then remove it.
61 Execute the file within the __main__ namespace.
62 If we get an exception, print a traceback with the top frame
63 (ourselves) excluded."""
64 # We cannot use real execfile since it has a bug where the file stays
65 # locked forever (under w32) if SyntaxError occurs.
66 # --- code based on code.py and PyShell.py.
67 try:
68 try:
69 source = open (file, "r").read()
70 code = compile (source, file, "exec")
71 # Other exceptions (shouldn't be any...) will (correctly) fall
72 # through to "final".
73 except (OverflowError, SyntaxError, ValueError):
74 # FIXME: When can compile() raise anything else than
75 # SyntaxError ????
76 format_exception (file, False)
77 return
78 try:
79 exec code in __main__.__dict__
80 except:
81 format_exception (file, True)
82 finally:
83 os.remove (file)
85 def eargs (name, imports):
86 "Get arglist of NAME for Eldoc &c."
87 try:
88 if imports: exec imports
89 parts = name.split ('.')
90 if len (parts) > 1:
91 exec 'import ' + parts[0] # might fail
92 func = eval (name)
93 if inspect.isbuiltin (func) or type(func) is type:
94 doc = func.__doc__
95 if doc.find (' ->') != -1:
96 print '_emacs_out', doc.split (' ->')[0]
97 else:
98 print '_emacs_out', doc.split ('\n')[0]
99 return
100 if inspect.ismethod (func):
101 func = func.im_func
102 if not inspect.isfunction (func):
103 print '_emacs_out '
104 return
105 (args, varargs, varkw, defaults) = inspect.getargspec (func)
106 # No space between name and arglist for consistency with builtins.
107 print '_emacs_out', \
108 func.__name__ + inspect.formatargspec (args, varargs, varkw,
109 defaults)
110 except:
111 print "_emacs_out "
113 def all_names (object):
114 """Return (an approximation to) a list of all possible attribute
115 names reachable via the attributes of OBJECT, i.e. roughly the
116 leaves of the dictionary tree under it."""
118 def do_object (object, names):
119 if inspect.ismodule (object):
120 do_module (object, names)
121 elif inspect.isclass (object):
122 do_class (object, names)
123 # Might have an object without its class in scope.
124 elif hasattr (object, '__class__'):
125 names.add ('__class__')
126 do_class (object.__class__, names)
127 # Probably not a good idea to try to enumerate arbitrary
128 # dictionaries...
129 return names
131 def do_module (module, names):
132 if hasattr (module, '__all__'): # limited export list
133 names.update(module.__all__)
134 for i in module.__all__:
135 do_object (getattr (module, i), names)
136 else: # use all names
137 names.update(dir (module))
138 for i in dir (module):
139 do_object (getattr (module, i), names)
140 return names
142 def do_class (object, names):
143 ns = dir (object)
144 names.update(ns)
145 if hasattr (object, '__bases__'): # superclasses
146 for i in object.__bases__: do_object (i, names)
147 return names
149 return do_object (object, set([]))
151 def complete (name, imports):
152 """Complete TEXT in NAMESPACE and print a Lisp list of completions.
153 Exec IMPORTS first."""
154 import __main__, keyword
156 def class_members(object):
157 names = dir (object)
158 if hasattr (object, '__bases__'):
159 for super in object.__bases__:
160 names = class_members (super)
161 return names
163 names = set([])
164 base = None
165 try:
166 dict = __main__.__dict__.copy()
167 if imports: exec imports in dict
168 l = len (name)
169 if not "." in name:
170 for src in [dir (__builtins__), keyword.kwlist, dict.keys()]:
171 for elt in src:
172 if elt[:l] == name: names.add(elt)
173 else:
174 base = name[:name.rfind ('.')]
175 name = name[name.rfind('.')+1:]
176 try:
177 object = eval (base, dict)
178 names = set(dir (object))
179 if hasattr (object, '__class__'):
180 names.add('__class__')
181 names.update(class_members (object))
182 except: names = all_names (dict)
183 except:
184 print sys.exc_info()
185 names = []
187 l = len(name)
188 print '_emacs_out (',
189 for n in names:
190 if name == n[:l]:
191 if base: print '"%s.%s"' % (base, n),
192 else: print '"%s"' % n,
193 print ')'
195 def ehelp (name, imports):
196 """Get help on string NAME.
197 First try to eval name for, e.g. user definitions where we need
198 the object. Otherwise try the string form."""
199 locls = {}
200 if imports:
201 try: exec imports in locls
202 except: pass
203 try: help (eval (name, globals(), locls))
204 except: help (name)
206 def eimport (mod, dir):
207 """Import module MOD with directory DIR at the head of the search path.
208 NB doesn't load from DIR if MOD shadows a system module."""
209 from __main__ import __dict__
211 path0 = sys.path[0]
212 sys.path[0] = dir
213 try:
214 try:
215 if __dict__.has_key(mod) and inspect.ismodule (__dict__[mod]):
216 reload (__dict__[mod])
217 else:
218 __dict__[mod] = __import__ (mod)
219 except:
220 (type, value, tb) = sys.exc_info ()
221 print "Traceback (most recent call last):"
222 traceback.print_exception (type, value, tb.tb_next)
223 finally:
224 sys.path[0] = path0
226 def modpath (module):
227 """Return the source file for the given MODULE (or None).
228 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
229 try:
230 path = __import__ (module).__file__
231 if path[-4:] == '.pyc' and os.path.exists (path[0:-1]):
232 path = path[:-1]
233 print "_emacs_out", path
234 except:
235 print "_emacs_out ()"
237 # print '_emacs_ok' # ready for input and can call continuation
239 # arch-tag: d90408f3-90e2-4de4-99c2-6eb9c7b9ca46