blob: ed234d32ca39e8bad810f08712b3a37b55304aa9 [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
7import macfs
Jack Jansen64aa1e22001-01-29 15:19:17 +00008import MACFS
Just van Rossum40f9b7b1999-01-30 22:39:17 +00009import MacOS
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000010from Carbon import Win
11from Carbon import Res
12from Carbon import Evt
Just van Rossum2ad94192002-07-12 12:06:17 +000013from Carbon import Qd
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
Just van Rossum40144012002-02-04 12:52:44 +000021if hasattr(Win, "FrontNonFloatingWindow"):
22 MyFrontWindow = Win.FrontNonFloatingWindow
23else:
24 MyFrontWindow = Win.FrontWindow
25
26
Just van Rossum73efed22000-04-09 19:45:22 +000027try:
Just van Rossum0f2fd162000-10-20 06:36:30 +000028 import Wthreading
Just van Rossum73efed22000-04-09 19:45:22 +000029except ImportError:
Just van Rossum0f2fd162000-10-20 06:36:30 +000030 haveThreading = 0
31else:
32 haveThreading = Wthreading.haveThreading
Just van Rossum73efed22000-04-09 19:45:22 +000033
Just van Rossum40f9b7b1999-01-30 22:39:17 +000034_scriptuntitledcounter = 1
Fred Drake79e75e12001-07-20 19:05:50 +000035_wordchars = string.ascii_letters + string.digits + "_"
Just van Rossum40f9b7b1999-01-30 22:39:17 +000036
37
Just van Rossum73efed22000-04-09 19:45:22 +000038runButtonLabels = ["Run all", "Stop!"]
39runSelButtonLabels = ["Run selection", "Pause!", "Resume"]
40
41
Just van Rossum40f9b7b1999-01-30 22:39:17 +000042class Editor(W.Window):
43
44 def __init__(self, path = "", title = ""):
45 defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs()
46 global _scriptuntitledcounter
47 if not path:
48 if title:
49 self.title = title
50 else:
51 self.title = "Untitled Script " + `_scriptuntitledcounter`
52 _scriptuntitledcounter = _scriptuntitledcounter + 1
53 text = ""
54 self._creator = W._signature
Jack Jansen9a389472002-03-29 21:26:04 +000055 self._eoln = os.linesep
Just van Rossum40f9b7b1999-01-30 22:39:17 +000056 elif os.path.exists(path):
57 path = resolvealiases(path)
58 dir, name = os.path.split(path)
59 self.title = name
60 f = open(path, "rb")
61 text = f.read()
62 f.close()
63 fss = macfs.FSSpec(path)
64 self._creator, filetype = fss.GetCreatorType()
65 else:
66 raise IOError, "file '%s' does not exist" % path
67 self.path = path
68
Just van Rossumc7ba0801999-05-21 21:42:27 +000069 if '\n' in text:
70 import EasyDialogs
71 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 Jansen64aa1e22001-01-29 15:19:17 +0000137 Res.FSpCreateResFile(self.path, self._creator, 'TEXT', MACFS.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:
368 import EasyDialogs
Just van Rossum25ddc632001-07-05 07:06:26 +0000369 Qd.InitCursor()
370 save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title,
371 default=1, no="Don\xd5t save")
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000372 if save > 0:
373 if self.domenu_save():
374 return 1
375 elif save < 0:
376 return 1
Just van Rossum25ddc632001-07-05 07:06:26 +0000377 self.globals = None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000378 W.Window.close(self)
379
380 def domenu_close(self, *args):
381 return self.close()
382
383 def domenu_save(self, *args):
384 if not self.path:
385 # Will call us recursively
386 return self.domenu_save_as()
387 data = self.editgroup.editor.get()
Jack Jansen9a389472002-03-29 21:26:04 +0000388 if self._eoln != '\r':
389 data = string.replace(data, '\r', self._eoln)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000390 fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings
391 fp.write(data)
392 fp.close()
393 fss = macfs.FSSpec(self.path)
394 fss.SetCreatorType(self._creator, 'TEXT')
395 self.getsettings()
396 self.writewindowsettings()
397 self.editgroup.editor.changed = 0
398 self.editgroup.editor.selchanged = 0
399 import linecache
400 if linecache.cache.has_key(self.path):
401 del linecache.cache[self.path]
402 import macostools
403 macostools.touched(self.path)
404
405 def can_save(self, menuitem):
406 return self.editgroup.editor.changed or self.editgroup.editor.selchanged
407
408 def domenu_save_as(self, *args):
409 fss, ok = macfs.StandardPutFile('Save as:', self.title)
410 if not ok:
411 return 1
412 self.showbreakpoints(0)
413 self.path = fss.as_pathname()
414 self.setinfotext()
415 self.title = os.path.split(self.path)[-1]
416 self.wid.SetWTitle(self.title)
417 self.domenu_save()
418 self.editgroup.editor.setfile(self.getfilename())
419 app = W.getapplication()
420 app.makeopenwindowsmenu()
421 if hasattr(app, 'makescriptsmenu'):
422 app = W.getapplication()
423 fss, fss_changed = app.scriptsfolder.Resolve()
424 path = fss.as_pathname()
425 if path == self.path[:len(path)]:
426 W.getapplication().makescriptsmenu()
427
428 def domenu_save_as_applet(self, *args):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000429 import buildtools
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000430
431 buildtools.DEBUG = 0 # ouch.
432
433 if self.title[-3:] == ".py":
434 destname = self.title[:-3]
435 else:
436 destname = self.title + ".applet"
437 fss, ok = macfs.StandardPutFile('Save as Applet:', destname)
438 if not ok:
439 return 1
440 W.SetCursor("watch")
441 destname = fss.as_pathname()
442 if self.path:
443 filename = self.path
444 if filename[-3:] == ".py":
445 rsrcname = filename[:-3] + '.rsrc'
446 else:
447 rsrcname = filename + '.rsrc'
448 else:
449 filename = self.title
450 rsrcname = ""
451
452 pytext = self.editgroup.editor.get()
453 pytext = string.split(pytext, '\r')
454 pytext = string.join(pytext, '\n') + '\n'
455 try:
456 code = compile(pytext, filename, "exec")
457 except (SyntaxError, EOFError):
458 raise buildtools.BuildError, "Syntax error in script %s" % `filename`
459
460 # Try removing the output file
461 try:
462 os.remove(destname)
463 except os.error:
464 pass
465 template = buildtools.findtemplate()
466 buildtools.process_common(template, None, code, rsrcname, destname, 0, 1)
467
468 def domenu_gotoline(self, *args):
469 self.linefield.selectall()
470 self.linefield.select(1)
471 self.linefield.selectall()
472
473 def domenu_selectline(self, *args):
474 self.editgroup.editor.expandselection()
475
476 def domenu_find(self, *args):
477 searchengine.show()
478
479 def domenu_entersearchstring(self, *args):
480 searchengine.setfindstring()
481
482 def domenu_replace(self, *args):
483 searchengine.replace()
484
485 def domenu_findnext(self, *args):
486 searchengine.findnext()
487
488 def domenu_replacefind(self, *args):
489 searchengine.replacefind()
490
491 def domenu_run(self, *args):
492 self.runbutton.push()
493
494 def domenu_runselection(self, *args):
495 self.runselbutton.push()
496
497 def run(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000498 if self._threadstate == (0, 0):
499 self._run()
500 else:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000501 lock = Wthreading.Lock()
502 lock.acquire()
503 self._thread.postException(KeyboardInterrupt)
504 if self._thread.isBlocked():
Just van Rossum73efed22000-04-09 19:45:22 +0000505 self._thread.start()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000506 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000507
508 def _run(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000509 if self.run_with_interpreter:
510 if self.editgroup.editor.changed:
511 import EasyDialogs
Just van Rossum2ad94192002-07-12 12:06:17 +0000512 Qd.InitCursor()
Just van Rossumdc3c6172001-06-19 21:37:33 +0000513 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
Just van Rossum0f2fd162000-10-20 06:36:30 +0000514 if save > 0:
515 if self.domenu_save():
516 return
517 elif save < 0:
518 return
519 if not self.path:
520 raise W.AlertError, "Can't run unsaved file"
521 self._run_with_interpreter()
Jack Jansenff773eb2002-03-31 22:01:33 +0000522 elif self.run_with_cl_interpreter:
Jack Jansenff773eb2002-03-31 22:01:33 +0000523 if self.editgroup.editor.changed:
524 import EasyDialogs
Just van Rossum2ad94192002-07-12 12:06:17 +0000525 Qd.InitCursor()
Jack Jansenff773eb2002-03-31 22:01:33 +0000526 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
527 if save > 0:
528 if self.domenu_save():
529 return
530 elif save < 0:
531 return
532 if not self.path:
533 raise W.AlertError, "Can't run unsaved file"
534 self._run_with_cl_interpreter()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000535 else:
536 pytext = self.editgroup.editor.get()
537 globals, file, modname = self.getenvironment()
538 self.execstring(pytext, globals, globals, file, modname)
539
540 def _run_with_interpreter(self):
541 interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter")
542 if not os.path.exists(interp_path):
543 raise W.AlertError, "Can't find interpreter"
544 import findertools
545 XXX
Jack Jansenff773eb2002-03-31 22:01:33 +0000546
547 def _run_with_cl_interpreter(self):
548 import Terminal
549 interp_path = os.path.join(sys.exec_prefix, "bin", "python")
550 file_path = self.path
551 if not os.path.exists(interp_path):
552 # This "can happen" if we are running IDE under MacPython. Try
553 # the standard location.
554 interp_path = "/Library/Frameworks/Python.framework/Versions/2.3/bin/python"
555 try:
556 fsr = macfs.FSRef(interp_path)
557 except macfs.Error:
558 raise W.AlertError, "Can't find command-line Python"
559 file_path = macfs.FSRef(macfs.FSSpec(self.path)).as_pathname()
560 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()
1028 import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +00001029 from Carbon import Res
Just van Rossumf7f93882001-11-02 19:24:41 +00001030 editor.textchanged()
1031 editor.selectionchanged()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001032 editor.ted.WEUseText(Res.Resource(Text))
1033 editor.ted.WECalText()
1034 editor.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +00001035 editor.GetWindow().InvalWindowRect(editor._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001036 #editor.ted.WEUpdate(self.w.wid.GetWindowPort().visRgn)
1037 EasyDialogs.Message("Replaced %d occurrences" % counter)
1038
1039 def dont(self):
1040 self.getparmsfromwindow()
1041 self.hide()
1042
1043 def replacefind(self):
1044 self.replace()
1045 self.findnext()
1046
1047 def setfindstring(self):
1048 editor = findeditor(self)
1049 if not editor:
1050 return
1051 find = editor.getselectedtext()
1052 if not find:
1053 return
1054 self.parms["find"] = find
1055 if self.w:
1056 self.w.find.edit.set(self.parms["find"])
1057 self.w.find.edit.selectall()
1058
1059 def findnext(self):
1060 editor = findeditor(self)
1061 if not editor:
1062 return
1063 find = self.parms["find"]
1064 if not find:
1065 return
1066 text = editor.get()
1067 if not self.parms["casesens"]:
1068 find = string.lower(find)
1069 text = string.lower(text)
1070 selstart, selend = editor.getselection()
1071 selstart, selend = min(selstart, selend), max(selstart, selend)
1072 if self.parms["wholeword"]:
1073 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +00001074 match = wholewordRE.search(text, selend)
1075 if match:
1076 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001077 else:
1078 pos = -1
1079 else:
1080 pos = string.find(text, find, selend)
1081 if pos >= 0:
1082 editor.setselection(pos, pos + len(find))
1083 return 1
1084 elif self.parms["wrap"]:
1085 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001086 match = wholewordRE.search(text, 0)
1087 if match:
1088 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001089 else:
1090 pos = -1
1091 else:
1092 pos = string.find(text, find)
1093 if selstart > pos >= 0:
1094 editor.setselection(pos, pos + len(find))
1095 return 1
1096
1097 def setparms(self):
1098 for key, value in self.parms.items():
1099 try:
1100 self.w[key].set(value)
1101 except KeyError:
1102 self.w.boxes[key].set(value)
1103
1104 def getparmsfromwindow(self):
1105 if not self.w:
1106 return
1107 for key, value in self.parms.items():
1108 try:
1109 value = self.w[key].get()
1110 except KeyError:
1111 value = self.w.boxes[key].get()
1112 self.parms[key] = value
1113
1114 def cancel(self):
1115 self.hide()
1116 self.setparms()
1117
1118 def hide(self):
1119 if self.w:
1120 self.w.wid.HideWindow()
1121 self.visible = 0
1122
1123 def writeprefs(self):
1124 import MacPrefs
1125 self.getparmsfromwindow()
1126 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1127 prefs.searchengine.casesens = self.parms["casesens"]
1128 prefs.searchengine.wrap = self.parms["wrap"]
1129 prefs.searchengine.wholeword = self.parms["wholeword"]
1130 prefs.save()
1131
1132
1133class TitledEditText(W.Group):
1134
1135 def __init__(self, possize, title, text = ""):
1136 W.Group.__init__(self, possize)
1137 self.title = W.TextBox((0, 0, 0, 16), title)
1138 self.edit = W.EditText((0, 16, 0, 0), text)
1139
1140 def set(self, value):
1141 self.edit.set(value)
1142
1143 def get(self):
1144 return self.edit.get()
1145
1146
1147class ClassFinder(W.PopupWidget):
1148
1149 def click(self, point, modifiers):
1150 W.SetCursor("watch")
1151 self.set(self._parentwindow.getclasslist())
1152 W.PopupWidget.click(self, point, modifiers)
1153
1154
1155def getminindent(lines):
1156 indent = -1
1157 for line in lines:
1158 stripped = string.strip(line)
1159 if not stripped or stripped[0] == '#':
1160 continue
1161 if indent < 0 or line[:indent] <> indent * '\t':
1162 indent = 0
1163 for c in line:
1164 if c <> '\t':
1165 break
1166 indent = indent + 1
1167 return indent
1168
1169
1170def getoptionkey():
1171 return not not ord(Evt.GetKeys()[7]) & 0x04
1172
1173
1174def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1175 modname="__main__", profiling=0):
1176 if debugging:
1177 import PyDebugger, bdb
1178 BdbQuit = bdb.BdbQuit
1179 else:
1180 BdbQuit = 'BdbQuitDummyException'
1181 pytext = string.split(pytext, '\r')
1182 pytext = string.join(pytext, '\n') + '\n'
1183 W.SetCursor("watch")
1184 globals['__name__'] = modname
1185 globals['__file__'] = filename
1186 sys.argv = [filename]
1187 try:
1188 code = compile(pytext, filename, "exec")
1189 except:
1190 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1191 # special. That's wrong because THIS case is special (could be literal
1192 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1193 # in imported module!!!
1194 tracebackwindow.traceback(1, filename)
1195 return
1196 try:
1197 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001198 if haveThreading:
1199 lock = Wthreading.Lock()
1200 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001201 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001202 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001203 else:
1204 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001205 elif not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001206 if hasattr(MacOS, 'EnableAppswitch'):
1207 MacOS.EnableAppswitch(0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001208 try:
1209 if profiling:
1210 import profile, ProfileBrowser
1211 p = profile.Profile()
1212 p.set_cmd(filename)
1213 try:
1214 p.runctx(code, globals, locals)
1215 finally:
1216 import pstats
1217
1218 stats = pstats.Stats(p)
1219 ProfileBrowser.ProfileBrowser(stats)
1220 else:
1221 exec code in globals, locals
1222 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001223 if not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001224 if hasattr(MacOS, 'EnableAppswitch'):
1225 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001226 except W.AlertError, detail:
1227 raise W.AlertError, detail
1228 except (KeyboardInterrupt, BdbQuit):
1229 pass
Just van Rossumf7f93882001-11-02 19:24:41 +00001230 except SystemExit, arg:
1231 if arg.code:
1232 sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001233 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001234 if haveThreading:
1235 import continuation
1236 lock = Wthreading.Lock()
1237 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001238 if debugging:
1239 sys.settrace(None)
1240 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1241 return
1242 else:
1243 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001244 if haveThreading:
1245 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001246 if debugging:
1247 sys.settrace(None)
1248 PyDebugger.stop()
1249
1250
Just van Rossum3eec7622001-07-10 19:25:40 +00001251_identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
Jack Jansen9ad27522001-02-21 13:54:31 +00001252
1253def identifieRE_match(str):
1254 match = _identifieRE.match(str)
1255 if not match:
1256 return -1
1257 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001258
1259def _filename_as_modname(fname):
1260 if fname[-3:] == '.py':
1261 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001262 match = _identifieRE.match(modname)
1263 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001264 return string.join(string.split(modname, '.'), '_')
1265
1266def findeditor(topwindow, fromtop = 0):
Just van Rossum40144012002-02-04 12:52:44 +00001267 wid = MyFrontWindow()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001268 if not fromtop:
1269 if topwindow.w and wid == topwindow.w.wid:
1270 wid = topwindow.w.wid.GetNextWindow()
1271 if not wid:
1272 return
1273 app = W.getapplication()
1274 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1275 window = W.getapplication()._windows[wid]
1276 else:
1277 return
1278 if not isinstance(window, Editor):
1279 return
1280 return window.editgroup.editor
1281
1282
1283class _EditorDefaultSettings:
1284
1285 def __init__(self):
1286 self.template = "%s, %d point"
1287 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1288 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001289 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001290 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1291
1292 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1293 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1294 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1295 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1296 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1297
1298 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1299 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1300 self.w.setdefaultbutton(self.w.okbutton)
1301 self.w.bind('cmd.', self.w.cancelbutton.push)
1302 self.w.open()
1303
1304 def picksize(self):
1305 app = W.getapplication()
1306 editor = findeditor(self)
1307 if editor is not None:
1308 width, height = editor._parentwindow._bounds[2:]
1309 self.w.xsize.set(`width`)
1310 self.w.ysize.set(`height`)
1311 else:
1312 raise W.AlertError, "No edit window found"
1313
1314 def dofont(self):
1315 import FontSettings
1316 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1317 if settings:
1318 self.fontsettings, self.tabsettings = settings
1319 sys.exc_traceback = None
1320 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1321
1322 def close(self):
1323 self.w.close()
1324 del self.w
1325
1326 def cancel(self):
1327 self.close()
1328
1329 def ok(self):
1330 try:
1331 width = string.atoi(self.w.xsize.get())
1332 except:
1333 self.w.xsize.select(1)
1334 self.w.xsize.selectall()
1335 raise W.AlertError, "Bad number for window width"
1336 try:
1337 height = string.atoi(self.w.ysize.get())
1338 except:
1339 self.w.ysize.select(1)
1340 self.w.ysize.selectall()
1341 raise W.AlertError, "Bad number for window height"
1342 self.windowsize = width, height
1343 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1344 self.close()
1345
1346def geteditorprefs():
1347 import MacPrefs
1348 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1349 try:
1350 fontsettings = prefs.pyedit.fontsettings
1351 tabsettings = prefs.pyedit.tabsettings
1352 windowsize = prefs.pyedit.windowsize
1353 except:
Just van Rossumf7f93882001-11-02 19:24:41 +00001354 fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001355 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1356 windowsize = prefs.pyedit.windowsize = (500, 250)
1357 sys.exc_traceback = None
1358 return fontsettings, tabsettings, windowsize
1359
1360def seteditorprefs(fontsettings, tabsettings, windowsize):
1361 import MacPrefs
1362 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1363 prefs.pyedit.fontsettings = fontsettings
1364 prefs.pyedit.tabsettings = tabsettings
1365 prefs.pyedit.windowsize = windowsize
1366 prefs.save()
1367
1368_defaultSettingsEditor = None
1369
1370def EditorDefaultSettings():
1371 global _defaultSettingsEditor
1372 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1373 _defaultSettingsEditor = _EditorDefaultSettings()
1374 else:
1375 _defaultSettingsEditor.w.select()
1376
1377def resolvealiases(path):
1378 try:
1379 return macfs.ResolveAliasFile(path)[0].as_pathname()
1380 except (macfs.error, ValueError), (error, str):
1381 if error <> -120:
1382 raise
1383 dir, file = os.path.split(path)
1384 return os.path.join(resolvealiases(dir), file)
1385
1386searchengine = SearchEngine()
1387tracebackwindow = Wtraceback.TraceBack()