How do I programmatically add a snippet in Ace Editor?

夙愿已清 提交于 2019-12-08 04:13:37

问题


I want to add my own custom code snippets to my ace editor input box.

How would I go about adding them?

From the documentation of Ace editor regarding snippets:

Currently, the only way to add custom snippets to a project is to create a plugin (as described here).

I saw a project called ace-snippet-extension but it has not been updated since 2016, and does more things than simply allowing me to add a snippet.

Additionally, I am using ES6+/ES2015+, so the require statements are confusing as well.

This is the result I'm looking for:


回答1:


After some research, I extracted the useful bits out of the ace-snippet-extension. Another tricky part is that snippets seem to require a certain type of indentation, which I've made a function for (not well-tested however)

Here is the 'library' code, named ace-snippets-extension-simple.js:

import ace from 'ace-builds'

export const registerSnippets = function(editor, session, mode, snippetText) {
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
    })

    var snippetManager = ace.require('ace/snippets').snippetManager

    var id = session.$mode.$id || ''
    var m = snippetManager.files[id]

    m.scope = mode
    m.snippetText = snippetText
    m.snippet = snippetManager.parseSnippetFile(snippetText, m.scope)

    snippetManager.register(m.snippet, m.scope)
}

export const createSnippets = snippets =>
    (Array.isArray(snippets) ? snippets : [snippets])
        .map(({ name, code }) =>
            [
                'snippet ' + name,
                code
                    .split('\n')
                    .map(c => '\t' + c)
                    .join('\n'),
            ].join('\n')
        )
        .join('\n')

Here is an example of the "consumer" code:

Use this to import the above.

import ace from 'ace-builds'
import { Range, EditSession } from 'ace-builds'
import 'ace-builds/src-noconflict/ext-language_tools'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/webpack-resolver'

import {
    registerSnippets,
    createSnippets,
} from './ace-snippets-extension-simple'

const editor = ace.edit(/*HTMLElement reference or css selector string*/)

// ...
// ...
// ...

editor.setOptions({
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: false,
})

editor.setTheme('ace/theme/monokai')
editor.session.setMode('ace/mode/javascript')

registerSnippets(
    editor,
    editor.session,
    'javascript',
    createSnippets([
        { name: 'build', code: 'console.log("build")' },
        { name: 'destroy', code: 'console.log("destroy")' },
    ])
)


来源:https://stackoverflow.com/questions/58377763/how-do-i-programmatically-add-a-snippet-in-ace-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!