logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

pyshell.py (62710B)


  1. #! /usr/bin/env python3
  2. import sys
  3. if __name__ == "__main__":
  4. sys.modules['idlelib.pyshell'] = sys.modules['__main__']
  5. try:
  6. from tkinter import *
  7. except ImportError:
  8. print("** IDLE can't import Tkinter.\n"
  9. "Your Python may not be configured for Tk. **", file=sys.__stderr__)
  10. raise SystemExit(1)
  11. # Valid arguments for the ...Awareness call below are defined in the following.
  12. # https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx
  13. if sys.platform == 'win32':
  14. try:
  15. import ctypes
  16. PROCESS_SYSTEM_DPI_AWARE = 1 # Int required.
  17. ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
  18. except (ImportError, AttributeError, OSError):
  19. pass
  20. from tkinter import messagebox
  21. if TkVersion < 8.5:
  22. root = Tk() # otherwise create root in main
  23. root.withdraw()
  24. from idlelib.run import fix_scaling
  25. fix_scaling(root)
  26. messagebox.showerror("Idle Cannot Start",
  27. "Idle requires tcl/tk 8.5+, not %s." % TkVersion,
  28. parent=root)
  29. raise SystemExit(1)
  30. from code import InteractiveInterpreter
  31. import itertools
  32. import linecache
  33. import os
  34. import os.path
  35. from platform import python_version
  36. import re
  37. import socket
  38. import subprocess
  39. from textwrap import TextWrapper
  40. import threading
  41. import time
  42. import tokenize
  43. import warnings
  44. from idlelib.colorizer import ColorDelegator
  45. from idlelib.config import idleConf
  46. from idlelib.delegator import Delegator
  47. from idlelib import debugger
  48. from idlelib import debugger_r
  49. from idlelib.editor import EditorWindow, fixwordbreaks
  50. from idlelib.filelist import FileList
  51. from idlelib.outwin import OutputWindow
  52. from idlelib import replace
  53. from idlelib import rpc
  54. from idlelib.run import idle_formatwarning, StdInputFile, StdOutputFile
  55. from idlelib.undo import UndoDelegator
  56. # Default for testing; defaults to True in main() for running.
  57. use_subprocess = False
  58. HOST = '127.0.0.1' # python execution server on localhost loopback
  59. PORT = 0 # someday pass in host, port for remote debug capability
  60. # Override warnings module to write to warning_stream. Initialize to send IDLE
  61. # internal warnings to the console. ScriptBinding.check_syntax() will
  62. # temporarily redirect the stream to the shell window to display warnings when
  63. # checking user's code.
  64. warning_stream = sys.__stderr__ # None, at least on Windows, if no console.
  65. def idle_showwarning(
  66. message, category, filename, lineno, file=None, line=None):
  67. """Show Idle-format warning (after replacing warnings.showwarning).
  68. The differences are the formatter called, the file=None replacement,
  69. which can be None, the capture of the consequence AttributeError,
  70. and the output of a hard-coded prompt.
  71. """
  72. if file is None:
  73. file = warning_stream
  74. try:
  75. file.write(idle_formatwarning(
  76. message, category, filename, lineno, line=line))
  77. file.write(">>> ")
  78. except (AttributeError, OSError):
  79. pass # if file (probably __stderr__) is invalid, skip warning.
  80. _warnings_showwarning = None
  81. def capture_warnings(capture):
  82. "Replace warning.showwarning with idle_showwarning, or reverse."
  83. global _warnings_showwarning
  84. if capture:
  85. if _warnings_showwarning is None:
  86. _warnings_showwarning = warnings.showwarning
  87. warnings.showwarning = idle_showwarning
  88. else:
  89. if _warnings_showwarning is not None:
  90. warnings.showwarning = _warnings_showwarning
  91. _warnings_showwarning = None
  92. capture_warnings(True)
  93. def extended_linecache_checkcache(filename=None,
  94. orig_checkcache=linecache.checkcache):
  95. """Extend linecache.checkcache to preserve the <pyshell#...> entries
  96. Rather than repeating the linecache code, patch it to save the
  97. <pyshell#...> entries, call the original linecache.checkcache()
  98. (skipping them), and then restore the saved entries.
  99. orig_checkcache is bound at definition time to the original
  100. method, allowing it to be patched.
  101. """
  102. cache = linecache.cache
  103. save = {}
  104. for key in list(cache):
  105. if key[:1] + key[-1:] == '<>':
  106. save[key] = cache.pop(key)
  107. orig_checkcache(filename)
  108. cache.update(save)
  109. # Patch linecache.checkcache():
  110. linecache.checkcache = extended_linecache_checkcache
  111. class PyShellEditorWindow(EditorWindow):
  112. "Regular text edit window in IDLE, supports breakpoints"
  113. def __init__(self, *args):
  114. self.breakpoints = []
  115. EditorWindow.__init__(self, *args)
  116. self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
  117. self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
  118. self.text.bind("<<open-python-shell>>", self.flist.open_shell)
  119. #TODO: don't read/write this from/to .idlerc when testing
  120. self.breakpointPath = os.path.join(
  121. idleConf.userdir, 'breakpoints.lst')
  122. # whenever a file is changed, restore breakpoints
  123. def filename_changed_hook(old_hook=self.io.filename_change_hook,
  124. self=self):
  125. self.restore_file_breaks()
  126. old_hook()
  127. self.io.set_filename_change_hook(filename_changed_hook)
  128. if self.io.filename:
  129. self.restore_file_breaks()
  130. self.color_breakpoint_text()
  131. rmenu_specs = [
  132. ("Cut", "<<cut>>", "rmenu_check_cut"),
  133. ("Copy", "<<copy>>", "rmenu_check_copy"),
  134. ("Paste", "<<paste>>", "rmenu_check_paste"),
  135. (None, None, None),
  136. ("Set Breakpoint", "<<set-breakpoint-here>>", None),
  137. ("Clear Breakpoint", "<<clear-breakpoint-here>>", None)
  138. ]
  139. def color_breakpoint_text(self, color=True):
  140. "Turn colorizing of breakpoint text on or off"
  141. if self.io is None:
  142. # possible due to update in restore_file_breaks
  143. return
  144. if color:
  145. theme = idleConf.CurrentTheme()
  146. cfg = idleConf.GetHighlight(theme, "break")
  147. else:
  148. cfg = {'foreground': '', 'background': ''}
  149. self.text.tag_config('BREAK', cfg)
  150. def set_breakpoint(self, lineno):
  151. text = self.text
  152. filename = self.io.filename
  153. text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
  154. try:
  155. self.breakpoints.index(lineno)
  156. except ValueError: # only add if missing, i.e. do once
  157. self.breakpoints.append(lineno)
  158. try: # update the subprocess debugger
  159. debug = self.flist.pyshell.interp.debugger
  160. debug.set_breakpoint_here(filename, lineno)
  161. except: # but debugger may not be active right now....
  162. pass
  163. def set_breakpoint_here(self, event=None):
  164. text = self.text
  165. filename = self.io.filename
  166. if not filename:
  167. text.bell()
  168. return
  169. lineno = int(float(text.index("insert")))
  170. self.set_breakpoint(lineno)
  171. def clear_breakpoint_here(self, event=None):
  172. text = self.text
  173. filename = self.io.filename
  174. if not filename:
  175. text.bell()
  176. return
  177. lineno = int(float(text.index("insert")))
  178. try:
  179. self.breakpoints.remove(lineno)
  180. except:
  181. pass
  182. text.tag_remove("BREAK", "insert linestart",\
  183. "insert lineend +1char")
  184. try:
  185. debug = self.flist.pyshell.interp.debugger
  186. debug.clear_breakpoint_here(filename, lineno)
  187. except:
  188. pass
  189. def clear_file_breaks(self):
  190. if self.breakpoints:
  191. text = self.text
  192. filename = self.io.filename
  193. if not filename:
  194. text.bell()
  195. return
  196. self.breakpoints = []
  197. text.tag_remove("BREAK", "1.0", END)
  198. try:
  199. debug = self.flist.pyshell.interp.debugger
  200. debug.clear_file_breaks(filename)
  201. except:
  202. pass
  203. def store_file_breaks(self):
  204. "Save breakpoints when file is saved"
  205. # XXX 13 Dec 2002 KBK Currently the file must be saved before it can
  206. # be run. The breaks are saved at that time. If we introduce
  207. # a temporary file save feature the save breaks functionality
  208. # needs to be re-verified, since the breaks at the time the
  209. # temp file is created may differ from the breaks at the last
  210. # permanent save of the file. Currently, a break introduced
  211. # after a save will be effective, but not persistent.
  212. # This is necessary to keep the saved breaks synched with the
  213. # saved file.
  214. #
  215. # Breakpoints are set as tagged ranges in the text.
  216. # Since a modified file has to be saved before it is
  217. # run, and since self.breakpoints (from which the subprocess
  218. # debugger is loaded) is updated during the save, the visible
  219. # breaks stay synched with the subprocess even if one of these
  220. # unexpected breakpoint deletions occurs.
  221. breaks = self.breakpoints
  222. filename = self.io.filename
  223. try:
  224. with open(self.breakpointPath, "r") as fp:
  225. lines = fp.readlines()
  226. except OSError:
  227. lines = []
  228. try:
  229. with open(self.breakpointPath, "w") as new_file:
  230. for line in lines:
  231. if not line.startswith(filename + '='):
  232. new_file.write(line)
  233. self.update_breakpoints()
  234. breaks = self.breakpoints
  235. if breaks:
  236. new_file.write(filename + '=' + str(breaks) + '\n')
  237. except OSError as err:
  238. if not getattr(self.root, "breakpoint_error_displayed", False):
  239. self.root.breakpoint_error_displayed = True
  240. messagebox.showerror(title='IDLE Error',
  241. message='Unable to update breakpoint list:\n%s'
  242. % str(err),
  243. parent=self.text)
  244. def restore_file_breaks(self):
  245. self.text.update() # this enables setting "BREAK" tags to be visible
  246. if self.io is None:
  247. # can happen if IDLE closes due to the .update() call
  248. return
  249. filename = self.io.filename
  250. if filename is None:
  251. return
  252. if os.path.isfile(self.breakpointPath):
  253. with open(self.breakpointPath, "r") as fp:
  254. lines = fp.readlines()
  255. for line in lines:
  256. if line.startswith(filename + '='):
  257. breakpoint_linenumbers = eval(line[len(filename)+1:])
  258. for breakpoint_linenumber in breakpoint_linenumbers:
  259. self.set_breakpoint(breakpoint_linenumber)
  260. def update_breakpoints(self):
  261. "Retrieves all the breakpoints in the current window"
  262. text = self.text
  263. ranges = text.tag_ranges("BREAK")
  264. linenumber_list = self.ranges_to_linenumbers(ranges)
  265. self.breakpoints = linenumber_list
  266. def ranges_to_linenumbers(self, ranges):
  267. lines = []
  268. for index in range(0, len(ranges), 2):
  269. lineno = int(float(ranges[index].string))
  270. end = int(float(ranges[index+1].string))
  271. while lineno < end:
  272. lines.append(lineno)
  273. lineno += 1
  274. return lines
  275. # XXX 13 Dec 2002 KBK Not used currently
  276. # def saved_change_hook(self):
  277. # "Extend base method - clear breaks if module is modified"
  278. # if not self.get_saved():
  279. # self.clear_file_breaks()
  280. # EditorWindow.saved_change_hook(self)
  281. def _close(self):
  282. "Extend base method - clear breaks when module is closed"
  283. self.clear_file_breaks()
  284. EditorWindow._close(self)
  285. class PyShellFileList(FileList):
  286. "Extend base class: IDLE supports a shell and breakpoints"
  287. # override FileList's class variable, instances return PyShellEditorWindow
  288. # instead of EditorWindow when new edit windows are created.
  289. EditorWindow = PyShellEditorWindow
  290. pyshell = None
  291. def open_shell(self, event=None):
  292. if self.pyshell:
  293. self.pyshell.top.wakeup()
  294. else:
  295. self.pyshell = PyShell(self)
  296. if self.pyshell:
  297. if not self.pyshell.begin():
  298. return None
  299. return self.pyshell
  300. class ModifiedColorDelegator(ColorDelegator):
  301. "Extend base class: colorizer for the shell window itself"
  302. def recolorize_main(self):
  303. self.tag_remove("TODO", "1.0", "iomark")
  304. self.tag_add("SYNC", "1.0", "iomark")
  305. ColorDelegator.recolorize_main(self)
  306. def removecolors(self):
  307. # Don't remove shell color tags before "iomark"
  308. for tag in self.tagdefs:
  309. self.tag_remove(tag, "iomark", "end")
  310. class ModifiedUndoDelegator(UndoDelegator):
  311. "Extend base class: forbid insert/delete before the I/O mark"
  312. def insert(self, index, chars, tags=None):
  313. try:
  314. if self.delegate.compare(index, "<", "iomark"):
  315. self.delegate.bell()
  316. return
  317. except TclError:
  318. pass
  319. UndoDelegator.insert(self, index, chars, tags)
  320. def delete(self, index1, index2=None):
  321. try:
  322. if self.delegate.compare(index1, "<", "iomark"):
  323. self.delegate.bell()
  324. return
  325. except TclError:
  326. pass
  327. UndoDelegator.delete(self, index1, index2)
  328. def undo_event(self, event):
  329. # Temporarily monkey-patch the delegate's .insert() method to
  330. # always use the "stdin" tag. This is needed for undo-ing
  331. # deletions to preserve the "stdin" tag, because UndoDelegator
  332. # doesn't preserve tags for deleted text.
  333. orig_insert = self.delegate.insert
  334. self.delegate.insert = \
  335. lambda index, chars: orig_insert(index, chars, "stdin")
  336. try:
  337. super().undo_event(event)
  338. finally:
  339. self.delegate.insert = orig_insert
  340. class UserInputTaggingDelegator(Delegator):
  341. """Delegator used to tag user input with "stdin"."""
  342. def insert(self, index, chars, tags=None):
  343. if tags is None:
  344. tags = "stdin"
  345. self.delegate.insert(index, chars, tags)
  346. class MyRPCClient(rpc.RPCClient):
  347. def handle_EOF(self):
  348. "Override the base class - just re-raise EOFError"
  349. raise EOFError
  350. def restart_line(width, filename): # See bpo-38141.
  351. """Return width long restart line formatted with filename.
  352. Fill line with balanced '='s, with any extras and at least one at
  353. the beginning. Do not end with a trailing space.
  354. """
  355. tag = f"= RESTART: {filename or 'Shell'} ="
  356. if width >= len(tag):
  357. div, mod = divmod((width -len(tag)), 2)
  358. return f"{(div+mod)*'='}{tag}{div*'='}"
  359. else:
  360. return tag[:-2] # Remove ' ='.
  361. class ModifiedInterpreter(InteractiveInterpreter):
  362. def __init__(self, tkconsole):
  363. self.tkconsole = tkconsole
  364. locals = sys.modules['__main__'].__dict__
  365. InteractiveInterpreter.__init__(self, locals=locals)
  366. self.restarting = False
  367. self.subprocess_arglist = None
  368. self.port = PORT
  369. self.original_compiler_flags = self.compile.compiler.flags
  370. _afterid = None
  371. rpcclt = None
  372. rpcsubproc = None
  373. def spawn_subprocess(self):
  374. if self.subprocess_arglist is None:
  375. self.subprocess_arglist = self.build_subprocess_arglist()
  376. self.rpcsubproc = subprocess.Popen(self.subprocess_arglist)
  377. def build_subprocess_arglist(self):
  378. assert (self.port!=0), (
  379. "Socket should have been assigned a port number.")
  380. w = ['-W' + s for s in sys.warnoptions]
  381. # Maybe IDLE is installed and is being accessed via sys.path,
  382. # or maybe it's not installed and the idle.py script is being
  383. # run from the IDLE source directory.
  384. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
  385. default=False, type='bool')
  386. command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
  387. return [sys.executable] + w + ["-c", command, str(self.port)]
  388. def start_subprocess(self):
  389. addr = (HOST, self.port)
  390. # GUI makes several attempts to acquire socket, listens for connection
  391. for i in range(3):
  392. time.sleep(i)
  393. try:
  394. self.rpcclt = MyRPCClient(addr)
  395. break
  396. except OSError:
  397. pass
  398. else:
  399. self.display_port_binding_error()
  400. return None
  401. # if PORT was 0, system will assign an 'ephemeral' port. Find it out:
  402. self.port = self.rpcclt.listening_sock.getsockname()[1]
  403. # if PORT was not 0, probably working with a remote execution server
  404. if PORT != 0:
  405. # To allow reconnection within the 2MSL wait (cf. Stevens TCP
  406. # V1, 18.6), set SO_REUSEADDR. Note that this can be problematic
  407. # on Windows since the implementation allows two active sockets on
  408. # the same address!
  409. self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
  410. socket.SO_REUSEADDR, 1)
  411. self.spawn_subprocess()
  412. #time.sleep(20) # test to simulate GUI not accepting connection
  413. # Accept the connection from the Python execution server
  414. self.rpcclt.listening_sock.settimeout(10)
  415. try:
  416. self.rpcclt.accept()
  417. except TimeoutError:
  418. self.display_no_subprocess_error()
  419. return None
  420. self.rpcclt.register("console", self.tkconsole)
  421. self.rpcclt.register("stdin", self.tkconsole.stdin)
  422. self.rpcclt.register("stdout", self.tkconsole.stdout)
  423. self.rpcclt.register("stderr", self.tkconsole.stderr)
  424. self.rpcclt.register("flist", self.tkconsole.flist)
  425. self.rpcclt.register("linecache", linecache)
  426. self.rpcclt.register("interp", self)
  427. self.transfer_path(with_cwd=True)
  428. self.poll_subprocess()
  429. return self.rpcclt
  430. def restart_subprocess(self, with_cwd=False, filename=''):
  431. if self.restarting:
  432. return self.rpcclt
  433. self.restarting = True
  434. # close only the subprocess debugger
  435. debug = self.getdebugger()
  436. if debug:
  437. try:
  438. # Only close subprocess debugger, don't unregister gui_adap!
  439. debugger_r.close_subprocess_debugger(self.rpcclt)
  440. except:
  441. pass
  442. # Kill subprocess, spawn a new one, accept connection.
  443. self.rpcclt.close()
  444. self.terminate_subprocess()
  445. console = self.tkconsole
  446. was_executing = console.executing
  447. console.executing = False
  448. self.spawn_subprocess()
  449. try:
  450. self.rpcclt.accept()
  451. except TimeoutError:
  452. self.display_no_subprocess_error()
  453. return None
  454. self.transfer_path(with_cwd=with_cwd)
  455. console.stop_readline()
  456. # annotate restart in shell window and mark it
  457. console.text.delete("iomark", "end-1c")
  458. console.write('\n')
  459. console.write(restart_line(console.width, filename))
  460. console.text.mark_set("restart", "end-1c")
  461. console.text.mark_gravity("restart", "left")
  462. if not filename:
  463. console.showprompt()
  464. # restart subprocess debugger
  465. if debug:
  466. # Restarted debugger connects to current instance of debug GUI
  467. debugger_r.restart_subprocess_debugger(self.rpcclt)
  468. # reload remote debugger breakpoints for all PyShellEditWindows
  469. debug.load_breakpoints()
  470. self.compile.compiler.flags = self.original_compiler_flags
  471. self.restarting = False
  472. return self.rpcclt
  473. def __request_interrupt(self):
  474. self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
  475. def interrupt_subprocess(self):
  476. threading.Thread(target=self.__request_interrupt).start()
  477. def kill_subprocess(self):
  478. if self._afterid is not None:
  479. self.tkconsole.text.after_cancel(self._afterid)
  480. try:
  481. self.rpcclt.listening_sock.close()
  482. except AttributeError: # no socket
  483. pass
  484. try:
  485. self.rpcclt.close()
  486. except AttributeError: # no socket
  487. pass
  488. self.terminate_subprocess()
  489. self.tkconsole.executing = False
  490. self.rpcclt = None
  491. def terminate_subprocess(self):
  492. "Make sure subprocess is terminated"
  493. try:
  494. self.rpcsubproc.kill()
  495. except OSError:
  496. # process already terminated
  497. return
  498. else:
  499. try:
  500. self.rpcsubproc.wait()
  501. except OSError:
  502. return
  503. def transfer_path(self, with_cwd=False):
  504. if with_cwd: # Issue 13506
  505. path = [''] # include Current Working Directory
  506. path.extend(sys.path)
  507. else:
  508. path = sys.path
  509. self.runcommand("""if 1:
  510. import sys as _sys
  511. _sys.path = %r
  512. del _sys
  513. \n""" % (path,))
  514. active_seq = None
  515. def poll_subprocess(self):
  516. clt = self.rpcclt
  517. if clt is None:
  518. return
  519. try:
  520. response = clt.pollresponse(self.active_seq, wait=0.05)
  521. except (EOFError, OSError, KeyboardInterrupt):
  522. # lost connection or subprocess terminated itself, restart
  523. # [the KBI is from rpc.SocketIO.handle_EOF()]
  524. if self.tkconsole.closing:
  525. return
  526. response = None
  527. self.restart_subprocess()
  528. if response:
  529. self.tkconsole.resetoutput()
  530. self.active_seq = None
  531. how, what = response
  532. console = self.tkconsole.console
  533. if how == "OK":
  534. if what is not None:
  535. print(repr(what), file=console)
  536. elif how == "EXCEPTION":
  537. if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
  538. self.remote_stack_viewer()
  539. elif how == "ERROR":
  540. errmsg = "pyshell.ModifiedInterpreter: Subprocess ERROR:\n"
  541. print(errmsg, what, file=sys.__stderr__)
  542. print(errmsg, what, file=console)
  543. # we received a response to the currently active seq number:
  544. try:
  545. self.tkconsole.endexecuting()
  546. except AttributeError: # shell may have closed
  547. pass
  548. # Reschedule myself
  549. if not self.tkconsole.closing:
  550. self._afterid = self.tkconsole.text.after(
  551. self.tkconsole.pollinterval, self.poll_subprocess)
  552. debugger = None
  553. def setdebugger(self, debugger):
  554. self.debugger = debugger
  555. def getdebugger(self):
  556. return self.debugger
  557. def open_remote_stack_viewer(self):
  558. """Initiate the remote stack viewer from a separate thread.
  559. This method is called from the subprocess, and by returning from this
  560. method we allow the subprocess to unblock. After a bit the shell
  561. requests the subprocess to open the remote stack viewer which returns a
  562. static object looking at the last exception. It is queried through
  563. the RPC mechanism.
  564. """
  565. self.tkconsole.text.after(300, self.remote_stack_viewer)
  566. return
  567. def remote_stack_viewer(self):
  568. from idlelib import debugobj_r
  569. oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
  570. if oid is None:
  571. self.tkconsole.root.bell()
  572. return
  573. item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid)
  574. from idlelib.tree import ScrolledCanvas, TreeNode
  575. top = Toplevel(self.tkconsole.root)
  576. theme = idleConf.CurrentTheme()
  577. background = idleConf.GetHighlight(theme, 'normal')['background']
  578. sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
  579. sc.frame.pack(expand=1, fill="both")
  580. node = TreeNode(sc.canvas, None, item)
  581. node.expand()
  582. # XXX Should GC the remote tree when closing the window
  583. gid = 0
  584. def execsource(self, source):
  585. "Like runsource() but assumes complete exec source"
  586. filename = self.stuffsource(source)
  587. self.execfile(filename, source)
  588. def execfile(self, filename, source=None):
  589. "Execute an existing file"
  590. if source is None:
  591. with tokenize.open(filename) as fp:
  592. source = fp.read()
  593. if use_subprocess:
  594. source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n"
  595. + source + "\ndel __file__")
  596. try:
  597. code = compile(source, filename, "exec")
  598. except (OverflowError, SyntaxError):
  599. self.tkconsole.resetoutput()
  600. print('*** Error in script or command!\n'
  601. 'Traceback (most recent call last):',
  602. file=self.tkconsole.stderr)
  603. InteractiveInterpreter.showsyntaxerror(self, filename)
  604. self.tkconsole.showprompt()
  605. else:
  606. self.runcode(code)
  607. def runsource(self, source):
  608. "Extend base class method: Stuff the source in the line cache first"
  609. filename = self.stuffsource(source)
  610. # at the moment, InteractiveInterpreter expects str
  611. assert isinstance(source, str)
  612. # InteractiveInterpreter.runsource() calls its runcode() method,
  613. # which is overridden (see below)
  614. return InteractiveInterpreter.runsource(self, source, filename)
  615. def stuffsource(self, source):
  616. "Stuff source in the filename cache"
  617. filename = "<pyshell#%d>" % self.gid
  618. self.gid = self.gid + 1
  619. lines = source.split("\n")
  620. linecache.cache[filename] = len(source)+1, 0, lines, filename
  621. return filename
  622. def prepend_syspath(self, filename):
  623. "Prepend sys.path with file's directory if not already included"
  624. self.runcommand("""if 1:
  625. _filename = %r
  626. import sys as _sys
  627. from os.path import dirname as _dirname
  628. _dir = _dirname(_filename)
  629. if not _dir in _sys.path:
  630. _sys.path.insert(0, _dir)
  631. del _filename, _sys, _dirname, _dir
  632. \n""" % (filename,))
  633. def showsyntaxerror(self, filename=None):
  634. """Override Interactive Interpreter method: Use Colorizing
  635. Color the offending position instead of printing it and pointing at it
  636. with a caret.
  637. """
  638. tkconsole = self.tkconsole
  639. text = tkconsole.text
  640. text.tag_remove("ERROR", "1.0", "end")
  641. type, value, tb = sys.exc_info()
  642. msg = getattr(value, 'msg', '') or value or "<no detail available>"
  643. lineno = getattr(value, 'lineno', '') or 1
  644. offset = getattr(value, 'offset', '') or 0
  645. if offset == 0:
  646. lineno += 1 #mark end of offending line
  647. if lineno == 1:
  648. pos = "iomark + %d chars" % (offset-1)
  649. else:
  650. pos = "iomark linestart + %d lines + %d chars" % \
  651. (lineno-1, offset-1)
  652. tkconsole.colorize_syntax_error(text, pos)
  653. tkconsole.resetoutput()
  654. self.write("SyntaxError: %s\n" % msg)
  655. tkconsole.showprompt()
  656. def showtraceback(self):
  657. "Extend base class method to reset output properly"
  658. self.tkconsole.resetoutput()
  659. self.checklinecache()
  660. InteractiveInterpreter.showtraceback(self)
  661. if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
  662. self.tkconsole.open_stack_viewer()
  663. def checklinecache(self):
  664. c = linecache.cache
  665. for key in list(c.keys()):
  666. if key[:1] + key[-1:] != "<>":
  667. del c[key]
  668. def runcommand(self, code):
  669. "Run the code without invoking the debugger"
  670. # The code better not raise an exception!
  671. if self.tkconsole.executing:
  672. self.display_executing_dialog()
  673. return 0
  674. if self.rpcclt:
  675. self.rpcclt.remotequeue("exec", "runcode", (code,), {})
  676. else:
  677. exec(code, self.locals)
  678. return 1
  679. def runcode(self, code):
  680. "Override base class method"
  681. if self.tkconsole.executing:
  682. self.restart_subprocess()
  683. self.checklinecache()
  684. debugger = self.debugger
  685. try:
  686. self.tkconsole.beginexecuting()
  687. if not debugger and self.rpcclt is not None:
  688. self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
  689. (code,), {})
  690. elif debugger:
  691. debugger.run(code, self.locals)
  692. else:
  693. exec(code, self.locals)
  694. except SystemExit:
  695. if not self.tkconsole.closing:
  696. if messagebox.askyesno(
  697. "Exit?",
  698. "Do you want to exit altogether?",
  699. default="yes",
  700. parent=self.tkconsole.text):
  701. raise
  702. else:
  703. self.showtraceback()
  704. else:
  705. raise
  706. except:
  707. if use_subprocess:
  708. print("IDLE internal error in runcode()",
  709. file=self.tkconsole.stderr)
  710. self.showtraceback()
  711. self.tkconsole.endexecuting()
  712. else:
  713. if self.tkconsole.canceled:
  714. self.tkconsole.canceled = False
  715. print("KeyboardInterrupt", file=self.tkconsole.stderr)
  716. else:
  717. self.showtraceback()
  718. finally:
  719. if not use_subprocess:
  720. try:
  721. self.tkconsole.endexecuting()
  722. except AttributeError: # shell may have closed
  723. pass
  724. def write(self, s):
  725. "Override base class method"
  726. return self.tkconsole.stderr.write(s)
  727. def display_port_binding_error(self):
  728. messagebox.showerror(
  729. "Port Binding Error",
  730. "IDLE can't bind to a TCP/IP port, which is necessary to "
  731. "communicate with its Python execution server. This might be "
  732. "because no networking is installed on this computer. "
  733. "Run IDLE with the -n command line switch to start without a "
  734. "subprocess and refer to Help/IDLE Help 'Running without a "
  735. "subprocess' for further details.",
  736. parent=self.tkconsole.text)
  737. def display_no_subprocess_error(self):
  738. messagebox.showerror(
  739. "Subprocess Connection Error",
  740. "IDLE's subprocess didn't make connection.\n"
  741. "See the 'Startup failure' section of the IDLE doc, online at\n"
  742. "https://docs.python.org/3/library/idle.html#startup-failure",
  743. parent=self.tkconsole.text)
  744. def display_executing_dialog(self):
  745. messagebox.showerror(
  746. "Already executing",
  747. "The Python Shell window is already executing a command; "
  748. "please wait until it is finished.",
  749. parent=self.tkconsole.text)
  750. class PyShell(OutputWindow):
  751. from idlelib.squeezer import Squeezer
  752. shell_title = "IDLE Shell " + python_version()
  753. # Override classes
  754. ColorDelegator = ModifiedColorDelegator
  755. UndoDelegator = ModifiedUndoDelegator
  756. # Override menus
  757. menu_specs = [
  758. ("file", "_File"),
  759. ("edit", "_Edit"),
  760. ("debug", "_Debug"),
  761. ("options", "_Options"),
  762. ("window", "_Window"),
  763. ("help", "_Help"),
  764. ]
  765. # Extend right-click context menu
  766. rmenu_specs = OutputWindow.rmenu_specs + [
  767. ("Squeeze", "<<squeeze-current-text>>"),
  768. ]
  769. _idx = 1 + len(list(itertools.takewhile(
  770. lambda rmenu_item: rmenu_item[0] != "Copy", rmenu_specs)
  771. ))
  772. rmenu_specs.insert(_idx, ("Copy with prompts",
  773. "<<copy-with-prompts>>",
  774. "rmenu_check_copy"))
  775. del _idx
  776. allow_line_numbers = False
  777. user_input_insert_tags = "stdin"
  778. # New classes
  779. from idlelib.history import History
  780. from idlelib.sidebar import ShellSidebar
  781. def __init__(self, flist=None):
  782. if use_subprocess:
  783. ms = self.menu_specs
  784. if ms[2][0] != "shell":
  785. ms.insert(2, ("shell", "She_ll"))
  786. self.interp = ModifiedInterpreter(self)
  787. if flist is None:
  788. root = Tk()
  789. fixwordbreaks(root)
  790. root.withdraw()
  791. flist = PyShellFileList(root)
  792. self.shell_sidebar = None # initialized below
  793. OutputWindow.__init__(self, flist, None, None)
  794. self.usetabs = False
  795. # indentwidth must be 8 when using tabs. See note in EditorWindow:
  796. self.indentwidth = 4
  797. self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>>\n'
  798. self.prompt_last_line = self.sys_ps1.split('\n')[-1]
  799. self.prompt = self.sys_ps1 # Changes when debug active
  800. text = self.text
  801. text.configure(wrap="char")
  802. text.bind("<<newline-and-indent>>", self.enter_callback)
  803. text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
  804. text.bind("<<interrupt-execution>>", self.cancel_callback)
  805. text.bind("<<end-of-file>>", self.eof_callback)
  806. text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
  807. text.bind("<<toggle-debugger>>", self.toggle_debugger)
  808. text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
  809. text.bind("<<copy-with-prompts>>", self.copy_with_prompts_callback)
  810. if use_subprocess:
  811. text.bind("<<view-restart>>", self.view_restart_mark)
  812. text.bind("<<restart-shell>>", self.restart_shell)
  813. self.squeezer = self.Squeezer(self)
  814. text.bind("<<squeeze-current-text>>",
  815. self.squeeze_current_text_event)
  816. self.save_stdout = sys.stdout
  817. self.save_stderr = sys.stderr
  818. self.save_stdin = sys.stdin
  819. from idlelib import iomenu
  820. self.stdin = StdInputFile(self, "stdin",
  821. iomenu.encoding, iomenu.errors)
  822. self.stdout = StdOutputFile(self, "stdout",
  823. iomenu.encoding, iomenu.errors)
  824. self.stderr = StdOutputFile(self, "stderr",
  825. iomenu.encoding, "backslashreplace")
  826. self.console = StdOutputFile(self, "console",
  827. iomenu.encoding, iomenu.errors)
  828. if not use_subprocess:
  829. sys.stdout = self.stdout
  830. sys.stderr = self.stderr
  831. sys.stdin = self.stdin
  832. try:
  833. # page help() text to shell.
  834. import pydoc # import must be done here to capture i/o rebinding.
  835. # XXX KBK 27Dec07 use text viewer someday, but must work w/o subproc
  836. pydoc.pager = pydoc.plainpager
  837. except:
  838. sys.stderr = sys.__stderr__
  839. raise
  840. #
  841. self.history = self.History(self.text)
  842. #
  843. self.pollinterval = 50 # millisec
  844. self.shell_sidebar = self.ShellSidebar(self)
  845. # Insert UserInputTaggingDelegator at the top of the percolator,
  846. # but make calls to text.insert() skip it. This causes only insert
  847. # events generated in Tcl/Tk to go through this delegator.
  848. self.text.insert = self.per.top.insert
  849. self.per.insertfilter(UserInputTaggingDelegator())
  850. def ResetFont(self):
  851. super().ResetFont()
  852. if self.shell_sidebar is not None:
  853. self.shell_sidebar.update_font()
  854. def ResetColorizer(self):
  855. super().ResetColorizer()
  856. theme = idleConf.CurrentTheme()
  857. tag_colors = {
  858. "stdin": {'background': None, 'foreground': None},
  859. "stdout": idleConf.GetHighlight(theme, "stdout"),
  860. "stderr": idleConf.GetHighlight(theme, "stderr"),
  861. "console": idleConf.GetHighlight(theme, "normal"),
  862. }
  863. for tag, tag_colors_config in tag_colors.items():
  864. self.text.tag_configure(tag, **tag_colors_config)
  865. if self.shell_sidebar is not None:
  866. self.shell_sidebar.update_colors()
  867. def replace_event(self, event):
  868. replace.replace(self.text, insert_tags="stdin")
  869. return "break"
  870. def get_standard_extension_names(self):
  871. return idleConf.GetExtensions(shell_only=True)
  872. def copy_with_prompts_callback(self, event=None):
  873. """Copy selected lines to the clipboard, with prompts.
  874. This makes the copied text useful for doc-tests and interactive
  875. shell code examples.
  876. This always copies entire lines, even if only part of the first
  877. and/or last lines is selected.
  878. """
  879. text = self.text
  880. selection_indexes = (
  881. self.text.index("sel.first linestart"),
  882. self.text.index("sel.last +1line linestart"),
  883. )
  884. if selection_indexes[0] is None:
  885. # There is no selection, so do nothing.
  886. return
  887. selected_text = self.text.get(*selection_indexes)
  888. selection_lineno_range = range(
  889. int(float(selection_indexes[0])),
  890. int(float(selection_indexes[1]))
  891. )
  892. prompts = [
  893. self.shell_sidebar.line_prompts.get(lineno)
  894. for lineno in selection_lineno_range
  895. ]
  896. selected_text_with_prompts = "\n".join(
  897. line if prompt is None else f"{prompt} {line}"
  898. for prompt, line in zip(prompts, selected_text.splitlines())
  899. ) + "\n"
  900. text.clipboard_clear()
  901. text.clipboard_append(selected_text_with_prompts)
  902. reading = False
  903. executing = False
  904. canceled = False
  905. endoffile = False
  906. closing = False
  907. _stop_readline_flag = False
  908. def set_warning_stream(self, stream):
  909. global warning_stream
  910. warning_stream = stream
  911. def get_warning_stream(self):
  912. return warning_stream
  913. def toggle_debugger(self, event=None):
  914. if self.executing:
  915. messagebox.showerror("Don't debug now",
  916. "You can only toggle the debugger when idle",
  917. parent=self.text)
  918. self.set_debugger_indicator()
  919. return "break"
  920. else:
  921. db = self.interp.getdebugger()
  922. if db:
  923. self.close_debugger()
  924. else:
  925. self.open_debugger()
  926. def set_debugger_indicator(self):
  927. db = self.interp.getdebugger()
  928. self.setvar("<<toggle-debugger>>", not not db)
  929. def toggle_jit_stack_viewer(self, event=None):
  930. pass # All we need is the variable
  931. def close_debugger(self):
  932. db = self.interp.getdebugger()
  933. if db:
  934. self.interp.setdebugger(None)
  935. db.close()
  936. if self.interp.rpcclt:
  937. debugger_r.close_remote_debugger(self.interp.rpcclt)
  938. self.resetoutput()
  939. self.console.write("[DEBUG OFF]\n")
  940. self.prompt = self.sys_ps1
  941. self.showprompt()
  942. self.set_debugger_indicator()
  943. def open_debugger(self):
  944. if self.interp.rpcclt:
  945. dbg_gui = debugger_r.start_remote_debugger(self.interp.rpcclt,
  946. self)
  947. else:
  948. dbg_gui = debugger.Debugger(self)
  949. self.interp.setdebugger(dbg_gui)
  950. dbg_gui.load_breakpoints()
  951. self.prompt = "[DEBUG ON]\n" + self.sys_ps1
  952. self.showprompt()
  953. self.set_debugger_indicator()
  954. def debug_menu_postcommand(self):
  955. state = 'disabled' if self.executing else 'normal'
  956. self.update_menu_state('debug', '*tack*iewer', state)
  957. def beginexecuting(self):
  958. "Helper for ModifiedInterpreter"
  959. self.resetoutput()
  960. self.executing = True
  961. def endexecuting(self):
  962. "Helper for ModifiedInterpreter"
  963. self.executing = False
  964. self.canceled = False
  965. self.showprompt()
  966. def close(self):
  967. "Extend EditorWindow.close()"
  968. if self.executing:
  969. response = messagebox.askokcancel(
  970. "Kill?",
  971. "Your program is still running!\n Do you want to kill it?",
  972. default="ok",
  973. parent=self.text)
  974. if response is False:
  975. return "cancel"
  976. self.stop_readline()
  977. self.canceled = True
  978. self.closing = True
  979. return EditorWindow.close(self)
  980. def _close(self):
  981. "Extend EditorWindow._close(), shut down debugger and execution server"
  982. self.close_debugger()
  983. if use_subprocess:
  984. self.interp.kill_subprocess()
  985. # Restore std streams
  986. sys.stdout = self.save_stdout
  987. sys.stderr = self.save_stderr
  988. sys.stdin = self.save_stdin
  989. # Break cycles
  990. self.interp = None
  991. self.console = None
  992. self.flist.pyshell = None
  993. self.history = None
  994. EditorWindow._close(self)
  995. def ispythonsource(self, filename):
  996. "Override EditorWindow method: never remove the colorizer"
  997. return True
  998. def short_title(self):
  999. return self.shell_title
  1000. COPYRIGHT = \
  1001. 'Type "help", "copyright", "credits" or "license()" for more information.'
  1002. def begin(self):
  1003. self.text.mark_set("iomark", "insert")
  1004. self.resetoutput()
  1005. if use_subprocess:
  1006. nosub = ''
  1007. client = self.interp.start_subprocess()
  1008. if not client:
  1009. self.close()
  1010. return False
  1011. else:
  1012. nosub = ("==== No Subprocess ====\n\n" +
  1013. "WARNING: Running IDLE without a Subprocess is deprecated\n" +
  1014. "and will be removed in a later version. See Help/IDLE Help\n" +
  1015. "for details.\n\n")
  1016. sys.displayhook = rpc.displayhook
  1017. self.write("Python %s on %s\n%s\n%s" %
  1018. (sys.version, sys.platform, self.COPYRIGHT, nosub))
  1019. self.text.focus_force()
  1020. self.showprompt()
  1021. # User code should use separate default Tk root window
  1022. import tkinter
  1023. tkinter._support_default_root = True
  1024. tkinter._default_root = None
  1025. return True
  1026. def stop_readline(self):
  1027. if not self.reading: # no nested mainloop to exit.
  1028. return
  1029. self._stop_readline_flag = True
  1030. self.top.quit()
  1031. def readline(self):
  1032. save = self.reading
  1033. try:
  1034. self.reading = True
  1035. self.top.mainloop() # nested mainloop()
  1036. finally:
  1037. self.reading = save
  1038. if self._stop_readline_flag:
  1039. self._stop_readline_flag = False
  1040. return ""
  1041. line = self.text.get("iomark", "end-1c")
  1042. if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C
  1043. line = "\n"
  1044. self.resetoutput()
  1045. if self.canceled:
  1046. self.canceled = False
  1047. if not use_subprocess:
  1048. raise KeyboardInterrupt
  1049. if self.endoffile:
  1050. self.endoffile = False
  1051. line = ""
  1052. return line
  1053. def isatty(self):
  1054. return True
  1055. def cancel_callback(self, event=None):
  1056. try:
  1057. if self.text.compare("sel.first", "!=", "sel.last"):
  1058. return # Active selection -- always use default binding
  1059. except:
  1060. pass
  1061. if not (self.executing or self.reading):
  1062. self.resetoutput()
  1063. self.interp.write("KeyboardInterrupt\n")
  1064. self.showprompt()
  1065. return "break"
  1066. self.endoffile = False
  1067. self.canceled = True
  1068. if (self.executing and self.interp.rpcclt):
  1069. if self.interp.getdebugger():
  1070. self.interp.restart_subprocess()
  1071. else:
  1072. self.interp.interrupt_subprocess()
  1073. if self.reading:
  1074. self.top.quit() # exit the nested mainloop() in readline()
  1075. return "break"
  1076. def eof_callback(self, event):
  1077. if self.executing and not self.reading:
  1078. return # Let the default binding (delete next char) take over
  1079. if not (self.text.compare("iomark", "==", "insert") and
  1080. self.text.compare("insert", "==", "end-1c")):
  1081. return # Let the default binding (delete next char) take over
  1082. if not self.executing:
  1083. self.resetoutput()
  1084. self.close()
  1085. else:
  1086. self.canceled = False
  1087. self.endoffile = True
  1088. self.top.quit()
  1089. return "break"
  1090. def linefeed_callback(self, event):
  1091. # Insert a linefeed without entering anything (still autoindented)
  1092. if self.reading:
  1093. self.text.insert("insert", "\n")
  1094. self.text.see("insert")
  1095. else:
  1096. self.newline_and_indent_event(event)
  1097. return "break"
  1098. def enter_callback(self, event):
  1099. if self.executing and not self.reading:
  1100. return # Let the default binding (insert '\n') take over
  1101. # If some text is selected, recall the selection
  1102. # (but only if this before the I/O mark)
  1103. try:
  1104. sel = self.text.get("sel.first", "sel.last")
  1105. if sel:
  1106. if self.text.compare("sel.last", "<=", "iomark"):
  1107. self.recall(sel, event)
  1108. return "break"
  1109. except:
  1110. pass
  1111. # If we're strictly before the line containing iomark, recall
  1112. # the current line, less a leading prompt, less leading or
  1113. # trailing whitespace
  1114. if self.text.compare("insert", "<", "iomark linestart"):
  1115. # Check if there's a relevant stdin range -- if so, use it.
  1116. # Note: "stdin" blocks may include several successive statements,
  1117. # so look for "console" tags on the newline before each statement
  1118. # (and possibly on prompts).
  1119. prev = self.text.tag_prevrange("stdin", "insert")
  1120. if (
  1121. prev and
  1122. self.text.compare("insert", "<", prev[1]) and
  1123. # The following is needed to handle empty statements.
  1124. "console" not in self.text.tag_names("insert")
  1125. ):
  1126. prev_cons = self.text.tag_prevrange("console", "insert")
  1127. if prev_cons and self.text.compare(prev_cons[1], ">=", prev[0]):
  1128. prev = (prev_cons[1], prev[1])
  1129. next_cons = self.text.tag_nextrange("console", "insert")
  1130. if next_cons and self.text.compare(next_cons[0], "<", prev[1]):
  1131. prev = (prev[0], self.text.index(next_cons[0] + "+1c"))
  1132. self.recall(self.text.get(prev[0], prev[1]), event)
  1133. return "break"
  1134. next = self.text.tag_nextrange("stdin", "insert")
  1135. if next and self.text.compare("insert lineend", ">=", next[0]):
  1136. next_cons = self.text.tag_nextrange("console", "insert lineend")
  1137. if next_cons and self.text.compare(next_cons[0], "<", next[1]):
  1138. next = (next[0], self.text.index(next_cons[0] + "+1c"))
  1139. self.recall(self.text.get(next[0], next[1]), event)
  1140. return "break"
  1141. # No stdin mark -- just get the current line, less any prompt
  1142. indices = self.text.tag_nextrange("console", "insert linestart")
  1143. if indices and \
  1144. self.text.compare(indices[0], "<=", "insert linestart"):
  1145. self.recall(self.text.get(indices[1], "insert lineend"), event)
  1146. else:
  1147. self.recall(self.text.get("insert linestart", "insert lineend"), event)
  1148. return "break"
  1149. # If we're between the beginning of the line and the iomark, i.e.
  1150. # in the prompt area, move to the end of the prompt
  1151. if self.text.compare("insert", "<", "iomark"):
  1152. self.text.mark_set("insert", "iomark")
  1153. # If we're in the current input and there's only whitespace
  1154. # beyond the cursor, erase that whitespace first
  1155. s = self.text.get("insert", "end-1c")
  1156. if s and not s.strip():
  1157. self.text.delete("insert", "end-1c")
  1158. # If we're in the current input before its last line,
  1159. # insert a newline right at the insert point
  1160. if self.text.compare("insert", "<", "end-1c linestart"):
  1161. self.newline_and_indent_event(event)
  1162. return "break"
  1163. # We're in the last line; append a newline and submit it
  1164. self.text.mark_set("insert", "end-1c")
  1165. if self.reading:
  1166. self.text.insert("insert", "\n")
  1167. self.text.see("insert")
  1168. else:
  1169. self.newline_and_indent_event(event)
  1170. self.text.update_idletasks()
  1171. if self.reading:
  1172. self.top.quit() # Break out of recursive mainloop()
  1173. else:
  1174. self.runit()
  1175. return "break"
  1176. def recall(self, s, event):
  1177. # remove leading and trailing empty or whitespace lines
  1178. s = re.sub(r'^\s*\n', '', s)
  1179. s = re.sub(r'\n\s*$', '', s)
  1180. lines = s.split('\n')
  1181. self.text.undo_block_start()
  1182. try:
  1183. self.text.tag_remove("sel", "1.0", "end")
  1184. self.text.mark_set("insert", "end-1c")
  1185. prefix = self.text.get("insert linestart", "insert")
  1186. if prefix.rstrip().endswith(':'):
  1187. self.newline_and_indent_event(event)
  1188. prefix = self.text.get("insert linestart", "insert")
  1189. self.text.insert("insert", lines[0].strip(),
  1190. self.user_input_insert_tags)
  1191. if len(lines) > 1:
  1192. orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
  1193. new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
  1194. for line in lines[1:]:
  1195. if line.startswith(orig_base_indent):
  1196. # replace orig base indentation with new indentation
  1197. line = new_base_indent + line[len(orig_base_indent):]
  1198. self.text.insert('insert', '\n' + line.rstrip(),
  1199. self.user_input_insert_tags)
  1200. finally:
  1201. self.text.see("insert")
  1202. self.text.undo_block_stop()
  1203. _last_newline_re = re.compile(r"[ \t]*(\n[ \t]*)?\Z")
  1204. def runit(self):
  1205. index_before = self.text.index("end-2c")
  1206. line = self.text.get("iomark", "end-1c")
  1207. # Strip off last newline and surrounding whitespace.
  1208. # (To allow you to hit return twice to end a statement.)
  1209. line = self._last_newline_re.sub("", line)
  1210. input_is_complete = self.interp.runsource(line)
  1211. if not input_is_complete:
  1212. if self.text.get(index_before) == '\n':
  1213. self.text.tag_remove(self.user_input_insert_tags, index_before)
  1214. self.shell_sidebar.update_sidebar()
  1215. def open_stack_viewer(self, event=None):
  1216. if self.interp.rpcclt:
  1217. return self.interp.remote_stack_viewer()
  1218. try:
  1219. sys.last_traceback
  1220. except:
  1221. messagebox.showerror("No stack trace",
  1222. "There is no stack trace yet.\n"
  1223. "(sys.last_traceback is not defined)",
  1224. parent=self.text)
  1225. return
  1226. from idlelib.stackviewer import StackBrowser
  1227. StackBrowser(self.root, self.flist)
  1228. def view_restart_mark(self, event=None):
  1229. self.text.see("iomark")
  1230. self.text.see("restart")
  1231. def restart_shell(self, event=None):
  1232. "Callback for Run/Restart Shell Cntl-F6"
  1233. self.interp.restart_subprocess(with_cwd=True)
  1234. def showprompt(self):
  1235. self.resetoutput()
  1236. prompt = self.prompt
  1237. if self.sys_ps1 and prompt.endswith(self.sys_ps1):
  1238. prompt = prompt[:-len(self.sys_ps1)]
  1239. self.text.tag_add("console", "iomark-1c")
  1240. self.console.write(prompt)
  1241. self.shell_sidebar.update_sidebar()
  1242. self.text.mark_set("insert", "end-1c")
  1243. self.set_line_and_column()
  1244. self.io.reset_undo()
  1245. def show_warning(self, msg):
  1246. width = self.interp.tkconsole.width
  1247. wrapper = TextWrapper(width=width, tabsize=8, expand_tabs=True)
  1248. wrapped_msg = '\n'.join(wrapper.wrap(msg))
  1249. if not wrapped_msg.endswith('\n'):
  1250. wrapped_msg += '\n'
  1251. self.per.bottom.insert("iomark linestart", wrapped_msg, "stderr")
  1252. def resetoutput(self):
  1253. source = self.text.get("iomark", "end-1c")
  1254. if self.history:
  1255. self.history.store(source)
  1256. if self.text.get("end-2c") != "\n":
  1257. self.text.insert("end-1c", "\n")
  1258. self.text.mark_set("iomark", "end-1c")
  1259. self.set_line_and_column()
  1260. self.ctip.remove_calltip_window()
  1261. def write(self, s, tags=()):
  1262. try:
  1263. self.text.mark_gravity("iomark", "right")
  1264. count = OutputWindow.write(self, s, tags, "iomark")
  1265. self.text.mark_gravity("iomark", "left")
  1266. except:
  1267. raise ###pass # ### 11Aug07 KBK if we are expecting exceptions
  1268. # let's find out what they are and be specific.
  1269. if self.canceled:
  1270. self.canceled = False
  1271. if not use_subprocess:
  1272. raise KeyboardInterrupt
  1273. return count
  1274. def rmenu_check_cut(self):
  1275. try:
  1276. if self.text.compare('sel.first', '<', 'iomark'):
  1277. return 'disabled'
  1278. except TclError: # no selection, so the index 'sel.first' doesn't exist
  1279. return 'disabled'
  1280. return super().rmenu_check_cut()
  1281. def rmenu_check_paste(self):
  1282. if self.text.compare('insert','<','iomark'):
  1283. return 'disabled'
  1284. return super().rmenu_check_paste()
  1285. def squeeze_current_text_event(self, event=None):
  1286. self.squeezer.squeeze_current_text()
  1287. self.shell_sidebar.update_sidebar()
  1288. def on_squeezed_expand(self, index, text, tags):
  1289. self.shell_sidebar.update_sidebar()
  1290. def fix_x11_paste(root):
  1291. "Make paste replace selection on x11. See issue #5124."
  1292. if root._windowingsystem == 'x11':
  1293. for cls in 'Text', 'Entry', 'Spinbox':
  1294. root.bind_class(
  1295. cls,
  1296. '<<Paste>>',
  1297. 'catch {%W delete sel.first sel.last}\n' +
  1298. root.bind_class(cls, '<<Paste>>'))
  1299. usage_msg = """\
  1300. USAGE: idle [-deins] [-t title] [file]*
  1301. idle [-dns] [-t title] (-c cmd | -r file) [arg]*
  1302. idle [-dns] [-t title] - [arg]*
  1303. -h print this help message and exit
  1304. -n run IDLE without a subprocess (DEPRECATED,
  1305. see Help/IDLE Help for details)
  1306. The following options will override the IDLE 'settings' configuration:
  1307. -e open an edit window
  1308. -i open a shell window
  1309. The following options imply -i and will open a shell:
  1310. -c cmd run the command in a shell, or
  1311. -r file run script from file
  1312. -d enable the debugger
  1313. -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else
  1314. -t title set title of shell window
  1315. A default edit window will be bypassed when -c, -r, or - are used.
  1316. [arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
  1317. Examples:
  1318. idle
  1319. Open an edit window or shell depending on IDLE's configuration.
  1320. idle foo.py foobar.py
  1321. Edit the files, also open a shell if configured to start with shell.
  1322. idle -est "Baz" foo.py
  1323. Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
  1324. window with the title "Baz".
  1325. idle -c "import sys; print(sys.argv)" "foo"
  1326. Open a shell window and run the command, passing "-c" in sys.argv[0]
  1327. and "foo" in sys.argv[1].
  1328. idle -d -s -r foo.py "Hello World"
  1329. Open a shell window, run a startup script, enable the debugger, and
  1330. run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
  1331. sys.argv[1].
  1332. echo "import sys; print(sys.argv)" | idle - "foobar"
  1333. Open a shell window, run the script piped in, passing '' in sys.argv[0]
  1334. and "foobar" in sys.argv[1].
  1335. """
  1336. def main():
  1337. import getopt
  1338. from platform import system
  1339. from idlelib import testing # bool value
  1340. from idlelib import macosx
  1341. global flist, root, use_subprocess
  1342. capture_warnings(True)
  1343. use_subprocess = True
  1344. enable_shell = False
  1345. enable_edit = False
  1346. debug = False
  1347. cmd = None
  1348. script = None
  1349. startup = False
  1350. try:
  1351. opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
  1352. except getopt.error as msg:
  1353. print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr)
  1354. sys.exit(2)
  1355. for o, a in opts:
  1356. if o == '-c':
  1357. cmd = a
  1358. enable_shell = True
  1359. if o == '-d':
  1360. debug = True
  1361. enable_shell = True
  1362. if o == '-e':
  1363. enable_edit = True
  1364. if o == '-h':
  1365. sys.stdout.write(usage_msg)
  1366. sys.exit()
  1367. if o == '-i':
  1368. enable_shell = True
  1369. if o == '-n':
  1370. print(" Warning: running IDLE without a subprocess is deprecated.",
  1371. file=sys.stderr)
  1372. use_subprocess = False
  1373. if o == '-r':
  1374. script = a
  1375. if os.path.isfile(script):
  1376. pass
  1377. else:
  1378. print("No script file: ", script)
  1379. sys.exit()
  1380. enable_shell = True
  1381. if o == '-s':
  1382. startup = True
  1383. enable_shell = True
  1384. if o == '-t':
  1385. PyShell.shell_title = a
  1386. enable_shell = True
  1387. if args and args[0] == '-':
  1388. cmd = sys.stdin.read()
  1389. enable_shell = True
  1390. # process sys.argv and sys.path:
  1391. for i in range(len(sys.path)):
  1392. sys.path[i] = os.path.abspath(sys.path[i])
  1393. if args and args[0] == '-':
  1394. sys.argv = [''] + args[1:]
  1395. elif cmd:
  1396. sys.argv = ['-c'] + args
  1397. elif script:
  1398. sys.argv = [script] + args
  1399. elif args:
  1400. enable_edit = True
  1401. pathx = []
  1402. for filename in args:
  1403. pathx.append(os.path.dirname(filename))
  1404. for dir in pathx:
  1405. dir = os.path.abspath(dir)
  1406. if not dir in sys.path:
  1407. sys.path.insert(0, dir)
  1408. else:
  1409. dir = os.getcwd()
  1410. if dir not in sys.path:
  1411. sys.path.insert(0, dir)
  1412. # check the IDLE settings configuration (but command line overrides)
  1413. edit_start = idleConf.GetOption('main', 'General',
  1414. 'editor-on-startup', type='bool')
  1415. enable_edit = enable_edit or edit_start
  1416. enable_shell = enable_shell or not enable_edit
  1417. # Setup root. Don't break user code run in IDLE process.
  1418. # Don't change environment when testing.
  1419. if use_subprocess and not testing:
  1420. NoDefaultRoot()
  1421. root = Tk(className="Idle")
  1422. root.withdraw()
  1423. from idlelib.run import fix_scaling
  1424. fix_scaling(root)
  1425. # set application icon
  1426. icondir = os.path.join(os.path.dirname(__file__), 'Icons')
  1427. if system() == 'Windows':
  1428. iconfile = os.path.join(icondir, 'idle.ico')
  1429. root.wm_iconbitmap(default=iconfile)
  1430. elif not macosx.isAquaTk():
  1431. if TkVersion >= 8.6:
  1432. ext = '.png'
  1433. sizes = (16, 32, 48, 256)
  1434. else:
  1435. ext = '.gif'
  1436. sizes = (16, 32, 48)
  1437. iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
  1438. for size in sizes]
  1439. icons = [PhotoImage(master=root, file=iconfile)
  1440. for iconfile in iconfiles]
  1441. root.wm_iconphoto(True, *icons)
  1442. # start editor and/or shell windows:
  1443. fixwordbreaks(root)
  1444. fix_x11_paste(root)
  1445. flist = PyShellFileList(root)
  1446. macosx.setupApp(root, flist)
  1447. if enable_edit:
  1448. if not (cmd or script):
  1449. for filename in args[:]:
  1450. if flist.open(filename) is None:
  1451. # filename is a directory actually, disconsider it
  1452. args.remove(filename)
  1453. if not args:
  1454. flist.new()
  1455. if enable_shell:
  1456. shell = flist.open_shell()
  1457. if not shell:
  1458. return # couldn't open shell
  1459. if macosx.isAquaTk() and flist.dict:
  1460. # On OSX: when the user has double-clicked on a file that causes
  1461. # IDLE to be launched the shell window will open just in front of
  1462. # the file she wants to see. Lower the interpreter window when
  1463. # there are open files.
  1464. shell.top.lower()
  1465. else:
  1466. shell = flist.pyshell
  1467. # Handle remaining options. If any of these are set, enable_shell
  1468. # was set also, so shell must be true to reach here.
  1469. if debug:
  1470. shell.open_debugger()
  1471. if startup:
  1472. filename = os.environ.get("IDLESTARTUP") or \
  1473. os.environ.get("PYTHONSTARTUP")
  1474. if filename and os.path.isfile(filename):
  1475. shell.interp.execfile(filename)
  1476. if cmd or script:
  1477. shell.interp.runcommand("""if 1:
  1478. import sys as _sys
  1479. _sys.argv = %r
  1480. del _sys
  1481. \n""" % (sys.argv,))
  1482. if cmd:
  1483. shell.interp.execsource(cmd)
  1484. elif script:
  1485. shell.interp.prepend_syspath(script)
  1486. shell.interp.execfile(script)
  1487. elif shell:
  1488. # If there is a shell window and no cmd or script in progress,
  1489. # check for problematic issues and print warning message(s) in
  1490. # the IDLE shell window; this is less intrusive than always
  1491. # opening a separate window.
  1492. # Warn if using a problematic OS X Tk version.
  1493. tkversionwarning = macosx.tkVersionWarning(root)
  1494. if tkversionwarning:
  1495. shell.show_warning(tkversionwarning)
  1496. # Warn if the "Prefer tabs when opening documents" system
  1497. # preference is set to "Always".
  1498. prefer_tabs_preference_warning = macosx.preferTabsPreferenceWarning()
  1499. if prefer_tabs_preference_warning:
  1500. shell.show_warning(prefer_tabs_preference_warning)
  1501. while flist.inversedict: # keep IDLE running while files are open.
  1502. root.mainloop()
  1503. root.destroy()
  1504. capture_warnings(False)
  1505. if __name__ == "__main__":
  1506. main()
  1507. capture_warnings(False) # Make sure turned off; see issue 18081