@barocss/math-editor-text
v0.2.4
Published
LaTeX source editing text integration for Barocss math editor.
Readme
@barocss/math-editor-text
Shared LaTeX range detection and a DOM editing popup for text-editor integrations. This package does not parse shader code.
npm install @barocss/math-editor @barocss/math-editor-textimport { resolveMathRange } from '@barocss/math-editor-text/ranges';
const source = 'Energy: $E=mc^2$.';
const range = resolveMathRange(source, { from: 11, to: 11 }, 'markdown');Packages
| Package | Host |
| --- | --- |
| @barocss/math-editor-codemirror6 | CodeMirror 6 extension |
| @barocss/math-editor-codemirror5 | CodeMirror 5 attachment |
| @barocss/math-editor-monaco | Monaco web editor attachment |
| Barocss Math Editor VS Code extension | Separate Webview and public document-edit API |
Import @barocss/math-editor/style.css and @barocss/math-editor-text/style.css with a browser adapter. The core and host editor remain external dependencies. No KaTeX installation is needed for the editing popup itself.
Editing contract
- Place the caret within a delimited formula, then click Edit formula or press Alt+Enter (Option+Enter on macOS).
- A nonempty selection can contain bare LaTeX. It must parse successfully before the editor opens.
- Opening the affordance does not move keyboard focus. Explicitly opening the popup does. Once open, it follows the source caret between formulas without taking focus. It hides outside math and resumes at the next formula until Apply or Cancel.
- Switching formulas keeps their unapplied drafts for the current source version. Returning to a formula restores its draft. Apply changes only the current formula; If other drafts remain, Apply or Cancel first shows a warning. Choose the explicit discard button to finish and clear them, or return to those formulas. Repeated Enter/Escape does not confirm discarding.
- Apply replaces the expression and preserves its leading/trailing whitespace, including delimiter line breaks, blank lines and indentation. Dollar and backslash delimiters remain intact. New serialized rows use the original CRLF/LF convention.
- Cancel and an unchanged Apply leave the original bytes and history untouched.
- A changed Apply is one host undo step. The host receives focus after Apply or Cancel.
- Any source edit or document switch invalidates an open draft, including edit-then-undo. An external change while popup editing still blocks Apply. Returning to the source caret reloads the current formula from the new source; old-version drafts are not restored. Drafts are not rebased onto concurrent changes.
- Read-only documents cannot apply changes. Destroy the attachment before removing a CodeMirror 5 host. CodeMirror 6 and Monaco clean up with their host lifecycle.
- The visual popup starts at 125% editing zoom. Choose 100%, 125%, or 150% in its header. The browser remembers the choice for later popups on the same origin. Zoom changes only the editing formula, not LaTeX, document size, source preview, buttons, or suggestion menus. If browser storage is blocked, the choice lasts for the controller lifetime.
- Popup key events remain inside the math editor. Its suggestions, selection, help, clipboard, and root transformations use the existing DOM editor.
Supported source detection
syntax: 'markdown' (default) recognizes $…$, $$…$$, \(…\), \[…\], and a bounded list of equation, alignment, cases, and matrix environments. It skips ordinary fenced code, inline code, indented code lines, and HTML comments. Single-dollar ranges cannot cross a newline and use conservative whitespace/currency rules.
syntax: 'latex' also skips percent line comments and common \verb, verbatim, lstlisting, and minted literal constructs. Detection does not imply parser support: an unsupported environment or command is rejected without modifying the source.
The scanner is not a complete Markdown or TeX parser. Custom macros, custom literal environments, nested Markdown containers, and dialect-specific delimiter rules need a host resolver. Hosts can disable automatic discovery for those documents or supply resolveRange(source, selection) using their syntax tree. Returning undefined suppresses the fallback scanner.
All offsets use UTF-16, and a range contains from, to, contentFrom, contentTo, and display. Environment ranges currently include their complete source, so an edited environment can be normalized by the math serializer. LaTeX comments, whitespace and aliases inside a changed formula are not preserved as source tokens.
Configuration
TextMathOptions accepts sourceEditing, visualZoom, syntax, locale, messages, resolveRange, onError, and toolbar. English and Korean labels are provided. Other locales can override the message dictionary and use the core's locale registration API for math-editor labels. Hosts should display onError in a visible status area.
createTextMathController(host, options) is the low-level interface. Selection uses
ordered from/to offsets and an optional head offset for the active end. This
places the menu at the active end of reverse selections. The host supplies source text, a monotonically changing revision, selection, caret coordinates, editability, focus, replacement, and focus restoration. Call refresh() on selection, document, layout, and read-only changes. Call destroy() to release document listeners and popups.
visualZoom: 100 | 125 | 150 sets the initial magnification instead of the saved preference. Set --me-text-editor-font-size to change the 100% base size (default 22px). Zoom uses font layout rather than a CSS transform so caret and selection geometry follow the formula.
Popup theme variables: --me-text-background, --me-text-foreground, --me-text-border, --me-text-muted, --me-text-accent, and --me-text-on-accent.
Development and license
Workspace exports point to src; publishConfig.exports points to dist. Build the math-editor core before node scripts/build-math-text.mjs from the repository root. Source ownership and versions remain in each package. These packages are not yet part of the existing npm release allowlist.
MIT, copyright barocss.com. See LICENSE.
Verification (2026-09-13)
31 source-range unit cases and 52 macOS Chromium checkpoints passed across CodeMirror 6, CodeMirror 5, and Monaco. The separate VS Code extension passed four command-opening checks and eight Webview Apply/Cancel/Undo/Redo checks in VS Code 1.103.1. These checks do not cover all browsers, operating systems, screen readers, or Markdown dialects.
Source completion and preview
Set sourceEditing: {} to enable LaTeX command suggestions in a browser host. Set
sourceEditing.renderPreview(latex, element, displayMode) to render above the caret.
KaTeX is optional, remains external, and must be installed by the consumer. Throw
from the renderer for incomplete input; the controller shows a localized status.
A caret after a variable or number opens source-preserving wrapping suggestions.
For example, choose Fraction after 4ab to insert \frac{4ab}{} and enter the
denominator. Roots, indexed roots, scripts and fences are also available.
Select a complete expression inside one math range to wrap that selection. The menu
shows the selected source; the preview renders that selection. Shift+Arrow selection
and mouse dragging both work. The menu waits for drag release. Up/Down keeps the
selection while choosing a wrapper, and Enter/Tab or a click applies it. Escape
closes the menu without collapsing the native selection. Split command names,
unbalanced groups, text arguments and selections across math delimiters are excluded.
Automatic wrapping suggestions start with no selected action. Press Down to choose
the first action, then Enter to apply it, or click an action. Until an action is
chosen, Enter and Tab keep their native host behavior. Typing a command or opening
Ctrl+Space explicitly still preselects a completion.
Command typing and Ctrl+Space open the catalog. Up/Down selects a candidate;
Enter/Tab inserts its LaTeX. Tab and Shift+Tab navigate inserted arguments.
With a caret inside an existing template, Tab keeps navigating instead of accepting an operand
wrapping suggestion; use Enter or click to accept that suggestion.
Escape dismisses source tools. Alt+Enter still opens visual editing. The host keeps
keyboard focus and owns changes and Undo. Composition, read-only state and disposal
suppress the overlay. Only detected math ranges are eligible.
latexCompletions(query, locale) returns id, label, glyph, insert, and UTF-16
argument stops. It is also available for custom native completion providers.
No source-wide parse/serialize cycle is used. Wrapping preserves contiguous variable/number
runs and simple scripts verbatim. The caret scanner distinguishes command spans from
operands, comments and braced text/environment names. It does not resolve custom macros
or infer arbitrary expression boundaries. Existing structure transformations remain
visual-editor actions. Completing a command in the middle replaces its full name;
existing arguments remain intact. Source mode tolerates whitespace beside paired
math delimiters. The default visual-import range scanner remains strict.
The provided dropdown is shared DOM UI; it does not install a host-native completion
provider or a general-purpose snippet engine.
See the source editing guide for setup, key behavior and limitations. The initial text packages are not published yet.
Visual popup suggestions use available viewport space, rather than the popup height. Real transformed/paint clipping boundaries still constrain the menu, and Apply/Cancel controls remain excluded from placement.
When wrapping a compound source expression in an exponent, visible parentheses preserve its scope: selecting a+b inserts {\left(a+b\right)}^{}. A single variable, number, or already grouped structure does not receive redundant parentheses. Source text inside the base remains unchanged.
