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