The @surrealdb/codemirror package adds SurrealQL to a CodeMirror 6 editor, for pages that let people write queries.
The package provides:
SurrealQL highlighting, including embedded JavaScript in
function() { ... }bodies.Folding for blocks, objects and arrays.
Automatic indentation and comment toggling.
A linter that reports syntax which a given SurrealDB version does not support.
Before you start
A project that already uses CodeMirror 6, with
@codemirror/stateand@codemirror/viewinstalled.A package manager such as npm, pnpm or yarn.
Install
npm install @surrealdb/codemirrorThe package ships ES module and CommonJS builds and its own TypeScript types.
Add SurrealQL to an editor
Pass the surrealql() extension to the editor state:
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { surrealql } from "@surrealdb/codemirror";
const state = EditorState.create({
doc: "SELECT * FROM person WHERE age > 18;",
extensions: [surrealql()],
});
new EditorView({
parent: document.getElementById("editor")!,
state,
});The surrealql() extension is a standard CodeMirror LanguageSupport, so it combines with other CodeMirror extensions such as themes, key maps and line numbers.
Lint for a SurrealDB version
surrealqlVersionLinter() takes the SurrealDB version your users run, and reports syntax in the document that this version does not support. Add it beside surrealql():
import { surrealql, surrealqlVersionLinter } from "@surrealdb/codemirror";
const extensions = [surrealql(), surrealqlVersionLinter("2.0.0")];The linter reports through @codemirror/lint, so diagnostics appear with the lint styling you have configured.
Edit part of a statement
Pass a scope to surrealql() when the editor holds a fragment instead of a full script. The scope sets what the editor expects to parse:
| Scope | Expected content |
|---|---|
permission | The contents of a PERMISSIONS clause, such as FOR select WHERE published = true. |
index | The clauses of an index definition, such as FIELDS name UNIQUE. |
const extensions = [surrealql("permission")];Use the grammar directly
@surrealdb/codemirror builds on @surrealdb/lezer, which holds the Lezer grammar. Use the CodeMirror package for an editor. Install the Lezer package on its own to parse SurrealQL into a syntax tree outside an editor.
See also
SurrealQL editor support for the VS Code extension, the JetBrains plugin and the language server.