【问题标题】:Ace Editor manually adding snippetsAce Editor 手动添加片段
【发布时间】:2014-11-23 05:13:44
【问题描述】:

TL;DR

我正在尝试通过函数调用手动触发 ace 编辑器 sn-ps,而不是传统的方法(键盘键)。

说明

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

Ace 编辑器支持 TextMate-ish sn-ps。

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

所以当我们调用这个函数时,它应该添加sn-p,突出显示sn-p标记并选择第一个。填写第一个并点击选项卡后,编辑器应移动到下一个 sn-p 标记。就像在 Kitchen Sink 示例中一样(但我想改为通过函数调用添加/触发 sn-ps)。

我尝试破解并制作了this function。但它混乱且不完整(不支持标记和制表符)。有什么本机方法吗?我见过一些使用snippetManager 的示例,但它们使用的是键盘触发器,而不是手动功能。

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

【问题讨论】:

    标签: javascript code-snippets ace-editor


    【解决方案1】:

    经过几个小时的hack和研究,我终于在ext-language_tools.js中发现了snippetManagerinsertSnippet函数,它是这样工作的:

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

    其实很简单,由于缺乏文档,之前找不到。

    【讨论】:

    • 格式是 TextMate-ish。只需将代码中的所有占位符替换为${number:text}(数字以1开头)即可。查看问题中的示例。
    • 你能提供一个你用过的sn-p的例子吗
    【解决方案2】:

    如果你不使用 RequireJS,那么下面的语法也可以:

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

    【讨论】:

      【解决方案3】:

      使用ace.define(...) 添加您的sn-p。 sn-ps 是用tex-like 语言编写的。

      • 对于在./src/lib/json-snippet.js 定义的片段:
      // 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} 定义文件类型及其sn-ps。

      • node_module/brace/snippets/ 找到现有的 sn-ps 以进行覆盖。

      import "brace/mode/json";
      import "brace/snippets/json";
      import "brace/ext/language_tools";
      

      欲了解更多信息,请查看:

      【讨论】:

        【解决方案4】:

        其他答案似乎有点陈旧或相当老套。这对我在 v1.4.12 上使用实际的 Ace API 很有用(尽管这似乎完全没有记录,令人沮丧)。

        const snippetManager = ace.require('ace/snippets').snippetManager;
        const snippetContent = `
        # scope: html
        snippet hello
            <p>Hello, \${1:name}!</p>
        `;
        const snippets = snippetManager.parseSnippetFile(snippetContent);
        snippetManager.register(snippets, 'html');
        

        html 交换为您想要的任何范围。

        在编辑器中输入“hello”,然后输入 TAB 以触发 sn-p。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-17
          相关资源
          最近更新 更多