Add YAML editing support to CodeMirror

How to add YAML highlighting, indentation and linting to CodeMirror, what each layer changes in your text, and when a plain text field is the better choice.

Adding YAML support to a CodeMirror editor is one of the more common requests for browser-based configuration tools, CI dashboards and content admin panels. This review covers what the YAML layer does to your text, which parts change only how the text looks, and where the limits are for copying, sharing and accessibility. It is based on general, documented CodeMirror behavior. It does not include measured benchmarks or hands-on test results, so verify package names and versions against current documentation before you depend on them.

Is CodeMirror YAML support suitable for your use?

For most browser apps where people write or edit YAML by hand, a CodeMirror editor with YAML language support and a linter is a reasonable choice. The main benefit is fast feedback. Structure is visible through highlighting, indentation follows the document's nesting, and syntax errors can be flagged before the text is saved or submitted.

The main tradeoff is that these features help people edit but do not guarantee correctness. Highlighting reflects the parser's view of the syntax. It does not show how a particular YAML loader will interpret a value. A syntax linter catches malformed YAML, but it does not check whether the document matches the schema your application expects. The editor also adds JavaScript weight and interaction complexity compared with a native text field.

A plain textarea is often the better choice in these situations:

  • The field holds a few short lines and is rarely edited.
  • Users mostly paste in finished YAML and submit it without changes.
  • Bundle size or page weight is a hard constraint.
  • You need native mobile text input behavior with no custom editor layer.
  • You cannot test the editor with the assistive technologies your users rely on.

What the YAML layer actually changes

The name causes some confusion. The "mirror" in CodeMirror does not mirror, flip or reverse text, and YAML support does not substitute characters or apply special fonts. The YAML layer is a set of editor extensions. Most of them change only how the document is displayed. A few can change the stored text, and only when they are triggered.

Feature | Changes stored text? | What it does
Syntax highlighting | No | Applies CSS classes to tokens such as keys, strings, comments and anchors
Code folding | No | Hides nested blocks visually; the text is still in the document
Lint diagnostics | No | Underlines ranges and lists messages; the document is unchanged
Auto-indentation | Yes, on Enter or explicit indent | Inserts spaces according to the configured indent unit
Tab key indentation (if enabled) | Yes | Inserts indentation instead of moving focus
External reformatting (for example, a formatter run on save) | Yes | Rewrites spacing, quoting and sometimes comment placement

Language support

In CodeMirror 6, YAML support comes from a dedicated language package, @codemirror/lang-yaml, which is built on a Lezer YAML grammar. It provides parsing for highlighting, folding and indentation. Older setups can instead use the YAML stream mode from @codemirror/legacy-modes, wrapped with StreamLanguage. That option gives tokenizer-level highlighting with less structural awareness. CodeMirror 5 shipped its own YAML mode, which is a separate API and is not compatible with version 6 extensions.

import { EditorView, basicSetup } from "codemirror";
import { yaml } from "@codemirror/lang-yaml";

new EditorView({
  doc: "name: example\nitems:\n  - one\n  - two\n",
  extensions: [basicSetup, yaml()],
  parent: document.body
});

If you are using the legacy stream mode, the language is defined like this instead:

import { StreamLanguage } from "@codemirror/language";
import { yaml } from "@codemirror/legacy-modes/mode/yaml";

const yamlLanguage = StreamLanguage.define(yaml);

Validation through linting

The language package does not report errors by itself. You need to connect a YAML parser to CodeMirror's lint extension. The sketch below uses the yaml npm package, whose parse errors carry character offsets. Those offsets line up with CodeMirror document positions because both use JavaScript string indexing.

import { linter } from "@codemirror/lint";
import { parseDocument } from "yaml";

const yamlLinter = linter(view => {
  const text = view.state.doc.toString();
  const doc = parseDocument(text);
  return doc.errors.map(err => ({
    from: Math.min(err.pos[0], text.length),
    to: Math.min(err.pos[1], text.length),
    severity: "error",
    message: err.message
  }));
});

This checks syntax only. To catch a missing required key or a value of the wrong type, you need schema validation on top of parsing. That means another library and another lint source. Treat the editor's lint result as advisory and repeat validation on the server, because client-side checks can be bypassed.

Where meaning can drift

Highlighting does not resolve types. Under YAML 1.1 rules, a bare value such as no or on may load as a boolean, while YAML 1.2 loaders treat it as a string. The editor colors the token the same way in both cases. If a value's type matters, quote it, or use a lint rule built on the same loader your application uses.

Reformatting is the main way the stored text can change in meaning or lose information. If you parse a document into data and serialize it back with a library that does not keep comments, the comments disappear. Key order, quoting style and multi-line string style can also change. If you add format-on-save, check that comments and anchors survive a round trip with your chosen library before turning it on for users.

Will the text stay readable and usable after copying or sharing?

Highlighting and folding are presentation only, so the underlying document is ordinary YAML text. When a user copies from the editor, they get document text, not colored markup. Folded sections are part of the document, so copying a range that covers a folded block includes the hidden lines. Confirm clipboard behavior in the specific destinations your users paste into, such as chat tools, ticket systems or terminals, rather than assuming one successful paste applies everywhere.

Pasting into the editor brings more risk. YAML does not allow tab characters for indentation, so tab-indented text copied from another source can produce an invalid document even though it looks aligned. A linter will flag this. Showing whitespace or converting tabs on paste are optional extras you would add yourself.

Search and editing

CodeMirror's search runs on the document text, so highlighting does not affect what matches. Folded regions may hide matches until they are unfolded. Browser find-in-page is less dependable in a virtualized editor, because CodeMirror renders only the visible part of long documents. Point users to the editor's own search command instead.

Bidirectional text

If YAML values contain right-to-left scripts, CodeMirror 6 shows them in bidirectional order on screen while the stored character order stays the same. Mixed-direction lines can look out of order near punctuation such as colons and dashes. The saved file is still correct, but people reviewing it visually may misread it. Test with real content if this applies to your users.

Accessibility

Some points are documented. By default, CodeMirror 6 does not bind the Tab key to indentation, so keyboard users can move focus out of the editor. YAML editing benefits from Tab indentation, but if you add it with the indentWithTab keymap, the editor's documented escape is to press Escape and then Tab to move focus. Tell users about this in visible help text. Lint diagnostics are available through a keyboard-reachable panel as well as through underlines, so do not rely on color alone to signal errors.

Other points are unverified. This review includes no testing with specific screen readers or browsers. Announcement of diagnostics, reading of indentation depth, and behavior inside folded regions should be checked with the assistive technologies your audience uses. Indentation carries meaning in YAML, and its visual cues do not reliably reach screen reader users. Validation messages that state the line and the problem in words help close that gap.

When to offer a plain-text equivalent

Provide a plain textarea fallback, or a download of the raw file, if users may work in environments where the editor fails to load, if assistive technology testing shows problems you cannot fix, or if the YAML needs to be reviewed outside the app. Because the stored content is already plain YAML, the fallback can use the same text without conversion.

Gaps in this review

  • No package versions, bundle sizes or performance figures were confirmed; check current package documentation.
  • No hands-on screen reader, mobile or cross-browser tests were performed.
  • Clipboard behavior in named destination apps was not tested.
  • Schema validation options for CodeMirror were not evaluated.