blob: cd3f3ccd28153e88d67d839d9b674b0b1a2e148d [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 Jansenfd0b00e2003-01-26 22:15:48 +000010import EasyDialogs
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000011from Carbon import Win
12from Carbon import Res
13from Carbon import Evt
Just van Rossum2ad94192002-07-12 12:06:17 +000014from Carbon import Qd
Just van Rossum40f9b7b1999-01-30 22:39:17 +000015import os
16import imp
17import sys
18import string
19import marshal
Jack Jansen9ad27522001-02-21 13:54:31 +000020import re
Just van Rossum40f9b7b1999-01-30 22:39:17 +000021
Just van Rossum40144012002-02-04 12:52:44 +000022if hasattr(Win, "FrontNonFloatingWindow"):
23 MyFrontWindow = Win.FrontNonFloatingWindow
24else:
25 MyFrontWindow = Win.FrontWindow
26
27
Just van Rossum73efed22000-04-09 19:45:22 +000028try:
Just van Rossum0f2fd162000-10-20 06:36:30 +000029 import Wthreading
Just van Rossum73efed22000-04-09 19:45:22 +000030except ImportError:
Just van Rossum0f2fd162000-10-20 06:36:30 +000031 haveThreading = 0
32else:
33 haveThreading = Wthreading.haveThreading
Just van Rossum73efed22000-04-09 19:45:22 +000034
Just van Rossum40f9b7b1999-01-30 22:39:17 +000035_scriptuntitledcounter = 1
Fred Drake79e75e12001-07-20 19:05:50 +000036_wordchars = string.ascii_letters + string.digits + "_"
Just van Rossum40f9b7b1999-01-30 22:39:17 +000037
38
Just van Rossum73efed22000-04-09 19:45:22 +000039runButtonLabels = ["Run all", "Stop!"]
40runSelButtonLabels = ["Run selection", "Pause!", "Resume"]
41
42
Just van Rossum40f9b7b1999-01-30 22:39:17 +000043class Editor(W.Window):
44
45 def __init__(self, path = "", title = ""):
46 defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs()
47 global _scriptuntitledcounter
48 if not path:
49 if title:
50 self.title = title
51 else:
52 self.title = "Untitled Script " + `_scriptuntitledcounter`
53 _scriptuntitledcounter = _scriptuntitledcounter + 1
54 text = ""
55 self._creator = W._signature
Jack Jansen9a389472002-03-29 21:26:04 +000056 self._eoln = os.linesep
Just van Rossum40f9b7b1999-01-30 22:39:17 +000057 elif os.path.exists(path):
58 path = resolvealiases(path)
59 dir, name = os.path.split(path)
60 self.title = name
61 f = open(path, "rb")
62 text = f.read()
63 f.close()
64 fss = macfs.FSSpec(path)
65 self._creator, filetype = fss.GetCreatorType()
66 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 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:
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()
392 fss = macfs.FSSpec(self.path)
393 fss.SetCreatorType(self._creator, 'TEXT')
394 self.getsettings()
395 self.writewindowsettings()
396 self.editgroup.editor.changed = 0
397 self.editgroup.editor.selchanged = 0
398 import linecache
399 if linecache.cache.has_key(self.path):
400 del linecache.cache[self.path]
401 import macostools
402 macostools.touched(self.path)
403
404 def can_save(self, menuitem):
405 return self.editgroup.editor.changed or self.editgroup.editor.selchanged
406
407 def domenu_save_as(self, *args):
Jack Jansenfd0b00e2003-01-26 22:15:48 +0000408 path = EasyDialogs.AskFileForSave(message='Save as:', savedFileName=self.title)
409 if not path:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000410 return 1
411 self.showbreakpoints(0)
Jack Jansenfd0b00e2003-01-26 22:15:48 +0000412 self.path = path
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000413 self.setinfotext()
414 self.title = os.path.split(self.path)[-1]
415 self.wid.SetWTitle(self.title)
416 self.domenu_save()
417 self.editgroup.editor.setfile(self.getfilename())
418 app = W.getapplication()
419 app.makeopenwindowsmenu()
420 if hasattr(app, 'makescriptsmenu'):
421 app = W.getapplication()
422 fss, fss_changed = app.scriptsfolder.Resolve()
423 path = fss.as_pathname()
424 if path == self.path[:len(path)]:
425 W.getapplication().makescriptsmenu()
426
427 def domenu_save_as_applet(self, *args):
Just van Rossumdc3c6172001-06-19 21:37:33 +0000428 import buildtools
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000429
430 buildtools.DEBUG = 0 # ouch.
431
432 if self.title[-3:] == ".py":
433 destname = self.title[:-3]
434 else:
435 destname = self.title + ".applet"
Jack Jansenfd0b00e2003-01-26 22:15:48 +0000436 destname = EasyDialogs.AskFileForSave(message='Save as Applet:',
437 savedFileName=destname)
438 if not destname:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000439 return 1
440 W.SetCursor("watch")
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000441 if self.path:
442 filename = self.path
443 if filename[-3:] == ".py":
444 rsrcname = filename[:-3] + '.rsrc'
445 else:
446 rsrcname = filename + '.rsrc'
447 else:
448 filename = self.title
449 rsrcname = ""
450
451 pytext = self.editgroup.editor.get()
452 pytext = string.split(pytext, '\r')
453 pytext = string.join(pytext, '\n') + '\n'
454 try:
455 code = compile(pytext, filename, "exec")
456 except (SyntaxError, EOFError):
457 raise buildtools.BuildError, "Syntax error in script %s" % `filename`
458
459 # Try removing the output file
460 try:
461 os.remove(destname)
462 except os.error:
463 pass
464 template = buildtools.findtemplate()
465 buildtools.process_common(template, None, code, rsrcname, destname, 0, 1)
466
467 def domenu_gotoline(self, *args):
468 self.linefield.selectall()
469 self.linefield.select(1)
470 self.linefield.selectall()
471
472 def domenu_selectline(self, *args):
473 self.editgroup.editor.expandselection()
474
475 def domenu_find(self, *args):
476 searchengine.show()
477
478 def domenu_entersearchstring(self, *args):
479 searchengine.setfindstring()
480
481 def domenu_replace(self, *args):
482 searchengine.replace()
483
484 def domenu_findnext(self, *args):
485 searchengine.findnext()
486
487 def domenu_replacefind(self, *args):
488 searchengine.replacefind()
489
490 def domenu_run(self, *args):
491 self.runbutton.push()
492
493 def domenu_runselection(self, *args):
494 self.runselbutton.push()
495
496 def run(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000497 if self._threadstate == (0, 0):
498 self._run()
499 else:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000500 lock = Wthreading.Lock()
501 lock.acquire()
502 self._thread.postException(KeyboardInterrupt)
503 if self._thread.isBlocked():
Just van Rossum73efed22000-04-09 19:45:22 +0000504 self._thread.start()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000505 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000506
507 def _run(self):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000508 if self.run_with_interpreter:
509 if self.editgroup.editor.changed:
Just van Rossum2ad94192002-07-12 12:06:17 +0000510 Qd.InitCursor()
Just van Rossumdc3c6172001-06-19 21:37:33 +0000511 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
Just van Rossum0f2fd162000-10-20 06:36:30 +0000512 if save > 0:
513 if self.domenu_save():
514 return
515 elif save < 0:
516 return
517 if not self.path:
518 raise W.AlertError, "Can't run unsaved file"
519 self._run_with_interpreter()
Jack Jansenff773eb2002-03-31 22:01:33 +0000520 elif self.run_with_cl_interpreter:
Jack Jansenff773eb2002-03-31 22:01:33 +0000521 if self.editgroup.editor.changed:
Just van Rossum2ad94192002-07-12 12:06:17 +0000522 Qd.InitCursor()
Jack Jansenff773eb2002-03-31 22:01:33 +0000523 save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1)
524 if save > 0:
525 if self.domenu_save():
526 return
527 elif save < 0:
528 return
529 if not self.path:
530 raise W.AlertError, "Can't run unsaved file"
531 self._run_with_cl_interpreter()
Just van Rossum0f2fd162000-10-20 06:36:30 +0000532 else:
533 pytext = self.editgroup.editor.get()
534 globals, file, modname = self.getenvironment()
535 self.execstring(pytext, globals, globals, file, modname)
536
537 def _run_with_interpreter(self):
538 interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter")
539 if not os.path.exists(interp_path):
540 raise W.AlertError, "Can't find interpreter"
541 import findertools
542 XXX
Jack Jansenff773eb2002-03-31 22:01:33 +0000543
544 def _run_with_cl_interpreter(self):
545 import Terminal
546 interp_path = os.path.join(sys.exec_prefix, "bin", "python")
547 file_path = self.path
548 if not os.path.exists(interp_path):
549 # This "can happen" if we are running IDE under MacPython. Try
550 # the standard location.
551 interp_path = "/Library/Frameworks/Python.framework/Versions/2.3/bin/python"
552 try:
553 fsr = macfs.FSRef(interp_path)
554 except macfs.Error:
555 raise W.AlertError, "Can't find command-line Python"
556 file_path = macfs.FSRef(macfs.FSSpec(self.path)).as_pathname()
557 cmd = '"%s" "%s" ; exit' % (interp_path, file_path)
558 t = Terminal.Terminal()
559 t.do_script(with_command=cmd)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000560
561 def runselection(self):
Just van Rossum73efed22000-04-09 19:45:22 +0000562 if self._threadstate == (0, 0):
563 self._runselection()
564 elif self._threadstate == (1, 1):
Just van Rossum0f2fd162000-10-20 06:36:30 +0000565 self._thread.block()
Just van Rossum73efed22000-04-09 19:45:22 +0000566 self.setthreadstate((1, 2))
567 elif self._threadstate == (1, 2):
568 self._thread.start()
569 self.setthreadstate((1, 1))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000570
571 def _runselection(self):
Jack Jansenff773eb2002-03-31 22:01:33 +0000572 if self.run_with_interpreter or self.run_with_cl_interpreter:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000573 raise W.AlertError, "Can't run selection with Interpreter"
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000574 globals, file, modname = self.getenvironment()
575 locals = globals
576 # select whole lines
577 self.editgroup.editor.expandselection()
578
579 # get lineno of first selected line
580 selstart, selend = self.editgroup.editor.getselection()
581 selstart, selend = min(selstart, selend), max(selstart, selend)
582 selfirstline = self.editgroup.editor.offsettoline(selstart)
583 alltext = self.editgroup.editor.get()
584 pytext = alltext[selstart:selend]
585 lines = string.split(pytext, '\r')
586 indent = getminindent(lines)
587 if indent == 1:
588 classname = ''
589 alllines = string.split(alltext, '\r')
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000590 for i in range(selfirstline - 1, -1, -1):
591 line = alllines[i]
592 if line[:6] == 'class ':
593 classname = string.split(string.strip(line[6:]))[0]
594 classend = identifieRE_match(classname)
595 if classend < 1:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000596 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000597 classname = classname[:classend]
598 break
599 elif line and line[0] not in '\t#':
Just van Rossumdc3c6172001-06-19 21:37:33 +0000600 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000601 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000602 raise W.AlertError, "Can't find a class."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000603 if globals.has_key(classname):
Just van Rossum25ddc632001-07-05 07:06:26 +0000604 klass = globals[classname]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000605 else:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000606 raise W.AlertError, "Can't find class \"%s\"." % classname
Just van Rossum25ddc632001-07-05 07:06:26 +0000607 # add class def
608 pytext = ("class %s:\n" % classname) + pytext
609 selfirstline = selfirstline - 1
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000610 elif indent > 0:
Just van Rossumdc3c6172001-06-19 21:37:33 +0000611 raise W.AlertError, "Can't run indented code."
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000612
613 # add "newlines" to fool compile/exec:
614 # now a traceback will give the right line number
615 pytext = selfirstline * '\r' + pytext
616 self.execstring(pytext, globals, locals, file, modname)
Just van Rossum25ddc632001-07-05 07:06:26 +0000617 if indent == 1 and globals[classname] is not klass:
618 # update the class in place
619 klass.__dict__.update(globals[classname].__dict__)
620 globals[classname] = klass
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000621
Just van Rossum73efed22000-04-09 19:45:22 +0000622 def setthreadstate(self, state):
623 oldstate = self._threadstate
624 if oldstate[0] <> state[0]:
625 self.runbutton.settitle(runButtonLabels[state[0]])
626 if oldstate[1] <> state[1]:
627 self.runselbutton.settitle(runSelButtonLabels[state[1]])
628 self._threadstate = state
629
630 def _exec_threadwrapper(self, *args, **kwargs):
631 apply(execstring, args, kwargs)
632 self.setthreadstate((0, 0))
633 self._thread = None
634
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000635 def execstring(self, pytext, globals, locals, file, modname):
636 tracebackwindow.hide()
637 # update windows
638 W.getapplication().refreshwindows()
639 if self.run_as_main:
640 modname = "__main__"
641 if self.path:
642 dir = os.path.dirname(self.path)
643 savedir = os.getcwd()
644 os.chdir(dir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000645 sys.path.insert(0, dir)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000646 else:
647 cwdindex = None
648 try:
Just van Rossum0f2fd162000-10-20 06:36:30 +0000649 if haveThreading:
650 self._thread = Wthreading.Thread(os.path.basename(file),
Just van Rossum73efed22000-04-09 19:45:22 +0000651 self._exec_threadwrapper, pytext, globals, locals, file, self.debugging,
652 modname, self.profiling)
653 self.setthreadstate((1, 1))
654 self._thread.start()
655 else:
656 execstring(pytext, globals, locals, file, self.debugging,
657 modname, self.profiling)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000658 finally:
659 if self.path:
660 os.chdir(savedir)
Just van Rossuma61f4ac1999-02-01 16:34:08 +0000661 del sys.path[0]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000662
663 def getenvironment(self):
664 if self.path:
665 file = self.path
666 dir = os.path.dirname(file)
667 # check if we're part of a package
668 modname = ""
669 while os.path.exists(os.path.join(dir, "__init__.py")):
670 dir, dirname = os.path.split(dir)
Just van Rossum2aaeb521999-02-05 21:58:25 +0000671 modname = dirname + '.' + modname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000672 subname = _filename_as_modname(self.title)
Just van Rossumf7f93882001-11-02 19:24:41 +0000673 if subname is None:
674 return self.globals, file, None
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000675 if modname:
676 if subname == "__init__":
Just van Rossum2aaeb521999-02-05 21:58:25 +0000677 # strip trailing period
678 modname = modname[:-1]
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000679 else:
Just van Rossum2aaeb521999-02-05 21:58:25 +0000680 modname = modname + subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000681 else:
682 modname = subname
683 if sys.modules.has_key(modname):
684 globals = sys.modules[modname].__dict__
685 self.globals = {}
686 else:
687 globals = self.globals
Just van Rossum73efed22000-04-09 19:45:22 +0000688 modname = subname
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000689 else:
690 file = '<%s>' % self.title
691 globals = self.globals
692 modname = file
693 return globals, file, modname
694
695 def write(self, stuff):
696 """for use as stdout"""
697 self._buf = self._buf + stuff
698 if '\n' in self._buf:
699 self.flush()
700
701 def flush(self):
702 stuff = string.split(self._buf, '\n')
703 stuff = string.join(stuff, '\r')
704 end = self.editgroup.editor.ted.WEGetTextLength()
705 self.editgroup.editor.ted.WESetSelection(end, end)
706 self.editgroup.editor.ted.WEInsert(stuff, None, None)
707 self.editgroup.editor.updatescrollbars()
708 self._buf = ""
709 # ? optional:
710 #self.wid.SelectWindow()
711
712 def getclasslist(self):
713 from string import find, strip
Just van Rossum24073ea1999-12-23 15:46:57 +0000714 methodRE = re.compile(r"\r[ \t]+def ")
715 findMethod = methodRE.search
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000716 editor = self.editgroup.editor
717 text = editor.get()
718 list = []
719 append = list.append
720 functag = "func"
721 classtag = "class"
722 methodtag = "method"
723 pos = -1
724 if text[:4] == 'def ':
725 append((pos + 4, functag))
726 pos = 4
727 while 1:
728 pos = find(text, '\rdef ', pos + 1)
729 if pos < 0:
730 break
731 append((pos + 5, functag))
732 pos = -1
733 if text[:6] == 'class ':
734 append((pos + 6, classtag))
735 pos = 6
736 while 1:
737 pos = find(text, '\rclass ', pos + 1)
738 if pos < 0:
739 break
740 append((pos + 7, classtag))
741 pos = 0
742 while 1:
Just van Rossum24073ea1999-12-23 15:46:57 +0000743 m = findMethod(text, pos + 1)
744 if m is None:
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000745 break
Just van Rossum24073ea1999-12-23 15:46:57 +0000746 pos = m.regs[0][0]
747 #pos = find(text, '\r\tdef ', pos + 1)
748 append((m.regs[0][1], methodtag))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000749 list.sort()
750 classlist = []
751 methodlistappend = None
752 offsetToLine = editor.ted.WEOffsetToLine
753 getLineRange = editor.ted.WEGetLineRange
754 append = classlist.append
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000755 for pos, tag in list:
756 lineno = offsetToLine(pos)
757 lineStart, lineEnd = getLineRange(lineno)
758 line = strip(text[pos:lineEnd])
759 line = line[:identifieRE_match(line)]
760 if tag is functag:
761 append(("def " + line, lineno + 1))
762 methodlistappend = None
763 elif tag is classtag:
764 append(["class " + line])
765 methodlistappend = classlist[-1].append
766 elif methodlistappend and tag is methodtag:
767 methodlistappend(("def " + line, lineno + 1))
768 return classlist
769
770 def popselectline(self, lineno):
771 self.editgroup.editor.selectline(lineno - 1)
772
773 def selectline(self, lineno, charoffset = 0):
774 self.editgroup.editor.selectline(lineno - 1, charoffset)
775
Just van Rossum12710051999-02-27 17:18:30 +0000776class _saveoptions:
777
Jack Jansen9a389472002-03-29 21:26:04 +0000778 def __init__(self, creator, eoln):
Just van Rossum12710051999-02-27 17:18:30 +0000779 self.rv = None
Jack Jansen9a389472002-03-29 21:26:04 +0000780 self.eoln = eoln
781 self.w = w = W.ModalDialog((260, 160), 'Save options')
Just van Rossum12710051999-02-27 17:18:30 +0000782 radiobuttons = []
783 w.label = W.TextBox((8, 8, 80, 18), "File creator:")
Just van Rossum3af507d1999-04-22 22:23:46 +0000784 w.ide_radio = W.RadioButton((8, 22, 160, 18), "This application", radiobuttons, self.ide_hit)
Jack Jansen9a389472002-03-29 21:26:04 +0000785 w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython Interpreter", radiobuttons, self.interp_hit)
786 w.interpx_radio = W.RadioButton((8, 62, 160, 18), "OSX PythonW Interpreter", radiobuttons, self.interpx_hit)
787 w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons)
788 w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect)
789 w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit)
Just van Rossum12710051999-02-27 17:18:30 +0000790 w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit)
791 w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit)
792 w.setdefaultbutton(w.okbutton)
793 if creator == 'Pyth':
794 w.interp_radio.set(1)
Just van Rossum3af507d1999-04-22 22:23:46 +0000795 elif creator == W._signature:
Just van Rossum12710051999-02-27 17:18:30 +0000796 w.ide_radio.set(1)
Jack Jansen9a389472002-03-29 21:26:04 +0000797 elif creator == 'PytX':
798 w.interpx_radio.set(1)
799 elif creator == '\0\0\0\0':
800 w.none_radio.set(1)
Just van Rossum12710051999-02-27 17:18:30 +0000801 else:
802 w.other_radio.set(1)
Jack Jansen9a389472002-03-29 21:26:04 +0000803
804 w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:")
805 radiobuttons = []
806 w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit)
807 w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit)
808 w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit)
809 if self.eoln == '\n':
810 w.unix_radio.set(1)
811 elif self.eoln == '\r\n':
812 w.win_radio.set(1)
813 else:
814 w.mac_radio.set(1)
815
Just van Rossum12710051999-02-27 17:18:30 +0000816 w.bind("cmd.", w.cancelbutton.push)
817 w.open()
818
819 def ide_hit(self):
Just van Rossum3af507d1999-04-22 22:23:46 +0000820 self.w.other_creator.set(W._signature)
Just van Rossum12710051999-02-27 17:18:30 +0000821
822 def interp_hit(self):
823 self.w.other_creator.set("Pyth")
824
Jack Jansen9a389472002-03-29 21:26:04 +0000825 def interpx_hit(self):
826 self.w.other_creator.set("PytX")
827
828 def none_hit(self):
829 self.w.other_creator.set("\0\0\0\0")
830
Just van Rossum12710051999-02-27 17:18:30 +0000831 def otherselect(self, *args):
832 sel_from, sel_to = self.w.other_creator.getselection()
833 creator = self.w.other_creator.get()[:4]
834 creator = creator + " " * (4 - len(creator))
835 self.w.other_creator.set(creator)
836 self.w.other_creator.setselection(sel_from, sel_to)
837 self.w.other_radio.set(1)
838
Jack Jansen9a389472002-03-29 21:26:04 +0000839 def mac_hit(self):
840 self.eoln = '\r'
841
842 def unix_hit(self):
843 self.eoln = '\n'
844
845 def win_hit(self):
846 self.eoln = '\r\n'
847
Just van Rossum12710051999-02-27 17:18:30 +0000848 def cancelbuttonhit(self):
849 self.w.close()
850
851 def okbuttonhit(self):
Jack Jansen9a389472002-03-29 21:26:04 +0000852 self.rv = (self.w.other_creator.get()[:4], self.eoln)
Just van Rossum12710051999-02-27 17:18:30 +0000853 self.w.close()
854
855
Jack Jansen9a389472002-03-29 21:26:04 +0000856def SaveOptions(creator, eoln):
857 s = _saveoptions(creator, eoln)
Just van Rossum12710051999-02-27 17:18:30 +0000858 return s.rv
859
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000860
861def _escape(where, what) :
862 return string.join(string.split(where, what), '\\' + what)
863
864def _makewholewordpattern(word):
865 # first, escape special regex chars
Just van Rossum3eec7622001-07-10 19:25:40 +0000866 for esc in "\\[]()|.*^+$?":
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000867 word = _escape(word, esc)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000868 notwordcharspat = '[^' + _wordchars + ']'
Jack Jansen9ad27522001-02-21 13:54:31 +0000869 pattern = '(' + word + ')'
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000870 if word[0] in _wordchars:
871 pattern = notwordcharspat + pattern
872 if word[-1] in _wordchars:
873 pattern = pattern + notwordcharspat
Jack Jansen9ad27522001-02-21 13:54:31 +0000874 return re.compile(pattern)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000875
Just van Rossumf376ef02001-11-18 14:12:43 +0000876
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000877class SearchEngine:
878
879 def __init__(self):
880 self.visible = 0
881 self.w = None
882 self.parms = { "find": "",
883 "replace": "",
884 "wrap": 1,
885 "casesens": 1,
886 "wholeword": 1
887 }
888 import MacPrefs
889 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
890 if prefs.searchengine:
891 self.parms["casesens"] = prefs.searchengine.casesens
892 self.parms["wrap"] = prefs.searchengine.wrap
893 self.parms["wholeword"] = prefs.searchengine.wholeword
894
895 def show(self):
896 self.visible = 1
897 if self.w:
898 self.w.wid.ShowWindow()
899 self.w.wid.SelectWindow()
900 self.w.find.edit.select(1)
901 self.w.find.edit.selectall()
902 return
903 self.w = W.Dialog((420, 150), "Find")
904
905 self.w.find = TitledEditText((10, 4, 300, 36), "Search for:")
906 self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:")
907
908 self.w.boxes = W.Group((10, 50, 300, 40))
909 self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive")
910 self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word")
911 self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around")
912
913 self.buttons = [ ("Find", "cmdf", self.find),
914 ("Replace", "cmdr", self.replace),
915 ("Replace all", None, self.replaceall),
Just van Rossumdc3c6172001-06-19 21:37:33 +0000916 ("Don't find", "cmdd", self.dont),
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000917 ("Cancel", "cmd.", self.cancel)
918 ]
919 for i in range(len(self.buttons)):
920 bounds = -90, 22 + i * 24, 80, 16
921 title, shortcut, callback = self.buttons[i]
922 self.w[title] = W.Button(bounds, title, callback)
923 if shortcut:
924 self.w.bind(shortcut, self.w[title].push)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000925 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000926 self.w.find.edit.bind("<key>", self.key)
927 self.w.bind("<activate>", self.activate)
928 self.w.bind("<close>", self.close)
929 self.w.open()
930 self.setparms()
931 self.w.find.edit.select(1)
932 self.w.find.edit.selectall()
933 self.checkbuttons()
934
935 def close(self):
936 self.hide()
937 return -1
938
939 def key(self, char, modifiers):
940 self.w.find.edit.key(char, modifiers)
941 self.checkbuttons()
942 return 1
943
944 def activate(self, onoff):
945 if onoff:
946 self.checkbuttons()
947
948 def checkbuttons(self):
949 editor = findeditor(self)
950 if editor:
951 if self.w.find.get():
952 for title, cmd, call in self.buttons[:-2]:
953 self.w[title].enable(1)
954 self.w.setdefaultbutton(self.w["Find"])
955 else:
956 for title, cmd, call in self.buttons[:-2]:
957 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000958 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000959 else:
960 for title, cmd, call in self.buttons[:-2]:
961 self.w[title].enable(0)
Just van Rossumdc3c6172001-06-19 21:37:33 +0000962 self.w.setdefaultbutton(self.w["Don't find"])
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000963
964 def find(self):
965 self.getparmsfromwindow()
966 if self.findnext():
967 self.hide()
968
969 def replace(self):
970 editor = findeditor(self)
971 if not editor:
972 return
973 if self.visible:
974 self.getparmsfromwindow()
975 text = editor.getselectedtext()
976 find = self.parms["find"]
977 if not self.parms["casesens"]:
978 find = string.lower(find)
979 text = string.lower(text)
980 if text == find:
981 self.hide()
982 editor.insert(self.parms["replace"])
983
984 def replaceall(self):
985 editor = findeditor(self)
986 if not editor:
987 return
988 if self.visible:
989 self.getparmsfromwindow()
990 W.SetCursor("watch")
991 find = self.parms["find"]
992 if not find:
993 return
994 findlen = len(find)
995 replace = self.parms["replace"]
996 replacelen = len(replace)
997 Text = editor.get()
998 if not self.parms["casesens"]:
999 find = string.lower(find)
1000 text = string.lower(Text)
1001 else:
1002 text = Text
1003 newtext = ""
1004 pos = 0
1005 counter = 0
1006 while 1:
1007 if self.parms["wholeword"]:
1008 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +00001009 match = wholewordRE.search(text, pos)
1010 if match:
1011 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001012 else:
1013 pos = -1
1014 else:
1015 pos = string.find(text, find, pos)
1016 if pos < 0:
1017 break
1018 counter = counter + 1
1019 text = text[:pos] + replace + text[pos + findlen:]
1020 Text = Text[:pos] + replace + Text[pos + findlen:]
1021 pos = pos + replacelen
1022 W.SetCursor("arrow")
1023 if counter:
1024 self.hide()
Jack Jansen5a6fdcd2001-08-25 12:15:04 +00001025 from Carbon import Res
Just van Rossumf7f93882001-11-02 19:24:41 +00001026 editor.textchanged()
1027 editor.selectionchanged()
Just van Rossum7b025512002-10-24 20:03:29 +00001028 editor.set(Text)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001029 EasyDialogs.Message("Replaced %d occurrences" % counter)
1030
1031 def dont(self):
1032 self.getparmsfromwindow()
1033 self.hide()
1034
1035 def replacefind(self):
1036 self.replace()
1037 self.findnext()
1038
1039 def setfindstring(self):
1040 editor = findeditor(self)
1041 if not editor:
1042 return
1043 find = editor.getselectedtext()
1044 if not find:
1045 return
1046 self.parms["find"] = find
1047 if self.w:
1048 self.w.find.edit.set(self.parms["find"])
1049 self.w.find.edit.selectall()
1050
1051 def findnext(self):
1052 editor = findeditor(self)
1053 if not editor:
1054 return
1055 find = self.parms["find"]
1056 if not find:
1057 return
1058 text = editor.get()
1059 if not self.parms["casesens"]:
1060 find = string.lower(find)
1061 text = string.lower(text)
1062 selstart, selend = editor.getselection()
1063 selstart, selend = min(selstart, selend), max(selstart, selend)
1064 if self.parms["wholeword"]:
1065 wholewordRE = _makewholewordpattern(find)
Jack Jansen9ad27522001-02-21 13:54:31 +00001066 match = wholewordRE.search(text, selend)
1067 if match:
1068 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001069 else:
1070 pos = -1
1071 else:
1072 pos = string.find(text, find, selend)
1073 if pos >= 0:
1074 editor.setselection(pos, pos + len(find))
1075 return 1
1076 elif self.parms["wrap"]:
1077 if self.parms["wholeword"]:
Jack Jansen9ad27522001-02-21 13:54:31 +00001078 match = wholewordRE.search(text, 0)
1079 if match:
1080 pos = match.start(1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001081 else:
1082 pos = -1
1083 else:
1084 pos = string.find(text, find)
1085 if selstart > pos >= 0:
1086 editor.setselection(pos, pos + len(find))
1087 return 1
1088
1089 def setparms(self):
1090 for key, value in self.parms.items():
1091 try:
1092 self.w[key].set(value)
1093 except KeyError:
1094 self.w.boxes[key].set(value)
1095
1096 def getparmsfromwindow(self):
1097 if not self.w:
1098 return
1099 for key, value in self.parms.items():
1100 try:
1101 value = self.w[key].get()
1102 except KeyError:
1103 value = self.w.boxes[key].get()
1104 self.parms[key] = value
1105
1106 def cancel(self):
1107 self.hide()
1108 self.setparms()
1109
1110 def hide(self):
1111 if self.w:
1112 self.w.wid.HideWindow()
1113 self.visible = 0
1114
1115 def writeprefs(self):
1116 import MacPrefs
1117 self.getparmsfromwindow()
1118 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1119 prefs.searchengine.casesens = self.parms["casesens"]
1120 prefs.searchengine.wrap = self.parms["wrap"]
1121 prefs.searchengine.wholeword = self.parms["wholeword"]
1122 prefs.save()
1123
1124
1125class TitledEditText(W.Group):
1126
1127 def __init__(self, possize, title, text = ""):
1128 W.Group.__init__(self, possize)
1129 self.title = W.TextBox((0, 0, 0, 16), title)
1130 self.edit = W.EditText((0, 16, 0, 0), text)
1131
1132 def set(self, value):
1133 self.edit.set(value)
1134
1135 def get(self):
1136 return self.edit.get()
1137
1138
1139class ClassFinder(W.PopupWidget):
1140
1141 def click(self, point, modifiers):
1142 W.SetCursor("watch")
1143 self.set(self._parentwindow.getclasslist())
1144 W.PopupWidget.click(self, point, modifiers)
1145
1146
1147def getminindent(lines):
1148 indent = -1
1149 for line in lines:
1150 stripped = string.strip(line)
1151 if not stripped or stripped[0] == '#':
1152 continue
1153 if indent < 0 or line[:indent] <> indent * '\t':
1154 indent = 0
1155 for c in line:
1156 if c <> '\t':
1157 break
1158 indent = indent + 1
1159 return indent
1160
1161
1162def getoptionkey():
1163 return not not ord(Evt.GetKeys()[7]) & 0x04
1164
1165
1166def execstring(pytext, globals, locals, filename="<string>", debugging=0,
1167 modname="__main__", profiling=0):
1168 if debugging:
1169 import PyDebugger, bdb
1170 BdbQuit = bdb.BdbQuit
1171 else:
1172 BdbQuit = 'BdbQuitDummyException'
1173 pytext = string.split(pytext, '\r')
1174 pytext = string.join(pytext, '\n') + '\n'
1175 W.SetCursor("watch")
1176 globals['__name__'] = modname
1177 globals['__file__'] = filename
1178 sys.argv = [filename]
1179 try:
1180 code = compile(pytext, filename, "exec")
1181 except:
1182 # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError
1183 # special. That's wrong because THIS case is special (could be literal
1184 # overflow!) and SyntaxError could mean we need a traceback (syntax error
1185 # in imported module!!!
1186 tracebackwindow.traceback(1, filename)
1187 return
1188 try:
1189 if debugging:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001190 if haveThreading:
1191 lock = Wthreading.Lock()
1192 lock.acquire()
Just van Rossum73efed22000-04-09 19:45:22 +00001193 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001194 lock.release()
Just van Rossum73efed22000-04-09 19:45:22 +00001195 else:
1196 PyDebugger.startfromhere()
Just van Rossum0f2fd162000-10-20 06:36:30 +00001197 elif not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001198 if hasattr(MacOS, 'EnableAppswitch'):
1199 MacOS.EnableAppswitch(0)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001200 try:
1201 if profiling:
1202 import profile, ProfileBrowser
1203 p = profile.Profile()
1204 p.set_cmd(filename)
1205 try:
1206 p.runctx(code, globals, locals)
1207 finally:
1208 import pstats
1209
1210 stats = pstats.Stats(p)
1211 ProfileBrowser.ProfileBrowser(stats)
1212 else:
1213 exec code in globals, locals
1214 finally:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001215 if not haveThreading:
Jack Jansen815d2bf2002-01-21 23:00:52 +00001216 if hasattr(MacOS, 'EnableAppswitch'):
1217 MacOS.EnableAppswitch(-1)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001218 except W.AlertError, detail:
1219 raise W.AlertError, detail
1220 except (KeyboardInterrupt, BdbQuit):
1221 pass
Just van Rossumf7f93882001-11-02 19:24:41 +00001222 except SystemExit, arg:
1223 if arg.code:
1224 sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001225 except:
Just van Rossum0f2fd162000-10-20 06:36:30 +00001226 if haveThreading:
1227 import continuation
1228 lock = Wthreading.Lock()
1229 lock.acquire()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001230 if debugging:
1231 sys.settrace(None)
1232 PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback)
1233 return
1234 else:
1235 tracebackwindow.traceback(1, filename)
Just van Rossum0f2fd162000-10-20 06:36:30 +00001236 if haveThreading:
1237 lock.release()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001238 if debugging:
1239 sys.settrace(None)
1240 PyDebugger.stop()
1241
1242
Just van Rossum3eec7622001-07-10 19:25:40 +00001243_identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
Jack Jansen9ad27522001-02-21 13:54:31 +00001244
1245def identifieRE_match(str):
1246 match = _identifieRE.match(str)
1247 if not match:
1248 return -1
1249 return match.end()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001250
1251def _filename_as_modname(fname):
1252 if fname[-3:] == '.py':
1253 modname = fname[:-3]
Jack Jansen9ad27522001-02-21 13:54:31 +00001254 match = _identifieRE.match(modname)
1255 if match and match.start() == 0 and match.end() == len(modname):
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001256 return string.join(string.split(modname, '.'), '_')
1257
1258def findeditor(topwindow, fromtop = 0):
Just van Rossum40144012002-02-04 12:52:44 +00001259 wid = MyFrontWindow()
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001260 if not fromtop:
1261 if topwindow.w and wid == topwindow.w.wid:
1262 wid = topwindow.w.wid.GetNextWindow()
1263 if not wid:
1264 return
1265 app = W.getapplication()
1266 if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-(
1267 window = W.getapplication()._windows[wid]
1268 else:
1269 return
1270 if not isinstance(window, Editor):
1271 return
1272 return window.editgroup.editor
1273
1274
1275class _EditorDefaultSettings:
1276
1277 def __init__(self):
1278 self.template = "%s, %d point"
1279 self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs()
1280 self.w = W.Dialog((328, 120), "Editor default settings")
Just van Rossumdc3c6172001-06-19 21:37:33 +00001281 self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont)
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001282 self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2]))
1283
1284 self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize)
1285 self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:")
1286 self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:")
1287 self.w.xsize = W.EditText((98, 48, 40, 20), `self.windowsize[0]`)
1288 self.w.ysize = W.EditText((148, 48, 40, 20), `self.windowsize[1]`)
1289
1290 self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
1291 self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok)
1292 self.w.setdefaultbutton(self.w.okbutton)
1293 self.w.bind('cmd.', self.w.cancelbutton.push)
1294 self.w.open()
1295
1296 def picksize(self):
1297 app = W.getapplication()
1298 editor = findeditor(self)
1299 if editor is not None:
1300 width, height = editor._parentwindow._bounds[2:]
1301 self.w.xsize.set(`width`)
1302 self.w.ysize.set(`height`)
1303 else:
1304 raise W.AlertError, "No edit window found"
1305
1306 def dofont(self):
1307 import FontSettings
1308 settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings)
1309 if settings:
1310 self.fontsettings, self.tabsettings = settings
1311 sys.exc_traceback = None
1312 self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2]))
1313
1314 def close(self):
1315 self.w.close()
1316 del self.w
1317
1318 def cancel(self):
1319 self.close()
1320
1321 def ok(self):
1322 try:
1323 width = string.atoi(self.w.xsize.get())
1324 except:
1325 self.w.xsize.select(1)
1326 self.w.xsize.selectall()
1327 raise W.AlertError, "Bad number for window width"
1328 try:
1329 height = string.atoi(self.w.ysize.get())
1330 except:
1331 self.w.ysize.select(1)
1332 self.w.ysize.selectall()
1333 raise W.AlertError, "Bad number for window height"
1334 self.windowsize = width, height
1335 seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize)
1336 self.close()
1337
1338def geteditorprefs():
1339 import MacPrefs
1340 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1341 try:
1342 fontsettings = prefs.pyedit.fontsettings
1343 tabsettings = prefs.pyedit.tabsettings
1344 windowsize = prefs.pyedit.windowsize
1345 except:
Just van Rossumf7f93882001-11-02 19:24:41 +00001346 fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0))
Just van Rossum40f9b7b1999-01-30 22:39:17 +00001347 tabsettings = prefs.pyedit.tabsettings = (8, 1)
1348 windowsize = prefs.pyedit.windowsize = (500, 250)
1349 sys.exc_traceback = None
1350 return fontsettings, tabsettings, windowsize
1351
1352def seteditorprefs(fontsettings, tabsettings, windowsize):
1353 import MacPrefs
1354 prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
1355 prefs.pyedit.fontsettings = fontsettings
1356 prefs.pyedit.tabsettings = tabsettings
1357 prefs.pyedit.windowsize = windowsize
1358 prefs.save()
1359
1360_defaultSettingsEditor = None
1361
1362def EditorDefaultSettings():
1363 global _defaultSettingsEditor
1364 if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"):
1365 _defaultSettingsEditor = _EditorDefaultSettings()
1366 else:
1367 _defaultSettingsEditor.w.select()
1368
1369def resolvealiases(path):
1370 try:
1371 return macfs.ResolveAliasFile(path)[0].as_pathname()
1372 except (macfs.error, ValueError), (error, str):
1373 if error <> -120:
1374 raise
1375 dir, file = os.path.split(path)
1376 return os.path.join(resolvealiases(dir), file)
1377
1378searchengine = SearchEngine()
1379tracebackwindow = Wtraceback.TraceBack()