PyShell.py 50.3 KB
Newer Older
1
#! /usr/bin/env python3
David Scherer's avatar
David Scherer committed
2 3

import os
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
4
import os.path
David Scherer's avatar
David Scherer committed
5 6 7
import sys
import getopt
import re
Chui Tey's avatar
Chui Tey committed
8 9
import socket
import time
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
10
import threading
Chui Tey's avatar
Chui Tey committed
11
import traceback
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
12
import types
David Scherer's avatar
David Scherer committed
13 14 15 16

import linecache
from code import InteractiveInterpreter

17
try:
18
    from tkinter import *
19
except ImportError:
20
    print("** IDLE can't import Tkinter.  " \
21
          "Your Python may not be configured for Tk. **", file=sys.__stderr__)
22
    sys.exit(1)
23
import tkinter.messagebox as tkMessageBox
David Scherer's avatar
David Scherer committed
24

25 26 27 28 29 30 31 32 33 34 35
from idlelib.EditorWindow import EditorWindow, fixwordbreaks
from idlelib.FileList import FileList
from idlelib.ColorDelegator import ColorDelegator
from idlelib.UndoDelegator import UndoDelegator
from idlelib.OutputWindow import OutputWindow
from idlelib.configHandler import idleConf
from idlelib import idlever
from idlelib import rpc
from idlelib import Debugger
from idlelib import RemoteDebugger
from idlelib import macosxSupport
Chui Tey's avatar
Chui Tey committed
36

37 38
HOST = '127.0.0.1' # python execution server on localhost loopback
PORT = 0  # someday pass in host, port for remote debug capability
39

40 41 42 43 44
try:
    from signal import SIGTERM
except ImportError:
    SIGTERM = 15

45 46 47 48 49 50
# Override warnings module to write to warning_stream.  Initialize to send IDLE
# internal warnings to the console.  ScriptBinding.check_syntax() will
# temporarily redirect the stream to the shell window to display warnings when
# checking user's code.
global warning_stream
warning_stream = sys.__stderr__
Chui Tey's avatar
Chui Tey committed
51 52 53 54 55
try:
    import warnings
except ImportError:
    pass
else:
Benjamin Peterson's avatar
Benjamin Peterson committed
56 57
    def idle_showwarning(message, category, filename, lineno,
                         file=None, line=None):
58 59
        if file is None:
            file = warning_stream
60
        try:
61
            file.write(warnings.formatwarning(message, category, filename,
62
                                              lineno, line=line))
63 64
        except IOError:
            pass  ## file (probably __stderr__) is invalid, warning dropped.
Chui Tey's avatar
Chui Tey committed
65
    warnings.showwarning = idle_showwarning
66
    def idle_formatwarning(message, category, filename, lineno, line=None):
67 68 69
        """Format warnings the IDLE way"""
        s = "\nWarning (from warnings module):\n"
        s += '  File \"%s\", line %s\n' % (filename, lineno)
70 71 72
        if line is None:
            line = linecache.getline(filename, lineno)
        line = line.strip()
73 74 75 76 77
        if line:
            s += "    %s\n" % line
        s += "%s: %s\n>>> " % (category.__name__, message)
        return s
    warnings.formatwarning = idle_formatwarning
Chui Tey's avatar
Chui Tey committed
78

79 80
def extended_linecache_checkcache(filename=None,
                                  orig_checkcache=linecache.checkcache):
81 82
    """Extend linecache.checkcache to preserve the <pyshell#...> entries

83 84
    Rather than repeating the linecache code, patch it to save the
    <pyshell#...> entries, call the original linecache.checkcache()
85
    (skipping them), and then restore the saved entries.
86 87 88

    orig_checkcache is bound at definition time to the original
    method, allowing it to be patched.
89
    """
David Scherer's avatar
David Scherer committed
90 91
    cache = linecache.cache
    save = {}
92 93 94 95
    for key in list(cache):
        if key[:1] + key[-1:] == '<>':
            save[key] = cache.pop(key)
    orig_checkcache(filename)
David Scherer's avatar
David Scherer committed
96
    cache.update(save)
97

98 99
# Patch linecache.checkcache():
linecache.checkcache = extended_linecache_checkcache
David Scherer's avatar
David Scherer committed
100

101

David Scherer's avatar
David Scherer committed
102
class PyShellEditorWindow(EditorWindow):
103
    "Regular text edit window in IDLE, supports breakpoints"
104

David Scherer's avatar
David Scherer committed
105
    def __init__(self, *args):
106
        self.breakpoints = []
107
        EditorWindow.__init__(self, *args)
David Scherer's avatar
David Scherer committed
108
        self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
109
        self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
David Scherer's avatar
David Scherer committed
110 111
        self.text.bind("<<open-python-shell>>", self.flist.open_shell)

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
112 113
        self.breakpointPath = os.path.join(idleConf.GetUserCfgDir(),
                                           'breakpoints.lst')
114 115
        # whenever a file is changed, restore breakpoints
        if self.io.filename: self.restore_file_breaks()
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
116 117
        def filename_changed_hook(old_hook=self.io.filename_change_hook,
                                  self=self):
118 119 120 121
            self.restore_file_breaks()
            old_hook()
        self.io.set_filename_change_hook(filename_changed_hook)

122 123
    rmenu_specs = [("Set Breakpoint", "<<set-breakpoint-here>>"),
                   ("Clear Breakpoint", "<<clear-breakpoint-here>>")]
David Scherer's avatar
David Scherer committed
124

125
    def set_breakpoint(self, lineno):
126 127
        text = self.text
        filename = self.io.filename
128
        text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
129 130
        try:
            i = self.breakpoints.index(lineno)
131
        except ValueError:  # only add if missing, i.e. do once
132 133 134 135 136 137
            self.breakpoints.append(lineno)
        try:    # update the subprocess debugger
            debug = self.flist.pyshell.interp.debugger
            debug.set_breakpoint_here(filename, lineno)
        except: # but debugger may not be active right now....
            pass
David Scherer's avatar
David Scherer committed
138

139 140 141 142 143 144 145 146 147
    def set_breakpoint_here(self, event=None):
        text = self.text
        filename = self.io.filename
        if not filename:
            text.bell()
            return
        lineno = int(float(text.index("insert")))
        self.set_breakpoint(lineno)

148
    def clear_breakpoint_here(self, event=None):
149 150 151 152
        text = self.text
        filename = self.io.filename
        if not filename:
            text.bell()
153
            return
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        lineno = int(float(text.index("insert")))
        try:
            self.breakpoints.remove(lineno)
        except:
            pass
        text.tag_remove("BREAK", "insert linestart",\
                        "insert lineend +1char")
        try:
            debug = self.flist.pyshell.interp.debugger
            debug.clear_breakpoint_here(filename, lineno)
        except:
            pass

    def clear_file_breaks(self):
        if self.breakpoints:
            text = self.text
            filename = self.io.filename
            if not filename:
                text.bell()
                return
            self.breakpoints = []
            text.tag_remove("BREAK", "1.0", END)
            try:
                debug = self.flist.pyshell.interp.debugger
                debug.clear_file_breaks(filename)
            except:
                pass

182
    def store_file_breaks(self):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
