codemirror-ml is a complete OCaml port of CodeMirror 6. It exists to provide a type-safe editor core and editor UI that can run both:
- in JavaScript/WebAssembly-adjacent web environments through Melange, and
- in native OCaml applications through a backend-neutral rendering/input abstraction, including LUI native hosts.
The port must use OCaml's type system and module system as a first-class design tool rather than mechanically imitate TypeScript's dynamic shapes. Invalid editor states should be unrepresentable where practical, while public behavior remains indistinguishable from upstream CodeMirror.
This is a clean OCaml implementation informed by the MIT-licensed upstream project. It must preserve the upstream copyright and license notices required by the MIT license.
The binding requirements for this repository are:
- Port all modern CodeMirror functionality. Legacy compatibility packages and CodeMirror 5-era historical baggage are explicitly out of scope.
- Behavior must be exactly the same as upstream CodeMirror.
- All meaningful upstream tests must be covered by ported tests.
- Support both Melange and native targets.
- Write this specification before implementation, then implement and verify against it.
- Use OCaml type-system and ecosystem best practices.
- Maximize parallel Devin child sessions for implementation and verification.
- A later application shell may provide a simple Lettera-like editing experience using LUI and
codemirror-ml; it is not an Obsidian clone.
legacy-modes, legacy entries in language-data, streamparser, the
StreamLanguage driver and other CodeMirror 5-era compatibility behavior
are outside the supported API, build and test scope. Retain the shared UTF-16
text, ECMAScript whitespace classification and State column helpers used
by modern languages. The supported language-data scope is the modern
language catalog and typed provider mechanism.
The canonical upstream repositories have moved from GitHub to https://code.haverbeke.berlin/codemirror/<name>. The baseline is the latest release tag for every package as resolved on 2026-11-29, not the stale GitHub mirror and not a moving main branch. Commit hashes are abbreviated here but must be recorded in full in the parity matrix when implementation starts. The official development manifest contains 37 packages: 13 core packages and 24 additional packages.
| Upstream repository | Package version | Release commit | Test files |
|---|---|---|---|
state |
6.7.6 |
651084c8a322 |
7 |
view |
6.44.2 |
139478818ccf |
13 |
language |
6.13.1 |
21a380682866 |
3 |
streamparser |
6.0.0 |
9419d08a7c85 |
0 |
commands |
6.11.2 |
2d2511920a72 |
5 |
search |
6.7.3 |
d1153bef3f36 |
3 |
autocomplete |
6.20.4 |
5e4c57ab8d0b |
1 |
lint |
6.9.8 |
f71583124fa1 |
1 |
collab |
6.1.1 |
b793fbc1992b |
2 |
language-data |
6.5.2 |
e0a0578fc1d1 |
0 |
merge |
6.13.0 |
d206cc871bf9 |
2 |
lsp-client |
6.3.1 |
dbb03b05afd3 |
2 |
basic-setup (codemirror package) |
6.0.2 |
76462c05acb1 |
0 |
lang-javascript |
6.2.5 |
a202a000e8d3 |
2 |
lang-java |
6.0.2 |
a75c10204fcc |
0 |
lang-json |
6.0.2 |
ef0c630e5f37 |
0 |
lang-cpp |
6.0.3 |
6abf50cbc667 |
0 |
lang-php |
6.0.2 |
ce25655e29f3 |
0 |
lang-python |
6.2.1 |
b29a2dd8f52b |
1 |
lang-go |
6.0.1 |
b6aa0b765989 |
1 |
lang-css |
6.3.1 |
253b0baa868d |
0 |
lang-sass |
6.0.2 |
ecf8367100b8 |
0 |
lang-html |
6.4.12 |
de1fbd825c6f |
1 |
lang-sql |
6.10.0 |
62abf00f18da |
2 |
lang-rust |
6.0.2 |
b78f62a7f345 |
0 |
lang-xml |
6.1.0 |
6fb53b56f591 |
1 |
lang-markdown |
6.5.3 |
7c1d1986d689 |
1 |
lang-lezer |
6.0.2 |
b963aba946a1 |
0 |
lang-wast |
6.0.2 |
3739cffcc59c |
0 |
lang-angular |
0.1.4 |
55bf1cdebf80 |
0 |
lang-vue |
0.1.3 |
50efb40d5a53 |
0 |
lang-liquid |
6.3.4 |
2afa0e211015 |
1 |
lang-less |
6.0.2 |
a07c8335e609 |
1 |
lang-yaml |
6.1.3 |
1a5b4f7d1e56 |
0 |
lang-jinja |
6.0.1 |
e317d9b9da2a |
2 |
legacy-modes |
6.5.5 |
cee55a6909d5 |
0 |
theme-one-dark |
6.1.3 |
5c4c69e48964 |
0 |
The upstream harness inventory found 1,199 executable cases in 20 of the 37 packages: 745 Node cases in 35 files and 454 browser cases in 14 files. That count excludes additional Lezer and utility dependency suites. Some browser bidi cases are live-layout sensitive; this does not permit omission, but requires pinned browser/font/layout qualification.
CodeMirror language packages depend on Lezer packages and small JavaScript runtime libraries. Full native behavior therefore requires OCaml implementations or semantically exact equivalents for:
@lezer/common@lezer/highlight@lezer/lr@lezer/cpp@lezer/css@lezer/go@lezer/html@lezer/java@lezer/javascript@lezer/json@lezer/markdown@lezer/php@lezer/python@lezer/rust@lezer/sass@lezer/xml@lezer/yaml@marijn/find-cluster-breakcreltstyle-modw3c-keyname
For Melange, JavaScript interop may be used only behind typed OCaml interfaces when a temporary bridge is necessary. Native targets must not depend on a JavaScript runtime. Temporary interop does not satisfy final native parity.
The target covers public behavior in the upstream packages listed above within the modern scope defined in section 2.1:
-
State and text core
- Immutable text tree and text iteration
- UTF-16-compatible position semantics where required for upstream parity
- Unicode code point and grapheme cluster behavior
- Lines, columns, character categories
- Changes, change sets, change descriptions, mapping, inversion, composition
- Single and multiple selections
- Range values, range sets, range set builders, span iterators, comparators
- State effects and effect types
- Annotations and annotation types
- Transactions and transaction specs
- State fields
- Facets, facet readers, precedence, compartments, extension resolution
- Editor state construction, reconfiguration, updates, and command dispatch
-
View core
- Editor view lifecycle and configuration
- View plugins and update listeners
- Viewport computation and measurement
- Height maps, block information, line/block layout
- Decorations, widgets, mark/line/block decorations, atomic ranges, replace decorations
- Panels, dialogs, tooltips, hover tooltips, gutters, layers, placeholders
- Selection drawing, rectangular selection, drop cursor, active line, whitespace and special character highlighting
- Bidirectional text ordering and visual motion
- Coordinates, position measurement, scrolling, scrolling into view
- Theme computation and CSS-class semantics on web
-
Input and interaction
- Keyboard events, keymaps, scoped handlers, browser/macOS variants
- Typing and composition/IME behavior
- Selection by mouse/pointer, drag/drop, copy/paste/cut
- DOM mutation/input observation on web
- Native equivalents through explicit immutable input events
- Focus, blur, scroll, resize, and platform event ordering
-
Commands and history
- Every exported command and default keymap
- Cursor/selection movement and modification
- Insertion, deletion, line operations, comment toggling, indentation
- Undo/redo, event grouping, selection restoration, branch behavior
-
Language integration
- Language and sublanguage abstraction
- Incremental parsing, parse contexts, scheduling, tree access
- Syntax highlighting and highlight styles
- Folding, indentation, bracket matching
- Language descriptions and language data
- Official language package integrations
-
Search
- Search query normalization and compilation
- Literal, case-insensitive, regexp, whole-word behavior
- Search cursors and iterators
- Panel behavior, replace/replace-all, selection matching, go-to-line
-
Autocomplete
- Completion sources, contexts, results, async completion
- Filtering, ranking, matching, sorting, commit characters
- Completion state machine, tooltip interaction, apply semantics
- Snippets and snippet fields
- Close brackets and word completion
-
Lint
- Diagnostics, severity, actions, markers
- Lint sources, scheduling, gutter/panel/tooltip behavior
-
Collaboration
- Collab state, shared effects, rebasing, remote transaction application
-
Merge
- Diffing, presentable diffs, chunks, unified and side-by-side merge views
- Accept/reject chunk behavior and original-document updates
-
LSP client
- Typed JSON-RPC/LSP transport and workspace synchronization
- Server capabilities, request/notification lifecycle, cancellation and stale-response handling
- Position mapping, completion, diagnostics, hover, formatting, rename, and all upstream client behavior
-
Preset and themes
- The
codemirrormeta-package/basic setup behavior - One Dark theme
- Extension composition and ordering identical to upstream
- The
Upstream TypeScript source and tests are the source of truth. Documentation is informative but not sufficient when it conflicts with tested behavior.
Behavior is considered exact when all of the following match upstream for the same input sequence:
- returned values and public observation points;
- document and selection state after each transaction;
- extension/facet/effect resolution order;
- mappings and inverse mappings;
- event ordering and command outcomes;
- parse trees, highlight tags, indentation, folding, and language data;
- search/autocomplete/lint/collab/merge state transitions;
- visible layout decisions that are backend-defined, modulo documented font metrics;
- error cases and boundary conditions.
TypeScript APIs sometimes accept loosely shaped objects or JavaScript-null/undefined combinations. OCaml APIs should use precise variants, records, options, and phantom types. Where an exact dynamic JavaScript behavior cannot be represented directly, the OCaml API must provide a total typed equivalent and document the correspondence.
Upstream CodeMirror positions are UTF-16 string offsets because JavaScript strings are UTF-16. This is observable behavior and cannot be replaced arbitrarily with byte offsets or scalar-value indices. The core must either:
- store text in a representation that exposes upstream-compatible UTF-16 positions, or
- maintain a proven-correct mapping layer with no observable drift.
The chosen representation must be documented and covered by Unicode, surrogate-pair, grapheme-cluster, line-ending, and column tests.
Browser-specific behavior must be reproduced on Melange. Native behavior must preserve the same backend-neutral state transitions. Where upstream behavior depends on browser DOM selection, clipboard, IME, CSS layout, or font measurement, the native adapter receives explicit typed events/measurements and the core state machine must make the same decisions for equivalent inputs.
No behavioral difference is accepted merely because a platform lacks a convenient API. Missing platform capabilities are implemented in the adapter or upstream LUI rather than weakening the core contract.
- Mirror upstream CodeMirror's implementation modularization. Port package by package and preserve the responsibility boundaries of upstream source modules where feasible; do not recombine unrelated logic merely because it is convenient for one backend.
- OCaml module names and library boundaries should make the upstream TypeScript module correspondence obvious (for example
State,Text,Change,Selection,Rangeset,Facet,Transaction,Editorview,Heightmap,Decoration,Input). A justified merge or split must be documented indocs/parity-matrix.md. - Use immutable persistent data structures for document and editor state.
- Use regular variants for closed state machines and polymorphic variants only for controlled extension points.
- Use records for stable public configuration objects.
- Use
.mlifiles as readable contracts for every public module. - Use first-class modules only where runtime extension requires them.
- Use phantom types where object capabilities must be statically separated.
- Use GADTs for typed effects, annotations, facets, and extension values when they improve type safety without harming ergonomics.
- Use
Result.tfor recoverable failures and reserve exceptions for programmer errors. - Do not use
Obj.magicor unsafe type casts. - Do not disable compiler warnings.
- Avoid needless mutation; where mutation is needed for performance, hide it behind a pure interface.
- Keep implementation details private and expose only intentional API surfaces.
The repository is organized as a set of small composable libraries rather than one monolithic library:
packages/
state/ upstream @codemirror/state: text, changes, selections, ranges, transactions, facets
view/ upstream @codemirror/view: viewport, layout, decoration, input state machines, view state
language/ upstream @codemirror/language integration and parser interfaces
language-data/ upstream @codemirror/language-data language discovery catalog
commands/ upstream @codemirror/commands and history
search/ upstream @codemirror/search state machines and query engine
autocomplete/ upstream @codemirror/autocomplete state machines and snippets
lint/ upstream @codemirror/lint diagnostic state machines
collab/ upstream @codemirror/collab collaboration/rebasing logic
merge/ upstream @codemirror/merge diff and merge state
lsp-client/ upstream @codemirror/lsp-client
lang-*/ upstream language packages, one directory per package
codemirror/ upstream basic-setup preset composition
theme-one-dark/ upstream One Dark theme data
lezer/
common/ OCaml Lezer common runtime
lr/ OCaml Lezer LR runtime
highlight/ OCaml Lezer highlight runtime
platform/
melange/ DOM/Melange adapter
native/ native adapter interfaces and reference implementation
lui/ future LUI integration layer
test/
upstream/ ported upstream tests, organized by upstream package
parity/ cross-backend parity and golden tests
property/ property-based invariant tests
perf/ throughput, allocation, and memory-regression benchmarks
melange/ Melange compile/runtime smoke tests
native/ native-only adapter tests
docs/
specification.md this document
parity-matrix.md implementation and test coverage matrix
architecture.md detailed module contracts as they are implemented
Names may be refined only when the upstream package/module correspondence remains explicit. Convenience regrouping that hides upstream responsibility boundaries is not allowed.
The core has no dependency on DOM, browser JavaScript, LUI, UI toolkits, or native windowing. A backend adapter implements typed capabilities such as:
- text measurement and font metrics;
- layout invalidation and frame scheduling;
- keyboard/pointer/IME/clipboard event delivery;
- selection rendering and hit testing;
- panels, tooltips, gutters, layers, and widget host surfaces;
- scrolling and viewport measurements.
Melange and native implementations may differ in rendering technology, but consume the same backend-neutral view model.
CodeMirror's extension system is behaviorally central. The port must preserve:
- extension flattening and ordering;
- facet input collection;
- precedence resolution;
- compartment replacement;
- dynamic facet computation;
- state field initialization and update order;
- transaction filtering and appending.
The OCaml design should make extension values typed and introspectable, but must not erase information needed for exact ordering.
The TypeScript implementation uses dynamically typed values. The OCaml port should represent these using type-safe constructors with existential packaging only at controlled boundaries. Public extension authors must not be able to confuse effect, annotation, or facet payloads accidentally.
Melange uses JavaScript promises/callback behavior where upstream behavior requires it. Native uses explicit effectful schedulers or Eio-compatible abstractions behind small interfaces. Shared logic must not hard-code either runtime.
Performance and memory use are correctness-adjacent requirements, not optional polish:
- Persistent document structures must share unchanged nodes; editing a large document must not copy the whole document.
- Position/line lookup, insertion, deletion, replacement, mapping, and iteration must match upstream asymptotic behavior and avoid accidental quadratic algorithms.
- Incremental parsing, heightmap/layout updates, decoration indexing, search scanning, and viewport rendering must reuse prior work where upstream does.
- Hidden allocation hotspots must be minimized: avoid repeated string concatenation, repeated list append/concat on large inputs, unbounded closure capture, and retaining obsolete document/layout/parser snapshots.
- Cache boundaries must be explicit and keyed by immutable inputs; invalidation must be precise enough to avoid recomputing whole documents or whole layouts for localized edits.
- Public operations that necessarily scan a document must expose or document that cost; implementation must not introduce additional asymptotic cost behind convenience wrappers.
- Native and Melange implementations must include allocation/throughput benchmarks for large-document editing, selection/range mapping, search, parsing/highlighting, viewport updates, and undo history growth. Benchmarks must detect gross regressions even when precise cross-platform timing differs.
- Memory behavior must preserve correctness first: sharing and caching must never mutate visible immutable values or lose lone-surrogate/UTF-16 semantics.
Every meaningful upstream test in the supported scope must be represented
in this repository. A test may be omitted only when all of the following
are documented in docs/parity-matrix.md:
- the precise upstream test name/file;
- why it is not meaningful in OCaml or on a particular backend;
- what equivalent invariant is covered instead;
- approval of the divergence.
Tests must not be weakened to fit implementation bugs. If upstream and implementation differ, implementation is wrong unless the user explicitly approves a documented divergence.
- Direct upstream ports: one-to-one behavioral cases organized by upstream package and file.
- Invariant/property tests: text/change/selection/range mapping round trips and metamorphic properties.
- Cross-backend parity tests: same transaction/event scripts run through Melange and native adapters with identical observable outputs.
- Melange compile and runtime tests: verify generated JavaScript and DOM interaction in a browser-like environment.
- Native tests: verify backend-neutral state machines and native adapter behavior without a JavaScript runtime.
- Integration tests: full editor scenarios including typing, selection, IME-like composition, search, autocomplete, lint, language parsing, undo/redo, collaboration, and merge.
- Regression tests: every discovered divergence gets a failing test before its fix.
The repository must eventually support at least:
dune build @all
dune runtest
dune build @melange-tests
dune build @native-testsExact commands may be refined in the implementation phase. CI must run both native and Melange verification.
Implementation is parallelized with child Devin sessions. Work is split only along boundaries that can be independently developed and merged.
- This specification.
- Repository licensing, README, agent guidance, Dune project skeleton.
- Test harness and parity matrix.
- Exact upstream reference inventory.
- Text representation and Unicode semantics.
- Changes, selections, ranges.
- Transactions, state fields, effects, annotations.
- Extension/facet/compartment system.
- Direct upstream state tests.
- Decorations and height maps.
- Viewport and layout state.
- Input/selection command state machines.
- Panel/tooltip/gutter/layer models.
- Backend adapter interface.
- Lezer interfaces and required OCaml runtime.
- Language abstraction, incremental parsing, highlighting.
- Folding, indentation, bracket matching.
- Commands/history.
- Search.
- Autocomplete/snippets/close brackets.
- Lint.
- Collab.
- Merge.
- Preset/basic setup/theme.
- Port the modern portion of the pinned language-data catalog with the same ordering, names, aliases, extensions, filename predicates, and loader selection. Use the language core's description types and matching algorithms on lossless UTF-16.
- Construct the catalog with a host-selected asynchronous type and an optional loader from a typed language request to language support. Hosts can use the bundled modern providers or supply their own. A missing provider returns a typed error naming its request. Loads remain lazy, share a pending operation, cache success per description, and can retry a recoverable failure.
- Port or generate OCaml implementations of upstream language package integrations.
- Implement or port required Lezer grammars.
- Port language tests and parser golden tests.
- Melange DOM adapter.
- Native adapter reference implementation.
- LUI integration layer.
- Cross-backend parity harness.
After the editor is functional, a separate simple Lettera-like editor experience may be built using LUI and codemirror-ml. It is not an Obsidian clone. Its detailed product scope must be informed by direct research of Lettera and, secondarily, Bear's Markdown editor.
Each child session must receive:
- the exact user requirements;
- the relevant section of this specification;
- the upstream baseline commit/package;
- a narrow module or package ownership boundary;
- an explicit deliverable: branch/PR, tests, report, or adapter implementation;
- a prohibition against weakening tests or hiding parity failures.
Shared foundational types are owned by the coordinator until stabilized. Children may implement independent leaf packages in parallel once those contracts exist.
The port is complete only when:
- every public upstream API in scope has an OCaml typed equivalent or a documented intentional API difference;
- every meaningful upstream test in scope is ported and passing;
- behavior parity is demonstrated for native and Melange;
- language integrations pass parser/highlighting golden tests;
- core editor scenarios pass end-to-end tests on both backends;
- large-document performance and memory benchmarks demonstrate persistent-structure sharing, incremental updates, bounded allocation, and no accidental quadratic behavior;
- documentation accurately describes module boundaries, parity status, and remaining platform caveats;
- no compiler warnings are disabled and no unsafe casts are used;
- CI validates native and Melange builds/tests.
Until all criteria are met, the README and parity matrix must state the exact incomplete areas rather than implying full parity.
Upstream CodeMirror is MIT-licensed. This repository must include the MIT license text and upstream copyright attribution. Source files that are close ports of upstream implementation logic should carry appropriate attribution comments. Clean-room architectural documentation may credit upstream as the behavioral reference.
This document is the required pre-implementation specification. No implementation is yet claimed. The initial work after this specification is scaffold creation, detailed inventory consolidation from parallel research sessions, and implementation of the state/text core.