blob: 6bfe128e3ce82ce960d9bbcc66bf0e5fd3023de4 [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001"""Extension to execute code outside the Python shell window.
2
Kurt B. Kaiser969de452002-06-12 03:28:57 +00003This adds the following commands:
David Scherer7aced172000-08-15 01:13:23 +00004
Kurt B. Kaiser969de452002-06-12 03:28:57 +00005- Check module does a full syntax check of the current module.
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +00006 It also runs the tabnanny to catch any inconsistent tabs.
David Scherer7aced172000-08-15 01:13:23 +00007
Kurt B. Kaiser63857a42002-09-05 02:31:20 +00008- Run module executes the module's code in the __main__ namespace. The window
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +00009 must have been saved previously. The module is added to sys.modules, and is
10 also added to the __main__ namespace.
David Scherer7aced172000-08-15 01:13:23 +000011
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +000012XXX GvR Redesign this interface (yet again) as follows:
Chui Tey5d2af632002-05-26 13:36:41 +000013
Kurt B. Kaisereb9637e2003-01-26 04:17:16 +000014- Present a dialog box for ``Run Module''
Chui Tey5d2af632002-05-26 13:36:41 +000015
16- Allow specify command line arguments in the dialog box
17
David Scherer7aced172000-08-15 01:13:23 +000018"""
19
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +000020import os
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +000021import re
22import string
23import tabnanny
24import tokenize
Georg Brandl14fc4272008-05-17 18:39:55 +000025import tkinter.messagebox as tkMessageBox
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000026from idlelib.EditorWindow import EditorWindow
Martin v. Löwis975a0792009-01-18 20:15:42 +000027from idlelib import PyShell, IOBinding
David Scherer7aced172000-08-15 01:13:23 +000028
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000029from idlelib.configHandler import idleConf
Ronald Oussoren5ee05672011-05-17 14:48:40 +020030from idlelib import macosxSupport
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +000031
David Scherer7aced172000-08-15 01:13:23 +000032indent_message = """Error: Inconsistent indentation detected!
33
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000341) Your indentation is outright incorrect (easy to fix), OR
David Scherer7aced172000-08-15 01:13:23 +000035
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000362) Your indentation mixes tabs and spaces.
David Scherer7aced172000-08-15 01:13:23 +000037
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +000038To fix case 2, change all tabs to spaces by using Edit->Select All followed \
39by Format->Untabify Region and specify the number of columns used by each tab.
40"""
Kurt B. Kaiser969de452002-06-12 03:28:57 +000041
David Scherer7aced172000-08-15 01:13:23 +000042class ScriptBinding:
Steven M. Gava42f6c642001-07-12 06:46:53 +000043
David Scherer7aced172000-08-15 01:13:23 +000044 menudefs = [
Kurt B. Kaiser969de452002-06-12 03:28:57 +000045 ('run', [None,
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +000046 ('Check Module', '<<check-module>>'),
Kurt B. Kaisereb9637e2003-01-26 04:17:16 +000047 ('Run Module', '<<run-module>>'), ]), ]
David Scherer7aced172000-08-15 01:13:23 +000048
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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054 self.root = self.editwin.root
David Scherer7aced172000-08-15 01:13:23 +000055
Ronald Oussoren5ee05672011-05-17 14:48:40 +020056 if macosxSupport.runningAsOSXApp():
57 self.editwin.text_frame.bind('<<run-module-event-2>>', self._run_module_event)
58
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +000059 def check_module_event(self, event):
David Scherer7aced172000-08-15 01:13:23 +000060 filename = self.getfilename()
61 if not filename:
Christian Heimesa156e092008-02-16 07:38:31 +000062 return 'break'
Thomas Wouters89f507f2006-12-13 04:49:30 +000063 if not self.checksyntax(filename):
Christian Heimesa156e092008-02-16 07:38:31 +000064 return 'break'
David Scherer7aced172000-08-15 01:13:23 +000065 if not self.tabnanny(filename):
Christian Heimesa156e092008-02-16 07:38:31 +000066 return 'break'
David Scherer7aced172000-08-15 01:13:23 +000067
68 def tabnanny(self, filename):
Martin v. Löwis975a0792009-01-18 20:15:42 +000069 # XXX: tabnanny should work on binary files as well
Victor Stinner85c67722011-09-02 00:57:04 +020070 with tokenize.open(filename) as f:
71 try:
72 tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
73 except tokenize.TokenError as msg:
74 msgtxt, (lineno, start) = msg
75 self.editwin.gotoline(lineno)
76 self.errorbox("Tabnanny Tokenizing Error",
77 "Token Error: %s" % msgtxt)
78 return False
79 except tabnanny.NannyNag as nag:
80 # The error messages from tabnanny are too confusing...
81 self.editwin.gotoline(nag.get_lineno())
82 self.errorbox("Tab/space error", indent_message)
83 return False
Neal Norwitz6453c1f2002-11-30 19:18:46 +000084 return True
David Scherer7aced172000-08-15 01:13:23 +000085
86 def checksyntax(self, filename):
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +000087 self.shell = shell = self.flist.open_shell()
88 saved_stream = shell.get_warning_stream()
89 shell.set_warning_stream(shell.stderr)
Terry Jan Reedy95f34ab2013-08-04 15:39:03 -040090 with open(filename, 'rb') as f:
91 source = f.read()
Martin v. Löwis975a0792009-01-18 20:15:42 +000092 if b'\r' in source:
93 source = source.replace(b'\r\n', b'\n')
94 source = source.replace(b'\r', b'\n')
95 if source and source[-1] != ord(b'\n'):
96 source = source + b'\n'
Guido van Rossum33d26892007-08-05 15:29:28 +000097 editwin = self.editwin
98 text = editwin.text
Kurt B. Kaiser3f8ace92003-06-05 02:38:32 +000099 text.tag_remove("ERROR", "1.0", "end")
David Scherer7aced172000-08-15 01:13:23 +0000100 try:
Guido van Rossum33d26892007-08-05 15:29:28 +0000101 # If successful, return the compiled code
102 return compile(source, filename, "exec")
Ned Deily79746422011-09-14 14:49:14 -0700103 except (SyntaxError, OverflowError, ValueError) as value:
104 msg = getattr(value, 'msg', '') or value or "<no detail available>"
105 lineno = getattr(value, 'lineno', '') or 1
106 offset = getattr(value, 'offset', '') or 0
Guido van Rossum33d26892007-08-05 15:29:28 +0000107 if offset == 0:
108 lineno += 1 #mark end of offending line
109 pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
110 editwin.colorize_syntax_error(text, pos)
111 self.errorbox("SyntaxError", "%-20s" % msg)
112 return False
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000113 finally:
114 shell.set_warning_stream(saved_stream)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000115
Kurt B. Kaisereb9637e2003-01-26 04:17:16 +0000116 def run_module_event(self, event):
Ronald Oussoren5ee05672011-05-17 14:48:40 +0200117 if macosxSupport.runningAsOSXApp():
118 # Tk-Cocoa in MacOSX is broken until at least
119 # Tk 8.5.9, and without this rather
120 # crude workaround IDLE would hang when a user
121 # tries to run a module using the keyboard shortcut
122 # (the menu item works fine).
123 self.editwin.text_frame.after(200,
124 lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
125 return 'break'
126 else:
127 return self._run_module_event(event)
128
129 def _run_module_event(self, event):
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000130 """Run the module after setting up the environment.
131
132 First check the syntax. If OK, make sure the shell is active and
133 then transfer the arguments, set the run environment's working
134 directory to the directory of the module being executed and also
135 add that directory to its sys.path if not already included.
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000136 """
Ronald Oussoren5ee05672011-05-17 14:48:40 +0200137
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +0000138 filename = self.getfilename()
139 if not filename:
Christian Heimesa156e092008-02-16 07:38:31 +0000140 return 'break'
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +0000141 code = self.checksyntax(filename)
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +0000142 if not code:
Christian Heimesa156e092008-02-16 07:38:31 +0000143 return 'break'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000144 if not self.tabnanny(filename):
Christian Heimesa156e092008-02-16 07:38:31 +0000145 return 'break'
Terry Jan Reedyda4c4672012-01-31 02:26:32 -0500146 interp = self.shell.interp
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000147 if PyShell.use_subprocess:
Terry Jan Reedyda4c4672012-01-31 02:26:32 -0500148 interp.restart_subprocess(with_cwd=False)
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000149 dirname = os.path.dirname(filename)
Chui Tey5d2af632002-05-26 13:36:41 +0000150 # XXX Too often this discards arguments the user just set...
151 interp.runcommand("""if 1:
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300152 __file__ = {filename!r}
Chui Tey5d2af632002-05-26 13:36:41 +0000153 import sys as _sys
154 from os.path import basename as _basename
155 if (not _sys.argv or
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300156 _basename(_sys.argv[0]) != _basename(__file__)):
157 _sys.argv = [__file__]
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000158 import os as _os
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300159 _os.chdir({dirname!r})
160 del _sys, _basename, _os
161 \n""".format(filename=filename, dirname=dirname))
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +0000162 interp.prepend_syspath(filename)
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000163 # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
164 # go to __stderr__. With subprocess, they go to the shell.
165 # Need to change streams in PyShell.ModifiedInterpreter.
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +0000166 interp.runcode(code)
Christian Heimesa156e092008-02-16 07:38:31 +0000167 return 'break'
David Scherer7aced172000-08-15 01:13:23 +0000168
169 def getfilename(self):
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000170 """Get source filename. If not saved, offer to save (or create) file
171
172 The debugger requires a source file. Make sure there is one, and that
173 the current version of the source buffer has been saved. If the user
174 declines to save or cancels the Save As dialog, return None.
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000175
176 If the user has configured IDLE for Autosave, the file will be
177 silently saved if it already exists and is dirty.
Kurt B. Kaiser8d1f11b2003-05-26 22:20:34 +0000178
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000179 """
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000180 filename = self.editwin.io.filename
David Scherer7aced172000-08-15 01:13:23 +0000181 if not self.editwin.get_saved():
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000182 autosave = idleConf.GetOption('main', 'General',
183 'autosave', type='bool')
184 if autosave and filename:
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000185 self.editwin.io.save(None)
186 else:
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400187 confirm = self.ask_save_dialog()
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000188 self.editwin.text.focus_set()
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400189 if confirm:
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000190 self.editwin.io.save(None)
191 filename = self.editwin.io.filename
192 else:
193 filename = None
David Scherer7aced172000-08-15 01:13:23 +0000194 return filename
195
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000196 def ask_save_dialog(self):
197 msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400198 confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
199 message=msg,
200 default=tkMessageBox.OK,
201 master=self.editwin.text)
202 return confirm
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000203
David Scherer7aced172000-08-15 01:13:23 +0000204 def errorbox(self, title, message):
205 # XXX This should really be a function of EditorWindow...
Ned Deily7a8e21a2011-01-29 23:34:19 +0000206 tkMessageBox.showerror(title, message, master=self.editwin.text)
David Scherer7aced172000-08-15 01:13:23 +0000207 self.editwin.text.focus_set()