Attachment 'lwickjr.Module.Edit.py'

Download

   1 import inspect
   2 import os
   3 import sys
   4 import UT
   5 
   6 try:
   7   Geometry = UT.Load(os.path.join(
   8     os.path.dirname(__file__),
   9     'Geometry.Pickle'))
  10 except:
  11   Geometry = {}
  12 
  13 class Edit:
  14   ## 200412.12: New in v?.?:
  15   ## * Added function with matching menu entry to unset the current
  16   ##   file`s edit-window geometry.
  17   ## 200503.15: No longer needed:
  18   ##  a means of purging the Geometry of all entries for files that no
  19   ##  longer exist.
  20   ## 200510.11: changed the call of `sitecustomize.patch` to
  21   ## `sitecustomize.patchNames` to reflect the name change in
  22   ## `sitecustomize`.
  23   def __init__(Self, editwin):
  24     global flist
  25     flist = editwin.flist
  26     geometry = Geometry.get(editwin.io.filename, '+46+44')
  27     editwin.top.geometry(geometry)
  28     Self.editwin = editwin
  29   menudefs = [ ('options', [('_Save window size and position',
  30                              '<<save-size>>'),
  31                             ('Clear window size and position',
  32                              '<<clear-size>>'),
  33                             None,
  34                             ]), ]
  35 
  36   def clear_size_event(Self, Event):
  37     try:
  38       del Geometry[Self.editwin.io.filename]
  39     except:
  40       pass
  41     save()
  42     UT.dump(Geometry)
  43     print `Self.editwin.root`
  44 
  45   def save_size_event(Self, Event):
  46     Geometry[Self.editwin.io.filename] = '%sx%s+%s+%s' % tuple(Self.editwin.get_geometry())
  47     save()
  48     UT.dump(Geometry)
  49     print `Self.editwin.root`
  50 
  51 def save():
  52   ## 200503.15: New in v?.?:
  53   ## * Added call to new purge() function.
  54   purge()
  55   UT.Save(os.path.join(os.path.dirname(__file__), 'Geometry.Pickle'), Geometry, True, 0)
  56   print >> sys.stderr, 'Geometry saved.'
  57 
  58 def purge():
  59   ## 200503.15: Version 0.0:
  60   ## Called by save() prior to saving, this function purges the
  61   ## Geometry dictionary of entries for files that no longer exist.
  62   for Path in sorted(Geometry.keys()):
  63     if Path:
  64       try: os.stat(Path)
  65       except:
  66         del Geometry[Path]
  67         print >> sys.stderr, 'Purged:', Path
  68 
  69 def edit(Thing='', ignoreCustomHook=False, *Args, **kwArgs):
  70   """Edit the source code of an object, if available
  71 
  72 Edit.edit(Thing)
  73 
  74 Version: 0.8
  75 
  76 Arguments:
  77   Thing: The object whose source is to be edited.
  78   ignoreCustomHook: A flag to ignore the `__Edit__` hook.
  79 
  80 Result:
  81   None (usually)
  82 
  83 Notes:
  84   Object must evaluate to an object that satisfies one or more of the
  85   following criteria:
  86   * The object has a callable attribute named __Edit__.
  87   * The module where the object was defined is identifiable [by module
  88     `inspect`], and the module's source is available to be edited.
  89   * The object is a string value that identifies a file on the host OS.
  90 
  91   If the object has a callable attribute named __Edit__, it is called,
  92   and the result is the return value, else the I.D.L.E. editor is
  93   invoked, with the source positioned at the object's definition, if
  94   possible, and None is returned. Live-object editors should be
  95   prepared to accept an optional keyword argument named `__file__`
  96   containing the filesystem path of the file that object was loaded
  97   from. This will not be present if edit did not unpickle the object
  98   from a file.
  99 
 100   When `ignoreCustomHook` is True, `edit`, does NOT honor `__Edit__`
 101   attributes. This is useful for creating classes whose instances use
 102   a custom editor, without invoking the custom editor on the class
 103   itself.
 104 
 105 Author:
 106   Lyster E. Wick Jr.
 107 """
 108   ## 200309.17: New in v0.5:
 109   ## * Support for I.D.L.E.'s internal editor added.
 110   ##   Old docstring:
 111   ##    An external editor is invoked on the source file,
 112   ##    and the module is reloaded when the editor returns.
 113   ## * Type-checking converted to use isinstance() instead of directly
 114   ##   comparing the result of type() with specific hard-coded types.
 115   ## 200310.23: New in v0.6:
 116   ## * Objects may define custom editors: Iff the `Thing` to be edited has a
 117   ##   callable attribute named `__Edit__`, `Thing.__Edit__(Thing)` is called
 118   ##   in place of the usual mechanism, and its return value is returned.
 119   ## 200311.03: New in v0.7: ???
 120   ## 200312.03: New in v0.8:
 121   ## * now uses module `inspect` to identify the source code of an
 122   ##   object, when possible
 123   ## 200312.03: New in v0.9:
 124   ## * added flag `ignoreCustomHook` to bypass the `__Edit__` custom editor hook.
 125   ## 200510.10: New in v0.10:
 126   ## * updated refrences to sitecustomize.patch to use the new name (.patchNames).
 127   ## 200511.06: New iv v0.11:
 128   ## * Added long-missing code to allow the editing of specified text files.
 129   ## * Removed references to the module a thing is defined in; since
 130   ##   module `inspect` deals with that, we don't have to.
 131   ## * Added the ability to extract a live object from a file containing a
 132   ##   pickle, and live-edit the resulting object.
 133   ## * Optimized module filename extension manipulation a tad,
 134   ##   tightening the test to trigger only when the whole extension
 135   ##   matches, instead of whenever the end of the name matches
 136   ##   without checking for the extension seperator.
 137   ## * Added an optional keyword `__file__` to the live-object editor
 138   ##   call when the object is extracted from a pickle.
 139   ## * Updated the docstring a tad.
 140   ## * Added comments to the code.
 141   ## * ??? Nothing else I can remember just a few miniutes later.
 142   global _LastEdited
 143   import sitecustomize, types
 144   if Thing=='':
 145     Thing = _LastEdited
 146   else:
 147     _LastEdited = Thing
 148   # We do this here, in case we have a live editable object without a
 149   # companion filesystem object.
 150   if not ignoreCustomHook \
 151     and hasattr(Thing, '__Edit__') \
 152     and callable(Thing.__Edit__):
 153     return Thing.__Edit__(Thing, *Args, **kwArgs)
 154   FileName  =None
 155   SourceLine=None
 156   try: FileName = inspect.getsourcefile(Thing)
 157   except: pass
 158   try: SourceLine = inspect.getsourcelines(Thing)[-1]
 159   except: pass
 160   # Do we have a file name instead of a live object?
 161   if isinstance(Thing, basestring) \
 162     and os.path.exists(Thing):
 163     FileName = sitecustomize._patch(Thing)
 164   if FileName is None:
 165     raise ValueError, "Can't identify source file of %r" % (Thing,)
 166   # Normalize the filespec case to match the filesystem.
 167   FileName = os.path.join(sitecustomize._patch(os.path.dirname(FileName)),os.path.basename(FileName))
 168   # If we have a module loaded from a bytecodefile, we need the sourcefile name.
 169   if FileName[-4:].lower() in (".pyc", "pyo"):   FileName=FileName[:-1]
 170   # Do we have a picklefile?
 171   try: Thing = UT.Load(FileName)
 172   except: pass
 173   # We do this again here, in case we found a pickled editable object
 174   # in the filesystem object.
 175   if not ignoreCustomHook \
 176     and hasattr(Thing, '__Edit__') \
 177     and callable(Thing.__Edit__):
 178     return Thing.__Edit__(Thing, __file__=FileName, *Args, **kwArgs)
 179   edit = flist.open(FileName)
 180   if SourceLine:
 181     edit.gotoline(SourceLine)
 182 
 183 _LastEdited = None
 184 __Aliases__ = {
 185   'edit': edit,
 186   'save': save,
 187   }
 188 import sys
 189 sys.modules['Edit']=sys.modules['idlelib.Edit']

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] (2005-11-19 16:33:10, 10.9 KB) [[attachment:lwickjr.Module.Alias.py]]
  • [get | view] (2005-11-19 16:34:55, 7.0 KB) [[attachment:lwickjr.Module.Edit.py]]
  • [get | view] (2005-11-26 16:46:21, 21.6 KB) [[attachment:lwickjr.Module.UT.py]]
 All files | Selected Files: delete move to page copy to page

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

Unable to edit the page? See the FrontPage for instructions.