【问题标题】:xterm.js - Getting current line textxterm.js - 获取当前行文本
【发布时间】:2019-01-14 21:26:31
【问题描述】:

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

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 搜索无济于事。

【问题讨论】:

    标签: javascript xtermjs


    【解决方案1】:

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

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

    【讨论】:

    • 我希望有办法解决这个问题,但我想没有办法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2011-05-12
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多