emacs2.py 8.1 KB

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