【问题标题】:NodeJS readline autocomplete several wordsNodeJS readline 自动补全几个单词
【发布时间】:2017-06-22 19:51:20
【问题描述】:

我正在使用 Readline 模块使用 NodeJS 制作一个简单的 CLI 应用程序。我想自动完成用户的输入。为此,我使用了模块的autocompletion function

function completer(line) {
   const completions = '.help .error .exit .quit .q'.split(' ');
   const hits = completions.filter((c) => c.startsWith(line));
   // show all completions if none found
   return [hits.length ? hits : completions, line];
}

使用此功能,我可以完成一个命令,但不能在同一行中完成多个命令:

例如:

(CLI App) > .e<tab>
            .error .exit

(CLI App) > .err<tab>
(CLI App) > .error

(CLI App) > .error .ex<tab>
            .help .error .exit .quit .q

我修改了完成函数以仅获取用户正在编写的当前命令的自动完成建议:

function completer(line) {
   const completions = '.help .error .exit .quit .q'.split(' ');
   const hits = completions.filter((c) => c.startsWith(line.split(' ').slice(-1)));

   return [hits.length ? hits : completions, line];
}

我得到了正确的建议,但用户输入没有改变:

(CLI App) > .e<tab>
            .error .exit

(CLI App) > .err<tab>
(CLI App) > .error

(CLI App) > .error .ex<tab>
            .exit
(CLI App) > .error .ex

有没有办法解决这个问题?非常感谢您提供的任何帮助。

谢谢。

【问题讨论】:

  • 如果你只有一个命中,如何将line 的最后一部分替换为命中?添加应该不难
  • 谢谢@ChrisSatchell。我替换了line 的最后一部分,它起作用了!!

标签: node.js autocomplete console-application command-line-interface


【解决方案1】:

使用 Chris 的提示,我得到了一个解决方案:将 line 的最后一部分替换为命中(当我只有一个时)。

我计算line(我想要自动完成的实际命令)最后一部分的长度,以将光标移动到该命令的开头。然后,我得到所有行减去当前命令,然后连接命中。最后,我将光标设置在行尾。

我尝试使用 docs 中的方法但运气不佳:readline.cursorTo(stream, x, y)readline.moveCursor(stream, dx, dy) 对我不起作用。

readline.clearLine(stream, dir) 方法清除所有行并且没有“从光标向右”(我想要的行为),尽管它存在于 doc 中。

function completer(line) {
    const completions = '.help .error .exit .quit .q'.split(' ');
    let cmds = line.split(' ');
    const hits = completions.filter((c) => c.startsWith(cmds.slice(-1)));

    if ((cmds.length > 1) && (hits.length === 1)) {
        let lastCmd = cmds.slice(-1)[0];
        let pos = lastCmd.length;
        rl.line = line.slice(0, -pos).concat(hits[0]);
        rl.cursor = rl.line.length + 1;
    }

    return [hits.length ? hits.sort() : completions.sort(), line];
}    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    相关资源
    最近更新 更多