blob: 7212622445b36992cb3468d7a0401b649298652d [file] [log] [blame]
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001"""A (less & less) simple Python editor"""
2
3import W
4import Wtraceback
5from Wkeys import *
6
Just van Rossum40f9b7b1999-01-30 22:39:17 +00007import MacOS
Jack Jansenfd0b00e2003-01-26 22:15:48 +00008import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +00009from Carbon import Win
10from Carbon import Res
11from Carbon import Evt
Just van Rossum2ad94192002-07-12 12:06:17 +000012from Carbon import Qd
Jack Jansene7ee17c2003-02-06 22:32:35 +000013from Carbon import File
Just van Rossum40f9b7b1999-01-30 22:39:17 +000014import os
15import imp
16import sys
17import string
18import marshal
Jack Jansen9ad27522001-02-21 13:54:31 +000019import re
Just van Rossum40f9b7b1999-01-30 22:39:17 +000020
Jack Jansene7ee17c2003-02-06 22:32:35 +000021smAllScripts = -3
22
Just van Rossum40144012002-02-04 12:52:44 +000023if hasattr(Win, "FrontNonFloatingWindow"):
24 MyFrontWindow = Win.FrontNonFloatingWindow
25else:
26 MyFrontWindow = Win.FrontWindow
27
28
Just van Rossum73efed22000-04-09 19:45:22 +000029try:
Just van Rossum0f2fd162000-10-20 06:36:30 +000030 import Wthreading
Just van Rossum73efed22000-04-09 19:45:22 +000031except ImportError:
Just van Rossum0f2fd162000-10-20 06:36:30 +000032 haveThreading = 0
33else:
34 haveThreading = Wthreading.haveThreading
Just van Rossum73efed22000-04-09 19:45:22 +000035
Just van Rossum40f9b7b1999-01-30 22:39:17 +000036_scriptuntitledcounter = 1
Fred Drake79e75e12001-07-20 19:05:50 +000037_wordchars = string.ascii_letters + string.digits + "_"
Just van Rossum40f9b7b1999-01-30 22:39:17 +000038
39
Just van Rossum73efed22000-04-09 19:45:22 +000040runButtonLabels = ["Run all", "Stop!"]
41runSelButtonLabels = ["Run selection", "Pause!", "Resume"]
42
43
Just van Rossum40f9b7b1999-01-30 22:39:17 +000044class Editor(W.Window):
45
46 def __init__(self, path = "", title = ""):
47 defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs()
48 global _scriptuntitledcounter
49 if not path:
50 if title:
51 self.title = title
52 else:
53 self.title = "Untitled Script " + `_scriptuntitledcounter`
54 _scriptuntitledcounter = _scriptuntitledcounter + 1
55 text = ""
56 self._creator = W._signature
Jack Jansen9a389472002-03-29 21:26:04 +000057 self._eoln = os.linesep
Just van Rossum40f9b7b1999-01-30 22:39:17 +000058 elif os.path.exists(path):
59 path = resolvealiases(path)
60 dir, name = os.path.split(path)
61 self.title = name
62 f = open(path, "rb")
63 text = f.read()
64 f.close()
Jack Jansene7ee17c2003-02-06 22:32:35 +000065 self._creator, filetype = MacOS.GetCreatorAndType(path)
Just van Rossum40f9b7b1999-01-30 22:39:17 +000066 else:
67 raise IOError, "file '%s' does not exist" % path
68 self.path = path
69
Just van Rossumc7ba0801999-05-21 21:42:27 +000070 if '\n' in text:
Just van Rossumc7ba0801999-05-21 21:42:27 +000071 if string.find(text, '\r\n') >= 0:
Jack Jansen9a389472002-03-29 21:26:04 +000072 self._eoln = '\r\n'
Just van Rossumc7ba0801999-05-21 21:42:27 +000073 else:
Jack Jansen9a389472002-03-29 21:26:04 +000074 self._eoln = '\n'
75 text = string.replace(text, self._eoln, '\r')
76 change = 0
Just van Rossumc7ba0801999-05-21 21:42:27 +000077 else:
78 change = 0
Jack Jansen9a389472002-03-29 21:26:04 +000079 self._eoln = '\r'
Just van Rossumc7ba0801999-05-21 21:42:27 +000080
Just van Rossum40f9b7b1999-01-30 22:39:17 +000081 self.settings = {}
82 if self.path:
83 self.readwindowsettings()
84 if self.settings.has_key("windowbounds"):
85 bounds = self.settings["windowbounds"]
86 else:
87 bounds = defaultwindowsize
88 if self.settings.has_key("fontsettings"):
89 self.fontsettings = self.settings["fontsettings"]
90 else:
91 self.fontsettings = defaultfontsettings
92 if self.settings.has_key("tabsize"):
93 try:
94 self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"]
95 except:
96 self.tabsettings = defaulttabsettings
97 else:
98 self.tabsettings = defaulttabsettings
Just van Rossum40f9b7b1999-01-30 22:39:17 +000099
Just van Rossumc7ba0801999-05-21 21:42:27 +0000100 W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000101 self.setupwidgets(text)
Just van Rossumc7ba0801999-05-21 21:42:27 +0000102 if change > 0:
Just van Rossumf7f93882001-11-02 19:24:41 +0000103 self.editgroup.editor.textchanged()
Just van Rossumc7ba0801999-05-21 21:42:27 +0000104
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000105 if self.settings.has_key("selection"):
106 selstart, selend = self.settings["selection"]
107 self.setselection(selstart, selend)
108 self.open()
109 self.setinfotext()
110 self.globals = {}
111 self._buf = "" # for write method
112 self.debugging = 0
113 self.profiling = 0
Jack Jansenff773eb2002-03-31 22:01:33 +0000114 self.run_as_main = self.settings.get("run_as_main", 0)
115 self.run_with_interpreter = self.settings.get("run_with_interpreter", 0)
116 self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
Just van Rossum73efed22000-04-09 19:45:22 +0000117 self._threadstate = (0, 0)
118 self._thread = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000119
120 def readwindowsettings(self):
121 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000122 resref = Res.FSpOpenResFile(self.path, 1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000123 except Res.Error:
124 return
125 try:
126 Res.UseResFile(resref)
127 data = Res.Get1Resource('PyWS', 128)
128 self.settings = marshal.loads(data.data)
129 except:
130 pass
131 Res.CloseResFile(resref)
132
133 def writewindowsettings(self):
134 try:
Jack Jansend13c3852000-06-20 21:59:25 +0000135 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000136 except Res.Error:
Jack Jansene7ee17c2003-02-06 22:32:35 +0000137 Res.FSpCreateResFile(self.path, self._creator, 'TEXT', smAllScripts)
Jack Jansend13c3852000-06-20 21:59:25 +0000138 resref = Res.FSpOpenResFile(self.path, 3)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000139 try:
140 data = Res.Resource(marshal.dumps(self.settings))
141 Res.UseResFile(resref)
142 try:
143 temp = Res.Get1Resource('PyWS', 128)
144 temp.RemoveResource()
145 except Res.Error:
146 pass
147 data.AddResource('PyWS', 128, "window settings")
148 finally:
149 Res.UpdateResFile(resref)
150 Res.CloseResFile(resref)
151
152 def getsettings(self):
153 self.settings = {}
154 self.settings["windowbounds"] = self.getbounds()
155 self.settings["selection"] = self.getselection()
156 self.settings["fontsettings"] = self.editgroup.editor.getfontsettings()
157 self.settings["tabsize"] = self.editgroup.editor.gettabsettings()
158 self.settings["run_as_main"] = self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000159 self.settings["run_with_interpreter"] = self.run_with_interpreter
Jack Jansenff773eb2002-03-31 22:01:33 +0000160 self.settings["run_with_cl_interpreter"] = self.run_with_cl_interpreter
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000161
162 def get(self):
163 return self.editgroup.editor.get()
164
165 def getselection(self):
166 return self.editgroup.editor.ted.WEGetSelection()
167
168 def setselection(self, selstart, selend):
169 self.editgroup.editor.setselection(selstart, selend)
170
171 def getfilename(self):
172 if self.path:
173 return self.path
174 return '<%s>' % self.title
175
176 def setupwidgets(self, text):
Just van Rossumf376ef02001-11-18 14:12:43 +0000177 topbarheight = 24
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000178 popfieldwidth = 80
179 self.lastlineno = None
180
181 # make an editor
182 self.editgroup = W.Group((0, topbarheight + 1, 0, 0))
183 editor = W.PyEditor((0, 0, -15,-15), text,
184 fontsettings = self.fontsettings,
185 tabsettings = self.tabsettings,
186 file = self.getfilename())
187
188 # make the widgets
189 self.popfield = ClassFinder((popfieldwidth - 17, -15, 16, 16), [], self.popselectline)
190 self.linefield = W.EditText((-1, -15, popfieldwidth - 15, 16), inset = (6, 1))
191 self.editgroup._barx = W.Scrollbar((popfieldwidth - 2, -15, -14, 16), editor.hscroll, max = 32767)
192 self.editgroup._bary = W.Scrollbar((-15, 14, 16, -14), editor.vscroll, max = 32767)
193 self.editgroup.editor = editor # add editor *after* scrollbars
194
195 self.editgroup.optionsmenu = W.PopupMenu((-15, -1, 16, 16), [])
196 self.editgroup.optionsmenu.bind('<click>', self.makeoptionsmenu)
197
198 self.bevelbox = W.BevelBox((0, 0, 0, topbarheight))
199 self.hline = W.HorizontalLine((0, topbarheight, 0, 0))
Just van Rossumf376ef02001-11-18 14:12:43 +0000200 self.infotext = W.TextBox((175, 6, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000))
201 self.runbutton = W.BevelButton((6, 4, 80, 16), runButtonLabels[0], self.run)
202 self.runselbutton = W.BevelButton((90, 4, 80, 16), runSelButtonLabels[0], self.runselection)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000203
204 # bind some keys
205 editor.bind("cmdr", self.runbutton.push)
206 editor.bind("enter", self.runselbutton.push)
207 editor.bind("cmdj", self.domenu_gotoline)
208 editor.bind("cmdd", self.domenu_toggledebugger)
209 editor.bind("<idle>", self.updateselection)
210
211 editor.bind("cmde", searchengine.setfindstring)
212 editor.bind("cmdf", searchengine.show)
213 editor.bind("cmdg", searchengine.findnext)
214 editor.bind("cmdshiftr", searchengine.replace)
215 editor.bind("cmdt", searchengine.replacefind)
216
217 self.linefield.bind("return", self.dolinefield)
218 self.linefield.bind("enter", self.dolinefield)
219 self.linefield.bind("tab", self.dolinefield)
220
221 # intercept clicks
222 editor.bind("<click>", self.clickeditor)
223 self.linefield.bind("<click>", self.clicklinefield)
224
225 def makeoptionsmenu(self):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000226 menuitems = [('Font settings\xc9', self.domenu_fontsettings),
227 ("Save options\xc9", self.domenu_options),
Just van Rossum12710051999-02-27 17:18:30 +0000228 '-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000229 ('\0' + chr(self.run_as_main) + 'Run as __main__', self.domenu_toggle_run_as_main),
Jack Jansenff773eb2002-03-31 22:01:33 +0000230 #('\0' + chr(self.run_with_interpreter) + 'Run with Interpreter', self.domenu_dtoggle_run_with_interpreter),
231 ('\0' + chr(self.run_with_cl_interpreter) + 'Run with commandline Python', self.domenu_toggle_run_with_cl_interpreter),
232 '-',
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000233 ('Modularize', self.domenu_modularize),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000234 ('Browse namespace\xc9', self.domenu_browsenamespace),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000235 '-']
236 if self.profiling:
237 menuitems = menuitems + [('Disable profiler', self.domenu_toggleprofiler)]
238 else:
239 menuitems = menuitems + [('Enable profiler', self.domenu_toggleprofiler)]
240 if self.editgroup.editor._debugger:
241 menuitems = menuitems + [('Disable debugger', self.domenu_toggledebugger),
242 ('Clear breakpoints', self.domenu_clearbreakpoints),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000243 ('Edit breakpoints\xc9', self.domenu_editbreakpoints)]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000244 else:
245 menuitems = menuitems + [('Enable debugger', self.domenu_toggledebugger)]
246 self.editgroup.optionsmenu.set(menuitems)
247
248 def domenu_toggle_run_as_main(self):
249 self.run_as_main = not self.run_as_main
Just van Rossum0f2fd162000-10-20 06:36:30 +0000250 self.run_with_interpreter = 0
Jack Jansenff773eb2002-03-31 22:01:33 +0000251 self.run_with_cl_interpreter = 0
Just van Rossumf7f93882001-11-02 19:24:41 +0000252 self.editgroup.editor.selectionchanged()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000253
Jack Jansenff773eb2002-03-31 22:01:33 +0000254 def XXdomenu_toggle_run_with_interpreter(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000255 self.run_with_interpreter = not self.run_with_interpreter
256 self.run_as_main = 0
Jack Jansenff773eb2002-03-31 22:01:33 +0000257 self.run_with_cl_interpreter = 0
258 self.editgroup.editor.selectionchanged()
259
260 def domenu_toggle_run_with_cl_interpreter(self):
261 self.run_with_cl_interpreter = not self.run_with_cl_interpreter
262 self.run_as_main = 0
263 self.run_with_interpreter = 0
Just van Rossumf7f93882001-11-02 19:24:41 +0000264 self.editgroup.editor.selectionchanged()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000265
266 def showbreakpoints(self, onoff):
267 self.editgroup.editor.showbreakpoints(onoff)
268 self.debugging = onoff
269
270 def domenu_clearbreakpoints(self, *args):
271 self.editgroup.editor.clearbreakpoints()
272
273 def domenu_editbreakpoints(self, *args):
274 self.editgroup.editor.editbreakpoints()
275
276 def domenu_toggledebugger(self, *args):
277 if not self.debugging:
278 W.SetCursor('watch')
279 self.debugging = not self.debugging
280 self.editgroup.editor.togglebreakpoints()
281
282 def domenu_toggleprofiler(self, *args):
283 self.profiling = not self.profiling
284
285 def domenu_browsenamespace(self, *args):
286 import PyBrowser, W
287 W.SetCursor('watch')
288 globals, file, modname = self.getenvironment()
289 if not modname:
290 modname = self.title
291 PyBrowser.Browser(globals, "Object browser: " + modname)
292
293 def domenu_modularize(self, *args):
294 modname = _filename_as_modname(self.title)
295 if not modname:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000296 raise W.AlertError, "Can't modularize \"%s\"" % self.title
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000297 run_as_main = self.run_as_main
298 self.run_as_main = 0
299 self.run()
300 self.run_as_main = run_as_main
301 if self.path:
302 file = self.path
303 else:
304 file = self.title
305
306 if self.globals and not sys.modules.has_key(modname):
307 module = imp.new_module(modname)
308 for attr in self.globals.keys():
309 setattr(module,attr,self.globals[attr])
310 sys.modules[modname] = module
311 self.globals = {}
312
313 def domenu_fontsettings(self, *args):
314 import FontSettings
315 fontsettings = self.editgroup.editor.getfontsettings()
316 tabsettings = self.editgroup.editor.gettabsettings()
317 settings = FontSettings.FontDialog(fontsettings, tabsettings)
318 if settings:
319 fontsettings, tabsettings = settings
320 self.editgroup.editor.setfontsettings(fontsettings)
321 self.editgroup.editor.settabsettings(tabsettings)
322
Just van Rossum12710051999-02-27 17:18:30 +0000323 def domenu_options(self, *args):
Just van Rossumca3d3072002-03-29 21:48:42 +0000324 rv = SaveOptions(self._creator, self._eoln)
325 if rv:
Just van Rossumf7f93882001-11-02 19:24:41 +0000326 self.editgroup.editor.selectionchanged() # ouch...
Just van Rossumca3d3072002-03-29 21:48:42 +0000327 self._creator, self._eoln = rv
Just van Rossum12710051999-02-27 17:18:30 +0000328
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000329 def clicklinefield(self):
330 if self._currentwidget <> self.linefield:
331 self.linefield.select(1)
332 self.linefield.selectall()
333 return 1
334
335 def clickeditor(self):
336 if self._currentwidget <> self.editgroup.editor:
337 self.dolinefield()
338 return 1
339
340 def updateselection(self, force = 0):
341 sel = min(self.editgroup.editor.getselection())
342 lineno = self.editgroup.editor.offsettoline(sel)
343 if lineno <> self.lastlineno or force:
344 self.lastlineno = lineno
345 self.linefield.set(str(lineno + 1))
346 self.linefield.selview()
347
348 def dolinefield(self):
349 try:
350 lineno = string.atoi(self.linefield.get()) - 1
351 if lineno <> self.lastlineno:
352 self.editgroup.editor.selectline(lineno)
353 self.updateselection(1)
354 except:
355 self.updateselection(1)
356 self.editgroup.editor.select(1)
357
358 def setinfotext(self):
359 if not hasattr(self, 'infotext'):
360 return
361 if self.path:
362 self.infotext.set(self.path)
363 else:
364 self.infotext.set("")
365
366 def close(self):
367 if self.editgroup.editor.changed:
Just van Rossum25ddc632001-07-05 07:06:26 +0000368 Qd.InitCursor()
369 save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title,
370 default=1, no="Don\xd5t save")
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000371 if save > 0:
372 if self.domenu_save():
373 return 1
374 elif save < 0:
375 return 1
Just van Rossum25ddc632001-07-05 07:06:26 +0000376 self.globals = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000377 W.Window.close(self)
378
379 def domenu_close(self, *args):
380 return self.close()
381
382 def domenu_save(self, *args):
383 if not self.path:
384 # Will call us recursively
385 return self.domenu_save_as()
386 data = self.editgroup.editor.get()
Jack Jansen9a389472002-03-29 21:26:04 +0000387 if self._eoln != '\r':
388 data = string.replace(data, '\r', self._eoln)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000389 fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings
390 fp.write(data)
391 fp.close()
Jack Jansene7ee17c2003-02-06 22:32:35 +0000392 MacOS.SetCreatorAndType(self.path, self._creator, 'TEXT')
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000393 self.getsettings()
394 self.writewindowsettings()
395 self.editgroup.editor.changed = 0
396 self.editgroup.editor.selchanged = 0
397 import linecache
398 if linecache.cache.has_key(self.path):
399 del linecache.cache[self.path]
400 import macostools
401 macostools.touched(self.path)
402
403 def can_save(self, menuitem):
404 return self.editgroup.editor.changed or self.editgroup.editor.selchanged
405
406 def domenu_save_as(self, *args):
Jack Jansenfd0b00e2003-01-26 22:15:48 +0000407 path = EasyDialogs.AskFileForSave(message='Save as:', savedFileName=self.title)
408 if not path:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000409 return 1
410 self.showbreakpoints(0)
Jack Jansenfd0b00e2003-01-26 22:15:48 +0000411 self.path = path
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000412 self.setinfotext()
413 self.title = os.path.split(self.path)[-1]
414 self.wid.SetWTitle(self.title)
415 self.domenu_save()
416 self.editgroup.editor.setfile(self.getfilename())
417 app = W.getapplication()
418 app.makeopenwindowsmenu()
419 if hasattr(app, 'makescriptsmenu'):
420 app = W.getapplication()
Jack Jansene7ee17c2003-02-06 22:32:35 +0000421 fsr, changed = app.scriptsfolder.FSResolveAlias(None)
422 path = fsr.as_pathname()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000423 if path == self.path[:len(path)]:
424 W.getapplication().makescriptsmenu()
425
426 def domenu_save_as_applet(self, *args):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000427 import buildtools
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000428
429 buildtools.DEBUG = 0 # ouch.
430
431 if self.title[-3:] == ".py":
432 destname = self.title[:-3]
433 else:
434 destname = self.title + ".applet"
Jack Jansenfd0b00e2003-01-26 22:15:48 +0000435 destname = EasyDialogs.AskFileForSave(message='Save as Applet:',
436 savedFileName=destname)
437 if not destname:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000438 return 1
439 W.SetCursor("watch")
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000440 if self.path:
441 filename = self.path
442 if filename[-3:] == ".py":
443 rsrcname = filename[:-3] + '.rsrc'
444 else:
445 rsrcname = filename + '.rsrc'
446 else:
447 filename = self.title
448 rsrcname = ""
449
450 pytext = self.editgroup.editor.get()
451 pytext = string.split(pytext, '\r')
452 pytext = string.join(pytext, '\n') + '\n'
453 try:
454 code = compile(pytext, filename, "exec")
455 except (SyntaxError, EOFError):
456 raise buildtools.BuildError, "Syntax error in script %s" % `filename`
Jack Jansenc0452da2003-02-12 15:38:37 +0000457
458 import tempfile
459 tmpdir = tempfile.mkdtemp()
460
461 if filename[-3:] != ".py":
462 filename = filename + ".py"
463 filename = os.path.join(tmpdir, os.path.split(filename)[1])
464 fp = open(filename, "w")
465 fp.write(pytext)
466 fp.close()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000467
468 # Try removing the output file
469 try:
470 os.remove(destname)
471 except os.error:
472 pass
473 template = buildtools.findtemplate()
Jack Jansenc0452da2003-02-12 15:38:37 +0000474 buildtools.process(template, filename, destname, rsrcname=rsrcname, progress=None)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000475
476 def domenu_gotoline(self, *args):
477 self.linefield.selectall()
478 self.linefield.select(1)
479 self.linefield.selectall()
480
481 def domenu_selectline(self, *args):
482 self.editgroup.editor.expandselection()
483
484 def domenu_find(self, *args):
485 searchengine.show()
486
487 def domenu_entersearchstring(self, *args):
488 searchengine.setfindstring()
489
490 def domenu_replace(self, *args):
491 searchengine.replace()
492
493 def domenu_findnext(self, *args):
494 searchengine.findnext()
495
496 def domenu_replacefind(self, *args):
497 searchengine.replacefind()
498
499 def domenu_run(self, *args):
500 self.runbutton.push()
501
502 def domenu_runselection(self, *args):
503 self.runselbutton.push()
504
505 def run(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000506 if self._threadstate == (0, 0):
507 self._run()
508 else:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000509 lock = Wthreading.Lock()
510 lock.acquire()
511 self._thread.postException(KeyboardInterrupt)
512 if self._thread.isBlocked():
Just van Rossum73efed22000-04-09 19:45:22 +0000513 self._thread.start()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000514 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000515
516 def _run(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000517 if self.run_with_interpreter:
518 if self.editgroup.editor.changed:
Just van Rossum2ad94192002-07-12 12:06:17 +0000519 Qd.InitCursor()
Just van Rossumdc3c6172001-06-19 21:37:33 +0000520 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
Just van Rossum0f2fd162000-10-20 06:36:30 +0000521 if save > 0:
522 if self.domenu_save():
523 return
524 elif save < 0:
525 return
526 if not self.path:
527 raise W.AlertError, "Can't run unsaved file"
528 self._run_with_interpreter()
Jack Jansenff773eb2002-03-31 22:01:33 +0000529 elif self.run_with_cl_interpreter:
Jack Jansenff773eb2002-03-31 22:01:33 +0000530 if self.editgroup.editor.changed:
Just van Rossum2ad94192002-07-12 12:06:17 +0000531 Qd.InitCursor()
Jack Jansenff773eb2002-03-31 22:01:33 +0000532 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
533 if save > 0:
534 if self.domenu_save():
535 return
536 elif save < 0:
537 return
538 if not self.path:
539 raise W.AlertError, "Can't run unsaved file"
540 self._run_with_cl_interpreter()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000541 else:
542 pytext = self.editgroup.editor.get()
543 globals, file, modname = self.getenvironment()
544 self.execstring(pytext, globals, globals, file, modname)
545
546 def _run_with_interpreter(self):
547 interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter")
548 if not os.path.exists(interp_path):
549 raise W.AlertError, "Can't find interpreter"
550 import findertools
551 XXX
Jack Jansenff773eb2002-03-31 22:01:33 +0000552
553 def _run_with_cl_interpreter(self):
554 import Terminal
555 interp_path = os.path.join(sys.exec_prefix, "bin", "python")
556 file_path = self.path
557 if not os.path.exists(interp_path):
Jack Jansene7ee17c2003-02-06 22:32:35 +0000558 # This "can happen" if we are running IDE under MacPython-OS9.
559 raise W.AlertError, "Can't find command-line Python"
Jack Jansenff773eb2002-03-31 22:01:33 +0000560 cmd = '"%s" "%s" ; exit' % (interp_path, file_path)
561 t = Terminal.Terminal()
562 t.do_script(with_command=cmd)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000563
564 def runselection(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000565 if self._threadstate == (0, 0):
566 self._runselection()
567 elif self._threadstate == (1, 1):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000568 self._thread.block()
Just van Rossum73efed22000-04-09 19:45:22 +0000569 self.setthreadstate((1, 2))
570 elif self._threadstate == (1, 2):
571 self._thread.start()
572 self.setthreadstate((1, 1))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000573
574 def _runselection(self):
Jack Jansenff773eb2002-03-31 22:01:33 +0000575 if self.run_with_interpreter or self.run_with_cl_interpreter:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000576 raise W.AlertError, "Can't run selection with Interpreter"
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000577 globals, file, modname = self.getenvironment()
578 locals = globals
579 # select whole lines
580 self.editgroup.editor.expandselection()
581
582 # get lineno of first selected line
583 selstart, selend = self.editgroup.editor.getselection()
584 selstart, selend = min(selstart, selend), max(selstart, selend)
585 selfirstline = self.editgroup.editor.offsettoline(selstart)
586 alltext = self.editgroup.editor.get()
587 pytext = alltext[selstart:selend]
588 lines = string.split(pytext, '\r')
589 indent = getminindent(lines)
590 if indent == 1:
591 classname = ''
592 alllines = string.split(alltext, '\r')
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000593 for i in range(selfirstline - 1, -1, -1):
594 line = alllines[i]
595 if line[:6] == 'class ':
596 classname = string.split(string.strip(line[6:]))[0]
597 classend = identifieRE_match(classname)
598 if classend < 1:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000599 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000600 classname = classname[:classend]
601 break
602 elif line and line[0] not in '\t#':
Just van Rossumdc3c6172001-06-19 21:37:33 +0000603 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000604 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000605 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000606 if globals.has_key(classname):
Just van Rossum25ddc632001-07-05 07:06:26 +0000607 klass = globals[classname]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000608 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000609 raise W.AlertError, "Can't find class \"%s\"." % classname
Just van Rossum25ddc632001-07-05 07:06:26 +0000610 # add class def
611 pytext = ("class %s:\n" % classname) + pytext
612 selfirstline = selfirstline - 1
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000613 elif indent > 0:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000614 raise W.AlertError, "Can't run indented code."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000615
616 # add "newlines" to fool compile/exec:
617 # now a traceback will give the right line number
618 pytext = selfirstline * '\r' + pytext
619 self.execstring(pytext, globals, locals, file, modname)
Just van Rossum25ddc632001-07-05 07:06:26 +0000620 if indent == 1 and globals[classname] is not klass:
621 # update the class in place
622 klass.__dict__.update(globals[classname].__dict__)
623 globals[classname] = klass
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000624
Just van Rossum73efed22000-04-09 19:45:22 +0000625 def setthreadstate(self, state):
626 oldstate = self._threadstate
627 if oldstate[0] <> state[0]:
628 self.runbutton.settitle(runButtonLabels[state[0]])
629 if oldstate[1] <> state[1]:
630 self.runselbutton.settitle(runSelButtonLabels[state[1]])
631 self._threadstate = state
632
633 def _exec_threadwrapper(self, *args, **kwargs):
634 apply(execstring, args, kwargs)
635 self.setthreadstate((0, 0))
636 self._thread = None
637
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000638 def execstring(self, pytext, globals, locals, file, modname):
639 tracebackwindow.hide()
640 # update windows
641 W.getapplication().refreshwindows()
642 if self.run_as_main:
643 modname = "__main__"
644 if self.path:
645 dir = os.path.dirname(self.path)
646 savedir = os.getcwd()
647 os.chdir(dir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000648 sys.path.insert(0, dir)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000649 else:
650 cwdindex = None
651 try:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000652 if haveThreading:
653 self._thread = Wthreading.Thread(os.path.basename(file),
Just van Rossum73efed22000-04-09 19:45:22 +0000654 self._exec_threadwrapper, pytext, globals, locals, file, self.debugging,
655 modname, self.profiling)
656 self.setthreadstate((1, 1))
657 self._thread.start()
658 else:
659 execstring(pytext, globals, locals, file, self.debugging,
660 modname, self.profiling)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000661 finally:
662 if self.path:
663 os.chdir(savedir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000664 del sys.path[0]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000665
666 def getenvironment(self):
667 if self.path:
668 file = self.path
669 dir = os.path.dirname(file)
670 # check if we're part of a package
671 modname = ""
672 while os.path.exists(os.path.join(dir, "__init__.py")):
673 dir, dirname = os.path.split(dir)
Just van Rossum2aaeb521999-02-05 21:58:25 +0000674 modname = dirname + '.' + modname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000675 subname = _filename_as_modname(self.title)
Just van Rossumf7f93882001-11-02 19:24:41 +0000676 if subname is None:
677 return self.globals, file, None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000678 if modname:
679 if subname == "__init__":
Just van Rossum2aaeb521999-02-05 21:58:25 +0000680 # strip trailing period
681 modname = modname[:-1]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000682 else:
Just van Rossum2aaeb521999-02-05 21:58:25 +0000683 modname = modname + subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000684 else:
685 modname = subname
686 if sys.modules.has_key(modname):
687 globals = sys.modules[modname].__dict__
688 self.globals = {}
689 else:
690 globals = self.globals
Just van Rossum73efed22000-04-09 19:45:22 +0000691 modname = subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000692 else:
693 file = '<%s>' % self.title
694 globals = self.globals
695 modname = file
696 return globals, file, modname
697
698 def write(self, stuff):
699 """for use as stdout"""
700 self._buf = self._buf + stuff
701 if '\n' in self._buf:
702 self.flush()
703
704 def flush(self):
705 stuff = string.split(self._buf, '\n')
706 stuff = string.join(stuff, '\r')
707 end = self.editgroup.editor.ted.WEGetTextLength()
708 self.editgroup.editor.ted.WESetSelection(end, end)
709 self.editgroup.editor.ted.WEInsert(stuff, None, None)
710 self.editgroup.editor.updatescrollbars()
711 self._buf = ""
712 # ? optional:
713 #self.wid.SelectWindow()
714
715 def getclasslist(self):
716 from string import find, strip
Just van Rossum24073ea1999-12-23 15:46:57 +0000717 methodRE = re.compile(r"\r[ \t]+def ")
718 findMethod = methodRE.search
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000719 editor = self.editgroup.editor
720 text = editor.get()
721 list = []
722 append = list.append
723 functag = "func"
724 classtag = "class"
725 methodtag = "method"
726 pos = -1
727 if text[:4] == 'def ':
728 append((pos + 4, functag))
729 pos = 4
730 while 1:
731 pos = find(text, '\rdef ', pos + 1)
732 if pos < 0:
733 break
734 append((pos + 5, functag))
735 pos = -1
736 if text[:6] == 'class ':
737 append((pos + 6, classtag))
738 pos = 6
739 while 1:
740 pos = find(text, '\rclass ', pos + 1)
741 if pos < 0:
742 break
743 append((pos + 7, classtag))
744 pos = 0
745 while 1:
Just van Rossum24073ea1999-12-23 15:46:57 +0000746 m = findMethod(text, pos + 1)
747 if m is None:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000748 break
Just van Rossum24073ea1999-12-23 15:46:57 +0000749 pos = m.regs[0][0]
750 #pos = find(text, '\r\tdef ', pos + 1)
751 append((m.regs[0][1], methodtag))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000752 list.sort()
753 classlist = []
754 methodlistappend = None
755 offsetToLine = editor.ted.WEOffsetToLine
756 getLineRange = editor.ted.WEGetLineRange
757 append = classlist.append
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000758 for pos, tag in list:
759 lineno = offsetToLine(pos)
760 lineStart, lineEnd = getLineRange(lineno)
761 line = strip(text[pos:lineEnd])
762 line = line[:identifieRE_match(line)]
763 if tag is functag:
764 append(("def " + line, lineno + 1))
765 methodlistappend = None
766 elif tag is classtag:
767 append(["class " + line])
768 methodlistappend = classlist[-1].append
769 elif methodlistappend and tag is methodtag:
770 methodlistappend(("def " + line, lineno + 1))
771 return classlist
772
773 def popselectline(self, lineno):
774 self.editgroup.editor.selectline(lineno - 1)
775
776 def selectline(self, lineno, charoffset = 0):
777 self.editgroup.editor.selectline(lineno - 1, charoffset)
778
Just van Rossum12710051999-02-27 17:18:30 +0000779class _saveoptions:
780
Jack Jansen9a389472002-03-29 21:26:04 +0000781 def __init__(self, creator, eoln):
Just van Rossum12710051999-02-27 17:18:30 +0000782 self.rv = None
Jack Jansen9a389472002-03-29 21:26:04 +0000783 self.eoln = eoln
784 self.w = w = W.ModalDialog((260, 160), 'Save options')
Just van Rossum12710051999-02-27 17:18:30 +0000785 radiobuttons = []
786 w.label = W.TextBox((8, 8, 80, 18), "File creator:")
Just van Rossum3af507d1999-04-22 22:23:46 +0000787 w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit)
Jack Jansen9a389472002-03-29 21:26:04 +0000788 w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython Interpreter", radiobuttons, self.interp_hit)
789 w.interpx_radio = W.RadioButton((8, 62, 160, 18), "OSX PythonW Interpreter", radiobuttons, self.interpx_hit)
790 w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons)
791 w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect)
792 w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit)
Just van Rossum12710051999-02-27 17:18:30 +0000793 w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit)
794 w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit)
795 w.setdefaultbutton(w.okbutton)
796 if creator == 'Pyth':
797 w.interp_radio.set(1)
Just van Rossum3af507d1999-04-22 22:23:46 +0000798 elif creator == W._signature:
Just van Rossum12710051999-02-27 17:18:30 +0000799 w.ide_radio.set(1)
Jack Jansen9a389472002-03-29 21:26:04 +0000800 elif creator == 'PytX':
801 w.interpx_radio.set(1)
802 elif creator == '\0\0\0\0':
803 w.none_radio.set(1)
Just van Rossum12710051999-02-27 17:18:30 +0000804 else:
805 w.other_radio.set(1)
Jack Jansen9a389472002-03-29 21:26:04 +0000806
807 w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:")
808 radiobuttons = []
809 w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit)
810 w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit)
811 w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit)
812 if self.eoln == '\n':
813 w.unix_radio.set(1)
814 elif self.eoln == '\r\n':
815 w.win_radio.set(1)
816 else:
817 w.mac_radio.set(1)
818
Just van Rossum12710051999-02-27 17:18:30 +0000819 w.bind("cmd.", w.cancelbutton.push)
820 w.open()
821
822 def ide_hit(self):
Just van Rossum3af507d1999-04-22 22:23:46 +0000823 self.w.other_creator.set(W._signature)
Just van Rossum12710051999-02-27 17:18:30 +0000824
825 def interp_hit(self):
826 self.w.other_creator.set("Pyth")
827
Jack Jansen9a389472002-03-29 21:26:04 +0000828 def interpx_hit(self):
829 self.w.other_creator.set("PytX")
830
831 def none_hit(self):
832 self.w.other_creator.set("\0\0\0\0")
833
Just van Rossum12710051999-02-27 17:18:30 +0000834 def otherselect(self, *args):
835 sel_from, sel_to = self.w.other_creator.getselection()
836 creator = self.w.other_creator.get()[:4]
837 creator = creator + " " * (4 - len(creator))
838 self.w.other_creator.set(creator)
839 self.w.other_creator.setselection(sel_from, sel_to)
840 self.w.other_radio.set(1)
841
Jack Jansen9a389472002-03-29 21:26:04 +0000842 def mac_hit(self):
843 self.eoln = '\r'
844
845 def unix_hit(self):
846 self.eoln = '\n'
847
848 def win_hit(self):
849 self.eoln = '\r\n'
850
Just van Rossum12710051999-02-27 17:18:30 +0000851 def cancelbuttonhit(self):
852 self.w.close()
853
854 def okbuttonhit(self):
Jack Jansen9a389472002-03-29 21:26:04 +0000855 self.rv = (self.w.other_creator.get()[:4], self.eoln)
Just van Rossum12710051999-02-27 17:18:30 +0000856 self.w.close()
857
858
Jack Jansen9a389472002-03-29 21:26:04 +0000859def SaveOptions(creator, eoln):
860 s = _saveoptions(creator, eoln)
Just van Rossum12710051999-02-27 17:18:30 +0000861 return s.rv
862
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000863
864def _escape(where, what) :
865 return string.join(string.split(where, what), '\\' + what)
866
867def _makewholewordpattern(word):
868 # first, escape special regex chars
Just van Rossum3eec7622001-07-10 19:25:40 +0000869 for esc in "\\[]()|.*^+$?":
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000870 word = _escape(word, esc)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000871 notwordcharspat = '[^' + _wordchars + ']'
Jack Jansen9ad27522001-02-21 13:54:31 +0000872 pattern = '(' + word + ')'
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000873 if word[0] in _wordchars:
874 pattern = notwordcharspat + pattern
875 if word[-1] in _wordchars:
876 pattern = pattern + notwordcharspat
Jack Jansen9ad27522001-02-21 13:54:31 +0000877 return re.compile(pattern)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000878
Just van Rossumf376ef02001-11-18 14:12:43 +0000879
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000880class SearchEngine:
881
882 def __init__(self):
883 self.visible = 0
884 self.w = None
885 self.parms = { "find": "",
886 "replace": "",
887 "wrap": 1,
888 "casesens": 1,
889 "wholeword": 1
890 }
891 import MacPrefs
892 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
893 if prefs.searchengine:
894 self.parms["casesens"] = prefs.searchengine.casesens
895 self.parms["wrap"] = prefs.searchengine.wrap
896 self.parms["wholeword"] = prefs.searchengine.wholeword
897
898 def show(self):
899 self.visible = 1
900 if self.w:
901 self.w.wid.ShowWindow()
902 self.w.wid.SelectWindow()
903 self.w.find.edit.select(1)
904 self.w.find.edit.selectall()
905 return
906 self.w = W.Dialog((420, 150), "Find")
907
908 self.w.find = TitledEditText((10, 4, 300, 36), "Search for:")
909 self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:")
910
911 self.w.boxes = W.Group((10, 50, 300, 40))
912 self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive")
913 self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word")
914 self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around")
915
916 self.buttons = [ ("Find", "cmdf", self.find),
917 ("Replace", "cmdr", self.replace),
918 ("Replace all", None, self.replaceall),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000919 ("Don't find", "cmdd", self.dont),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000920 ("Cancel", "cmd.", self.cancel)
921 ]
922 for i in range(len(self.buttons)):
923 bounds = -90, 22 + i * 24, 80, 16
924 title, shortcut, callback = self.buttons[i]
925 self.w[title] = W.Button(bounds, title, callback)
926 if shortcut:
927 self.w.bind(shortcut, self.w[title].push)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000928 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000929 self.w.find.edit.bind("<key>", self.key)
930 self.w.bind("<activate>", self.activate)
931 self.w.bind("<close>", self.close)
932 self.w.open()
933 self.setparms()
934 self.w.find.edit.select(1)
935 self.w.find.edit.selectall()
936 self.checkbuttons()
937
938 def close(self):
939 self.hide()
940 return -1
941
942 def key(self, char, modifiers):
943 self.w.find.edit.key(char, modifiers)
944 self.checkbuttons()
945 return 1
946
947 def activate(self, onoff):
948 if onoff:
949 self.checkbuttons()
950
951 def checkbuttons(self):
952 editor = findeditor(self)
953 if editor:
954 if self.w.find.get():
955 for title, cmd, call in self.buttons[:-2]:
956 self.w[title].enable(1)
957 self.w.setdefaultbutton(self.w["Find"])
958 else:
959 for title, cmd, call in self.buttons[:-2]:
960 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000961 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000962 else:
963 for title, cmd, call in self.buttons[:-2]:
964 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000965 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000966
967 def find(self):
968 self.getparmsfromwindow()
969 if self.findnext():
970 self.hide()
971
972 def replace(self):
973 editor = findeditor(self)
974 if not editor:
975 return
976 if self.visible:
977 self.getparmsfromwindow()
978 text = editor.getselectedtext()
979 find = self.parms["find"]
980 if not self.parms["casesens"]:
981 find = string.lower(find)
982 text = string.lower(text)
983 if text == find:
984 self.hide()
985 editor.insert(self.parms["replace"])
986
987 def replaceall(self):
988 editor = findeditor(self)
989 if not editor:
990 return
991 if self.visible:
992 self.getparmsfromwindow()
993 W.SetCursor("watch")
994 find = self.parms["find"]
995 if not find:
996 return
997 findlen = len(find)
998 replace = self.parms["replace"]
999 replacelen = len(replace)
1000 Text = editor.get()
1001 if not self.parms["casesens"]:
1002 find = string.lower(find)
1003 text = string.lower(Text)
1004 else:
1005 text = Text
1006 newtext = ""
1007 pos = 0
1008 counter = 0
1009 while 1:
1010 if self.parms["wholeword"]:
1011 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +00001012 match = wholewordRE.search(text, pos)
1013 if match:
1014 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001015 else:
1016 pos = -1
1017 else:
1018 pos = string.find(text, find, pos)
1019 if pos < 0:
1020 break
1021 counter = counter + 1
1022 text = text[:pos] + replace + text[pos + findlen:]
1023 Text = Text[:pos] + replace + Text[pos + findlen:]
1024 pos = pos + replacelen
1025 W.SetCursor("arrow")
1026 if counter:
1027 self.hide()
Jack Jansen5a6fdcd2001-08-25 12:15:04 +00001028 from Carbon import Res
Just van Rossumf7f93882001-11-02 19:24:41 +00001029 editor.textchanged()
1030 editor.selectionchanged()
Just van Rossum7b025512002-10-24 20:03:29 +00001031 editor.set(Text)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001032 EasyDialogs.Message("Replaced %d occurrences" % counter)
1033
1034 def dont(self):
1035 self.getparmsfromwindow()
1036 self.hide()
1037
1038 def replacefind(self):
1039 self.replace()
1040 self.findnext()
1041
1042 def setfindstring(self):
1043 editor = findeditor(self)
1044 if not editor:
1045 return
1046 find = editor.getselectedtext()
1047 if not find:
1048 return
1049 self.parms["find"] = find
1050 if self.w:
1051 self.w.find.edit.set(self.parms["find"])
1052 self.w.find.edit.selectall()
1053
1054 def findnext(self):
1055 editor = findeditor(self)
1056 if not editor:
1057 return
1058 find = self.parms["find"]
1059 if not find:
1060 return
1061 text = editor.get()
1062 if not self.parms["casesens"]:
1063 find = string.lower(find)
1064 text = string.lower(text)
1065 selstart, selend = editor.getselection()
1066 selstart, selend = min(selstart, selend), max(selstart, selend)
1067 if self.parms["wholeword"]:
1068 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +00001069 match = wholewordRE.search(text, selend)
1070 if match:
1071 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001072 else:
1073 pos = -1
1074 else:
1075 pos = string.find(text, find, selend)
1076 if pos >= 0:
1077 editor.setselection(pos, pos + len(find))
1078 return 1
1079 elif self.parms["wrap"]:
1080 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001081 match = wholewordRE.search(text, 0)
1082 if match:
1083 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001084 else:
1085 pos = -1
1086 else:
1087 pos = string.find(text, find)
1088 if selstart > pos >= 0:
1089 editor.setselection(pos, pos + len(find))
1090 return 1
1091
1092 def setparms(self):
1093 for key, value in self.parms.items():
1094 try:
1095 self.w[key].set(value)
1096 except KeyError:
1097 self.w.boxes[key].set(value)
1098
1099 def getparmsfromwindow(self):
1100 if not self.w:
1101 return
1102 for key, value in self.parms.items():
1103 try:
1104 value = self.w[key].get()
1105 except KeyError:
1106 value = self.w.boxes[key].get()
1107 self.parms[key] = value
1108
1109 def cancel(self):
1110 self.hide()
1111 self.setparms()
1112
1113 def hide(self):
1114 if self.w:
1115 self.w.wid.HideWindow()
1116 self.visible = 0
1117
1118 def writeprefs(self):
1119 import MacPrefs
1120 self.getparmsfromwindow()
1121 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1122 prefs.searchengine.casesens = self.parms["casesens"]
1123 prefs.searchengine.wrap = self.parms["wrap"]
1124 prefs.searchengine.wholeword = self.parms["wholeword"]
1125 prefs.save()
1126
1127
1128class TitledEditText(W.Group):
1129
1130 def __init__(self, possize, title, text = ""):
1131 W.Group.__init__(self, possize)
1132 self.title = W.TextBox((0, 0, 0, 16), title)
1133 self.edit = W.EditText((0, 16, 0, 0), text)
1134
1135 def set(self, value):
1136 self.edit.set(value)
1137
1138 def get(self):
1139 return self.edit.get()
1140
1141
1142class ClassFinder(W.PopupWidget):
1143
1144 def click(self, point, modifiers):
1145 W.SetCursor("watch")
1146 self.set(self._parentwindow.getclasslist())
1147 W.PopupWidget.click(self, point, modifiers)
1148
1149
1150def getminindent(lines):
1151 indent = -1
1152 for line in lines:
1153 stripped = string.strip(line)
1154 if not stripped or stripped[0] == '#':
1155 continue
1156 if indent < 0 or line[:indent] <> indent * '\t':
1157 indent = 0
1158 for c in line:
1159 if c <> '\t':
1160 break
1161 indent = indent + 1
1162 return indent
1163
1164
1165def getoptionkey():
1166 return not not ord(Evt.GetKeys()[7]) & 0x04
1167
1168
1169def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1170 modname="__main__", profiling=0):
1171 if debugging:
1172 import PyDebugger, bdb
1173 BdbQuit = bdb.BdbQuit
1174 else:
1175 BdbQuit = 'BdbQuitDummyException'
1176 pytext = string.split(pytext, '\r')
1177 pytext = string.join(pytext, '\n') + '\n'
1178 W.SetCursor("watch")
1179 globals['__name__'] = modname
1180 globals['__file__'] = filename
1181 sys.argv = [filename]
1182 try:
1183 code = compile(pytext, filename, "exec")
1184 except:
1185 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1186 # special. That's wrong because THIS case is special (could be literal
1187 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1188 # in imported module!!!
1189 tracebackwindow.traceback(1, filename)
1190 return
1191 try:
1192 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001193 if haveThreading:
1194 lock = Wthreading.Lock()
1195 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001196 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001197 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001198 else:
1199 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001200 elif not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001201 if hasattr(MacOS, 'EnableAppswitch'):
1202 MacOS.EnableAppswitch(0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001203 try:
1204 if profiling:
1205 import profile, ProfileBrowser
1206 p = profile.Profile()
1207 p.set_cmd(filename)
1208 try:
1209 p.runctx(code, globals, locals)
1210 finally:
1211 import pstats
1212
1213 stats = pstats.Stats(p)
1214 ProfileBrowser.ProfileBrowser(stats)
1215 else:
1216 exec code in globals, locals
1217 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001218 if not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001219 if hasattr(MacOS, 'EnableAppswitch'):
1220 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001221 except W.AlertError, detail:
1222 raise W.AlertError, detail
1223 except (KeyboardInterrupt, BdbQuit):
1224 pass
Just van Rossumf7f93882001-11-02 19:24:41 +00001225 except SystemExit, arg:
1226 if arg.code:
1227 sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001228 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001229 if haveThreading:
1230 import continuation
1231 lock = Wthreading.Lock()
1232 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001233 if debugging:
1234 sys.settrace(None)
1235 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1236 return
1237 else:
1238 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001239 if haveThreading:
1240 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001241 if debugging:
1242 sys.settrace(None)
1243 PyDebugger.stop()
1244
1245
Just van Rossum3eec7622001-07-10 19:25:40 +00001246_identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
Jack Jansen9ad27522001-02-21 13:54:31 +00001247
1248def identifieRE_match(str):
1249 match = _identifieRE.match(str)
1250 if not match:
1251 return -1
1252 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001253
1254def _filename_as_modname(fname):
1255 if fname[-3:] == '.py':
1256 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001257 match = _identifieRE.match(modname)
1258 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001259 return string.join(string.split(modname, '.'), '_')
1260
1261def findeditor(topwindow, fromtop = 0):
Just van Rossum40144012002-02-04 12:52:44 +00001262 wid = MyFrontWindow()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001263 if not fromtop:
1264 if topwindow.w and wid == topwindow.w.wid:
1265 wid = topwindow.w.wid.GetNextWindow()
1266 if not wid:
1267 return
1268 app = W.getapplication()
1269 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1270 window = W.getapplication()._windows[wid]
1271 else:
1272 return
1273 if not isinstance(window, Editor):
1274 return
1275 return window.editgroup.editor
1276
1277
1278class _EditorDefaultSettings:
1279
1280 def __init__(self):
1281 self.template = "%s, %d point"
1282 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1283 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001284 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001285 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1286
1287 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1288 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1289 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1290 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1291 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1292
1293 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1294 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1295 self.w.setdefaultbutton(self.w.okbutton)
1296 self.w.bind('cmd.', self.w.cancelbutton.push)
1297 self.w.open()
1298
1299 def picksize(self):
1300 app = W.getapplication()
1301 editor = findeditor(self)
1302 if editor is not None:
1303 width, height = editor._parentwindow._bounds[2:]
1304 self.w.xsize.set(`width`)
1305 self.w.ysize.set(`height`)
1306 else:
1307 raise W.AlertError, "No edit window found"
1308
1309 def dofont(self):
1310 import FontSettings
1311 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1312 if settings:
1313 self.fontsettings, self.tabsettings = settings
1314 sys.exc_traceback = None
1315 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1316
1317 def close(self):
1318 self.w.close()
1319 del self.w
1320
1321 def cancel(self):
1322 self.close()
1323
1324 def ok(self):
1325 try:
1326 width = string.atoi(self.w.xsize.get())
1327 except:
1328 self.w.xsize.select(1)
1329 self.w.xsize.selectall()
1330 raise W.AlertError, "Bad number for window width"
1331 try:
1332 height = string.atoi(self.w.ysize.get())
1333 except:
1334 self.w.ysize.select(1)
1335 self.w.ysize.selectall()
1336 raise W.AlertError, "Bad number for window height"
1337 self.windowsize = width, height
1338 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1339 self.close()
1340
1341def geteditorprefs():
1342 import MacPrefs
1343 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1344 try:
1345 fontsettings = prefs.pyedit.fontsettings
1346 tabsettings = prefs.pyedit.tabsettings
1347 windowsize = prefs.pyedit.windowsize
1348 except:
Just van Rossumf7f93882001-11-02 19:24:41 +00001349 fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001350 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1351 windowsize = prefs.pyedit.windowsize = (500, 250)
1352 sys.exc_traceback = None
1353 return fontsettings, tabsettings, windowsize
1354
1355def seteditorprefs(fontsettings, tabsettings, windowsize):
1356 import MacPrefs
1357 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1358 prefs.pyedit.fontsettings = fontsettings
1359 prefs.pyedit.tabsettings = tabsettings
1360 prefs.pyedit.windowsize = windowsize
1361 prefs.save()
1362
1363_defaultSettingsEditor = None
1364
1365def EditorDefaultSettings():
1366 global _defaultSettingsEditor
1367 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1368 _defaultSettingsEditor = _EditorDefaultSettings()
1369 else:
1370 _defaultSettingsEditor.w.select()
1371
1372def resolvealiases(path):
1373 try:
Jack Jansene7ee17c2003-02-06 22:32:35 +00001374 fsr, d1, d2 = File.FSResolveAliasFile(path, 1)
1375 path = fsr.as_pathname()
1376 return path
1377 except (File.Error, ValueError), (error, str):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001378 if error <> -120:
1379 raise
1380 dir, file = os.path.split(path)
1381 return os.path.join(resolvealiases(dir), file)
1382
1383searchengine = SearchEngine()
1384tracebackwindow = Wtraceback.TraceBack()