183 184 185 186 187 188
        "Save breakpoints when file is saved"
        # XXX 13 Dec 2002 KBK Currently the file must be saved before it can
        #     be run.  The breaks are saved at that time.  If we introduce
        #     a temporary file save feature the save breaks functionality
        #     needs to be re-verified, since the breaks at the time the
        #     temp file is created may differ from the breaks at the last
189 190 191 192
        #     permanent save of the file.  Currently, a break introduced
        #     after a save will be effective, but not persistent.
        #     This is necessary to keep the saved breaks synched with the
        #     saved file.
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206
        #
        #     Breakpoints are set as tagged ranges in the text.  Certain
        #     kinds of edits cause these ranges to be deleted: Inserting
        #     or deleting a line just before a breakpoint, and certain
        #     deletions prior to a breakpoint.  These issues need to be
        #     investigated and understood.  It's not clear if they are
        #     Tk issues or IDLE issues, or whether they can actually
        #     be fixed.  Since a modified file has to be saved before it is
        #     run, and since self.breakpoints (from which the subprocess
        #     debugger is loaded) is updated during the save, the visible
        #     breaks stay synched with the subprocess even if one of these
        #     unexpected breakpoint deletions occurs.
        breaks = self.breakpoints
        filename = self.io.filename
207
        try:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
208
            lines = open(self.breakpointPath,"r").readlines()
209
        except IOError:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
210 211
            lines = []
        new_file = open(self.breakpointPath,"w")
212
        for line in lines:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
213
            if not line.startswith(filename + '='):
214
                new_file.write(line)
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
215 216 217 218
        self.update_breakpoints()
        breaks = self.breakpoints
        if breaks:
            new_file.write(filename + '=' + str(breaks) + '\n')
219 220 221 222
        new_file.close()

    def restore_file_breaks(self):
        self.text.update()   # this enables setting "BREAK" tags to be visible
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
223 224 225
        filename = self.io.filename
        if filename is None:
            return
226
        if os.path.isfile(self.breakpointPath):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
227
            lines = open(self.breakpointPath,"r").readlines()
228
            for line in lines:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
229
                if line.startswith(filename + '='):
230
                    breakpoint_linenumbers = eval(line[len(filename)+1:])
231 232
                    for breakpoint_linenumber in breakpoint_linenumbers:
                        self.set_breakpoint(breakpoint_linenumber)
233

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
234 235
    def update_breakpoints(self):
        "Retrieves all the breakpoints in the current window"
236
        text = self.text
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250
        ranges = text.tag_ranges("BREAK")
        linenumber_list = self.ranges_to_linenumbers(ranges)
        self.breakpoints = linenumber_list

    def ranges_to_linenumbers(self, ranges):
        lines = []
        for index in range(0, len(ranges), 2):
            lineno = int(float(ranges[index]))
            end = int(float(ranges[index+1]))
            while lineno < end:
                lines.append(lineno)
                lineno += 1
        return lines

251
# XXX 13 Dec 2002 KBK Not used currently
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
252 253 254 255 256
#    def saved_change_hook(self):
#        "Extend base method - clear breaks if module is modified"
#        if not self.get_saved():
#            self.clear_file_breaks()
#        EditorWindow.saved_change_hook(self)
257 258 259 260 261

    def _close(self):
        "Extend base method - clear breaks when module is closed"
        self.clear_file_breaks()
        EditorWindow._close(self)
262

David Scherer's avatar
David Scherer committed
263 264

class PyShellFileList(FileList):
265
    "Extend base class: IDLE supports a shell and breakpoints"
David Scherer's avatar
David Scherer committed
266

267 268
    # override FileList's class variable, instances return PyShellEditorWindow
    # instead of EditorWindow when new edit windows are created.
David Scherer's avatar
David Scherer committed
269 270 271 272 273 274
    EditorWindow = PyShellEditorWindow

    pyshell = None

    def open_shell(self, event=None):
        if self.pyshell:
275
            self.pyshell.top.wakeup()
David Scherer's avatar
David Scherer committed
276 277
        else:
            self.pyshell = PyShell(self)
278 279 280
            if self.pyshell:
                if not self.pyshell.begin():
                    return None
David Scherer's avatar
David Scherer committed
281 282 283 284
        return self.pyshell


class ModifiedColorDelegator(ColorDelegator):
285
    "Extend base class: colorizer for the shell window itself"
286

287 288 289
    def __init__(self):
        ColorDelegator.__init__(self)
        self.LoadTagDefs()
David Scherer's avatar
David Scherer committed
290 291 292 293 294

    def recolorize_main(self):
        self.tag_remove("TODO", "1.0", "iomark")
        self.tag_add("SYNC", "1.0", "iomark")
        ColorDelegator.recolorize_main(self)
295

296 297 298 299 300 301 302 303 304
    def LoadTagDefs(self):
        ColorDelegator.LoadTagDefs(self)
        theme = idleConf.GetOption('main','Theme','name')
        self.tagdefs.update({
            "stdin": {'background':None,'foreground':None},
            "stdout": idleConf.GetHighlight(theme, "stdout"),
            "stderr": idleConf.GetHighlight(theme, "stderr"),
            "console": idleConf.GetHighlight(theme, "console"),
        })
David Scherer's avatar
David Scherer committed
305 306

class ModifiedUndoDelegator(UndoDelegator):
307
    "Extend base class: forbid insert/delete before the I/O mark"
David Scherer's avatar
David Scherer committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

    def insert(self, index, chars, tags=None):
        try:
            if self.delegate.compare(index, "<", "iomark"):
                self.delegate.bell()
                return
        except TclError:
            pass
        UndoDelegator.insert(self, index, chars, tags)

    def delete(self, index1, index2=None):
        try:
            if self.delegate.compare(index1, "<", "iomark"):
                self.delegate.bell()
                return
        except TclError:
            pass
        UndoDelegator.delete(self, index1, index2)

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
327 328 329 330 331 332 333

class MyRPCClient(rpc.RPCClient):

    def handle_EOF(self):
        "Override the base class - just re-raise EOFError"
        raise EOFError

334

David Scherer's avatar
David Scherer committed
335 336 337 338 339 340
class ModifiedInterpreter(InteractiveInterpreter):

    def __init__(self, tkconsole):
        self.tkconsole = tkconsole
        locals = sys.modules['__main__'].__dict__
        InteractiveInterpreter.__init__(self, locals=locals)
341
        self.save_warnings_filters = None
342
        self.restarting = False
343 344
        self.subprocess_arglist = None
        self.port = PORT
David Scherer's avatar
David Scherer committed
345

Chui Tey's avatar
Chui Tey committed
346 347 348
    rpcclt = None
    rpcpid = None

349
    def spawn_subprocess(self):
350
        if self.subprocess_arglist is None:
351
            self.subprocess_arglist = self.build_subprocess_arglist()
352
        args = self.subprocess_arglist
353
        self.rpcpid = os.spawnv(os.P_NOWAIT, sys.executable, args)
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
354

355
    def build_subprocess_arglist(self):
356 357
        assert (self.port!=0), (
            "Socket should have been assigned a port number.")
358 359 360 361
        w = ['-W' + s for s in sys.warnoptions]
        # Maybe IDLE is installed and is being accessed via sys.path,
        # or maybe it's not installed and the idle.py script is being
        # run from the IDLE source directory.
362 363
        del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
                                       default=False, type='bool')
364
        if __name__ == 'idlelib.PyShell':
365
            command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
366
        else:
