blob: 028b0dbd21dfe63c0e8b465dffbd8380102a5fac [file] [log] [blame]
wohlganger58fc71c2017-09-10 16:19:47 -05001"""Execute code from an editor.
David Scherer7aced172000-08-15 01:13:23 +00002
wohlganger58fc71c2017-09-10 16:19:47 -05003Check module: do a full syntax check of the current module.
4Also run the tabnanny to catch any inconsistent tabs.
David Scherer7aced172000-08-15 01:13:23 +00005
wohlganger58fc71c2017-09-10 16:19:47 -05006Run module: also execute the module's code in the __main__ namespace.
7The window must have been saved previously. The module is added to
8sys.modules, and is also added to the __main__ namespace.
David Scherer7aced172000-08-15 01:13:23 +00009
wohlganger58fc71c2017-09-10 16:19:47 -050010TODO: Specify command line arguments in a dialog box.
David Scherer7aced172000-08-15 01:13:23 +000011"""
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +000012import os
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +000013import tabnanny
Terry Jan Reedy57e51132020-12-06 22:22:33 -050014import time
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +000015import tokenize
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040016
Georg Brandl14fc4272008-05-17 18:39:55 +000017import tkinter.messagebox as tkMessageBox
David Scherer7aced172000-08-15 01:13:23 +000018
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040019from idlelib.config import idleConf
20from idlelib import macosx
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040021from idlelib import pyshell
Cheryl Sabella201bc2d2019-06-17 22:24:10 -040022from idlelib.query import CustomRun
Terry Jan Reedye3f90b22019-10-26 21:15:10 -040023from idlelib import outwin
Kurt B. Kaiser6c638b62003-05-26 06:23:10 +000024
David Scherer7aced172000-08-15 01:13:23 +000025indent_message = """Error: Inconsistent indentation detected!
26
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000271) Your indentation is outright incorrect (easy to fix), OR
David Scherer7aced172000-08-15 01:13:23 +000028
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +0000292) Your indentation mixes tabs and spaces.
David Scherer7aced172000-08-15 01:13:23 +000030
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +000031To fix case 2, change all tabs to spaces by using Edit->Select All followed \
32by Format->Untabify Region and specify the number of columns used by each tab.
33"""
Kurt B. Kaiser969de452002-06-12 03:28:57 +000034
Terry Jan Reedy5c28e9f2015-08-06 00:54:07 -040035
David Scherer7aced172000-08-15 01:13:23 +000036class ScriptBinding:
Steven M. Gava42f6c642001-07-12 06:46:53 +000037
David Scherer7aced172000-08-15 01:13:23 +000038 def __init__(self, editwin):
39 self.editwin = editwin
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040040 # Provide instance variables referenced by debugger
David Scherer7aced172000-08-15 01:13:23 +000041 # XXX This should be done differently
42 self.flist = self.editwin.flist
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043 self.root = self.editwin.root
Ngalim Siregar35b87e62019-07-21 22:37:28 +070044 # cli_args is list of strings that extends sys.argv
45 self.cli_args = []
Terry Jan Reedy57e51132020-12-06 22:22:33 -050046 self.perf = 0.0 # Workaround for macOS 11 Uni2; see bpo-42508.
Ronald Oussoren5ee05672011-05-17 14:48:40 +020047
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +000048 def check_module_event(self, event):
Terry Jan Reedye3f90b22019-10-26 21:15:10 -040049 if isinstance(self.editwin, outwin.OutputWindow):
50 self.editwin.text.bell()
51 return 'break'
David Scherer7aced172000-08-15 01:13:23 +000052 filename = self.getfilename()
53 if not filename:
Christian Heimesa156e092008-02-16 07:38:31 +000054 return 'break'
Thomas Wouters89f507f2006-12-13 04:49:30 +000055 if not self.checksyntax(filename):
Christian Heimesa156e092008-02-16 07:38:31 +000056 return 'break'
David Scherer7aced172000-08-15 01:13:23 +000057 if not self.tabnanny(filename):
Christian Heimesa156e092008-02-16 07:38:31 +000058 return 'break'
Serhiy Storchaka213ce122017-06-27 07:02:32 +030059 return "break"
David Scherer7aced172000-08-15 01:13:23 +000060
61 def tabnanny(self, filename):
Martin v. Löwis975a0792009-01-18 20:15:42 +000062 # XXX: tabnanny should work on binary files as well
Victor Stinner85c67722011-09-02 00:57:04 +020063 with tokenize.open(filename) as f:
64 try:
65 tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
66 except tokenize.TokenError as msg:
Terry Jan Reedyc6dd5b12015-08-14 16:59:42 -040067 msgtxt, (lineno, start) = msg.args
Victor Stinner85c67722011-09-02 00:57:04 +020068 self.editwin.gotoline(lineno)
69 self.errorbox("Tabnanny Tokenizing Error",
70 "Token Error: %s" % msgtxt)
71 return False
72 except tabnanny.NannyNag as nag:
73 # The error messages from tabnanny are too confusing...
74 self.editwin.gotoline(nag.get_lineno())
75 self.errorbox("Tab/space error", indent_message)
76 return False
Neal Norwitz6453c1f2002-11-30 19:18:46 +000077 return True
David Scherer7aced172000-08-15 01:13:23 +000078
79 def checksyntax(self, filename):
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +000080 self.shell = shell = self.flist.open_shell()
81 saved_stream = shell.get_warning_stream()
82 shell.set_warning_stream(shell.stderr)
Terry Jan Reedy95f34ab2013-08-04 15:39:03 -040083 with open(filename, 'rb') as f:
84 source = f.read()
Martin v. Löwis975a0792009-01-18 20:15:42 +000085 if b'\r' in source:
86 source = source.replace(b'\r\n', b'\n')
87 source = source.replace(b'\r', b'\n')
88 if source and source[-1] != ord(b'\n'):
89 source = source + b'\n'
Guido van Rossum33d26892007-08-05 15:29:28 +000090 editwin = self.editwin
91 text = editwin.text
Kurt B. Kaiser3f8ace92003-06-05 02:38:32 +000092 text.tag_remove("ERROR", "1.0", "end")
David Scherer7aced172000-08-15 01:13:23 +000093 try:
Guido van Rossum33d26892007-08-05 15:29:28 +000094 # If successful, return the compiled code
95 return compile(source, filename, "exec")
Ned Deily79746422011-09-14 14:49:14 -070096 except (SyntaxError, OverflowError, ValueError) as value:
97 msg = getattr(value, 'msg', '') or value or "<no detail available>"
98 lineno = getattr(value, 'lineno', '') or 1
99 offset = getattr(value, 'offset', '') or 0
Guido van Rossum33d26892007-08-05 15:29:28 +0000100 if offset == 0:
101 lineno += 1 #mark end of offending line
102 pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
103 editwin.colorize_syntax_error(text, pos)
104 self.errorbox("SyntaxError", "%-20s" % msg)
105 return False
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +0000106 finally:
107 shell.set_warning_stream(saved_stream)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000108
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400109 def run_custom_event(self, event):
Terry Jan Reedy57e51132020-12-06 22:22:33 -0500110 return self.run_module_event(event, customize=True)
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400111
Terry Jan Reedy57e51132020-12-06 22:22:33 -0500112 def run_module_event(self, event, *, customize=False):
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000113 """Run the module after setting up the environment.
114
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400115 First check the syntax. Next get customization. If OK, make
116 sure the shell is active and then transfer the arguments, set
117 the run environment's working directory to the directory of the
118 module being executed and also add that directory to its
119 sys.path if not already included.
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000120 """
Terry Jan Reedy57e51132020-12-06 22:22:33 -0500121 if macosx.isCocoaTk() and (time.perf_counter() - self.perf < .05):
122 return 'break'
Terry Jan Reedye3f90b22019-10-26 21:15:10 -0400123 if isinstance(self.editwin, outwin.OutputWindow):
124 self.editwin.text.bell()
125 return 'break'
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +0000126 filename = self.getfilename()
127 if not filename:
Christian Heimesa156e092008-02-16 07:38:31 +0000128 return 'break'
Kurt B. Kaiser0cd233f2005-08-23 03:25:38 +0000129 code = self.checksyntax(filename)
Kurt B. Kaiser92b5ca32002-12-17 21:16:12 +0000130 if not code:
Christian Heimesa156e092008-02-16 07:38:31 +0000131 return 'break'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000132 if not self.tabnanny(filename):
Christian Heimesa156e092008-02-16 07:38:31 +0000133 return 'break'
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400134 if customize:
135 title = f"Customize {self.editwin.short_title()} Run"
Ngalim Siregar35b87e62019-07-21 22:37:28 +0700136 run_args = CustomRun(self.shell.text, title,
137 cli_args=self.cli_args).result
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400138 if not run_args: # User cancelled.
139 return 'break'
Ngalim Siregar35b87e62019-07-21 22:37:28 +0700140 self.cli_args, restart = run_args if customize else ([], True)
Terry Jan Reedyda4c4672012-01-31 02:26:32 -0500141 interp = self.shell.interp
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400142 if pyshell.use_subprocess and restart:
143 interp.restart_subprocess(
Serhiy Storchaka06cb94b2019-10-04 13:09:52 +0300144 with_cwd=False, filename=filename)
Kurt B. Kaiserce5b6d52003-05-31 23:44:18 +0000145 dirname = os.path.dirname(filename)
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400146 argv = [filename]
Ngalim Siregar35b87e62019-07-21 22:37:28 +0700147 if self.cli_args:
148 argv += self.cli_args
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400149 interp.runcommand(f"""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
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400153 argv = {argv!r}
Chui Tey5d2af632002-05-26 13:36:41 +0000154 if (not _sys.argv or
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400155 _basename(_sys.argv[0]) != _basename(__file__) or
156 len(argv) > 1):
157 _sys.argv = argv
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})
Terry Jan Reedyc59295a2019-09-09 23:10:44 -0400160 del _sys, argv, _basename, _os
Cheryl Sabella201bc2d2019-06-17 22:24:10 -0400161 \n""")
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.
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -0400165 # 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,
Terry Jan Reedy3be2e542015-09-25 22:22:55 -0400201 parent=self.editwin.text)
Kurt B. Kaiser0a429822011-05-12 15:25:24 -0400202 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...
Terry Jan Reedy3be2e542015-09-25 22:22:55 -0400206 tkMessageBox.showerror(title, message, parent=self.editwin.text)
David Scherer7aced172000-08-15 01:13:23 +0000207 self.editwin.text.focus_set()
Terry Jan Reedy57e51132020-12-06 22:22:33 -0500208 self.perf = time.perf_counter()
Terry Jan Reedy4d921582018-06-19 19:12:52 -0400209
210
211if __name__ == "__main__":
212 from unittest import main
213 main('idlelib.idle_test.test_runscript', verbosity=2,)