Skip to content

Commit 9a26d70

Browse files
committed
WASM REPL: better implementation of ctrl+c behavior
1 parent 25fd7fc commit 9a26d70

1 file changed

Lines changed: 27 additions & 10 deletions

File tree

Tools/wasm/emscripten/web_example/index.html

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -248,12 +248,9 @@
248248
break;
249249
case "\x03": // CTRL+C
250250
this.input = "";
251-
this.xterm.write("\n");
252-
this.xterm.write(
253-
"\x1b[" + (this.cursorPosition + 4) + "D",
254-
);
255251
this.cursorPosition = 0;
256-
this.resolveInput("" + "\n");
252+
this.historyIndex = -1;
253+
this.resolveInput("__WASM_REPL_CTRLC__\n");
257254
break;
258255
case "\x09": // TAB
259256
this.handleTab();
@@ -456,13 +453,16 @@
456453
// Hack to ensure cursor input start doesn't end up after user input
457454
setTimeout(() => {
458455
this.handleCursorInsert(
459-
this.inputBuffer.nextLine(),
456+
this.inputBuffer.nextLine()
460457
);
461458
}, 1);
462459
}
463460
return new Promise((resolve, reject) => {
464461
this.resolveInput = (value) => {
465-
if (value.replace(/\s/g, "").length != 0) {
462+
if (
463+
value.replace(/\s/g, "").length != 0 &&
464+
value != "__WASM_REPL_CTRLC__\n"
465+
) {
466466
if (this.historyIndex !== -1) {
467467
this.historyBuffer[this.historyIndex] =
468468
this.history[this.historyIndex];
@@ -575,10 +575,27 @@
575575
replButton.addEventListener("click", (e) => {
576576
terminal.clear();
577577
terminal.reset(); // reset the history
578+
const REPL = `
579+
class WASMREPLKeyboardInterrupt(KeyboardInterrupt):
580+
pass
581+
582+
import sys
583+
import code
584+
import builtins
585+
586+
def _interrupt_aware_input(prompt=''):
587+
line = builtins.input(prompt)
588+
if line.strip() == '__WASM_REPL_CTRLC__':
589+
raise KeyboardInterrupt()
590+
return line
591+
592+
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
593+
banner = f'Python {sys.version} on {sys.platform}\\n{cprt}'
594+
595+
code.interact(banner=banner, readfunc=_interrupt_aware_input, exitmsg='')
596+
`;
578597
programRunning(true);
579-
// Need to use "-i -" to force interactive mode.
580-
// Looks like isatty always returns false in emscripten
581-
pythonWorkerManager.run({ args: ["-i", "-"], files: {} });
598+
pythonWorkerManager.run({ args: ["-c", REPL], files: {} });
582599
});
583600

584601
stopButton.addEventListener("click", (e) => {

0 commit comments

Comments
 (0)