367
            command = "__import__('run').main(%r)" % (del_exitf,)
368 369 370 371 372 373
        if sys.platform[:3] == 'win' and ' ' in sys.executable:
            # handle embedded space in path by quoting the argument
            decorated_exec = '"%s"' % sys.executable
        else:
            decorated_exec = sys.executable
        return [decorated_exec] + w + ["-c", command, str(self.port)]
374

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
375
    def start_subprocess(self):
376 377
        addr = (HOST, self.port)
        # GUI makes several attempts to acquire socket, listens for connection
378
        for i in range(3):
Chui Tey's avatar
Chui Tey committed
379 380
            time.sleep(i)
            try:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
381
                self.rpcclt = MyRPCClient(addr)
Chui Tey's avatar
Chui Tey committed
382
                break
383
            except socket.error as err:
384
                pass
Chui Tey's avatar
Chui Tey committed
385
        else:
386 387
            self.display_port_binding_error()
            return None
388 389 390 391 392 393 394 395 396 397 398 399
        # if PORT was 0, system will assign an 'ephemeral' port. Find it out:
        self.port = self.rpcclt.listening_sock.getsockname()[1]
        # if PORT was not 0, probably working with a remote execution server
        if PORT != 0:
            # To allow reconnection within the 2MSL wait (cf. Stevens TCP
            # V1, 18.6),  set SO_REUSEADDR.  Note that this can be problematic
            # on Windows since the implementation allows two active sockets on
            # the same address!
            self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
                                           socket.SO_REUSEADDR, 1)
        self.spawn_subprocess()
        #time.sleep(20) # test to simulate GUI not accepting connection
400
        # Accept the connection from the Python execution server
401 402 403
        self.rpcclt.listening_sock.settimeout(10)
        try:
            self.rpcclt.accept()
404
        except socket.timeout as err:
405 406
            self.display_no_subprocess_error()
            return None
407 408 409
        self.rpcclt.register("stdin", self.tkconsole)
        self.rpcclt.register("stdout", self.tkconsole.stdout)
        self.rpcclt.register("stderr", self.tkconsole.stderr)
Chui Tey's avatar
Chui Tey committed
410
        self.rpcclt.register("flist", self.tkconsole.flist)
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
411
        self.rpcclt.register("linecache", linecache)
412
        self.rpcclt.register("interp", self)
413
        self.transfer_path()
Chui Tey's avatar
Chui Tey committed
414
        self.poll_subprocess()
415
        return self.rpcclt
Chui Tey's avatar
Chui Tey committed
416

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
417
    def restart_subprocess(self):
418
        if self.restarting:
419
            return self.rpcclt
420
        self.restarting = True
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
421
        # close only the subprocess debugger
422 423
        debug = self.getdebugger()
        if debug:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
424
            try:
425
                # Only close subprocess debugger, don't unregister gui_adap!
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
426 427 428 429
                RemoteDebugger.close_subprocess_debugger(self.rpcclt)
            except:
                pass
        # Kill subprocess, spawn a new one, accept connection.
430 431
        self.rpcclt.close()
        self.unix_terminate()
432
        console = self.tkconsole
433
        was_executing = console.executing
434
        console.executing = False
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
435
        self.spawn_subprocess()
436 437
        try:
            self.rpcclt.accept()
438
        except socket.timeout as err:
439 440
            self.display_no_subprocess_error()
            return None
441
        self.transfer_path()
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
442
        # annotate restart in shell window and mark it
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
443
        console.text.delete("iomark", "end-1c")
