【问题标题】:Ace editor | Automatic code block completion王牌编辑器 |自动代码块完成
【发布时间】:2017-04-16 09:38:16
【问题描述】:

使用 ace 编辑器,除了 sn-p 补全之外,我还想在用户键入时提供自动补全。举个例子,我有以下sn-p

\begin{${1:something}}

\end{${1:something}}

现在这可以作为通用的 sn-p。现在作为用户输入

\begin{equation}

并点击 ENTER 我想插入一个匹配的结束块,如第一个 sn-p 所示。有没有比添加键盘处理程序并检查前面的文本更好的方法?可能是一种显示自定义“sn-p”的方法,其中包括 ${1} 的值作为自动完成?

【问题讨论】:

    标签: javascript autocomplete editor ace-editor


    【解决方案1】:

    我现在已经通过在光标前有命令时触发自动完成来解决这个问题。这解决了这两个问题,因为 ENTER 键插入当前选定的 sn-p。我使用以下代码触发了自动完成:

    editor.commands.on("afterExec", function(e) {
            if (e.command.name === "insertstring") {
                if (getCommand(editor)) {
                    editor.execCommand("startAutocomplete");
                }
            }
    });
    

    getCommand 基本判断光标后是否有命令。现在,当有命令时会触发自动完成功能,因此需要自定义完成程序来从输入的包含 \end 标记的命令动态构建 sn-ps。

    identifierRegexps: [/[\\a-zA-Z0-9{}\[\]]/],
    getCompletions: function(editor, session, pos, prefix, callback) {
        const command = getCommand(editor);
        if (!command) { callback(null, []); return }
        const completions = [];
    
        let caption = command.cmd;
        if (command.mods.length > 0) caption += `[${command.mods}]`;
        if (command.args.length > 0) caption += `{${command.args}}`;
    
        let snippet = command.cmd;
        if (command.mods.length > 0) snippet += `[${command.mods}]`;
        if (command.args.length > 0) snippet += `{${command.args}}`;
    
        if (command.cmd === '\\begin') {
            snippet += '\n\t${1}';
            snippet += `\n\\end{${command.args}}`
        }
    
        completions.push({
            caption: caption,
            snippet: snippet,
            meta: command.cmd === '\\begin' ? 'env' : 'cmd',
        });
    
        callback(null, completions);
    }
    

    请注意标识符Regexps,它是防止编辑器保留用户在触发自动完成之前输入的旧命令所必需的。它基本上匹配所有字母数字字符以及括号和反斜杠。然后我通过执行以下代码将此代码添加到编辑器中:

    langTools.addCompleter(customCompleter);
    

    其中 customCompleter 是上面显示的对象。

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多