# Architecture ## Components | File | Responsibility | | --- | --- | | `src/index.ts` | Registers settings, content scripts, the welcome command, clipboard messages and the native formatting dialog. | | `src/renderer.ts` | Styles supported Markdown fences, highlights code, adds controls and preserves Joplin round-trip metadata. | | `src/viewer.ts` | Handles Copy, Wrap and Format in rendered notes, including Rich Text application and Undo behavior. | | `src/languagePicker.ts` | Adds searchable language choices to the native TinyMCE code-source dialog. | | `src/editor.ts` | Registers the Markdown editor command that applies formatting through the active editor. | | `src/editorCards.ts`, `src/editor.css` | Opt-in CodeMirror 6 card widgets, source reveal, source toggle and editor styling. | | `src/readingPosition.ts` | Temporary visible-code-row hand-off between Markdown and Rich Text, without note edits. | | `src/replaceFence.ts` | Locates and validates the selected fence against the current document before replacing its code. | | `src/formatLanguages.ts` | Maps explicit language labels and aliases to formatter engines. | | `src/formatCode.ts` | Runs bundled formatters and loads their packaged WASM assets. | | `src/formatBasic.ts` | Preserves retro BASIC statements while aligning line numbers and indenting recognised blocks. | | `src/retro.ts`, `src/retro.css` | Maps machine-specific BASIC labels to local fonts/palettes and reads/writes the per-fence `retro` flag. | | `src/code-studio.css` | Dark cards, font, line numbers, wrapping, sticky toolbar and print styling. | | `src/formatPreview.ts` | Builds the escaped, aligned Original/Formatted comparison and change highlights. | | `src/formatDialog.ts` | Links vertical scrolling in both preview panes, including after reopening the dialog. | | `src/formatDialog.css` | Comparison layout, line numbers, change colours and typography. | | `scripts/build.mjs` | Bundles runtime code, copies assets and licences, and packages the Joplin installer. | ## Rendering and copying The Markdown-it content script renders ordinary fenced code blocks as dark cards. Diagram fences are delegated to Joplin or their own plugins. Highlight.js supplies syntax colours; multiline highlight spans are split into balanced visual rows. The plugin bundles JetBrains Mono. Line numbers and controls are presentation elements. The hidden `joplin-source` element retains the original code and the opening/closing fence metadata Joplin needs when converting Rich Text back to Markdown. Copy reads the source text and asks the plugin process to write it to Joplin's clipboard API. The toolbar uses sticky positioning within the card. `overflow: clip` on the card allows it to remain visible while the note scrolls; print styling returns it to a static position. The live status element sits inside this non-editable toolbar. Formatting feedback appears on its own wrapping row below the controls, keeping “Already formatted” and errors visible on long blocks; empty feedback occupies no row. Print styling hides feedback. Machine-specific BASIC blocks also have a checkbox button for Retro display, using the same capture-phase mouse and keyboard handling as other controls. Its `retro` flag is stored in the fence info, outside the code; quoted filenames containing that word are not flags. Markdown uses the existing editor command with an optional replacement info string. When only metadata changes, `replaceFence` validates the current target and replaces just the opening line, preserving code bytes, container indentation, line endings and other blocks. Rich Text updates `data-joplin-source-open` and the generated card in one TinyMCE Undo transaction, then signals the normal save events. Undo/Redo refreshes the checkbox, info and palette from the restored source metadata. Read-only editors reject toggles. Joplin's native source dialog replaces only an editable block's inner HTML, leaving the outer card's data attributes stale. The hidden source's `data-joplin-language` and opening fence are authoritative: the viewer synchronises the outer language, info, checkbox and palette before Retro/Format actions, on initial load and on `joplin-noteDidUpdate`. This prevents a language edit or stale tick state from making a toggle fail or restoring the previous language. The native dialog and Undo transaction paths remain unchanged. The renderer and native comparison dialog load the same `retro.css` and 19 registered font files, including five named CC BY-SA geometry/spacing variants. The palette is applied to the code surface; Macintosh captions also use Chicago. Cards hide their generated gutter and suppress syntax colours in retro mode; comparison panes retain line numbers, change highlights and aligned rows. Generic BASIC has no machine profile. The original font licences, notices, provenance and hashes ship under `retro-fonts/`; no font is downloaded or installed at runtime. BBC mode choices use a whitelisted standalone `retro-mode=` field, independently of the `retro` flag. The selector is hidden when the checkbox is off; its saved value remains. Both the host message boundary and shared metadata helper reject unknown modes. TinyMCE mode changes use the same transaction path as checkbox changes; Undo/Redo rebuilds the selector and data attributes from source metadata. Capture handlers stop editor gestures on the native select without preventing its normal mouse/keyboard behaviour. The comparison receives the same validated mode. Font variants have genuine advance widths, avoiding transformed text that would break wrapping and horizontal scrolling. Mode 6 gradients use local scrolling backgrounds and the same row pitch in cards and comparisons. Mode 6 surfaces omit the usual screen border and vertical padding, so the first text row begins immediately and black gaps span the width instead of stopping at coloured side gutters. Paper occupies 1em and the gap 0.25em of each 1.25em row; the bands remain aligned while scrolling and scaling the font. ## Markdown editor cards `renderInEditor` defaults to false. The CodeMirror content script requests the current display settings through its message context; settings changes are also sent to the active editor. A revision guard prevents a late initial reply from overriding newer settings. Editor commands and assets remain separate from the viewer event handlers. A CodeMirror StateField parses the current document with the existing Markdown-it dependency when enabled and the document changes. Parsing is skipped while the feature is disabled or all-source mode is active; returning to cards parses the current document. Fence maps locate complete blocks, preserving the same fence indexes used by `replaceFence`, including diagram fences. Decorations replace eligible, unselected fences with block widgets. Widget DOM uses the unchanged renderer rule and its escaped source, settings, highlighting and retro metadata. Highlighting runs when CodeMirror creates the widget DOM, rather than on each selection change. Unclosed fences, diagrams and blocks above 500,000 characters remain source. Cursor/selection overlap reveals a block. Edit source and double-click move the native cursor into its content, retaining container prefixes. The source toolbar is a native CodeMirror top panel, so Format and View code card remain reachable when document virtualisation removes distant source lines. It follows the current block and refreshes its formatting target after edits. A low-precedence Escape binding runs after native search/selection handlers; focused panel controls also pass modified editor shortcuts through CodeMirror's editor scope. An explicit preview effect records the current selection object, allowing cards to return without moving the caret or adding text after a final fence. Enabling cards on a newly attached editor applies this preview to Joplin's restored caret. Subsequent selection changes and typing clear it. Clicking another card, the editor's blank space, or outside the editor also finishes source editing when no text range is selected. Blur handling is queued outside the view update and ignores focus within the editor's controls. The opening and closing source lines receive `cs-source-line` decorations. Their scoped CSS restores Joplin's `.cm-hidden` CodeMark spans, which otherwise hide fence backticks on inactive lines. Other Markdown markup and preferences are unchanged. A high-precedence arrow event handler reveals a neighbouring card before the ordinary vertical movement binding runs, preventing a block widget from being skipped. Modified keyboard shortcuts still reach CodeMirror from focused card controls; unmodified control keys retain native button/select behaviour. Opening editor search reveals all source. Returning through the session source toggle also previews the current block. These display effects leave the document and history untouched. No atomic ranges or replacement editing surface are introduced. Copy, Format and retro changes use the same validated host handler as the renderer through `context.postMessage`. Formatting still opens the native comparison; Apply and retro changes use `codeStudioFormatApply`, the current document check and CodeMirror's native history. The legacy editor's existing formatting command remains unchanged. Read-only widgets disable editing controls. Pending settings replies are ignored after editor destruction. The source toolbar's Format button and the assignable `codeStudioFormatCurrent` command reuse that host formatting path. The command parses the current document on demand, so it also works when cards are disabled or the all-source toggle is active. It requires a single selection contained in one complete, eligible fence with an explicit supported formatter. A pending source preview suppresses blur-based card return; completion restores editor focus only if the same note is still open. Applying formatting keeps a single caret on its previous physical line/column, clamped to the final content line when formatting removes rows; the replacement and selection form one native Undo transaction. Per-block view memory belongs to the current editor instance. It records the relative source row/column, source scroll offset, caret's viewport offset, card horizontal scroll and wrapping override. Double-click uses the rendered row number; Edit source uses the saved position. CodeMirror changes map block positions through ordinary edits, dropping deleted anchors; our formatting replacement retains its anchor. Joplin's note ID facet clears memory when notes change, including identical-text notes. No note metadata, settings or disk state are added for this memory. Joplin 3.7.22's CM5-compatible `lineAtHeight`/`heightAtLine` methods map a replacement widget to one line. When these methods exist, the editor integration supplies measured code-row boundaries inside our own card widgets and delegates all other positions to the original methods. Widget estimates cover cards not yet in the DOM. Returning to a card and changing display settings restore the visible source row after CodeMirror's layout/scroll anchoring completes. The original compatibility methods are restored on editor destruction. Rich Text stores a pixel percentage while Markdown uses a source-line percentage, so percentages alone cannot provide a reliable cross-editor hand-off. With editor cards enabled, deliberate reading/editing movement records the visible fence index, exact source/info, row and fractional row offset through the existing local message channel. The host keeps the latest reading anchor, regardless of which editor last wrote it: a return without intervening scrolling must still restore that anchor. It separately retains the latest Markdown card/source/all-source choice and an exact-block-checked caret offset. Rich Text movement preserves that Markdown choice. A temporary blur preview leaves editing intent intact; its next-frame display update lets position capture finish before editor disposal. Source restoration applies its native caret and viewport without changing note text or Undo. Explicit card return clears source-editing intent. Reading and view-state messages validate note IDs, source bounds, mode names, offsets and numeric fields. Movement is debounced, pending movement is flushed outside view updates on focus loss, and outgoing-editor scroll resets are ignored once focus is lost. Scroll events are followed only after deliberate input; early input is saved after initialisation instead of being lost. Rich Text attachment is retried through the existing late-editor hooks. Refresh revisions, note checks, destruction guards and user-interaction checks prevent late initialisation from jumping an editor the user has already moved. Ordinary display-setting changes preserve the current viewport rather than restoring an old hand-off. The normal rendered Markdown viewer does not participate. These anchors and mode choices remain in memory for the app session. `sourceLineNumbers` is a separate persisted preference, defaulting to false. The source-toolbar checkbox and settings entry update that same key. A native CodeMirror gutter numbers code rows relative to each complete eligible fence, excluding opening/closing markers and prose. Native line blocks handle wrapping and selection; the gutter cannot enter copied text or Undo. Cards retain their existing independent line-number preference. Source numbering also works with cards disabled or all-source/search views; the shared fence field parses those cases only when the gutter needs it. The gutter is hidden when no source is displayed, and its spacer reserves the required digit width. No Joplin-wide line-number preference is changed. CodeMirror modules are external to the packaged JavaScript and loaded only when the CM6 integration is attached, using Joplin's own `require`. Development dependencies supply types and the real browser editor used by tests. The build bundles shared styles and local font bytes into `dist/editor.css`, then embeds that text as the editor script's inline CSS asset. This avoids relative font URLs and the native file-asset loading path. The standalone generated stylesheet is not duplicated in the installer. The viewer's stylesheet, font assets and event script are unchanged. ## Language chooser The renderer exports a catalogue assembled from its existing labels, Highlight.js language names/aliases and explicit formatter labels. Entries are grouped by case-insensitive display name, with a primary spelling chosen from the formatter labels first, then Highlight.js canonical names. Other spellings are stored as searchable aliases instead of repeated rows. Catalogue-only names distinguish JSONC/JSON5, XHTML and Zsh, and consolidate the C64 and Dragon 32/64 synonyms. Shell-session highlighting remains separate from POSIX shell scripts despite Highlight.js using the canonical name `shell`. The build embeds this catalogue in the viewer bundle using an esbuild define; the viewer does not import Highlight.js or fetch another asset to populate the list. In Rich Text, the viewer registers a TinyMCE `OpenWindow` listener once per editor. Attachment is attempted when scripts load, on the next animation frame, and on editor focus/double-click so late initialisation is covered. The listener recognises the native code-source dialog by its `languageInput` and `codeTextArea` data fields, then augments its existing enabled Language input. Unrelated dialogs, read-only/disabled fields and inputs already owning a datalist are untouched. The listener is removed when the iframe unloads. The combobox/listbox uses the parent document and TinyMCE menu classes. Filtering/ranking matches primary values, display names and aliases. Directly typed aliases are accepted without being expanded to the primary value; inline completion also recognises those spellings. Native browser datalist navigation conflicted with TinyMCE’s dialog keyboard handling, so a local suggestion list handles only navigation/selection keys. Selection calls the dialog’s public `setData` API for `languageInput`; code, OK/Cancel, submission and note/editor transactions remain owned by Joplin. The list stays closed on attachment/focus. In the closed field, ordinary text insertion can complete a language-value prefix through `setData`, selecting only the suggested suffix. Exact aliases, deletion, paste, composition and edits away from the end do not trigger replacement. Enter accepts the suffix without submitting; Escape restores the typed prefix. Consumed navigation/selection keys also consume their matching keyup because TinyMCE handles dialog Escape on key release. Explicit arrow-button/keyboard opening exposes the list, where typing filters language names and aliases. A label without a match can still be submitted as typed. This integration relies on the [native code-dialog structure](https://github.com/laurent22/joplin/blob/v3.7.22/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/utils/useEditDialog.ts) verified against Joplin 3.7.22 / TinyMCE 6.8.5 and the [TinyMCE dialog events](https://www.tiny.cloud/docs/tinymce/6/events/#openwindow); a changed dialog structure safely retains the ordinary field. It does not alter Markdown autocomplete. ## Formatting Only an explicit supported language label enables Format. Automatic highlighting guesses do not select a formatter. Code is limited to 500,000 characters for this operation. The viewer sends the original code, language, fence info and fence index to the plugin process. It formats locally and opens Joplin's native preview dialog. Cancel and the two Copy actions do not edit the note. Apply checks that the selected note has not changed, then uses the appropriate editor path. The comparison uses whitespace-free line keys for alignment only, so changed indentation and interior spacing remain paired. Exact raw text determines character-level highlights using bundled jsdiff. Unique matching lines anchor the comparison before jsdiff aligns the intervening regions. Added/removed lines have hatched partner rows, keeping both panes the same height; vertical scroll events in either pane move the other. Horizontal scrolling remains independent. Both panes have neutral black backgrounds, with grey removed text and green added text. Changed spaces/tabs receive visible `·`/`→` overlays that retain their original widths; added/removed line breaks use `↵`, missing final line breaks use `∅`, and carriage returns use `␍`. The dialog script uses a single delegated listener that survives HTML replacement. Common leading/trailing lines are aligned first. Line comparison has a shared 200 ms budget and a maximum edit distance of 4,000 within each gap between unique anchors. If a gap exhausts the budget, only that gap uses positional pairing; subsequent anchors remain aligned. Character highlighting has a separate shared 200 ms budget, with at most 20 ms and 2,000 edits per line; exhausted regions receive a broader highlight. All source lines, including their final newline state, are preserved. Copy/Apply use the raw strings rather than comparison markup, whitespace symbols or padding rows. The dialog script is packaged and loaded through Joplin's `dialogs.addScript` API. - **Markdown:** the custom editor command reads the current document, verifies the target, and replaces only the matching fence through an editor transaction. The replacement preserves container prefixes, fence boundaries and surrounding text, and re-parses the result for validation. - **Rich Text:** the viewer uses TinyMCE's Undo transaction to update the hidden source, fence metadata and highlighted rows, then signals `joplinChange` and `nodeChanged` so Joplin saves the edit. Rich Text detection uses the parent window's TinyMCE instance. The iframe's `tinymce` property can be shadowed by a DOM element. Avoid changing a Rich Text Format button's disabled state while opening a preview: TinyMCE can capture generated button state in its Undo snapshots. The viewer also resets transient controls on Undo/Redo. Toolbar clicks are handled during document capture, before the editor's block-selection handlers. Mouse down/up and double-click events on toolbar controls are consumed so selection cannot replace the clicked control or open the source editor. The code itself retains Joplin's normal source-edit gestures. Keyboard controls use the same capture approach. Joplin's [Rich Text source-edit listener](https://github.com/laurent22/joplin/blob/v3.7.22/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/utils/useEditDialogEventListeners.ts) handles double-clicks inside `joplin-editable` blocks; its handler does not exclude plugin toolbar buttons. ## Formatter engines - Prettier: JavaScript, TypeScript, JSON, web templates/styles, YAML, Markdown and GraphQL, with plugins for XML, TOML and PHP. - Ruff WASM: Python, four spaces and preserved quote style. - shfmt WASM: Bash/POSIX shell, two spaces and no simplification. - gofmt WASM: standard Go formatting. - clang-format WASM: C-family languages and Protocol Buffers. - SQL Formatter: the supported SQL dialects. - StyLua WASM: Lua, two-space indentation and no require sorting. - Dart WASM: dart_style; version 0.3.0 is pinned because 0.4.0 failed a basic valid-input probe. - Scalar rustfmt WASM: Rust 2021, with import and module reordering disabled. The browser entry accepts explicit packaged bytes; its compressed artifact is expanded at build time, so runtime decompression/downloads are unnecessary. WASI exposes only an in-memory work directory. - dprint WASM: Dockerfile and Terraform/OpenTofu/HCL, initialised from packaged bytes with no external processes. - Prettier PowerShell: PowerShell 7 layout, with token/literal preservation checked before returning output. It retains aliases, cmdlets, hashtable order and keyword case; it rejects synthesised delimiters rather than repairing malformed code. - Local BASIC layout formatter: generic BASIC, BBC, Sinclair, Commodore V2, Locomotive, Applesoft, GW-BASIC, QBasic, Atari BASIC, AMOS, Macintosh Microsoft BASIC/QuickBASIC, STOS/GFA, MSX, ZX81, Dragon, Archimedes and Oric Atmos. It changes only leading layout whitespace and normalises line endings. It does not parse/execute programs or change statement boundaries, casing, data or program numbers. Indentation is bounded and overlarge output is rejected. Formatter initialisation promises are cached per asset, so concurrent first requests share a load. Failed initialisation is removed from the cache for retry. HCL has a local Highlight.js grammar, including heredocs; BASIC dialect labels use generic BASIC syntax colouring. See the README for labels and aliases. None of these engines executes code, and no formatter makes network requests. Syntax rejection varies by formatter; this feature is not a compiler or semantic validator.