444 445 446
        if was_executing:
            console.write('\n')
            console.showprompt()
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
447 448 449 450
        halfbar = ((int(console.width) - 16) // 2) * '='
        console.write(halfbar + ' RESTART ' + halfbar)
        console.text.mark_set("restart", "end-1c")
        console.text.mark_gravity("restart", "left")
451
        console.showprompt()
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
452
        # restart subprocess debugger
453
        if debug:
454
            # Restarted debugger connects to current instance of debug GUI
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
455
            gui = RemoteDebugger.restart_subprocess_debugger(self.rpcclt)
456 457
            # reload remote debugger breakpoints for all PyShellEditWindows
            debug.load_breakpoints()
458
        self.restarting = False
459
        return self.rpcclt
460

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
461
    def __request_interrupt(self):
462
        self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
463 464

    def interrupt_subprocess(self):
465
        threading.Thread(target=self.__request_interrupt).start()
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
466

467
    def kill_subprocess(self):
468 469 470 471
        try:
            self.rpcclt.close()
        except AttributeError:  # no socket
            pass
472 473 474
        self.unix_terminate()
        self.tkconsole.executing = False
        self.rpcclt = None
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
475

476 477 478 479 480 481 482 483 484 485 486 487 488
    def unix_terminate(self):
        "UNIX: make sure subprocess is terminated and collect status"
        if hasattr(os, 'kill'):
            try:
                os.kill(self.rpcpid, SIGTERM)
            except OSError:
                # process already terminated:
                return
            else:
                try:
                    os.waitpid(self.rpcpid, 0)
                except OSError:
                    return
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
489

490 491 492
    def transfer_path(self):
        self.runcommand("""if 1:
        import sys as _sys
493
        _sys.path = %r
494
        del _sys
495
        \n""" % (sys.path,))
496

Chui Tey's avatar
Chui Tey committed
497 498 499 500 501 502
    active_seq = None

    def poll_subprocess(self):
        clt = self.rpcclt
        if clt is None:
            return
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
503
        try:
504 505 506 507
            response = clt.pollresponse(self.active_seq, wait=0.05)
        except (EOFError, IOError, KeyboardInterrupt):
            # lost connection or subprocess terminated itself, restart
            # [the KBI is from rpc.SocketIO.handle_EOF()]
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
508 509
            if self.tkconsole.closing:
                return
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
510 511
            response = None
            self.restart_subprocess()
Chui Tey's avatar
Chui Tey committed
512 513 514 515
        if response:
            self.tkconsole.resetoutput()
            self.active_seq = None
            how, what = response
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
516
            console = self.tkconsole.console
Chui Tey's avatar
Chui Tey committed
517 518
            if how == "OK":
                if what is not None:
519
                    print(repr(what), file=console)
Chui Tey's avatar
Chui Tey committed
520 521 522 523
            elif how == "EXCEPTION":
                if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
                    self.remote_stack_viewer()
            elif how == "ERROR":
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
524
                errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
525 526
                print(errmsg, what, file=sys.__stderr__)
                print(errmsg, what, file=console)
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
527
            # we received a response to the currently active seq number:
528 529 530 531
            try:
                self.tkconsole.endexecuting()
            except AttributeError:  # shell may have closed
                pass
532 533 534 535
        # Reschedule myself
        if not self.tkconsole.closing:
            self.tkconsole.text.after(self.tkconsole.pollinterval,
                                      self.poll_subprocess)
Chui Tey's avatar
Chui Tey committed
536

537 538 539 540 541 542 543 544
    debugger = None

    def setdebugger(self, debugger):
        self.debugger = debugger

    def getdebugger(self):
        return self.debugger

545 546 547 548 549 550
    def open_remote_stack_viewer(self):
        """Initiate the remote stack viewer from a separate thread.

        This method is called from the subprocess, and by returning from this
        method we allow the subprocess to unblock.  After a bit the shell
        requests the subprocess to open the remote stack viewer which returns a
551
        static object looking at the last exception.  It is queried through
552 553 554 555 556 557
        the RPC mechanism.

        """
        self.tkconsole.text.after(300, self.remote_stack_viewer)
        return

Chui Tey's avatar
Chui Tey committed
558
    def remote_stack_viewer(self):
559
        from idlelib import RemoteObjectBrowser
560
        oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
Chui Tey's avatar
Chui Tey committed
561 562 563 564
        if oid is None:
            self.tkconsole.root.bell()
            return
        item = RemoteObjectBrowser.StubObjectTreeItem(self.rpcclt, oid)
565
        from idlelib.TreeWidget import ScrolledCanvas, TreeNode
Chui Tey's avatar
Chui Tey committed
566
        top = Toplevel(self.tkconsole.root)
567 568 569
        theme = idleConf.GetOption('main','Theme','name')
        background = idleConf.GetHighlight(theme, 'normal')['background']
        sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
Chui Tey's avatar
Chui Tey committed
570 571 572 573 574
        sc.frame.pack(expand=1, fill="both")
        node = TreeNode(sc.canvas, None, item)
        node.expand()
        # XXX Should GC the remote tree when closing the window

David Scherer's avatar
David Scherer committed
575 576 577
    gid = 0

    def execsource(self, source):
578
        "Like runsource() but assumes complete exec source"
David Scherer's avatar
David Scherer committed
579 580 581 582
        filename = self.stuffsource(source)
        self.execfile(filename, source)

    def execfile(self, filename, source=None):
583
        "Execute an existing file"
David Scherer's avatar
David Scherer committed
584 585 586 587 588 589
        if source is None:
            source = open(filename, "r").read()
        try:
            code = compile(source, filename, "exec")
        except (OverflowError, SyntaxError):
            self.tkconsole.resetoutput()
590
            tkerr = self.tkconsole.stderr
591 592
            print('*** Error in script or command!\n', file=tkerr)
            print('Traceback (most recent call last):', file=tkerr)
David Scherer's avatar
David Scherer committed
593
            InteractiveInterpreter.showsyntaxerror(self, filename)
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
594
            self.tkconsole.showprompt()
David Scherer's avatar
David Scherer committed
595 596 597 598
        else:
            self.runcode(code)

    def runsource(self, source):
599
        "Extend base class method: Stuff the source in the line cache first"
David Scherer's avatar
David Scherer committed
600 601
        filename = self.stuffsource(source)
        self.more = 0
602 603
        self.save_warnings_filters = warnings.filters[:]
        warnings.filterwarnings(action="error", category=SyntaxWarning)
604 605 606
        # at the moment, InteractiveInterpreter expects str
        assert isinstance(source, str)
        #if isinstance(source, str):
607
        #    from idlelib import IOBinding
608 609 610 611 612 613
        #    try:
        #        source = source.encode(IOBinding.encoding)
        #    except UnicodeError:
        #        self.tkconsole.resetoutput()
        #        self.write("Unsupported characters in input\n")
        #        return
614
        try:
615 616
            # InteractiveInterpreter.runsource() calls its runcode() method,
            # which is overridden (see below)
617 618 619 620 621
            return InteractiveInterpreter.runsource(self, source, filename)
        finally:
            if self.save_warnings_filters is not None:
                warnings.filters[:] = self.save_warnings_filters
                self.save_warnings_filters = None
David Scherer's avatar
David Scherer committed
622 623

    def stuffsource(self, source):
624
        "Stuff source in the filename cache"
David Scherer's avatar
David Scherer committed
625 626
        filename = "<pyshell#%d>" % self.gid
        self.gid = self.gid + 1
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
627
        lines = source.split("\n")
David Scherer's avatar
David Scherer committed
628 629
        linecache.cache[filename] = len(source)+1, 0, lines, filename
        return filename
630

631 632 633
    def prepend_syspath(self, filename):
        "Prepend sys.path with file's directory if not already included"
        self.runcommand("""if 1:
634
            _filename = %r
635 636 637 638 639 640
            import sys as _sys
            from os.path import dirname as _dirname
            _dir = _dirname(_filename)
            if not _dir in _sys.path:
                _sys.path.insert(0, _dir)
            del _filename, _sys, _dirname, _dir
641
            \n""" % (filename,))
642

David Scherer's avatar
David Scherer committed
643
    def showsyntaxerror(self, filename=None):
644
        """Override Interactive Interpreter method: Use Colorizing
645 646 647 648 649

        Color the offending position instead of printing it and pointing at it
        with a caret.

        """
650 651 652
        tkconsole = self.tkconsole
        text = tkconsole.text
        text.tag_remove("ERROR", "1.0", "end")
David Scherer's avatar
David Scherer committed
653
        type, value, tb = sys.exc_info()
654 655 656 657 658 659 660
        msg = value.msg or "<no detail available>"
        lineno = value.lineno or 1
        offset = value.offset or 0
        if offset == 0:
            lineno += 1 #mark end of offending line
        if lineno == 1:
            pos = "iomark + %d chars" % (offset-1)
David Scherer's avatar
David Scherer committed
661
        else:
662 663 664 665 666 667
            pos = "iomark linestart + %d lines + %d chars" % \
                  (lineno-1, offset-1)
        tkconsole.colorize_syntax_error(text, pos)
        tkconsole.resetoutput()
        self.write("SyntaxError: %s\n" % msg)
        tkconsole.showprompt()
David Scherer's avatar
David Scherer committed
668 669

    def showtraceback(self):
670
        "Extend base class method to reset output properly"
David Scherer's avatar
David Scherer committed
671 672 673
        self.tkconsole.resetoutput()
        self.checklinecache()
        InteractiveInterpreter.showtraceback(self)
Chui Tey's avatar
Chui Tey committed
674 675
        if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
            self.tkconsole.open_stack_viewer()
David Scherer's avatar
David Scherer committed
676 677 678

    def checklinecache(self):
        c = linecache.cache
679
        for key in list(c.keys()):
David Scherer's avatar
David Scherer committed
680 681 682
            if key[:1] + key[-1:] != "<>":
                del c[key]

Chui Tey's avatar
Chui Tey committed
683
    def runcommand(self, code):
684
        "Run the code without invoking the debugger"
Chui Tey's avatar
Chui Tey committed
685 686
        # The code better not raise an exception!
        if self.tkconsole.executing:
687
            self.display_executing_dialog()
Chui Tey's avatar
Chui Tey committed
688 689
            return 0
        if self.rpcclt:
690
            self.rpcclt.remotequeue("exec", "runcode", (code,), {})
Chui Tey's avatar
Chui Tey committed
691
        else:
692
            exec(code, self.locals)
Chui Tey's avatar
Chui Tey committed
693 694
        return 1

David Scherer's avatar
David Scherer committed
695
    def runcode(self, code):
696
        "Override base class method"
Chui Tey's avatar
Chui Tey committed
697
        if self.tkconsole.executing:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
698
            self.interp.restart_subprocess()
Chui Tey's avatar
Chui Tey committed
699
        self.checklinecache()
700 701 702
        if self.save_warnings_filters is not None:
            warnings.filters[:] = self.save_warnings_filters
            self.save_warnings_filters = None
David Scherer's avatar
David Scherer committed
703 704
        debugger = self.debugger
        try:
705
            self.tkconsole.beginexecuting()
706 707 708 709 710 711 712 713 714 715 716 717 718 719
            if not debugger and self.rpcclt is not None:
                self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
                                                        (code,), {})
            elif debugger:
                debugger.run(code, self.locals)
            else:
                exec(code, self.locals)
        except SystemExit:
            if not self.tkconsole.closing:
                if tkMessageBox.askyesno(
                    "Exit?",
                    "Do you want to exit altogether?",
                    default="yes",
                    master=self.tkconsole.text):
