adding custom snippets

Hello,
I’m currently trying to make a scheme code editor with codemirror 6.

For the moment I have a really basic setup that looks like this :

const initialState = EditorState.create({
  doc: `
(define (hello)
  (post 'Hello_World))
`,
  extensions: [
    basicSetup,
    StreamLanguage.define(scheme),
    oneDark,
    ],
});
  this.view = new EditorView({
  parent: document.getElementById(this.editorId),
  state: initialState,
});

As I saw in the reference it could be possible to implement a snippet feature, but I really don’t know how to do it… Can I have a simple example of how can I implement that feature?

Thank you very much

Guillaume

The website CodeMirror 6 has a demo with snippets (e.g. for), source code is here: https://github.com/codemirror/website . There might be a simpler demo out there though.

Hey thank you for you answer, I have the feeling that in these examples with Javascript, snippets are embedded in the language mode. In my case I don’t want to create a mode just add snippets as adding extensions to my setup. I tried to understand how it’s made but for the moment it’s too complicated for me. It’s why I would like to have a little example.

But I will look deeper inside it.
Thank you

Something like this enables an extra snippet completion for JavaScript. See snippetCompletion and language data.

import {EditorState, EditorView, basicSetup} from "@codemirror/basic-setup"
import {javascript, javascriptLanguage} from "@codemirror/lang-javascript"
import {snippetCompletion} from "@codemirror/autocomplete"

let state = EditorState.create({extensions: [
  basicSetup,
  javascript(),
  javascriptLanguage.data.of({
    autocomplete: [
      snippetCompletion('mySnippet(${one}, ${two})', {label: 'mySnippet'})
    ]
  })
]})
1 Like

Thank you marijn, this is working pretty well.
Do you think is possible to do the same but with a legacy language? In my case with scheme? I mean I understand you example but when I import a language with : StreamLanguage.define(“scheme”), I can’t use data.of method on it, or (I suppose) I missed something.

Sorry it’s anoying and I feel a little ambarassed I would really like to understand better all of this but I have started codemirror 6 since only few days now… Anyway thank you very much for your help

My bad, it’s working pretty well with a legacy language also, just have to declare it first :

const schemeLang = StreamLanguage.define(scheme) 

const initialState = EditorState.create({
  doc: 
`
(define (hello)
  (post 'Hello_World))
`,
  extensions: [
    basicSetup,
    schemeLang,
    schemeLang.data.of({
    autocomplete: [
      snippetCompletion('mySnippet(${one}, ${two})', {label: 'mySnippet'})
    ]
    }),
    oneDark,
    ],
});

Thank you so much, my coding weekend can start now :slight_smile: