I’m attempting to create a YAML editor in a Vue 3 app using CodeMirror 6, and I’m having problems integrating syntax highlighting in it, in particular making string text green, e.g.
description: my description
where My description
is green
As a starter, here is my Editor.vue
component that implements it.
<script setup>
import { Codemirror } from 'vue-codemirror'
import {ref} from 'vue';
import { yaml } from '@codemirror/lang-yaml'
import { yamlLinter } from '@/codemirror/yamlLinter'
import { yamlHints } from '@/codemirror/yamlHints'
import { autocompletion } from '@codemirror/autocomplete'
import dedent from 'dedent'
const code = ref(dedent`
name: Internet2
version: 1
`)
/* Editor extensions */
const extensions = [
yaml(),
yamlLinter(),
autocompletion({
override: [yamlHints],
activateOnTyping: true
}),
]
</script>
<template>
<main class="min-h-screen">
<div class="w-full max-w-2xl px-4">
<h1 class="text-3xl font-bold mb-6 text-center">YAML Editor</h1>
<!-- Codemirror component -->
<Codemirror
v-model="code"
:autofocus="true"
:indent-with-tab="true"
:tabSize="2"
:extensions="extensions"
style="height: 400px; border: 1px solid black"
class="w-full max-w-2xl border rounded overflow-auto"
></Codemirror>
</div>
</main>
</template>
I’ve tried various implementations, such as really basic with just CSS
<style>
/* scope it to the editor wrapper if you wish */
.cm-string {
/* Tailwind’s emerald‑500, pick any green you like */
color: #10b981;
}
</style>
But the problem is that the normal use of the cm-string
class is removed by Vite, so instead, you just get
<div class="cm-activeLine cm-line">- <span class="ͼl">description</span>: My description.</div>
I tried something like this
// src/codemirror/greenStrings.js
import { HighlightStyle, tags } from '@codemirror/highlight'
import { syntaxHighlighting } from '@codemirror/language'
export const greenStrings = syntaxHighlighting(
HighlightStyle.define([
{ tag: tags.string, color: '#10b981' }
])
)
and then add it in my Editor.vue like this
import { greenStrings } from '@/codemirror/greenStrings'
const code = ref(dedent`
name: Internet2
version: 1
`)
/* Editor extensions */
const extensions = [
yaml(),,
greenStrings,
yamlLinter(),
autocompletion({
override: [yamlHints],
activateOnTyping: true
}),
]
or even this
import { EditorView } from '@codemirror/view'
// This applies to whatever minified class CM6 gives strings at runtime
export const greenStrings = EditorView.theme({
'.cm-line [style*="string"]': { color: '#10b981' }
})
but none work.
The latest version of @codemirror/highlight
is 0.19.8
, which doesn’t seem to work so well with v6.
What is the best way to implement syntax highlighting, since what I’m trying obviously isn’t working?