blob: 3d11e975554e94c9b3b0d1757a8314102d5e090b [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 string
22import tabnanny
23import tokenize
Georg Brandl14fc4272008-05-17 18:39:55 +000024import tkinter.messagebox as tkMessageBox
Terry Jan Reedy27336182015-05-14 18:10:50 -040025from idlelib import PyShell
David Scherer7aced172000-08-15 01:13:23 +000026
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000027from idlelib.configHandler import idleConf
Ronald Oussoren5ee05672011-05-17 14:48:40 +020028from idlelib import macosxSupport
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +000029
David Scherer7aced172000-08-15 01:13:23 +000030indent_message = """Error: Inconsistent indentation detected!
31
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000321) Your indentation is outright incorrect (easy to fix), OR
David Scherer7aced172000-08-15 01:13:23 +000033
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000342) Your indentation mixes tabs and spaces.
David Scherer7aced172000-08-15 01:13:23 +000035
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +000036To fix case 2, change all tabs to spaces by using Edit->Select All followed \
37by Format->Untabify Region and specify the number of columns used by each tab.
38"""
Kurt B. Kaiser969de452002-06-12 03:28:57 +000039
David Scherer7aced172000-08-15 01:13:23 +000040class ScriptBinding:
Steven M. Gava42f6c642001-07-12 06:46:53 +000041
David Scherer7aced172000-08-15 01:13:23 +000042 menudefs = [
Kurt B. Kaiser969de452002-06-12 03:28:57 +000043 ('run', [None,
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +000044 ('Check Module', '<<check-module>>'),
Kurt B. Kaisereb9637e2003-01-26 04:17:16 +000045 ('Run Module', '<<run-module>>'), ]), ]
David Scherer7aced172000-08-15 01:13:23 +000046
47 def __init__(self, editwin):
48 self.editwin = editwin
49 # Provide instance variables referenced by Debugger
50 # XXX This should be done differently
51 self.flist = self.editwin.flist
Thomas Wouters0e3f5912006-08-11 14:57:12 +000052 self.root = self.editwin.root
David Scherer7aced172000-08-15 01:13:23 +000053
Ned Deilyb7601672014-03-27 20:49:14 -070054 if macosxSupport.isCocoaTk():
Ronald Oussoren5ee05672011-05-17 14:48:40 +020055 self.editwin.text_frame.bind('<<run-module-event-2>>', self._run_module_event)
56
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +000057 def check_module_event(self, event):
David Scherer7aced172000-08-15 01:13:23 +000058 filename = self.getfilename()
59 if not filename:
Christian Heimesa156e092008-02-16 07:38:31 +000060 return 'break'
Thomas Wouters89f507f2006-12-13 04:49:30 +000061 if not self.checksyntax(filename):
Christian Heimesa156e092008-02-16 07:38:31 +000062 return 'break'
David Scherer7aced172000-08-15 01:13:23 +000063 if not self.tabnanny(filename):
Christian Heimesa156e092008-02-16 07:38:31 +000064 return 'break'
David Scherer7aced172000-08-15 01:13:23 +000065
66 def tabnanny(self, filename):
Martin v. Löwis975a0792009-01-18 20:15:42 +000067 # XXX: tabnanny should work on binary files as well
Victor Stinner85c67722011-09-02 00:57:04 +020068 with tokenize.open(filename) as f:
69 try:
70 tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
71 except tokenize.TokenError as msg:
72 msgtxt, (lineno, start) = msg
73 self.editwin.gotoline(lineno)
74 self.errorbox("Tabnanny Tokenizing Error",
75 "Token Error: %s" % msgtxt)
76 return False
77 except tabnanny.NannyNag as nag:
78 # The error messages from tabnanny are too confusing...
79 self.editwin.gotoline(nag.get_lineno())
80 self.errorbox("Tab/space error", indent_message)
81 return False
Neal Norwitz6453c1f2002-11-30 19:18:46 +000082 return True
David Scherer7aced172000-08-15 01:13:23 +000083
84 def checksyntax(self, filename):
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +000085 self.shell = shell = self.flist.open_shell()
86 saved_stream = shell.get_warning_stream()
87 shell.set_warning_stream(shell.stderr)
Terry Jan Reedy95f34ab2013-08-04 15:39:03 -040088 with open(filename, 'rb') as f:
89 source = f.read()
Martin v. Löwis975a0792009-01-18 20:15:42 +000090 if b'\r' in source:
91 source = source.replace(b'\r\n', b'\n')
92 source = source.replace(b'\r', b'\n')
93 if source and source[-1] != ord(b'\n'):
94 source = source + b'\n'
Guido van Rossum33d26892007-08-05 15:29:28 +000095 editwin = self.editwin
96 text = editwin.text
Kurt B. Kaiser3f8ace92003-06-05 02:38:32 +000097 text.tag_remove("ERROR", "1.0", "end")
David Scherer7aced172000-08-15 01:13:23 +000098 try:
Guido van Rossum33d26892007-08-05 15:29:28 +000099 # If successful, return the compiled code
100 return compile(source, filename, "exec")
Ned Deily79746422011-09-14 14:49:14 -0700101 except (SyntaxError, OverflowError, ValueError) as value:
102 msg = getattr(value, 'msg', '') or value or "<no detail available>"
103 lineno = getattr(value, 'lineno', '') or 1
104 offset = getattr(value, 'offset', '') or 0
Guido van Rossum33d26892007-08-05 15:29:28 +0000105 if offset == 0:
106 lineno += 1 #mark end of offending line
107 pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
108 editwin.colorize_syntax_error(text, pos)
109 self.errorbox("SyntaxError", "%-20s" % msg)
110 return False
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000111 finally:
112 shell.set_warning_stream(saved_stream)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000113
Kurt B. Kaisereb9637e2003-01-26 04:17:16 +0000114 def run_module_event(self, event):
Ned Deilyb7601672014-03-27 20:49:14 -0700115 if macosxSupport.isCocoaTk():
Ronald Oussoren5ee05672011-05-17 14:48:40 +0200116 # Tk-Cocoa in MacOSX is broken until at least
117 # Tk 8.5.9, and without this rather
118 # crude workaround IDLE would hang when a user
119 # tries to run a module using the keyboard shortcut
120 # (the menu item works fine).
121 self.editwin.text_frame.after(200,
122 lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
123 return 'break'
124 else:
125 return self._run_module_event(event)
126
127 def _run_module_event(self, event):
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000128 """Run the module after setting up the environment.
129
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.
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000134 """
Ronald Oussoren5ee05672011-05-17 14:48:40 +0200135
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +0000136 filename = self.getfilename()
137 if not filename:
Christian Heimesa156e092008-02-16 07:38:31 +0000138 return 'break'
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +0000139 code = self.checksyntax(filename)
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +0000140 if not code:
Christian Heimesa156e092008-02-16 07:38:31 +0000141 return 'break'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142 if not self.tabnanny(filename):
Christian Heimesa156e092008-02-16 07:38:31 +0000143 return 'break'
Terry Jan Reedyda4c4672012-01-31 02:26:32 -0500144 interp = self.shell.interp
Kurt B. Kaiser7f38ec02003-05-15 03:19:42 +0000145 if PyShell.use_subprocess:
Terry Jan Reedyda4c4672012-01-31 02:26:32 -0500146 interp.restart_subprocess(with_cwd=False)
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000147 dirname = os.path.dirname(filename)
Chui Tey5d2af632002-05-26 13:36:41 +0000148 # XXX Too often this discards arguments the user just set...
149 interp.runcommand("""if 1:
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300150 __file__ = {filename!r}
Chui Tey5d2af632002-05-26 13:36:41 +0000151 import sys as _sys
152 from os.path import basename as _basename
153 if (not _sys.argv or
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300154 _basename(_sys.argv[0]) != _basename(__file__)):
155 _sys.argv = [__file__]
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000156 import os as _os
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300157 _os.chdir({dirname!r})
158 del _sys, _basename, _os
159 \n""".format(filename=filename, dirname=dirname))
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +0000160 interp.prepend_syspath(filename)
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000161 # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
162 # go to __stderr__. With subprocess, they go to the shell.
163 # Need to change streams in PyShell.ModifiedInterpreter.
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +0000164 interp.runcode(code)
Christian Heimesa156e092008-02-16 07:38:31 +0000165 return 'break'
David Scherer7aced172000-08-15 01:13:23 +0000166
167 def getfilename(self):
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000168 """Get source filename. If not saved, offer to save (or create) file
169
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.
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000173
174 If the user has configured IDLE for Autosave, the file will be
175 silently saved if it already exists and is dirty.
Kurt B. Kaiser8d1f11b2003-05-26 22:20:34 +0000176
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000177 """
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000178 filename = self.editwin.io.filename
David Scherer7aced172000-08-15 01:13:23 +0000179 if not self.editwin.get_saved():
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000180 autosave = idleConf.GetOption('main', 'General',
181 'autosave', type='bool')
182 if autosave and filename:
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000183 self.editwin.io.save(None)
184 else:
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400185 confirm = self.ask_save_dialog()
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000186 self.editwin.text.focus_set()
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400187 if confirm:
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000188 self.editwin.io.save(None)
189 filename = self.editwin.io.filename
190 else:
191 filename = None
David Scherer7aced172000-08-15 01:13:23 +0000192 return filename
193
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000194 def ask_save_dialog(self):
195 msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400196 confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
197 message=msg,
198 default=tkMessageBox.OK,
199 master=self.editwin.text)
200 return confirm
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000201
David Scherer7aced172000-08-15 01:13:23 +0000202 def errorbox(self, title, message):
203 # XXX This should really be a function of EditorWindow...
Ned Deily7a8e21a2011-01-29 23:34:19 +0000204 tkMessageBox.showerror(title, message, master=self.editwin.text)
David Scherer7aced172000-08-15 01:13:23 +0000205 self.editwin.text.focus_set()