Ace编辑器手动添加代码段

Ace Editor manually adding snippets

本文关键字:代码 添加 编辑器 Ace      更新时间:2023-09-26

TL;DR

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

解释

我需要一个函数,它将编辑器和一个代码片段字符串作为参数,并将该代码片段添加到编辑器中。CCD_ 1。

Ace编辑器支持TextMate风格的代码段。

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

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

我试着破解并实现了这个功能。但它是混乱和不完整的(不支持标记和制表)。有本地方法吗?我看到了一些使用snippetManager的例子,但它们使用键盘触发器,而不是手动功能。

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

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

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

实际上很容易,由于缺乏文档,无法更早找到它。

如果您不使用RequireJS,那么以下语法也适用:

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

使用ace.define(...)添加代码段。这些片段是用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}function addSnippet(editor, snippet)0来定义文件类型及其片段。

  • node_module/brace/snippets/中查找现有的代码段以进行覆盖。

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

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

  • Demo
  • 此存储库

其他答案似乎有点陈旧或相当粗糙。这对我在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交换到您想要的任何范围。

在编辑器中键入";你好";然后是TAB以触发该片段。