720
                    raise
721
                else:
722
                    self.showtraceback()
723 724 725 726 727 728
            else:
                raise
        except:
            if use_subprocess:
                print("IDLE internal error in runcode()",
                      file=self.tkconsole.stderr)
David Scherer's avatar
David Scherer committed
729
                self.showtraceback()
730 731 732 733 734 735 736
                self.tkconsole.endexecuting()
            else:
                if self.tkconsole.canceled:
                    self.tkconsole.canceled = False
                    print("KeyboardInterrupt", file=self.tkconsole.stderr)
                else:
                    self.showtraceback()
737 738
        finally:
            if not use_subprocess:
739 740 741 742
                try:
                    self.tkconsole.endexecuting()
                except AttributeError:  # shell may have closed
                    pass
David Scherer's avatar
David Scherer committed
743 744

    def write(self, s):
745
        "Override base class method"
746
        self.tkconsole.stderr.write(s)
David Scherer's avatar
David Scherer committed
747

748 749 750
    def display_port_binding_error(self):
        tkMessageBox.showerror(
            "Port Binding Error",
751 752 753 754 755 756
            "IDLE can't bind to a TCP/IP port, which is necessary to "
            "communicate with its Python execution server.  This might be "
            "because no networking is installed on this computer.  "
            "Run IDLE with the -n command line switch to start without a "
            "subprocess and refer to Help/IDLE Help 'Running without a "
            "subprocess' for further details.",
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
            master=self.tkconsole.text)

    def display_no_subprocess_error(self):
        tkMessageBox.showerror(
            "Subprocess Startup Error",
            "IDLE's subprocess didn't make connection.  Either IDLE can't "
            "start a subprocess or personal firewall software is blocking "
            "the connection.",
            master=self.tkconsole.text)

    def display_executing_dialog(self):
        tkMessageBox.showerror(
            "Already executing",
            "The Python Shell window is already executing a command; "
            "please wait until it is finished.",
            master=self.tkconsole.text)


David Scherer's avatar
David Scherer committed
775 776 777 778 779 780 781 782
class PyShell(OutputWindow):

    shell_title = "Python Shell"

    # Override classes
    ColorDelegator = ModifiedColorDelegator
    UndoDelegator = ModifiedUndoDelegator

783
    # Override menus
784 785 786
    menu_specs = [
        ("file", "_File"),
        ("edit", "_Edit"),
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
787
        ("debug", "_Debug"),
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
788
        ("options", "_Options"),
789 790 791
        ("windows", "_Windows"),
        ("help", "_Help"),
    ]
David Scherer's avatar
David Scherer committed
792

793 794 795 796 797
    if macosxSupport.runningAsOSXApp():
        del menu_specs[-3]
        menu_specs[-2] = ("windows", "_Window")


David Scherer's avatar
David Scherer committed
798
    # New classes
799
    from idlelib.IdleHistory import History
David Scherer's avatar
David Scherer committed
800 801

    def __init__(self, flist=None):
802
        if use_subprocess:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
803 804
            ms = self.menu_specs
            if ms[2][0] != "shell":
805
                ms.insert(2, ("shell", "She_ll"))
David Scherer's avatar
David Scherer committed
806 807 808 809 810 811
        self.interp = ModifiedInterpreter(self)
        if flist is None:
            root = Tk()
            fixwordbreaks(root)
            root.withdraw()
            flist = PyShellFileList(root)
812
        #
David Scherer's avatar
David Scherer committed
813
        OutputWindow.__init__(self, flist, None, None)
814
        #
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
815 816 817 818 819
##        self.config(usetabs=1, indentwidth=8, context_use_ps1=1)
        self.usetabs = True
        # indentwidth must be 8 when using tabs.  See note in EditorWindow:
        self.indentwidth = 8
        self.context_use_ps1 = True
820
        #
David Scherer's avatar
David Scherer committed
821 822 823 824 825 826 827
        text = self.text
        text.configure(wrap="char")
        text.bind("<<newline-and-indent>>", self.enter_callback)
        text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
        text.bind("<<interrupt-execution>>", self.cancel_callback)
        text.bind("<<end-of-file>>", self.eof_callback)
        text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
828
        text.bind("<<toggle-debugger>>", self.toggle_debugger)
David Scherer's avatar
David Scherer committed
829
        text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
830 831
        self.color = color = self.ColorDelegator()
        self.per.insertfilter(color)
832 833 834
        if use_subprocess:
            text.bind("<<view-restart>>", self.view_restart_mark)
            text.bind("<<restart-shell>>", self.restart_shell)
835
        #
David Scherer's avatar
David Scherer committed
836 837 838
        self.save_stdout = sys.stdout
        self.save_stderr = sys.stderr
        self.save_stdin = sys.stdin
839
        from idlelib import IOBinding
840 841 842
        self.stdout = PseudoFile(self, "stdout", IOBinding.encoding)
        self.stderr = PseudoFile(self, "stderr", IOBinding.encoding)
        self.console = PseudoFile(self, "console", IOBinding.encoding)
Chui Tey's avatar
Chui Tey committed
843 844
        if not use_subprocess:
            sys.stdout = self.stdout
845
            sys.stderr = self.stderr
Chui Tey's avatar
Chui Tey committed
846
            sys.stdin = self
847 848 849 850 851 852 853 854
        try:
            # page help() text to shell.
            import pydoc # import must be done here to capture i/o rebinding.
            # XXX KBK 27Dec07 use a textView someday, but must work w/o subproc
            pydoc.pager = pydoc.plainpager
        except:
            sys.stderr = sys.__stderr__
            raise
855
        #
David Scherer's avatar
David Scherer committed
856
        self.history = self.History(self.text)
857
        #
858
        self.pollinterval = 50  # millisec
Chui Tey's avatar
Chui Tey committed
859

860 861 862
    def get_standard_extension_names(self):
        return idleConf.GetExtensions(shell_only=True)

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
863 864 865 866 867
    reading = False
    executing = False
    canceled = False
    endoffile = False
    closing = False
David Scherer's avatar
David Scherer committed
868

869
    def set_warning_stream(self, stream):
870 871
        global warning_stream
        warning_stream = stream
872 873 874 875

    def get_warning_stream(self):
        return warning_stream

David Scherer's avatar
David Scherer committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    def toggle_debugger(self, event=None):
        if self.executing:
            tkMessageBox.showerror("Don't debug now",
                "You can only toggle the debugger when idle",
                master=self.text)
            self.set_debugger_indicator()
            return "break"
        else:
            db = self.interp.getdebugger()
            if db:
                self.close_debugger()
            else:
                self.open_debugger()

    def set_debugger_indicator(self):
        db = self.interp.getdebugger()
        self.setvar("<<toggle-debugger>>", not not db)

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
894
    def toggle_jit_stack_viewer(self, event=None):
