Add PyErr_WarnEx()
[pytest.git] / Lib / idlelib / ScriptBinding.py
blob878425dc1e2c2e795b13c752f1d528a60da306f1
1 """Extension to execute code outside the Python shell window.
3 This adds the following commands:
5 - Check module does a full syntax check of the current module.
6 It also runs the tabnanny to catch any inconsistent tabs.
8 - Run module executes the module's code in the __main__ namespace. The window
9 must have been saved previously. The module is added to sys.modules, and is
10 also added to the __main__ namespace.
12 XXX GvR Redesign this interface (yet again) as follows:
14 - Present a dialog box for ``Run Module''
16 - Allow specify command line arguments in the dialog box
18 """
20 import os
21 import re
22 import string
23 import tabnanny
24 import tokenize
25 import tkMessageBox
26 import PyShell
28 from configHandler import idleConf
30 IDENTCHARS = string.ascii_letters + string.digits + "_"
32 indent_message = """Error: Inconsistent indentation detected!
34 1) Your indentation is outright incorrect (easy to fix), OR
36 2) Your indentation mixes tabs and spaces.
38 To fix case 2, change all tabs to spaces by using Edit->Select All followed \
39 by Format->Untabify Region and specify the number of columns used by each tab.
40 """
42 class ScriptBinding:
44 menudefs = [
45 ('run', [None,
46 ('Check Module', '<<check-module>>'),
47 ('Run Module', '<<run-module>>'), ]), ]
49 def __init__(self, editwin):
50 self.editwin = editwin
51 # Provide instance variables referenced by Debugger
52 # XXX This should be done differently
53 self.flist = self.editwin.flist
54 self.root = self.editwin.root
56 def check_module_event(self, event):
57 filename = self.getfilename()
58 if not filename:
59 return
60 if not self.tabnanny(filename):
61 return
62 self.checksyntax(filename)
64 def tabnanny(self, filename):
65 f = open(filename, 'r')
66 try:
67 tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
68 except tokenize.TokenError, msg:
69 msgtxt, (lineno, start) = msg
70 self.editwin.gotoline(lineno)
71 self.errorbox("Tabnanny Tokenizing Error",
72 "Token Error: %s" % msgtxt)
73 return False
74 except tabnanny.NannyNag, nag:
75 # The error messages from tabnanny are too confusing...
76 self.editwin.gotoline(nag.get_lineno())
77 self.errorbox("Tab/space error", indent_message)
78 return False
79 return True
81 def checksyntax(self, filename):
82 self.shell = shell = self.flist.open_shell()
83 saved_stream = shell.get_warning_stream()
84 shell.set_warning_stream(shell.stderr)
85 f = open(filename, 'r')
86 source = f.read()
87 f.close()
88 if '\r' in source:
89 source = re.sub(r"\r\n", "\n", source)
90 source = re.sub(r"\r", "\n", source)
91 if source and source[-1] != '\n':
92 source = source + '\n'
93 text = self.editwin.text
94 text.tag_remove("ERROR", "1.0", "end")
95 try:
96 try:
97 # If successful, return the compiled code
98 return compile(source, filename, "exec")
99 except (SyntaxError, OverflowError), err:
100 try:
101 msg, (errorfilename, lineno, offset, line) = err
102 if not errorfilename:
103 err.args = msg, (filename, lineno, offset, line)
104 err.filename = filename
105 self.colorize_syntax_error(msg, lineno, offset)
106 except:
107 msg = "*** " + str(err)
108 self.errorbox("Syntax error",
109 "There's an error in your program:\n" + msg)
110 return False
111 finally:
112 shell.set_warning_stream(saved_stream)
114 def colorize_syntax_error(self, msg, lineno, offset):
115 text = self.editwin.text
116 pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
117 text.tag_add("ERROR", pos)
118 char = text.get(pos)
119 if char and char in IDENTCHARS:
120 text.tag_add("ERROR", pos + " wordstart", pos)
121 if '\n' == text.get(pos): # error at line end
122 text.mark_set("insert", pos)
123 else:
124 text.mark_set("insert", pos + "+1c")
125 text.see(pos)
127 def run_module_event(self, event):
128 """Run the module after setting up the environment.
130 First check the syntax. If OK, make sure the shell is active and
131 then transfer the arguments, set the run environment's working
132 directory to the directory of the module being executed and also
133 add that directory to its sys.path if not already included.
136 filename = self.getfilename()
137 if not filename:
138 return
139 if not self.tabnanny(filename):
140 return
141 code = self.checksyntax(filename)
142 if not code:
143 return
144 shell = self.shell
145 interp = shell.interp
146 if PyShell.use_subprocess:
147 shell.restart_shell()
148 dirname = os.path.dirname(filename)
149 # XXX Too often this discards arguments the user just set...
150 interp.runcommand("""if 1:
151 _filename = %r
152 import sys as _sys
153 from os.path import basename as _basename
154 if (not _sys.argv or
155 _basename(_sys.argv[0]) != _basename(_filename)):
156 _sys.argv = [_filename]
157 import os as _os
158 _os.chdir(%r)
159 del _filename, _sys, _basename, _os
160 \n""" % (filename, dirname))
161 interp.prepend_syspath(filename)
162 # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
163 # go to __stderr__. With subprocess, they go to the shell.
164 # Need to change streams in PyShell.ModifiedInterpreter.
165 interp.runcode(code)
167 def getfilename(self):
168 """Get source filename. If not saved, offer to save (or create) file
170 The debugger requires a source file. Make sure there is one, and that
171 the current version of the source buffer has been saved. If the user
172 declines to save or cancels the Save As dialog, return None.
174 If the user has configured IDLE for Autosave, the file will be
175 silently saved if it already exists and is dirty.
178 filename = self.editwin.io.filename
179 if not self.editwin.get_saved():
180 autosave = idleConf.GetOption('main', 'General',
181 'autosave', type='bool')
182 if autosave and filename:
183 self.editwin.io.save(None)
184 else:
185 reply = self.ask_save_dialog()
186 self.editwin.text.focus_set()
187 if reply == "ok":
188 self.editwin.io.save(None)
189 filename = self.editwin.io.filename
190 else:
191 filename = None
192 return filename
194 def ask_save_dialog(self):
195 msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
196 mb = tkMessageBox.Message(title="Save Before Run or Check",
197 message=msg,
198 icon=tkMessageBox.QUESTION,
199 type=tkMessageBox.OKCANCEL,
200 default=tkMessageBox.OK,
201 master=self.editwin.text)
202 return mb.show()
204 def errorbox(self, title, message):
205 # XXX This should really be a function of EditorWindow...
206 tkMessageBox.showerror(title, message, master=self.editwin.text)
207 self.editwin.text.focus_set()