PageRenderTime 42ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/kcr/pypy
Python | 223 lines | 214 code | 2 blank | 7 comment | 3 complexity | 454354ce25b4dcfd69f9cc457e6709f1 MD5 | raw file
Possible License(s): Apache-2.0
  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, ValueError), 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. interp = self.shell.interp
  125. if PyShell.use_subprocess:
  126. interp.restart_subprocess(with_cwd=False)
  127. dirname = os.path.dirname(filename)
  128. # XXX Too often this discards arguments the user just set...
  129. interp.runcommand("""if 1:
  130. _filename = %r
  131. import sys as _sys
  132. from os.path import basename as _basename
  133. if (not _sys.argv or
  134. _basename(_sys.argv[0]) != _basename(_filename)):
  135. _sys.argv = [_filename]
  136. import os as _os
  137. _os.chdir(%r)
  138. del _filename, _sys, _basename, _os
  139. \n""" % (filename, dirname))
  140. interp.prepend_syspath(filename)
  141. # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
  142. # go to __stderr__. With subprocess, they go to the shell.
  143. # Need to change streams in PyShell.ModifiedInterpreter.
  144. interp.runcode(code)
  145. return 'break'
  146. if macosxSupport.runningAsOSXApp():
  147. # Tk-Cocoa in MacOSX is broken until at least
  148. # Tk 8.5.9, and without this rather
  149. # crude workaround IDLE would hang when a user
  150. # tries to run a module using the keyboard shortcut
  151. # (the menu item works fine).
  152. _run_module_event = run_module_event
  153. def run_module_event(self, event):
  154. self.editwin.text_frame.after(200,
  155. lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
  156. return 'break'
  157. def getfilename(self):
  158. """Get source filename. If not saved, offer to save (or create) file
  159. The debugger requires a source file. Make sure there is one, and that
  160. the current version of the source buffer has been saved. If the user
  161. declines to save or cancels the Save As dialog, return None.
  162. If the user has configured IDLE for Autosave, the file will be
  163. silently saved if it already exists and is dirty.
  164. """
  165. filename = self.editwin.io.filename
  166. if not self.editwin.get_saved():
  167. autosave = idleConf.GetOption('main', 'General',
  168. 'autosave', type='bool')
  169. if autosave and filename:
  170. self.editwin.io.save(None)
  171. else:
  172. confirm = self.ask_save_dialog()
  173. self.editwin.text.focus_set()
  174. if confirm:
  175. self.editwin.io.save(None)
  176. filename = self.editwin.io.filename
  177. else:
  178. filename = None
  179. return filename
  180. def ask_save_dialog(self):
  181. msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
  182. confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
  183. message=msg,
  184. default=tkMessageBox.OK,
  185. master=self.editwin.text)
  186. return confirm
  187. def errorbox(self, title, message):
  188. # XXX This should really be a function of EditorWindow...
  189. tkMessageBox.showerror(title, message, master=self.editwin.text)
  190. self.editwin.text.focus_set()