Ace Editor手动添加片段

问题描述 投票:13回答:3

TL; DR

我试图通过函数调用手动触发ace编辑器片段,而不是传统的方法(键盘键)。

说明

我需要一个函数,它将编辑器和片段字符串作为参数,并将该片段添加到编辑器中。 function addSnippet(editor, snippet)

Ace编辑器支持TextMate-ish片段。

if (${1:condition_name}) {
     ${2:body}
}

因此,当我们调用此函数时,它应该添加代码段,突出显示代码段标记并选择第一个。填充第一个并点击标签后,编辑器应移至下一个片段标记。就像在Kitchen Sink示例中一样(但我想通过函数调用添加/触发片段)。

我试图破解我的方式并制作this function。但它是凌乱和不完整的(不支持标记和标签按下)。这有什么原生方法吗?我见过几个使用snippetManager的例子,但它们使用的是键盘触发器,而不是手动功能。

有关此问题的任何帮助将不胜感激。谢谢。

javascript code-snippets ace-editor
3个回答
28
投票

经过几个小时的黑客攻击和研究,我终于在insertSnippet遇到了snippetManagerext-language_tools.js功能,它的工作原理如下:

var snippetManager = ace.require("ace/snippets").snippetManager;
snippetManager.insertSnippet(editor, snippet);

实际上非常简单,由于缺乏文档而无法提前找到它。


5
投票

如果您不使用RequireJS,则以下语法也可以使用:

ace.config.loadModule('ace/ext/language_tools', function () {
    editor.insertSnippet(snippetText);
});

1
投票

使用ace.define(...)添加代码段。这些片段用tex-like语言编写。

  • 对于./src/lib/json-snippet.js定义的Snippet:
// eslint-disable-next-line
const snippet = '# AddNode\n\
snippet addn\n\
    {\n\
        "nodeName": "${1:node_name}",\n\
        "algorithmName": "${2:algo_name}",\n\
        "input": []\n\
    }\n\
';

export default snippet;
// import your snippet
import snippet from "../lib/json-snippet";

// SUPER HACK FOR ADDING SNIPPETS
ace.define("ace/snippets/json", ["require", "exports", "module"], (e, t, n) => {
    // eslint-disable-next-line
    (t.snippetText = snippet), (t.scope = "json");
});
  • 使用brace/mode/{filetype}brace/snippets/{filetype}来定义文件类型和它的片段。
  • 查找node_module/brace/snippets/的现有片段以覆盖。
import "brace/mode/json";
import "brace/snippets/json";
import "brace/ext/language_tools";

有关更多信息,请查看:

© www.soinside.com 2019 - 2024. All rights reserved.