David Scherer's avatar
David Scherer committed
895 896 897 898 899 900 901
        pass # All we need is the variable

    def close_debugger(self):
        db = self.interp.getdebugger()
        if db:
            self.interp.setdebugger(None)
            db.close()
902 903
            if self.interp.rpcclt:
                RemoteDebugger.close_remote_debugger(self.interp.rpcclt)
David Scherer's avatar
David Scherer committed
904 905 906 907 908 909 910
            self.resetoutput()
            self.console.write("[DEBUG OFF]\n")
            sys.ps1 = ">>> "
            self.showprompt()
        self.set_debugger_indicator()

    def open_debugger(self):
Chui Tey's avatar
Chui Tey committed
911
        if self.interp.rpcclt:
912 913 914 915 916 917
            dbg_gui = RemoteDebugger.start_remote_debugger(self.interp.rpcclt,
                                                           self)
        else:
            dbg_gui = Debugger.Debugger(self)
        self.interp.setdebugger(dbg_gui)
        dbg_gui.load_breakpoints()
Chui Tey's avatar
Chui Tey committed
918 919 920 921
        sys.ps1 = "[DEBUG ON]\n>>> "
        self.showprompt()
        self.set_debugger_indicator()

David Scherer's avatar
David Scherer committed
922
    def beginexecuting(self):
923
        "Helper for ModifiedInterpreter"
David Scherer's avatar
David Scherer committed
924 925 926 927
        self.resetoutput()
        self.executing = 1

    def endexecuting(self):
928
        "Helper for ModifiedInterpreter"
David Scherer's avatar
David Scherer committed
929 930
        self.executing = 0
        self.canceled = 0
Chui Tey's avatar
Chui Tey committed
931
        self.showprompt()
David Scherer's avatar
David Scherer committed
932 933

    def close(self):
934
        "Extend EditorWindow.close()"
David Scherer's avatar
David Scherer committed
935
        if self.executing:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
936
            response = tkMessageBox.askokcancel(
David Scherer's avatar
David Scherer committed
937
                "Kill?",
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
938
                "The program is still running!\n Do you want to kill it?",
David Scherer's avatar
David Scherer committed
939
                default="ok",
940
                parent=self.text)
941
            if response is False:
David Scherer's avatar
David Scherer committed
942
                return "cancel"
943 944 945
        if self.reading:
            self.top.quit()
        self.canceled = True
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
946 947 948
        self.closing = True
        # Wait for poll_subprocess() rescheduling to stop
        self.text.after(2 * self.pollinterval, self.close2)
949 950 951

    def close2(self):
        return EditorWindow.close(self)
David Scherer's avatar
David Scherer committed
952 953

    def _close(self):
954
        "Extend EditorWindow._close(), shut down debugger and execution server"
David Scherer's avatar
David Scherer committed
955
        self.close_debugger()
956 957
        if use_subprocess:
            self.interp.kill_subprocess()
David Scherer's avatar
David Scherer committed
958 959 960 961 962 963 964 965 966
        # Restore std streams
        sys.stdout = self.save_stdout
        sys.stderr = self.save_stderr
        sys.stdin = self.save_stdin
        # Break cycles
        self.interp = None
        self.console = None
        self.flist.pyshell = None
        self.history = None
967
        EditorWindow._close(self)
David Scherer's avatar
David Scherer committed
968 969

    def ispythonsource(self, filename):
970
        "Override EditorWindow method: never remove the colorizer"
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
971
        return True
David Scherer's avatar
David Scherer committed
972 973 974 975

    def short_title(self):
        return self.shell_title

976
    COPYRIGHT = \
977
          'Type "copyright", "credits" or "license()" for more information.'
978

David Scherer's avatar
David Scherer committed
979
    def begin(self):
980
        self.text.mark_set("iomark", "insert")
David Scherer's avatar
David Scherer committed
981
        self.resetoutput()
982 983
        if use_subprocess:
            nosub = ''
984 985 986
            client = self.interp.start_subprocess()
            if not client:
                self.close()
987
                return False
988 989
        else:
            nosub = "==== No Subprocess ===="
990 991
        self.write("Python %s on %s\n%s\n%s" %
                   (sys.version, sys.platform, self.COPYRIGHT, nosub))
David Scherer's avatar
David Scherer committed
992
        self.showprompt()
993 994
        import tkinter
        tkinter._default_root = None # 03Jan04 KBK What's this?
995
        return True
David Scherer's avatar
David Scherer committed
996 997 998 999 1000

    def readline(self):
        save = self.reading
        try:
            self.reading = 1
1001
            self.top.mainloop()  # nested mainloop()
David Scherer's avatar
David Scherer committed
1002 1003 1004
        finally:
            self.reading = save
        line = self.text.get("iomark", "end-1c")
1005 1006
        if len(line) == 0:  # may be EOF if we quit our mainloop with Ctrl-C
            line = "\n"
David Scherer's avatar
David Scherer committed
1007 1008 1009
        self.resetoutput()
        if self.canceled:
            self.canceled = 0
1010 1011
            if not use_subprocess:
                raise KeyboardInterrupt
David Scherer's avatar
David Scherer committed
1012 1013
        if self.endoffile:
            self.endoffile = 0
1014
            line = ""
David Scherer's avatar
David Scherer committed
1015 1016 1017
        return line

    def isatty(self):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1018
        return True
David Scherer's avatar
David Scherer committed
1019

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1020
    def cancel_callback(self, event=None):
David Scherer's avatar
David Scherer committed
1021 1022 1023 1024 1025 1026 1027
        try:
            if self.text.compare("sel.first", "!=", "sel.last"):
                return # Active selection -- always use default binding
        except:
            pass
        if not (self.executing or self.reading):
            self.resetoutput()
1028
            self.interp.write("KeyboardInterrupt\n")
David Scherer's avatar
David Scherer committed
1029 1030 1031
            self.showprompt()
            return "break"
        self.endoffile = 0
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1032
        self.canceled = 1
1033
        if (self.executing and self.interp.rpcclt):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1034 1035 1036 1037
            if self.interp.getdebugger():
                self.interp.restart_subprocess()
            else:
                self.interp.interrupt_subprocess()
1038 1039
        if self.reading:
            self.top.quit()  # exit the nested mainloop() in readline()
David Scherer's avatar
David Scherer committed
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        return "break"

    def eof_callback(self, event):
        if self.executing and not self.reading:
            return # Let the default binding (delete next char) take over
        if not (self.text.compare("iomark", "==", "insert") and
                self.text.compare("insert", "==", "end-1c")):
            return # Let the default binding (delete next char) take over
        if not self.executing:
            self.resetoutput()
            self.close()
        else:
            self.canceled = 0
            self.endoffile = 1
            self.top.quit()
        return "break"

    def linefeed_callback(self, event):
        # Insert a linefeed without entering anything (still autoindented)
        if self.reading:
            self.text.insert("insert", "\n")
            self.text.see("insert")
        else:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1063
            self.newline_and_indent_event(event)
David Scherer's avatar
David Scherer committed
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        return "break"

    def enter_callback(self, event):
        if self.executing and not self.reading:
            return # Let the default binding (insert '\n') take over
        # If some text is selected, recall the selection
        # (but only if this before the I/O mark)
        try:
            sel = self.text.get("sel.first", "sel.last")
            if sel:
                if self.text.compare("sel.last", "<=", "iomark"):
