blob: 5cb818d833ba890b941a31163438a54ec95b77c5 [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 tabnanny
22import tokenize
Georg Brandl14fc4272008-05-17 18:39:55 +000023import tkinter.messagebox as tkMessageBox
Terry Jan Reedy27336182015-05-14 18:10:50 -040024from idlelib import PyShell
David Scherer7aced172000-08-15 01:13:23 +000025
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000026from idlelib.configHandler import idleConf
Ronald Oussoren5ee05672011-05-17 14:48:40 +020027from idlelib import macosxSupport
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +000028
David Scherer7aced172000-08-15 01:13:23 +000029indent_message = """Error: Inconsistent indentation detected!
30
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000311) Your indentation is outright incorrect (easy to fix), OR
David Scherer7aced172000-08-15 01:13:23 +000032
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000332) Your indentation mixes tabs and spaces.
David Scherer7aced172000-08-15 01:13:23 +000034
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +000035To fix case 2, change all tabs to spaces by using Edit->Select All followed \
36by Format->Untabify Region and specify the number of columns used by each tab.
37"""
Kurt B. Kaiser969de452002-06-12 03:28:57 +000038
Terry Jan Reedy5c28e9f2015-08-06 00:54:07 -040039
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:
Terry Jan Reedyc6dd5b12015-08-14 16:59:42 -040072 msgtxt, (lineno, start) = msg.args
Victor Stinner85c67722011-09-02 00:57:04 +020073 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 Reedy5c28e9f2015-08-06 00:54:07 -0400146 interp.restart_subprocess(with_cwd=False, filename=
147 self.editwin._filename_to_unicode(filename))
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000148 dirname = os.path.dirname(filename)
Chui Tey5d2af632002-05-26 13:36:41 +0000149 # XXX Too often this discards arguments the user just set...
150 interp.runcommand("""if 1:
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300151 __file__ = {filename!r}
Chui Tey5d2af632002-05-26 13:36:41 +0000152 import sys as _sys
153 from os.path import basename as _basename
154 if (not _sys.argv or
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300155 _basename(_sys.argv[0]) != _basename(__file__)):
156 _sys.argv = [__file__]
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000157 import os as _os
Andrew Svetlovdfe980b2012-04-05 21:54:39 +0300158 _os.chdir({dirname!r})
159 del _sys, _basename, _os
160 \n""".format(filename=filename, dirname=dirname))
Kurt B. Kaiser11659ad2003-05-15 23:23:21 +0000161 interp.prepend_syspath(filename)
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000162 # 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.
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +0000165 interp.runcode(code)
Christian Heimesa156e092008-02-16 07:38:31 +0000166 return 'break'
David Scherer7aced172000-08-15 01:13:23 +0000167
168 def getfilename(self):
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000169 """Get source filename. If not saved, offer to save (or create) file
170
171 The debugger requires a source file. Make sure there is one, and that
172 the current version of the source buffer has been saved. If the user
173 declines to save or cancels the Save As dialog, return None.
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000174
175 If the user has configured IDLE for Autosave, the file will be
176 silently saved if it already exists and is dirty.
Kurt B. Kaiser8d1f11b2003-05-26 22:20:34 +0000177
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000178 """
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000179 filename = self.editwin.io.filename
David Scherer7aced172000-08-15 01:13:23 +0000180 if not self.editwin.get_saved():
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000181 autosave = idleConf.GetOption('main', 'General',
182 'autosave', type='bool')
183 if autosave and filename:
Kurt B. Kaiserd5e1cef2002-12-19 03:25:34 +0000184 self.editwin.io.save(None)
185 else:
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400186 confirm = self.ask_save_dialog()
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000187 self.editwin.text.focus_set()
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400188 if confirm:
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000189 self.editwin.io.save(None)
190 filename = self.editwin.io.filename
191 else:
192 filename = None
David Scherer7aced172000-08-15 01:13:23 +0000193 return filename
194
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000195 def ask_save_dialog(self):
196 msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400197 confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
198 message=msg,
199 default=tkMessageBox.OK,
Terry Jan Reedy3be2e542015-09-25 22:22:55 -0400200 parent=self.editwin.text)
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400201 return confirm
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +0000202
David Scherer7aced172000-08-15 01:13:23 +0000203 def errorbox(self, title, message):
204 # XXX This should really be a function of EditorWindow...
Terry Jan Reedy3be2e542015-09-25 22:22:55 -0400205 tkMessageBox.showerror(title, message, parent=self.editwin.text)
David Scherer7aced172000-08-15 01:13:23 +0000206 self.editwin.text.focus_set()