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

    Syntax tree
    
            

    Installation

    Two packages: the grammar on its own, and the CodeMirror language built on it.

    Terminal
    pnpm add codemirror-spreadsheet

    Use lezer-spreadsheet alone if you only need the parser, for example to list the references of a formula on a server.

    Usage

    formula-bar.ts
    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.

    ModeWhenArrow keys
    readyNothing is being edited. Typing starts an entry; F2 edits.Left to the host, to move between cells.
    enterA new entry is being typed.Start a reference where one can go; otherwise commit and move on.
    pointA reference is being chosen.Move it. Shift stretches it, Ctrl+Space takes the whole column, Shift+Space the whole row.
    editAfter 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.

    pointing.ts
    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.

    theme.ts
    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 variableOn
    .cm-spreadsheet-referenceEvery reference. Its colour is in --cm-spreadsheet-reference.
    .cm-spreadsheet-reference-activeThe reference at the caret: the one typing, F4 or pointing changes.
    [data-formula-mode]The editor content, with the current mode.
    .cm-spreadsheet-hintThe argument hint tooltip.

    Function lists

    Engines support different functions, so the list is plain JSON you can swap, edit or replace.

    FileFunctionsDocumented
    functions/default.json136136
    functions/hyperformula.json423131
    functions/ironcalc.json497133
    functions.ts
    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.

    NodeExample
    Cell, ColumnRange, RowRange$A$1, A:C, 1:3
    RangeReferenceA1:B2, A1:INDEX(B:B,3)
    QualifiedReference'Q1 Sales'!B2, [Book.xlsx]Sheet1!A1
    IntersectionReference, UnionReferenceA1:B2 B2:C3, (A1,B1)
    StructuredReference, SpillReferenceTable1[@Amount], A1#
    FunctionCall, RefFunctionCall, CallExpressionSUM(1,2), INDEX(A:A,1), LAMBDA(x,x+1)(2)
    BinaryExpression, UnaryExpression, PercentExpression1+2, -A1, 5%
    ArrayConstant, ArrayFormula{1,2;3,4}, {=SUM(A1:A3*B1:B3)}

    API reference

    spreadsheet(config)

    OptionDefaultWhat it does
    functionsdefaultFunctionsFunctions to complete and show argument hints for.
    sheets, namesnoneSheet names and named ranges to complete and colour.
    dialectdefaultDialectSeparators, boolean and error names.
    pointingoffReady, enter, point and edit modes.
    referenceColorsseven coloursPalette for references, or false. Sets the referencePalette facet.
    highlight, autocomplete, argumentHints, bracketMatchingtrueTurn a bundled extension off to supply your own.

    Reading the editor

    FunctionReturns
    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.