PageRenderTime 36ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/idlelib/ScriptBinding.py

https://bitbucket.org/dac_io/pypy
Python | 224 lines | 215 code | 2 blank | 7 comment | 3 complexity | c1bdab2b468c50c1a268fc7d76b10549 MD5 | raw file
  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.runningAsOSXApp():
  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, msg:
  54. msgtxt, (lineno, start) = msg
  55. self.editwin.gotoline(lineno)
  56. self.errorbox("Tabnanny Tokenizing Error",
  57. "Token Error: %s" % msgtxt)
  58. return False
  59. except tabnanny.NannyNag, 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. f = open(filename, 'r')
  70. source = f.read()
  71. f.close()
  72. if '\r' in source:
  73. source = re.sub(r"\r\n", "\n", source)
  74. source = re.sub(r"\r", "\n", source)
  75. if source and source[-1] != '\n':
  76. source = source + '\n'
  77. text = self.editwin.text
  78. text.tag_remove("ERROR", "1.0", "end")
  79. try:
  80. try:
  81. # If successful, return the compiled code
  82. return compile(source, filename, "exec")
  83. except (SyntaxError, OverflowError), err:
  84. try:
  85. msg, (errorfilename, lineno, offset, line) = err
  86. if not errorfilename:
  87. err.args = msg, (filename, lineno, offset, line)
  88. err.filename = filename
  89. self.colorize_syntax_error(msg, lineno, offset)
  90. except:
  91. msg = "*** " + str(err)
  92. self.errorbox("Syntax error",
  93. "There's an error in your program:\n" + msg)
  94. return False
  95. finally:
  96. shell.set_warning_stream(saved_stream)
  97. def colorize_syntax_error(self, msg, lineno, offset):
  98. text = self.editwin.text
  99. pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
  100. text.tag_add("ERROR", pos)
  101. char = text.get(pos)
  102. if char and char in IDENTCHARS:
  103. text.tag_add("ERROR", pos + " wordstart", pos)
  104. if '\n' == text.get(pos): # error at line end
  105. text.mark_set("insert", pos)
  106. else:
  107. text.mark_set("insert", pos + "+1c")
  108. text.see(pos)
  109. def run_module_event(self, event):
  110. """Run the module after setting up the environment.
  111. First check the syntax. If OK, make sure the shell is active and
  112. then transfer the arguments, set the run environment's working
  113. directory to the directory of the module being executed and also
  114. add that directory to its sys.path if not already included.
  115. """
  116. filename = self.getfilename()
  117. if not filename:
  118. return 'break'
  119. code = self.checksyntax(filename)
  120. if not code:
  121. return 'break'
  122. if not self.tabnanny(filename):
  123. return 'break'
  124. shell = self.shell
  125. interp = shell.interp
  126. if PyShell.use_subprocess:
  127. shell.restart_shell()
  128. dirname = os.path.dirname(filename)
  129. # XXX Too often this discards arguments the user just set...
  130. interp.runcommand("""if 1:
  131. _filename = %r
  132. import sys as _sys
  133. from os.path import basename as _basename
  134. if (not _sys.argv or
  135. _basename(_sys.argv[0]) != _basename(_filename)):
  136. _sys.argv = [_filename]
  137. import os as _os
  138. _os.chdir(%r)
  139. del _filename, _sys, _basename, _os
  140. \n""" % (filename, dirname))
  141. interp.prepend_syspath(filename)
  142. # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
  143. # go to __stderr__. With subprocess, they go to the shell.
  144. # Need to change streams in PyShell.ModifiedInterpreter.
  145. interp.runcode(code)
  146. return 'break'
  147. if macosxSupport.runningAsOSXApp():
  148. # Tk-Cocoa in MacOSX is broken until at least
  149. # Tk 8.5.9, and without this rather
  150. # crude workaround IDLE would hang when a user
  151. # tries to run a module using the keyboard shortcut
  152. # (the menu item works fine).
  153. _run_module_event = run_module_event
  154. def run_module_event(self, event):
  155. self.editwin.text_frame.after(200,
  156. lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
  157. return 'break'
  158. def getfilename(self):
  159. """Get source filename. If not saved, offer to save (or create) file
  160. The debugger requires a source file. Make sure there is one, and that
  161. the current version of the source buffer has been saved. If the user
  162. declines to save or cancels the Save As dialog, return None.
  163. If the user has configured IDLE for Autosave, the file will be
  164. silently saved if it already exists and is dirty.
  165. """
  166. filename = self.editwin.io.filename
  167. if not self.editwin.get_saved():
  168. autosave = idleConf.GetOption('main', 'General',
  169. 'autosave', type='bool')
  170. if autosave and filename:
  171. self.editwin.io.save(None)
  172. else:
  173. confirm = self.ask_save_dialog()
  174. self.editwin.text.focus_set()
  175. if confirm:
  176. self.editwin.io.save(None)
  177. filename = self.editwin.io.filename
  178. else:
  179. filename = None
  180. return filename
  181. def ask_save_dialog(self):
  182. msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
  183. confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
  184. message=msg,
  185. default=tkMessageBox.OK,
  186. master=self.editwin.text)
  187. return confirm
  188. def errorbox(self, title, message):
  189. # XXX This should really be a function of EditorWindow...
  190. tkMessageBox.showerror(title, message, master=self.editwin.text)
  191. self.editwin.text.focus_set()