Getting started
Usage
Add the comark() extension to a CodeMirror 6 editor in vanilla JavaScript, Vue, or React, with presets, plugins, and a live playground example.
Vanilla
import { basicSetup } from 'codemirror'
import { EditorView } from '@codemirror/view'
import { comark } from 'comark-codemirror'
import { presetBuiltins } from 'comark-codemirror/presets/builtins'
const view = new EditorView({
parent: document.querySelector('#editor')!,
doc: '# Hello\n',
extensions: [
basicSetup,
comark({
plugins: presetBuiltins(),
components: [
{ name: 'card', kind: 'block', props: { title: { type: 'string', required: true }, variant: { enum: ['soft', 'outline'] } }, slots: [{ name: 'footer' }] },
],
}),
],
})
comark() adds the language, the completion menus, the keymap, lint, hover and the theme. It registers its completion source through language data, so do not pass autocompletion({ override }) — that would replace it. Add your own sources as plugins.
Vue
<script setup lang="ts">
import { EditorView } from '@codemirror/view'
import { basicSetup } from 'codemirror'
import { comark } from 'comark-codemirror'
const model = defineModel<string>({ default: '' })
const el = ref<HTMLElement>()
let view: EditorView | undefined
onMounted(() => {
view = new EditorView({
parent: el.value!,
doc: model.value,
extensions: [
basicSetup,
comark(),
EditorView.updateListener.of(u => u.docChanged && (model.value = u.state.doc.toString())),
],
})
})
onBeforeUnmount(() => view?.destroy())
</script>
<template>
<div ref="el" />
</template>
React
import { EditorView } from '@codemirror/view'
import { basicSetup } from 'codemirror'
import { comark } from 'comark-codemirror'
import { useEffect, useRef } from 'react'
export function Editor({ value, onChange }: { value: string, onChange: (v: string) => void }) {
const el = useRef<HTMLDivElement>(null)
useEffect(() => {
const view = new EditorView({
parent: el.current!,
doc: value,
extensions: [basicSetup, comark(), EditorView.updateListener.of(u => u.docChanged && onChange(u.state.doc.toString()))],
})
return () => view.destroy()
}, [])
return <div ref={el} />
}
Changing options later
Options are part of the extension. Put comark() in a compartment and reconfigure it when your component manifest or data change:
import { Compartment } from '@codemirror/state'
const comarkConfig = new Compartment()
// extensions: [basicSetup, comarkConfig.of(comark({ components }))]
view.dispatch({ effects: comarkConfig.reconfigure(comark({ components: await loadComponents() })) })
Dark mode
The theme reads CodeMirror's light/dark flag. With a dark theme such as @codemirror/theme-one-dark, the menus and syntax colors switch automatically. See Theming.