我现在已经通过在光标前有命令时触发自动完成来解决这个问题。这解决了这两个问题,因为 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 是上面显示的对象。