Attachment 'sage_emacs.py'

Download

   1 """Definitions used by commands sent to inferior Python in python.el."""
   2 
   3 # Copyright (C) 2004, 2005, 2006, 2007  Free Software Foundation, Inc.
   4 # Author: Dave Love <fx@gnu.org>
   5 
   6 # This file is part of GNU Emacs.
   7 
   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 2, or (at your option)
  11 # any later version.
  12 
  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.
  17 
  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.
  22 
  23 import os, sys, traceback, inspect, __main__
  24 from sets import Set
  25 import xreload
  26 
  27 __all__ = ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
  28 
  29 # Don't kill debug setting if it has been specified
  30 try:
  31     _emacs_py_debug
  32 except:
  33     _emacs_py_debug = True
  34 
  35 # Don't kill xreload setting if it has been specified
  36 try:
  37     _emacs_py_xreload
  38 except:
  39     _emacs_py_xreload = False
  40 
  41 def eexecfile (file):
  42     """Execute FILE and then remove it.
  43     Execute the file within the __main__ namespace.
  44     If we get an exception, print a traceback with the top frame
  45     (ourselves) excluded."""
  46     try:
  47        try: execfile (file, __main__.__dict__)
  48        except:
  49 	    (type, value, tb) = sys.exc_info ()
  50 	    # Lose the stack frame for this location.
  51 	    tb = tb.tb_next
  52 	    if tb is None:	# print_exception won't do it
  53 		print "Traceback (most recent call last):"
  54 	    traceback.print_exception (type, value, tb)
  55     finally:
  56 	os.remove (file)
  57 
  58 def eargs (name, imports):
  59     "Get arglist of NAME for Eldoc &c."
  60     try:
  61 	if imports: exec imports
  62 	parts = name.split ('.')
  63 	if len (parts) > 1:
  64 	    exec 'import ' + parts[0] # might fail
  65 	func = eval (name)
  66 	if inspect.isbuiltin (func) or type(func) is type:
  67 	    doc = func.__doc__
  68 	    if doc.find (' ->') != -1:
  69 		print '_emacs_out', doc.split (' ->')[0]
  70 	    else:
  71 		print '_emacs_out', doc.split ('\n')[0]
  72 	    return
  73 	if inspect.ismethod (func):
  74 	    func = func.im_func
  75 	if not inspect.isfunction (func):
  76             print '_emacs_out '
  77             return
  78 	(args, varargs, varkw, defaults) = inspect.getargspec (func)
  79 	# No space between name and arglist for consistency with builtins.
  80 	print '_emacs_out', \
  81 	    func.__name__ + inspect.formatargspec (args, varargs, varkw,
  82 						   defaults)
  83     except:
  84 	print "_emacs_out "
  85 
  86 def all_names (object):
  87     """Return (an approximation to) a list of all possible attribute
  88     names reachable via the attributes of OBJECT, i.e. roughly the
  89     leaves of the dictionary tree under it."""
  90 
  91     def do_object (object, names):
  92 	if inspect.ismodule (object):
  93 	    do_module (object, names)
  94 	elif inspect.isclass (object):
  95 	    do_class (object, names)
  96 	# Might have an object without its class in scope.
  97 	elif hasattr (object, '__class__'):
  98 	    names.add ('__class__')
  99 	    do_class (object.__class__, names)
 100 	# Probably not a good idea to try to enumerate arbitrary
 101 	# dictionaries...
 102 	return names
 103 
 104     def do_module (module, names):
 105 	if hasattr (module, '__all__'):	# limited export list
 106 	    names.union_update (module.__all__)
 107 	    for i in module.__all__:
 108 		do_object (getattr (module, i), names)
 109 	else:			# use all names
 110 	    names.union_update (dir (module))
 111 	    for i in dir (module):
 112 		do_object (getattr (module, i), names)
 113 	return names
 114 
 115     def do_class (object, names):
 116 	ns = dir (object)
 117 	names.union_update (ns)
 118 	if hasattr (object, '__bases__'): # superclasses
 119 	    for i in object.__bases__: do_object (i, names)
 120 	return names
 121 
 122     return do_object (object, Set ([]))
 123 
 124 def ipython_complete (name, imports=None):
 125     """Complete NAME using IPython and print a Lisp list of completions.
 126     IMPORTS is ignored at this time; kepy for compatibility with complete.
 127     """
 128     try:
 129         import __main__
 130         names = __main__.__IP.Completer.all_completions(name)
 131     except NameError:
 132         print "_emacs_out ()"
 133         
 134     print '_emacs_out (',
 135     for n in names:
 136         print '"%s"' % n,
 137     print ')'
 138 
 139 def complete (name, imports):
 140     """Complete TEXT in NAMESPACE and print a Lisp list of completions.
 141     Exec IMPORTS first."""
 142     import __main__, keyword
 143 
 144     def class_members(object):
 145 	names = dir (object)
 146 	if hasattr (object, '__bases__'):
 147 	    for super in object.__bases__:
 148 		names = class_members (super)
 149 	return names	
 150 
 151     names = Set ([])
 152     base = None
 153     try:
 154 	dict = __main__.__dict__.copy()
 155 	if imports: exec imports in dict
 156 	l = len (name)
 157 	if not "." in name:
 158 	    for list in [dir (__builtins__), keyword.kwlist, dict.keys()]:
 159 		for elt in list:
 160 		    if elt[:l] == name: names.add(elt)
 161 	else:
 162 	    base = name[:name.rfind ('.')]
 163 	    name = name[name.rfind('.')+1:]
 164 	    try:
 165 		object = eval (base, dict)
 166 		names = Set (dir (object))
 167 		if hasattr (object, '__class__'):
 168 		    names.add('__class__')
 169 		    names.union_update (class_members (object))
 170 	    except: names = all_names (dict)
 171     except: return []
 172     l = len(name)
 173     print '_emacs_out (',
 174     for n in names:
 175 	if name == n[:l]:
 176 	    if base: print '"%s.%s"' % (base, n),
 177 	    else: print '"%s"' % n,
 178     print ')'
 179 
 180 def ehelp (name, imports):
 181     """Get help on string NAME.
 182     First try to eval name for, e.g. user definitions where we need
 183     the object.  Otherwise try the string form."""
 184     locls = {}
 185     if imports:
 186 	try: exec imports in locls
 187 	except: pass
 188     try: help (eval (name, globals(), locls))
 189     except: help (name)
 190 
 191 def eimport (modname, dir, use_xreload=False):
 192     """Import module MODNAME from directory DIR at the head of the search path.
 193     NB doesn't load from DIR if MODNAME shadows a system module."""
 194     from __main__ import __dict__
 195 
 196     if _emacs_py_debug:
 197         print "Loading module %r from directory %r" % (modname, dir)
 198 
 199     old_path = sys.path
 200     sys.path = [dir] # XXX for now + sys.path
 201     try:
 202 	if True: # try:
 203             already_loaded = False
 204             try:
 205                 # easiest way to peel back the package structure
 206                 # print len(__dict__.keys())
 207                 mod = eval(modname, __dict__)
 208                 already_loaded = True
 209             except:
 210                 print "ACK!"
 211                 already_loaded = False            
 212 
 213             if already_loaded:
 214                 if use_xreload or _emacs_py_xreload:
 215                     if _emacs_py_debug:
 216                         print "xreload-ing %s" % mod
 217                     xreload.xreload (mod, path=[dir])
 218                 else:
 219                     if _emacs_py_debug:
 220                         print "reload-ing %s" % mod
 221                     reload (mod)
 222 	    else:
 223                 if _emacs_py_debug:
 224                     print "__import__(%r)" % modname
 225                 from __main__ import __dict__
 226 		__dict__[modname] = __import__ (modname)
 227 # 	except:
 228 #             traceback.print_exc()
 229 #             raise
 230     finally:
 231 	sys.path = old_path
 232 
 233 def modpath (module):
 234     """Return the source file for the given MODULE (or None).
 235 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
 236     try:
 237 	path = __import__ (module).__file__
 238 	if path[-4:] == '.pyc' and os.path.exists (path[0:-1]):
 239 	    path = path[:-1]
 240 	print "_emacs_out", path
 241     except:
 242 	print "_emacs_out ()"
 243 
 244 # print '_emacs_ok'		# ready for input and can call continuation
 245 
 246 # arch-tag: d90408f3-90e2-4de4-99c2-6eb9c7b9ca46

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2007-07-02 20:48:04, 0.5 KB) [[attachment:latex_7467776ede1bec69c698fdd6d8643fb43d54fa9f_p1.png]]
  • [get | view] (2007-06-15 00:55:02, 0.6 KB) [[attachment:pyrex-mode.el]]
  • [get | view] (2008-06-14 05:31:24, 430.3 KB) [[attachment:sage-mode-0.2.spkg]]
  • [get | view] (2008-06-17 05:41:57, 195.9 KB) [[attachment:sage-mode-0.3.1.spkg]]
  • [get | view] (2008-06-15 19:54:13, 195.6 KB) [[attachment:sage-mode-0.3.spkg]]
  • [get | view] (2008-06-18 01:01:49, 198.6 KB) [[attachment:sage-mode-0.4.spkg]]
  • [get | view] (2009-02-11 18:37:36, 215.4 KB) [[attachment:sage-mode-0.5.1.spkg]]
  • [get | view] (2009-02-19 21:12:24, 220.2 KB) [[attachment:sage-mode-0.5.2.spkg]]
  • [get | view] (2009-03-13 06:17:56, 235.1 KB) [[attachment:sage-mode-0.5.3.spkg]]
  • [get | view] (2009-03-13 17:36:34, 237.0 KB) [[attachment:sage-mode-0.5.4.spkg]]
  • [get | view] (2009-02-01 02:34:09, 212.7 KB) [[attachment:sage-mode-0.5.spkg]]
  • [get | view] (2009-05-17 18:06:57, 259.8 KB) [[attachment:sage-mode-0.6-dr.spkg]]
  • [get | view] (2009-05-15 18:22:26, 256.4 KB) [[attachment:sage-mode-0.6-nt.spkg]]
  • [get | view] (2009-05-12 04:35:18, 253.6 KB) [[attachment:sage-mode-0.6.spkg]]
  • [get | view] (2011-10-08 04:12:00, 263.3 KB) [[attachment:sage-mode-0.7.spkg]]
  • [get | view] (2007-06-15 00:52:58, 32.8 KB) [[attachment:sage-mode.el]]
  • [get | view] (2007-06-15 00:54:18, 7.5 KB) [[attachment:sage_emacs.py]]
  • [get | view] (2007-06-15 01:10:12, 26.0 KB) [[attachment:sagetest.py]]
  • [get | view] (2007-06-15 00:54:34, 6.9 KB) [[attachment:xreload.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.