[Pythonmac-SIG] Accessing front window in IDE
Joseph J. Strout
joe@strout.net
Fri, 8 Oct 1999 08:30:32 -0700
At 6:28 AM -0400 10/08/99, Gordon Worley wrote:
>Could you please write a short example of how to [get the frontmost window].
OK, here's a script that, when run, adds "# Spam!" to the end of the
frontmost window if that's an editor window. You'll note a couple of
simpler demos, which simply inspect the window or the editor object,
commented out. Place this in your IDE Scripts folder, and get the
IDE to rescan this folder with the "Python > Preferences > Set
Scripts Folder" menu command.
----------------------------------------------------------------------
"""
This script illustrates how to access the contents of the frontmost window
in the Python IDE. Handy for making little utilities for the "Scripts"
menu, like text reformatters and such.
"""
import W
import Win
import PyEdit
import Res
import PyAdvancedEditor
# get a reference to the Python object corresponding to the frontmost window
wid = Win.FrontWindow()
if wid and W._application._windows.has_key(wid):
window = W._application._windows[wid]
else:
window = None
# now, see if that's an editor window...
if window and isinstance(window, PyEdit.Editor):
# yep, we have an editor window... do something with (or to) it!
# demo 1: just inspect the window
#inspect(window)
# demo 2: inspect the actual editor
#editor = window.editgroup.editor
#inspect(editor)
# demo 3: grab the text, and operate on it
editor = window.editgroup.editor
selStart, selEnd = editor.ted.WEGetSelection()
text = editor.get()
text = text + "\r# Spam!"
editor.set(text)
editor.ted.WESetSelection(selStart, selEnd)
if isinstance(editor, PyAdvancedEditor.PyAdvancedEditor):
editor.markDirty(0, len(text))
----------------------------------------------------------------------
In the place where I've done "text = text + "\r# Spam!"", you could
instead do any manipulation on the text you want -- it's the full
text in the editor, with lines separated by '\r' characters. You
could tabify, detabify, etc. Or you could leave the text alone, and
do something with the window -- e.g., if you're good with
AppleEvents, you could write us a "Reveal in Finder" script that
switches to the Finder and selects the file corresponding to this
editor window.
If you do any of these, please post them here or on a web page so the
rest of us can enjoy them too!
Cheers,
-- Joe
,------------------------------------------------------------------.
| Joseph J. Strout Biocomputing -- The Salk Institute |
| joe@strout.net http://www.strout.net |
`------------------------------------------------------------------'