outwin.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. """Editor window that can serve as an output file.
  2. """
  3. import re
  4. from tkinter import messagebox
  5. from idlelib.editor import EditorWindow
  6. from idlelib import iomenu
  7. file_line_pats = [
  8. # order of patterns matters
  9. r'file "([^"]*)", line (\d+)',
  10. r'([^\s]+)\((\d+)\)',
  11. r'^(\s*\S.*?):\s*(\d+):', # Win filename, maybe starting with spaces
  12. r'([^\s]+):\s*(\d+):', # filename or path, ltrim
  13. r'^\s*(\S.*?):\s*(\d+):', # Win abs path with embedded spaces, ltrim
  14. ]
  15. file_line_progs = None
  16. def compile_progs():
  17. "Compile the patterns for matching to file name and line number."
  18. global file_line_progs
  19. file_line_progs = [re.compile(pat, re.IGNORECASE)
  20. for pat in file_line_pats]
  21. def file_line_helper(line):
  22. """Extract file name and line number from line of text.
  23. Check if line of text contains one of the file/line patterns.
  24. If it does and if the file and line are valid, return
  25. a tuple of the file name and line number. If it doesn't match
  26. or if the file or line is invalid, return None.
  27. """
  28. if not file_line_progs:
  29. compile_progs()
  30. for prog in file_line_progs:
  31. match = prog.search(line)
  32. if match:
  33. filename, lineno = match.group(1, 2)
  34. try:
  35. f = open(filename, "r")
  36. f.close()
  37. break
  38. except OSError:
  39. continue
  40. else:
  41. return None
  42. try:
  43. return filename, int(lineno)
  44. except TypeError:
  45. return None
  46. class OutputWindow(EditorWindow):
  47. """An editor window that can serve as an output file.
  48. Also the future base class for the Python shell window.
  49. This class has no input facilities.
  50. Adds binding to open a file at a line to the text widget.
  51. """
  52. # Our own right-button menu
  53. rmenu_specs = [
  54. ("Cut", "<<cut>>", "rmenu_check_cut"),
  55. ("Copy", "<<copy>>", "rmenu_check_copy"),
  56. ("Paste", "<<paste>>", "rmenu_check_paste"),
  57. (None, None, None),
  58. ("Go to file/line", "<<goto-file-line>>", None),
  59. ]
  60. allow_code_context = False
  61. def __init__(self, *args):
  62. EditorWindow.__init__(self, *args)
  63. self.text.bind("<<goto-file-line>>", self.goto_file_line)
  64. # Customize EditorWindow
  65. def ispythonsource(self, filename):
  66. "Python source is only part of output: do not colorize."
  67. return False
  68. def short_title(self):
  69. "Customize EditorWindow title."
  70. return "Output"
  71. def maybesave(self):
  72. "Customize EditorWindow to not display save file messagebox."
  73. return 'yes' if self.get_saved() else 'no'
  74. # Act as output file
  75. def write(self, s, tags=(), mark="insert"):
  76. """Write text to text widget.
  77. The text is inserted at the given index with the provided
  78. tags. The text widget is then scrolled to make it visible
  79. and updated to display it, giving the effect of seeing each
  80. line as it is added.
  81. Args:
  82. s: Text to insert into text widget.
  83. tags: Tuple of tag strings to apply on the insert.
  84. mark: Index for the insert.
  85. Return:
  86. Length of text inserted.
  87. """
  88. if isinstance(s, bytes):
  89. s = s.decode(iomenu.encoding, "replace")
  90. self.text.insert(mark, s, tags)
  91. self.text.see(mark)
  92. self.text.update()
  93. return len(s)
  94. def writelines(self, lines):
  95. "Write each item in lines iterable."
  96. for line in lines:
  97. self.write(line)
  98. def flush(self):
  99. "No flushing needed as write() directly writes to widget."
  100. pass
  101. def showerror(self, *args, **kwargs):
  102. messagebox.showerror(*args, **kwargs)
  103. def goto_file_line(self, event=None):
  104. """Handle request to open file/line.
  105. If the selected or previous line in the output window
  106. contains a file name and line number, then open that file
  107. name in a new window and position on the line number.
  108. Otherwise, display an error messagebox.
  109. """
  110. line = self.text.get("insert linestart", "insert lineend")
  111. result = file_line_helper(line)
  112. if not result:
  113. # Try the previous line. This is handy e.g. in tracebacks,
  114. # where you tend to right-click on the displayed source line
  115. line = self.text.get("insert -1line linestart",
  116. "insert -1line lineend")
  117. result = file_line_helper(line)
  118. if not result:
  119. self.showerror(
  120. "No special line",
  121. "The line you point at doesn't look like "
  122. "a valid file name followed by a line number.",
  123. parent=self.text)
  124. return
  125. filename, lineno = result
  126. self.flist.gotofileline(filename, lineno)
  127. # These classes are currently not used but might come in handy
  128. class OnDemandOutputWindow:
  129. tagdefs = {
  130. # XXX Should use IdlePrefs.ColorPrefs
  131. "stdout": {"foreground": "blue"},
  132. "stderr": {"foreground": "#007700"},
  133. }
  134. def __init__(self, flist):
  135. self.flist = flist
  136. self.owin = None
  137. def write(self, s, tags, mark):
  138. if not self.owin:
  139. self.setup()
  140. self.owin.write(s, tags, mark)
  141. def setup(self):
  142. self.owin = owin = OutputWindow(self.flist)
  143. text = owin.text
  144. for tag, cnf in self.tagdefs.items():
  145. if cnf:
  146. text.tag_configure(tag, **cnf)
  147. text.tag_raise('sel')
  148. self.write = self.owin.write
  149. if __name__ == '__main__':
  150. from unittest import main
  151. main('idlelib.idle_test.test_outwin', verbosity=2, exit=False)