Skip to main content
docs/internals/architecture

Architecture

The shared C++ core, the platform layers and threads, the tree-sitter binding and the Nitro layer.

Edit this page

The editor engine is one C++ core under cpp/core, shared by Android and iOS. It holds the document, the selection, undo, the editing commands, decorations, search, the tree-sitter parsing and the rows and scroll of the layout, behind a C API that Kotlin calls through JNI and Swift calls directly. Each platform keeps its own view, line layout, input and drawing, in Kotlin and in Swift, with the same layers and the same names, and it is bound to React Native through Nitro Views. The TypeScript wrapper, the core, the tree-sitter runtime, the grammars and the test vectors are shared.

Why CodePad has its own engine​

A TextInput is one field stretched over a document: no gutter, no horizontal scroll, no control over undo and a layout of the whole text on every edit. A WebView pays a bridge and a second runtime per keystroke. The core stores the document, and each platform draws it through its own text layout API (StaticLayout on Android, Core Text on iOS), one visible line at a time. The soft keyboard talks to it through the platform's input protocol, so composition, suggestions and swipe typing work as in any text field.

Layers​

Under me.sectiontn.codepad in android/src/main/java:

LayerHoldsDepends on
coreEditorCore, Document, UndoManager, DecorationSet, TextMovement, Searcher and EditorFrame, thin Kotlin facades over the C++ core.CoreNative
inputImeSession, the keyboard protocol, and KeyCommands, the hardware key table.core
syntaxSyntaxEngine and its thread, CoreNative, the JNI binding to the C++ core, LanguageRegistry, Highlighter, the per line span cache.core
layoutLineLayout over StaticLayout, LayoutCache, Viewport (the facade over the core's layout), CaretMover, GutterMetrics.core, syntax
viewCodeEditorView: drawing, gestures, scrolling, the input connection, handles, the edit menu, the keyboard inset tracker.every layer before it
com.margelo.nitro.codepadHybridCodeEditorView and HybridCodepad, the Nitro layer.view

The core runs tests/vectors/*.json on the JVM and under swift test. The keyboard protocol replays recordings: tests/ime/*.json from real Gboard sessions through ImeSession, and tests/ime-ios/*.json from the iOS keyboard through MarkedTextSession. A keyboard bug gets a recording before a fix.

core​

The document is immutable UTF-16 text in shared chunks, plus a table of line starts. An edit builds a new text that shares every chunk outside the edited range. A parse or a reader on another thread goes on reading the version it started with, and an edit copies only the chunks it changes. \r\n and a \r on its own become \n on load. One replacement is the only mutation. The main thread prepares it outside the lock and commits it under the exclusive lock. A draw reads the document in one call, cp_editor_frame: the core's layout picks the visible lines, and the call returns the selection, their starts, and the lines to lay out with their spans and text. Undo groups hold the inverse changes plus the selection before and after. Single character typing merges into the previous group when it is adjacent, within a second and not a newline. API edits never merge with typing.

syntax​

The parsing and highlighting run in the same core. One serial thread per editor holds the parser and the live tree. It applies each edit, reparses incrementally, reconciles the injected trees against the ranges tree-sitter reports as changed, and publishes an immutable snapshot to the main thread. The first parse of a large file runs with a time budget and resumes, and an edit during a parse is replayed onto its tree once it finishes.

The main thread queries the published snapshot for the visible lines only and caches the spans per line. A snapshot lists the regions whose structure changed, so the painter re-queries only the visible lines inside those regions. Overlapping captures apply in pattern order and the later pattern takes precedence, which is the rule nvim queries are written for.

layout​

LineLayout turns a line into a StaticLayout at the wrap width. The row height is uniform, round(fontSize * lineHeight), so a fallback font for emoji or CJK never changes it. The core's layout stores a row count per line, with unmeasured lines counting as one, the gap rows under decorated lines, and the scroll. Edits update the rows inside the core before the change callback runs. Viewport is the facade over it. Once the view has laid out the frame's lines, one more call, cp_layout_measure, records their row counts and the widest line. It returns the view top of each visible line, their rows and every gap, and the painters read that copy until the draw ends. A draw makes these two core calls, and a fling frame makes one scroll call. LayoutCache is an LRU around the viewport. Only a wrap width change drops it, and the scroll is then re-anchored to the top visible line.

view​

CodeEditorView is an android.view.View with an input connection, so the input method treats it as a text editor. It draws in this order: background, active line, search matches, bracket pair, selection, text, composing underline, gutter, caret, handles, placeholder. The view blocks its parent from intercepting touches only when it can scroll in the drag direction, which lets a parent ScrollView take over. Its input connection is a BaseInputConnection subclass over the document. The keyboard inset tracker registers a window insets animation callback when avoidKeyboard is on.

The same layers in Swift​

ios/Codepad/ mirrors the Kotlin layers file for file:

LayerHoldsDiffers from Android
coreThe same facades over the C++ core, plus BracketMatcher.Swift calls the C API directly, with no JNI.
inputKeyCommands with the Mac modifiers, GestureMachine, MarkedTextSession (the UITextInput composition logic).A long press places the caret under the loupe, a triple tap selects the line.
syntaxSyntaxEngine on a serial queue, LanguageRegistry, Highlighter, SearchController.No JNI: Swift calls the core's C API directly.
layoutLineLayout over Core Text, ThemeColors as CGColors, the rest one to one.Tests on macOS.
viewCodeEditorView, a UIScrollView. TextInputView, the UITextInput conformer. The recycled LineLayers, the highlight, cursor and handle views, the gesture recognizer, the edit menu, the keyboard inset tracker and the undo manager bridge.UIKit, on the main actor, tested by XCTest on the simulator.
nitroHybridCodeEditorView and HybridCodepad.Nonisolated for the JS thread's readers. View work hops to the main actor.

The pure layers compile as a Swift package at the repository root, with the tree-sitter runtime and the twenty-two grammars as C targets and the core with PCRE2 as one more target, so swift test runs the vectors, the syntax and layout suites and the keyboard replays on macOS in seconds. The pod compiles the same files plus view and nitro. Both use the Swift 6 language mode.

The view is a UIScrollView whose content view conforms to UITextInput over UTF-16 offsets, so the system keyboard, dictation, autocorrect and hardware keys talk to the document directly. The visible lines are recycled CALayers drawn through Core Text, keyed by the line's and the snapshot's revision. The selection UI is a UITextSelectionDisplayInteraction with the editor's own highlight, cursor and handle views, which is what lets the theme's selection and cursor apply exactly. The loupe is a UITextLoupeSession, the edit menu a UIEditMenuInteraction, and undoManager a Foundation UndoManager subclass over the core's groups. The scroll view's contentInset is never used, so contentInsets, the keyboard inset, scrollToLine and onContentSizeChange keep the Android semantics. Keyboard avoidance reads a tracking view pinned to the window's keyboardLayoutGuide through its presentation layer on every frame.

Threads​

ThreadDoes
MainMutates the document, selection and layout, holds the keyboard state, draws
JSSync readers under the read lock, receives events
Syntax, one per editorParses, runs injections, publishes snapshots, and runs search on iOS
Search, one per editor, Android onlyRuns search over a snapshot of the text

The document lock is the core's std::shared_mutex. The main thread is the only writer and holds it exclusively only while it commits a change. Writers from JavaScript post to the main thread and resolve after the change is applied, so a detached view still resolves them.

The tree-sitter binding​

The runtime is tree-sitter 0.26, vendored into the core library with hidden symbols. A generated parser.c is self contained, so language packages never link against the runtime. The binding works in UTF-16: the input is UTF16LE and byte offsets are halved at the boundary, so Kotlin and Swift see the offsets JavaScript uses. The parser's read callback reads the document's chunks in place, and a parse never calls back into the JVM. Predicates (eq?, match?, any-of?, contains?, has-parent?, has-ancestor? with their not- and any- forms) are evaluated in the core, with match? on PCRE2, and lua-match? patterns become regular expressions at generation time.

Injections and kept trees​

The host tree's injection query yields ranges with a language. The name is converted to lowercase and aliased, #offset! trims columns, injection.combined ranges form one tree, children are always included, and injected trees do not run their own injection query.

Injected trees survive across snapshots. The engine keeps each one with the hull of its match and its extent, plus a copy of the host tree from the last completed pass. An edit goes to the reference tree and, by arithmetic, to the hulls and extents. A kept tree takes an edit only when the edit reaches it, and an edit before it accumulates as a shift the painter reads through. After a host reparse, ts_tree_get_changed_ranges gives the regions whose structure differs, the edits' own spans are added, and the injections query runs over those regions only. A kept tree the regions meet reparses against its old tree, and every other tree is carried over with no parser call. The first pass after setText or a language switch covers the whole document.

The Nitro layer​

HybridCodeEditorView owns one CodeEditorView, diffs incoming props into setters, wires the callbacks and forwards the methods. Sync readers take the document read lock on the JS thread. getCursorRect() and getVisibleLines() read a layout snapshot the main thread publishes after each layout pass. The wrapper fills in the defaults, wraps every callback once and normalizes theme.tokens into { color, bold, italic } structs.

HybridCodepad.availableLanguages() lists the marker files under assets/codepad-languages/ on Android and scans the class list for CPLang classes on iOS. The registry loads a language by name, checks its ABI against the runtime, compiles its queries once and caches the result for the process.

Conventions​

  • UTF-16 offsets, half open ranges and 0 based lines and columns, in Kotlin, Swift, the parser and JavaScript alike.
  • An unknown or failed language is one warning and plain text. Ranges clamp and swap. Methods called before onReady operate on the empty document. Only a regular expression that does not compile throws.
  • Native never emits events from prop setters during the first batch, and object props are compared by identity before they cross.