1075
                    self.recall(sel, event)
David Scherer's avatar
David Scherer committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
                    return "break"
        except:
            pass
        # If we're strictly before the line containing iomark, recall
        # the current line, less a leading prompt, less leading or
        # trailing whitespace
        if self.text.compare("insert", "<", "iomark linestart"):
            # Check if there's a relevant stdin range -- if so, use it
            prev = self.text.tag_prevrange("stdin", "insert")
            if prev and self.text.compare("insert", "<", prev[1]):
1086
                self.recall(self.text.get(prev[0], prev[1]), event)
David Scherer's avatar
David Scherer committed
1087 1088 1089
                return "break"
            next = self.text.tag_nextrange("stdin", "insert")
            if next and self.text.compare("insert lineend", ">=", next[0]):
1090
                self.recall(self.text.get(next[0], next[1]), event)
David Scherer's avatar
David Scherer committed
1091
                return "break"
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1092
            # No stdin mark -- just get the current line, less any prompt
1093 1094 1095 1096 1097 1098
            indices = self.text.tag_nextrange("console", "insert linestart")
            if indices and \
               self.text.compare(indices[0], "<=", "insert linestart"):
                self.recall(self.text.get(indices[1], "insert lineend"), event)
            else:
                self.recall(self.text.get("insert linestart", "insert lineend"), event)
David Scherer's avatar
David Scherer committed
1099
            return "break"
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1100
        # If we're between the beginning of the line and the iomark, i.e.
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1101
        # in the prompt area, move to the end of the prompt
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1102
        if self.text.compare("insert", "<", "iomark"):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1103
            self.text.mark_set("insert", "iomark")
David Scherer's avatar
David Scherer committed
1104 1105 1106
        # If we're in the current input and there's only whitespace
        # beyond the cursor, erase that whitespace first
        s = self.text.get("insert", "end-1c")
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1107
        if s and not s.strip():
David Scherer's avatar
David Scherer committed
1108 1109 1110 1111
            self.text.delete("insert", "end-1c")
        # If we're in the current input before its last line,
        # insert a newline right at the insert point
        if self.text.compare("insert", "<", "end-1c linestart"):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1112
            self.newline_and_indent_event(event)
David Scherer's avatar
David Scherer committed
1113 1114 1115 1116 1117 1118 1119
            return "break"
        # We're in the last line; append a newline and submit it
        self.text.mark_set("insert", "end-1c")
        if self.reading:
            self.text.insert("insert", "\n")
            self.text.see("insert")
        else:
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1120
            self.newline_and_indent_event(event)
David Scherer's avatar
David Scherer committed
1121 1122 1123
        self.text.tag_add("stdin", "iomark", "end-1c")
        self.text.update_idletasks()
        if self.reading:
1124
            self.top.quit() # Break out of recursive mainloop()
David Scherer's avatar
David Scherer committed
1125 1126 1127 1128
        else:
            self.runit()
        return "break"

1129
    def recall(self, s, event):
1130 1131 1132 1133
        # remove leading and trailing empty or whitespace lines
        s = re.sub(r'^\s*\n', '' , s)
        s = re.sub(r'\n\s*$', '', s)
        lines = s.split('\n')
1134 1135 1136 1137
        self.text.undo_block_start()
        try:
            self.text.tag_remove("sel", "1.0", "end")
            self.text.mark_set("insert", "end-1c")
1138 1139
            prefix = self.text.get("insert linestart", "insert")
            if prefix.rstrip().endswith(':'):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1140
                self.newline_and_indent_event(event)
1141 1142
                prefix = self.text.get("insert linestart", "insert")
            self.text.insert("insert", lines[0].strip())
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1143
            if len(lines) > 1:
1144 1145
                orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
                new_base_indent  = re.search(r'^([ \t]*)', prefix).group(0)
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1146
                for line in lines[1:]:
1147 1148 1149 1150
                    if line.startswith(orig_base_indent):
                        # replace orig base indentation with new indentation
                        line = new_base_indent + line[len(orig_base_indent):]
                    self.text.insert('insert', '\n'+line.rstrip())
1151 1152 1153
        finally:
            self.text.see("insert")
            self.text.undo_block_stop()
David Scherer's avatar
David Scherer committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

    def runit(self):
        line = self.text.get("iomark", "end-1c")
        # Strip off last newline and surrounding whitespace.
        # (To allow you to hit return twice to end a statement.)
        i = len(line)
        while i > 0 and line[i-1] in " \t":
            i = i-1
        if i > 0 and line[i-1] == "\n":
            i = i-1
        while i > 0 and line[i-1] in " \t":
            i = i-1
        line = line[:i]
        more = self.interp.runsource(line)

    def open_stack_viewer(self, event=None):
Chui Tey's avatar
Chui Tey committed
1170 1171
        if self.interp.rpcclt:
            return self.interp.remote_stack_viewer()
David Scherer's avatar
David Scherer committed
1172 1173 1174 1175 1176 1177 1178 1179
        try:
            sys.last_traceback
        except:
            tkMessageBox.showerror("No stack trace",
                "There is no stack trace yet.\n"
                "(sys.last_traceback is not defined)",
                master=self.text)
            return
1180
        from idlelib.StackViewer import StackBrowser
David Scherer's avatar
David Scherer committed
1181 1182
        sv = StackBrowser(self.root, self.flist)

Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1183 1184 1185 1186 1187
    def view_restart_mark(self, event=None):
        self.text.see("iomark")
        self.text.see("restart")

    def restart_shell(self, event=None):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1188
        self.interp.restart_subprocess()
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1189

David Scherer's avatar
David Scherer committed
1190 1191 1192 1193 1194 1195 1196 1197
    def showprompt(self):
        self.resetoutput()
        try:
            s = str(sys.ps1)
        except:
            s = ""
        self.console.write(s)
        self.text.mark_set("insert", "end-1c")
Chui Tey's avatar
Chui Tey committed
1198
        self.set_line_and_column()
1199
        self.io.reset_undo()
David Scherer's avatar
David Scherer committed
1200 1201 1202 1203 1204 1205 1206 1207

    def resetoutput(self):
        source = self.text.get("iomark", "end-1c")
        if self.history:
            self.history.history_store(source)
        if self.text.get("end-2c") != "\n":
            self.text.insert("end-1c", "\n")
        self.text.mark_set("iomark", "end-1c")
Chui Tey's avatar
Chui Tey committed
1208
        self.set_line_and_column()
David Scherer's avatar
David Scherer committed
1209 1210

    def write(self, s, tags=()):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1211 1212 1213 1214 1215
        try:
            self.text.mark_gravity("iomark", "right")
            OutputWindow.write(self, s, tags, "iomark")
            self.text.mark_gravity("iomark", "left")
        except:
1216 1217
            raise ###pass  # ### 11Aug07 KBK if we are expecting exceptions
                           # let's find out what they are and be specific.
David Scherer's avatar
David Scherer committed
1218 1219
        if self.canceled:
            self.canceled = 0
1220 1221
            if not use_subprocess:
                raise KeyboardInterrupt
David Scherer's avatar
David Scherer committed
1222

1223
class PseudoFile(object):
David Scherer's avatar
David Scherer committed
1224

1225
    def __init__(self, shell, tags, encoding=None):
David Scherer's avatar
David Scherer committed
1226 1227
        self.shell = shell
        self.tags = tags
