xterm.js-获取当前行文本

时间:2019-01-14 21:26:31

标签: 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);
});

示例来自xterm.js主页(已修改)

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

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

1 个答案:

答案 0 :(得分:3)

这不是最优雅的解决方案,但是通过将“ 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);
});

您的问题出现在我的搜索中,以寻求类似的解决方案,因此感谢您提交! :)