xterm.js-获取当前行文本

con*_*ger 7 javascript xtermjs

我正在开发一个小型xterm.js应用程序(刚刚开始),我想知道当用户按下Enter时如何从当前行获取文本。这是程序:

var term = new Terminal();
term.open(document.getElementById('terminal'));
term.prompt = () => {
  term.write('\r\n$ ');
};
term.writeln('This is a shell emulator.');
term.prompt();

term.on('key', function(key, ev) {
  const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;

  if (ev.keyCode === 13) {
    term.prompt();
    console.log(curr_line);
    var curr_line = ""
  } else if (ev.keyCode === 8) {
    // Do not delete the prompt
    if (term.x > 2) {
      curr_line = curr_line.slice(0, -1);
      term.write('\b \b');
    }
  } else if (printable) {
    curr_line += ev.key;
    console.log(curr_line, ev.key)
    term.write(key);
  }
});

term.on('paste', function(data) {
  term.write(data);
});
Run Code Online (Sandbox Code Playgroud)

取自xterm.js主页的示例(并进行了修改)

如您所见,我的尝试是每次遇到key事件时都添加一行文本(或在退格键上删除)。但是,这不起作用,因为它在异步函数内部。

是否xterm.js附带了另一个允许您获取当前行内容的功能,或者有其他解决方法?我的Google搜索无济于事。

小智 5

不是最优雅的解决方案,但是通过将“curr_line”移动到全局范围内,我们可以在“on key”事件之间保持它的持久性。

var term = new Terminal();
term.open(document.getElementById('terminal'));
term.prompt = () => {
    term.write('\r\n$ ');
};
term.writeln('This is a shell emulator.');
term.prompt();

// Move curr_line outside of async scope.
var curr_line = '';

term.on('key', function(key, ev) {
    const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;

    if (ev.keyCode === 13) {
        term.prompt();
        console.log(curr_line);
        curr_line = '';
    } else if (ev.keyCode === 8) {
        // Do not delete the prompt
        if (term.x > 2) {
            curr_line = curr_line.slice(0, -1);
            term.write('\b \b');
        }
    } else if (printable) {
        curr_line += ev.key;
        console.log(curr_line, ev.key)
        term.write(key);
    }
});

term.on('paste', function(data) {
    term.write(data);
});
Run Code Online (Sandbox Code Playgroud)

您的问题出现在我寻找类似解决方案的过程中,因此感谢您提交!:)