1228
        self.encoding = encoding
David Scherer's avatar
David Scherer committed
1229 1230 1231 1232

    def write(self, s):
        self.shell.write(s, self.tags)

1233 1234 1235
    def writelines(self, lines):
        for line in lines:
            self.write(line)
David Scherer's avatar
David Scherer committed
1236 1237 1238 1239 1240

    def flush(self):
        pass

    def isatty(self):
Kurt B. Kaiser's avatar
Kurt B. Kaiser committed
1241
        return True
David Scherer's avatar
David Scherer committed
1242

1243

David Scherer's avatar
David Scherer committed
1244 1245
usage_msg = """\

1246 1247 1248
USAGE: idle  [-deins] [-t title] [file]*
       idle  [-dns] [-t title] (-c cmd | -r file) [arg]*
       idle  [-dns] [-t title] - [arg]*
1249

1250
  -h         print this help message and exit
1251
  -n         run IDLE without a subprocess (see Help/IDLE Help for details)
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

The following options will override the IDLE 'settings' configuration:

  -e         open an edit window
  -i         open a shell window

The following options imply -i and will open a shell:

  -c cmd     run the command in a shell, or
  -r file    run script from file

  -d         enable the debugger
  -s         run $IDLESTARTUP or $PYTHONSTARTUP before anything else
  -t title   set title of shell window

A default edit window will be bypassed when -c, -r, or - are used.

[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].

Examples:
David Scherer's avatar
David Scherer committed
1272

1273 1274
idle
        Open an edit window or shell depending on IDLE's configuration.
1275

1276 1277 1278 1279 1280 1281 1282
idle foo.py foobar.py
        Edit the files, also open a shell if configured to start with shell.

idle -est "Baz" foo.py
        Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
        window with the title "Baz".

1283
idle -c "import sys; print(sys.argv)" "foo"
1284 1285 1286 1287 1288 1289 1290 1291
        Open a shell window and run the command, passing "-c" in sys.argv[0]
        and "foo" in sys.argv[1].

idle -d -s -r foo.py "Hello World"
        Open a shell window, run a startup script, enable the debugger, and
        run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
        sys.argv[1].

1292
echo "import sys; print(sys.argv)" | idle - "foobar"
1293 1294
        Open a shell window, run the script piped in, passing '' in sys.argv[0]
        and "foobar" in sys.argv[1].
David Scherer's avatar
David Scherer committed
1295 1296
"""

1297
def main():
1298 1299
    global flist, root, use_subprocess

1300
    use_subprocess = True
1301
    enable_shell = True
1302 1303
    enable_edit = False
    debug = False
1304 1305
    cmd = None
    script = None
1306
    startup = False
1307
    try:
1308
        opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
1309
    except getopt.error as msg:
1310 1311 1312 1313 1314 1315
        sys.stderr.write("Error: %s\n" % str(msg))
        sys.stderr.write(usage_msg)
        sys.exit(2)
    for o, a in opts:
        if o == '-c':
            cmd = a
1316
            enable_shell = True
1317
        if o == '-d':
1318 1319
            debug = True
            enable_shell = True
1320
        if o == '-e':
1321
            enable_edit = True
1322
            enable_shell = False
1323 1324 1325 1326 1327
        if o == '-h':
            sys.stdout.write(usage_msg)
            sys.exit()
        if o == '-i':
            enable_shell = True
1328 1329
        if o == '-n':
            use_subprocess = False
1330 1331
        if o == '-r':
            script = a
1332 1333 1334
            if os.path.isfile(script):
                pass
            else:
1335
                print("No script file: ", script)
1336 1337
                sys.exit()
            enable_shell = True
1338
        if o == '-s':
1339 1340
            startup = True
            enable_shell = True
1341 1342
        if o == '-t':
            PyShell.shell_title = a
1343 1344 1345 1346 1347
            enable_shell = True
    if args and args[0] == '-':
        cmd = sys.stdin.read()
        enable_shell = True
    # process sys.argv and sys.path:
1348 1349
    for i in range(len(sys.path)):
        sys.path[i] = os.path.abspath(sys.path[i])
1350 1351 1352 1353 1354 1355 1356 1357 1358
    if args and args[0] == '-':
        sys.argv = [''] + args[1:]
    elif cmd:
        sys.argv = ['-c'] + args
    elif script:
        sys.argv = [script] + args
    elif args:
        enable_edit = True
        pathx = []
1359 1360
        for filename in args:
            pathx.append(os.path.dirname(filename))
1361 1362 1363 1364
        for dir in pathx:
            dir = os.path.abspath(dir)
            if not dir in sys.path:
                sys.path.insert(0, dir)
1365
    else:
1366 1367
        dir = os.getcwd()
        if dir not in sys.path:
1368
            sys.path.insert(0, dir)
1369 1370
    # check the IDLE settings configuration (but command line overrides)
    edit_start = idleConf.GetOption('main', 'General',
1371
                                    'editor-on-startup', type='bool')
1372 1373
    enable_edit = enable_edit or edit_start
    # start editor and/or shell windows:
1374
    root = Tk(className="Idle")
1375

1376 1377 1378
    fixwordbreaks(root)
    root.withdraw()
    flist = PyShellFileList(root)
1379 1380
    macosxSupport.setupApp(root, flist)

1381 1382 1383 1384 1385 1386
    if enable_edit:
        if not (cmd or script):
            for filename in args:
                flist.open(filename)
            if not args:
                flist.new()
1387
    if enable_shell:
1388 1389
        shell = flist.open_shell()
        if not shell:
1390
            return # couldn't open shell
1391 1392 1393 1394 1395 1396 1397 1398

        if macosxSupport.runningAsOSXApp() and flist.dict:
            # On OSX: when the user has double-clicked on a file that causes
            # IDLE to be launched the shell window will open just in front of
            # the file she wants to see. Lower the interpreter window when
            # there are open files.
            shell.top.lower()

1399 1400 1401 1402
    shell = flist.pyshell
    # handle remaining options:
    if debug:
        shell.open_debugger()
1403 1404 1405 1406
    if startup:
        filename = os.environ.get("IDLESTARTUP") or \
                   os.environ.get("PYTHONSTARTUP")
        if filename and os.path.isfile(filename):
1407
            shell.interp.execfile(filename)
1408
    if shell and cmd or script:
1409 1410
        shell.interp.runcommand("""if 1:
            import sys as _sys
1411
            _sys.argv = %r
1412
            del _sys
1413
            \n""" % (sys.argv,))
1414 1415 1416
        if cmd:
            shell.interp.execsource(cmd)
        elif script:
1417
            shell.interp.prepend_syspath(script)
1418
            shell.interp.execfile(script)
1419

1420 1421 1422 1423 1424 1425 1426
    # Check for problematic OS X Tk versions and print a warning message
    # in the IDLE shell window; this is less intrusive than always opening
    # a separate window.
    tkversionwarning = macosxSupport.tkVersionWarning(root)
    if tkversionwarning:
        shell.interp.runcommand(''.join(("print('", tkversionwarning, "')")))

1427 1428 1429
    root.mainloop()
    root.destroy()

David Scherer's avatar
David Scherer committed
1430
if __name__ == "__main__":
1431
    sys.modules['PyShell'] = sys.modules['__main__']
David Scherer's avatar
David Scherer committed
1432
    main()