CodeMirror Spreadsheet
A formula editor for spreadsheets: a Lezer grammar, completion, argument hints, coloured references and pointing.
←↑↓→ point Shift stretch Ctrl Space column Shift Space row F4 cycle $ F2 edit Enter commit Esc cancel
Installation
Two packages: the grammar on its own, and the CodeMirror language built on it.
pnpm add codemirror-spreadsheetUse lezer-spreadsheet alone if you only need the parser, for example to list the references of a formula on a server.
Usage
import { EditorView, keymap } from "@codemirror/view";
import { defaultKeymap } from "@codemirror/commands";
import { completionKeymap } from "@codemirror/autocomplete";
import { spreadsheet, onReferencesChange } from "codemirror-spreadsheet";
new EditorView({
parent: document.querySelector("#formula-bar")!,
doc: "=SUM(A1:B2)",
extensions: [
keymap.of([...completionKeymap, ...defaultKeymap]),
spreadsheet({
sheets: () => workbook.sheetNames(),
names: [{ name: "TaxRate", detail: "Sheet1!$H$1" }],
}),
// Outline the referenced ranges on your grid, in the editor's colours.
onReferencesChange((references) => grid.outline(references)),
],
});Modes
Pass pointing and the editor keeps the four modes a spreadsheet shows in its status bar. The badge in the formula bar above shows the current one.
| Mode | When | Arrow keys |
|---|---|---|
| ready | Nothing is being edited. Typing starts an entry; F2 edits. | Left to the host, to move between cells. |
| enter | A new entry is being typed. | Start a reference where one can go; otherwise commit and move on. |
| point | A reference is being chosen. | Move it. Shift stretches it, Ctrl+Space takes the whole column, Shift+Space the whole row. |
| edit | After F2, or a click into the text. | Move the caret. The mouse can still point. |
Enter and Tab commit, Escape cancels, F2 switches between edit and enter. Read the mode with getFormulaMode(state) or listen with onFormulaModeChange.
Pointing
In enter mode an arrow key starts a reference wherever the grammar allows one: after =, an operator, (, : or an argument separator. That is read from the syntax tree. Anywhere else the key commits the entry, as in a spreadsheet.
spreadsheet({
pointing: {
mode: "ready", // a formula bar that is always visible
origin: () => grid.activeCell, // where the arrow keys start from
rows: grid.rowCount,
columns: grid.columnCount,
commit: (view, direction) => grid.commit(view.state.doc.toString(), direction),
cancel: (view) => grid.cancel(),
},
});
// The mouse: a click or drag on your grid.
cell.onmousedown = (event) => {
event.preventDefault();
pointAt(view, { row, column }, { extend: event.shiftKey });
};
// A column or row header: A:A, 1:2.
columnHeader.onmousedown = (event) => {
event.preventDefault();
pointAt(view, { row: 0, column }, { span: "columns", extend: event.shiftKey });
};Accessibility
Every pointed reference and every mode change is announced through CodeMirror's live region. F2 always returns the arrow keys to the caret, so the text can be edited from the keyboard alone, and an open completion list keeps the arrow keys.
Theming
Everything visible can be replaced the CodeMirror way: a facet for the reference palette, a highlight style for the tokens, classes for the rest.
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
import { Compartment } from "@codemirror/state";
import { tags } from "@lezer/highlight";
import { spreadsheet, referencePalette, onActiveReferenceChange } from "codemirror-spreadsheet";
const palette = new Compartment();
[
spreadsheet({ highlight: false }), // bring your own token colours
syntaxHighlighting(HighlightStyle.define([
{ tag: tags.function(tags.variableName), color: "var(--purple)" },
{ tag: tags.number, color: "var(--yellow)" },
])),
// Any CSS colour: hex, var(), light-dark(). Reconfigure to follow your theme.
palette.of(referencePalette.of(["var(--ref-1)", "var(--ref-2)", "var(--ref-3)"])),
// The reference at the caret, to mark its cells on your grid.
onActiveReferenceChange((reference) => grid.setActiveRange(reference?.range ?? null)),
];| Class or variable | On |
|---|---|
.cm-spreadsheet-reference | Every reference. Its colour is in --cm-spreadsheet-reference. |
.cm-spreadsheet-reference-active | The reference at the caret: the one typing, F4 or pointing changes. |
[data-formula-mode] | The editor content, with the current mode. |
.cm-spreadsheet-hint | The argument hint tooltip. |
Function lists
Engines support different functions, so the list is plain JSON you can swap, edit or replace.
| File | Functions | Documented |
|---|---|---|
functions/default.json | 136 | 136 |
functions/hyperformula.json | 423 | 131 |
functions/ironcalc.json | 497 | 133 |
import ironcalc from "codemirror-spreadsheet/functions/ironcalc.json";
spreadsheet({
functions: [...ironcalc, { name: "MYFN", description: "Mine.", parameters: [{ name: "x" }] }],
});Syntax tree
The grammar follows Aivaloglou, Hoepelman and Hermans, A grammar for spreadsheet formulas evaluated on two large datasets (2015). References have their own nodes so they are easy to find.
| Node | Example |
|---|---|
Cell, ColumnRange, RowRange | $A$1, A:C, 1:3 |
RangeReference | A1:B2, A1:INDEX(B:B,3) |
QualifiedReference | 'Q1 Sales'!B2, [Book.xlsx]Sheet1!A1 |
IntersectionReference, UnionReference | A1:B2 B2:C3, (A1,B1) |
StructuredReference, SpillReference | Table1[@Amount], A1# |
FunctionCall, RefFunctionCall, CallExpression | SUM(1,2), INDEX(A:A,1), LAMBDA(x,x+1)(2) |
BinaryExpression, UnaryExpression, PercentExpression | 1+2, -A1, 5% |
ArrayConstant, ArrayFormula | {1,2;3,4}, {=SUM(A1:A3*B1:B3)} |
API reference
spreadsheet(config)
| Option | Default | What it does |
|---|---|---|
functions | defaultFunctions | Functions to complete and show argument hints for. |
sheets, names | none | Sheet names and named ranges to complete and colour. |
dialect | defaultDialect | Separators, boolean and error names. |
pointing | off | Ready, enter, point and edit modes. |
referenceColors | seven colours | Palette for references, or false. Sets the referencePalette facet. |
highlight, autocomplete, argumentHints, bracketMatching | true | Turn a bundled extension off to supply your own. |
Reading the editor
| Function | Returns |
|---|---|
getReferences(state) | Every reference with its range, sheet and colour. |
getActiveReference(state) | The reference at the caret, or null. |
getPointer(state) | The reference being pointed at, or null. |
getFormulaMode(state) | "ready" | "enter" | "point" | "edit" |
getArgumentHint(state) | The function and argument around the caret. |
pointAt(view, cell, options) | Writes a reference from a click or drag on your grid. |