Skip to content

Options by name: setOption/getOption, optionChange, defineOption, init hooks, autofocus, phrase (Refs #41) - #90

Draft
DJAscendance wants to merge 10 commits into
masterfrom
feat/options
Draft

DJAscendance wants to merge 10 commits into
masterfrom
feat/options

Conversation

@DJAscendance

@DJAscendance DJAscendance commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Refs #41

Ledger rows: 82 lineNumberFor, 341 CodeMirror constructor, 436 setOption (with getOption), 482 phrase, 514 defineOptions.

Base: 7d917785a1b65259b238f35a3fad98343d8a6d02 (master, merged in); parent PR head 941d6c6cfcf4eebc4b4d0e36a9386def958def99
Head: ac0238af964e2cfd1d36b7568b2227dcd86f3a3c

Integration: Stacked on #89 (941d6c6); merge in order #81, #83, #86, #89, #90, #91, #92. Until the PR below it merges, this PR's diff against master includes that PR.

What this adds

The new module is crates/cm-view/src/options.rs.

  • OptionValue covers Null, Bool, Number, Str, Phrases and Formatter. OldValue is Init or Value.
  • Editor::get_option(name) returns None for an unknown name (CM5's undefined).
  • Editor::set_option(name, value), as in methods.js:43:
    • It does nothing when the value is unchanged, except for mode.
    • Otherwise it stores the value and runs the option's handler in an operation:
      • mode: doc.modeOption + loadMode;
      • indentUnit: loadMode;
      • tabSize;
      • lineWrapping: wrappingChanged;
      • lineNumbers, firstLineNumber, lineNumberFormatter: updateGutters;
      • flattenSpans, maxHighlightLength: resetModeState;
      • undoDepth;
      • viewportMargin: refresh.
    • It then fires optionChange (Editor::on_option_change, immediate).
    • Unknown names and wrong value types return OptionError.
  • options::define_option(name, default, handler, not_on_init) is CodeMirror.defineOption for custom options. Their handlers run on a new editor with OldValue::Init, unless not_on_init. Built-in names are refused, because built-in options are typed fields.
  • options::BUILT_IN lists the implemented option names, and options::default_option(name) gives CodeMirror.defaults.
  • The constructor now ends like CodeMirror.js:80-90: custom handlers with Init, EditorOptions::finish_init, then the options::define_init_hook hooks. With EditorOptions::autofocus, a 20 ms timeout runs onFocus unless the editor is already focused. In CM5 the focus listener is registered after input.focus(), so that timeout is what focuses the editor.
  • Editor::line_number_for(i) returns lineNumberFormatter(i + firstLineNumber), using EditorOptions::line_number_formatter.
  • Editor::phrase(text) reads the phrases option (EditorOptions::phrases).

Upstream refs (pinned 4ca3d05)

src/edit/options.js:24-183; src/edit/methods.js:43-52, 437-440; src/edit/CodeMirror.js:63-90, 216-217; src/line/utils_line.js:83.

Tests and evidence

  • crates/cm-view/tests/options.rs:
    • set_get_and_option_change: the tabSize handler changes the layout, unchanged values are a no-op, mode always runs, and errors are returned.
    • line_number_for_and_gutter_options
    • phrases
    • define_option_custom: Init versus notOnInit, old values, defaults, and the built-in refusal.
    • finish_init_and_init_hooks: finishInit runs before the hooks.
    • autofocus_focuses_after_20ms
  • Strict, on the top of the stack (Cursor drawing: showCursorWhenSelecting, cursorHeight, fat cursor, overwriteToggle (Refs #51) #92 0b167ad, which contains this PR and every PR below it): cargo test --workspace --no-fail-fast gave 834 passed, 0 failed, 0 ignored. The same under xvfb-run -a: 834 passed, 0 failed. tools/web-test.sh: all 5 browser profiles passed 63/63.

Known differences

  • (Fixed in the integration merge: the gutter now formats numbers through line_number_for.)
  • Options without a native field are not settable: theme, gutters, specialChars, inputStyle, scrollbarStyle, and others (listed in the ledger spec). readOnly "nocursor", the lineSeparator handler (re-splitting the document) and keyMap attach/detach are not ported.
  • CM5 accepts any value. The port type-checks the value.
  • Init hooks run after the constructor's display update, not inside its operation.

Coverage change

  • 482, 82: NOT_PORTED/PARTIAL → PORTED
  • 341, 436, 514: PARTIAL → PARTIAL (each with narrower remaining gaps)

After the merge, the native renderer, cm-web's frame and the gutter width all format numbers through line_number_for (row 82). lineNumberFor uses the absolute line number and does not subtract doc.first, as CM5 does. New test: line_number_formatter_sizes_gutter.

CI: pending (Actions cannot start: billing)

)

cursorCoords/charCoords/coordsChar/lineAtHeight/heightAtLine method forms
(cursor_coords_in, char_coords_in, coords_char_in, line_at_height_in,
height_at_line_in) with page and window modes over a host-supplied
window origin and page scroll, start=null/true/false, clipPos, LineHandle
arguments, includeWidgets (no widgets yet) and the end-of-document
adjustment; intoCoordSystem/fromCoordSystem ported with CM5's div
(viewOffset) semantics. The port's internal document-y frame is now
CoordSys::Doc. Checked against a CM5 recording (cm5-coord-systems.json).
… (Refs #54)

get_scroll_info() returns CM5's {left, top, height, width, clientHeight,
clientWidth}; scroll_into_view_target takes null (cursor plus
cursorScrollMargin), a line number, a position, a range, a coordinate box
or a box range (scrollToCoordsRange); scroll_rect_into_view is the
immediate, thresholded scrollIntoView(cm, rect) helper. Checked against a
CM5 recording (cm5-scroll-api.json), including scrollTo and scrollIntoView
inside one operation.
NamedListeners (one copy-on-write list per event name) and cm_core::Emitter
port on/off/getHandlers/signal/hasHandler for string-named and custom
events on any object; the editor, documents, line handles and markers get
a named table beside their typed lists. Editor::signal_dom_event and
on_dom_event port signalDOMEvent; key_down, key_press, mouse_down, paste
and maybeScrollWindow (scrollCursorIntoView) signal before handling, and a
handler that calls prevent_default or sets codemirror_ignore pre-empts
the editor.
… reset (Refs #50)

The editor keeps the blink: restart_blink on focus (also when already
focused), after an operation that changed the selection and after a
handled key; cursor_blink_visible / next_blink_in follow the
cursorBlinkRate option (> 0 blinks, 0 shows, < 0 hides). Blurring stops
the blink and schedules onBlur's 150 ms display.shift reset, run by the
host through run_timers / next_timer_in. The native window draws and
wakes from these instead of its fixed 530 ms timer.
…t hooks, autofocus, phrase (Refs #41)

set_option/get_option map CM5 option names onto EditorOptions, run each
option's handler in an operation (mode, indentUnit, tabSize, lineWrapping,
the gutter options, resetModeState options, undoDepth, viewportMargin) and
fire optionChange. define_option adds custom options with handlers run on
init (CodeMirror.Init) unless notOnInit; the constructor ends with
finishInit, the defineInitHook hooks and autofocus's 20 ms onFocus timer.
line_number_for applies lineNumberFormatter; phrase reads the phrases
option. Stacked on feat/focus-blink (run_timers).
into_coord_system honors include_widgets as CM5 does: without it the box
moves below the widgets above the line (widgetTopHeight), before the
"line" early return; master's into_coords path is the include_widgets =
false case. Exports keep both sides' items. New test
into_coord_system_include_widgets.
Keep both listener sets (gutter/line-widget events and named events).
… uses lineNumberFor

Keep both sides' options fields, listeners and README sections. The
native renderer, cm-web's frame and the line-number width now format
numbers through line_number_for (lineNumberFor: lineNumberFormatter(i +
firstLineNumber), without subtracting doc.first, as update_line.js:114
and line_numbers.js:34 do). Render number buffers are keyed by text.
New test line_number_formatter_sizes_gutter.
@github-actions

Copy link
Copy Markdown

MiniMax-M3.1-Flash QA

Review findings

1. lineWrapping option handler reverses the stored value — high severity

Location: crates/cm-view/src/options.rs, built_in_handler, "lineWrapping" branch

"lineWrapping" => {
    let v = self.options.line_wrapping;
    self.options.line_wrapping = !v;
    self.set_line_wrapping(v);
}

set_option first stores the new value through set_field:

set_field(&mut self.options, name, &value)?;

For set_option("lineWrapping", true), the stored value is therefore true when the handler runs. The handler then changes it back to false before calling set_line_wrapping(true).

This means:

  • get_option("lineWrapping") can return the opposite of the requested value.
  • The editor state and the options state diverge.
  • The new test set_get_and_option_change should fail its assertion that cm.options.line_wrapping is true, unless set_line_wrapping independently mutates the field.

Please remove the inversion, or explicitly verify the intended semantics of set_line_wrapping and update the field consistently. A regression test should assert both the option value and the actual wrapping behavior after setting true and false.


2. Local coordinate conversion appears to apply the window origin — high severity

Location: crates/cm-view/src/editor.rs, into_coord_system and from_coord_system

The "local" coordinate system is documented as relative to the editor's sizer, not to the host window. However, into_coord_system uses line_space_origin(), which includes display.window_origin:

let (lx, ly) = self.line_space_origin();
...
r.left += lx + px;
r.right += lx + px;

For a host with a nonzero editor position, local coordinates should not include the host window origin. The conversion should be relative to the sizer/line-space origin within the editor.

The inverse has the same issue:

CoordSys::Local => {
    let (ox, oy) = self.display.window_origin;
    left += ox + self.gutter_width - self.display.scroll_left;
    top += oy - self.display.scroll_top;
}

This adds the window origin and later subtracts line_space_origin(), effectively canceling the origin for x, but it also fails to apply the editor-local gutter offset consistently. The expected local-to-div conversion should be based on the local sizer origin, not the host window origin.

Please add explicit tests with a nonzero window_origin for:

  • char_coords_in(..., CoordSys::Local)
  • coords_char_in(..., CoordSys::Local)
  • height_at_line_in(..., CoordSys::Local)
  • the local/document round trip

The existing coordinate-system recording may not catch this if the tested cases use zero window origin or if the recorded expectations are being interpreted inconsistently.


3. Formatted line-number width uses Unicode scalar count instead of UTF-16 code units — medium severity

Location: crates/cm-view/src/render.rs

let digits = n.chars().count() as f32;

CM5 computes the displayed string width from JavaScript string length, which is measured in UTF-16 code units. chars().count() differs for characters outside the Basic Multilingual Plane: for example, an emoji is one Rust char but two UTF-16 code units.

Since lineNumberFormatter can return arbitrary Unicode strings, this can miscalculate the gutter width and line-number positioning.

Use:

let digits = n.encode_utf16().count() as f32;

or otherwise match the browser/CM5 text-measurement semantics. Add a test using a non-BMP formatter result, such as "😀", and verify the gutter width and alignment.


4. The new Options API is not fully covered for option-handler ordering and old-value semantics — medium severity

Location: crates/cm-view/src/options.rs

The implementation states that optionChange runs after the option handler, but there is no explicit test verifying the ordering between:

  1. the option-specific handler,
  2. optionChange,
  3. any mutation performed by the handler.

Likewise, the custom option tests verify the handler arguments but do not verify that OldValue::Value(...) contains the actual previous value when the value was changed multiple times.

Because option handlers can mutate the editor, it would be useful to add tests that verify:

  • optionChange observes the new value.
  • The option-specific handler runs before optionChange.
  • The old value passed to a custom handler is the value from the preceding set_option call.
  • Setting the same value does not fire optionChange or invoke the handler, except for mode.
  • A custom option handler is not run when not_on_init is true.

This is particularly important because the README now presents this behavior as a supported public API.


5. Emitter::signal and named-event APIs expose raw Any values without a checked conversion API — low/medium severity

Location: crates/cm-core/src/events.rs

The public API uses:

pub type Args<'a> = &'a [&'a dyn Any];

This makes the API flexible, but every caller must manually downcast values. A mismatch between the producer and consumer will silently result in the handler receiving no useful value, as shown by on_dom_event:

if let Some(e) = args.first().and_then(|a| a.downcast_ref::<DomEvent>()) {
    f(cx, e)
}

If the downcast fails, the handler is silently not called. For a public event API, consider either:

  • returning a typed result from the conversion,
  • logging/asserting on a downcast failure,
  • or providing typed helper methods for common argument types.

At minimum, add tests that verify the behavior when a handler is registered for a DOM event but signaled with the wrong argument type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant