ScriptBinding.py 8.3 KB

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