Skip to content

Latest commit

 

History

History
796 lines (636 loc) · 51.2 KB

code-editor.md

File metadata and controls

796 lines (636 loc) · 51.2 KB

Code editor

code-editor is a code editor for IDEs, shader editors and tools: syntax colors, line numbers, folding, many carets, a find and replace bar with regexes, go to line, a minimap, diagnostics, and the hooks a language server needs. For RFML markup and CSS it has code completion from the live UI, with color squares, a color picker and image previews.

It is a native widget in rf-widgets (rf_widgets::code). One node draws the gutter, the text, the selections, the scroll bar and the popups. The text is an rf_text::TextBuffer, so typing, Ctrl+D and scrolling cost the same in ten lines and in a million.

<box style="flex-direction: column; height: 240">
  <code-editor id="src" language="rust" minimap
               on-change="src.change" on-cursor="src.cursor" on-save="src.save"
               on-clipboard="src.clip" on-find="src.find" on-request="src.ask" on-gutter="src.gutter"
               style="flex-grow: 1; font-size: 13"/>
</box>

Widgets::install adds the type. The editor needs a running Widgets in the UI: call Widgets::install and then attach (or give the input to Widgets::input). The Widgets makes the popups (the completion list, its doc window, signature help, hover), the find bar and the edit menu. rf_widgets::install alone adds only the type. Then the editor works, but no popup shows, and set_completions, set_signature and set_hover put a warning in Ui::take_warnings (rf-app prints it). Size the editor with CSS. Its font is mono unless CSS says otherwise.

attribute default meaning
language a language name or file extension: rust, rs, c, cpp, json, css, xml, rfml, html, md, glsl, hlsl, wgsl, py, js, ts, tsx... Empty: plain text
text the text, for small texts in markup (use code::set_text for files)
line-numbers true the line numbers in the gutter
minimap false the minimap at the right (also --rf-code-minimap: on in CSS)
read-only false the text cannot change; carets, selection and copy still work
tab-size 4 spaces per indent level
use-tabs false Tab inserts a tab character, not spaces
word-wrap false long lines break into rows at the width of the editor (see word wrap)
multi-cursor-modifier ctrl ctrl: Ctrl/Cmd+click adds a caret and Alt+click goes to the definition. alt: the other way round
completion-triggers . characters that ask for completions when typed
completion-word-chars characters that are part of a word for the completion list, beside letters, digits and _. With -, the list stays open over align-items
find-bar auto auto: Ctrl+F, Ctrl+H and Ctrl+G open the built-in find bar. none: they only send on-find, for an app with a bar of its own
on-change the text changed (payload change, or resync)
on-cursor a caret or selection moved (cursor)
on-save Ctrl+S (save)
on-clipboard copy, cut, paste happened (copy, cut, paste); the clipboard itself works with no app code
on-find Ctrl+F, Ctrl+H, Ctrl+G (find, replace, goto). The built-in bar opens by itself; with find-bar="none" show your own
on-request the editor asks the app (completion, hover, signature, definition)
on-gutter the marker column was clicked (gutter)

The actions have the event "emit", like those of every native widget. The details come from code::take_events.

Showing a file

// from: crates/renderfi/examples/guide_code.rs#code-markup
const EDITOR: &str = r##"
<box class="app">
  <code-editor id="src" class="grow" language="rust"
               on-change="src.change" on-save="src.save" on-clipboard="src.clip"
               on-request="src.ask" on-gutter="src.gutter"/>
</box>"##;

const SOURCE: &str = "fn area(w: f32, h: f32) -> f32 {\n    w * h\n}\n\nfn main() {\n    let a = area(3.0, 4.0);\n    println!(\"{a}\");\n}\n";

/// Show a file: the text, a problem and a breakpoint. The language came
/// from the markup; `code::set_language` changes it.
pub fn open(ui: &mut Ui, src: NodeId) {
    code::set_text(ui, src, SOURCE);
    code::set_diagnostics(
        ui,
        src,
        vec![Diagnostic { start: Pos::new(5, 8), end: Pos::new(5, 9), severity: Severity::Warning, message: "unused variable `a`".into(), source: "rustc".into() }],
    );
    code::set_markers(ui, src, vec![Marker { line: 5, kind: MarkerKind::Breakpoint }]);
}

code::set_text starts over: undo, folds, diagnostics and markers go. For a file from disk or the network, use ui.load_file(path): it never blocks, and the bytes arrive as AssetEvent::File from ui.asset_events() at a later update (assets). The apps/code example does this for a file tree with tabs.

Keys and mouse

The keys follow the platform. The key table of the UI (Ui::edit_keys, renderfi::EditKeys) is Pc on Windows and Linux and Mac on macOS. On a Mac, Cmd takes the place of Ctrl. The second column shows the keys of a Mac (as in VS Code).

Windows, Linux macOS what it does
arrows, Home, End, Page Up/Down the same move the carets (Shift: select). Home goes to the first character, then to the line start
Ctrl+Left/Right, Ctrl+Backspace, Ctrl+Delete Alt+Left/Right, Alt+Backspace, Alt+Delete the same by words
Ctrl+Home, Ctrl+End Cmd+Up, Cmd+Down the start and the end of the text
Cmd+Left, Cmd+Right the start and the end of the line
Ctrl+Up/Down scroll by a line (the caret stays)
Ctrl+F Cmd+F the find bar
Ctrl+H Cmd+Alt+F (also Cmd+H) the find bar with the replace field
Ctrl+G Ctrl+G go to a line (42, or 42:7 for a column)
F3, Shift+F3 (Enter, Shift+Enter in the find bar) Cmd+G, Cmd+Shift+G, F3 the next and the previous match
Ctrl+D Cmd+D select the word, then add the next match of the selection as a caret
Ctrl+Shift+L Cmd+Shift+L select every match of the selection
Ctrl+click (or Alt+click, see multi-cursor-modifier) Cmd+click add a caret
Ctrl+Alt+Up/Down Cmd+Alt+Up/Down add a caret on the line above or below
Alt+drag, Shift+Alt+drag the same a column: one selection per line
Ctrl+C, Ctrl+X, Ctrl+V (also Ctrl+Insert, Shift+Delete, Shift+Insert) Cmd+C, Cmd+X, Cmd+V copy, cut and paste at every caret (see the clipboard)
Ctrl+A Cmd+A select all
Ctrl+Z, Ctrl+Shift+Z, Ctrl+Y Cmd+Z, Cmd+Shift+Z undo and redo. Each command is one step, also at many carets
Tab, Shift+Tab, Ctrl+], Ctrl+[ Tab, Shift+Tab, Cmd+], Cmd+[ indent and outdent the selected lines (Tab with no selection puts in an indent)
Ctrl+/ Cmd+/ comment or uncomment the lines with the comment marks of the language's grammar (its line comment, else its block comment)
Alt+Up/Down the same move the lines up or down
Shift+Alt+Up/Down the same copy the lines above or below
Ctrl+Shift+K Cmd+Shift+K delete the lines (Ctrl+X and Shift+Delete with no selection cut them)
Ctrl+Enter Cmd+Enter a new line below
Ctrl+Shift+[ , Ctrl+Shift+] Cmd+Alt+[ , Cmd+Alt+] fold and unfold the block at the caret
Ctrl+Shift+\ Cmd+Shift+\ jump to the matching bracket
Ctrl+Space Ctrl+Space ask for completions; with the list open, hide or show the doc beside it
F12, Alt+click the same ask for the definition
Ctrl+S Cmd+S on-save
Alt+Z Alt+Z word wrap on and off (see Word wrap)
Escape the same close a popup, then the find bar, then go back to one caret
double click, triple click the same select a word, a line; a drag after it extends by words or lines
middle click (Linux) paste the primary selection there
right click the same the edit menu: Undo, Redo, Cut, Copy, Paste, Select All, then Find, Replace, Go to Line and Toggle Line Comment, each with its key (rf-widgets, widgets)

The commands and their keys are one table in rf_widgets::code::keys. CodeCommand names each command, keys::command_of gives the command of a key, and keys::shortcut the key of a command as a menu shows it. The editor, its edit menu and the find bar read their keys from there. code::commands(ui) lists every command with its name and its key, for a command list or a menu of your own. code::run(ui, editor, command) runs one:

// from: crates/renderfi/examples/guide_code.rs#code-commands
/// A menu of your own: every command of the editor with its key in the
/// UI's key table (Ctrl+F, or Cmd+F on macOS).
pub fn command_menu(ui: &Ui) -> Vec<String> {
    code::commands(ui).into_iter().map(|(_, name, key)| format!("{name}  {key}")).collect()
}

/// A choice of the menu runs the command, as its key does.
pub fn comment_lines(ui: &mut Ui, src: NodeId) {
    code::run(ui, src, CodeCommand::ToggleComment);
}

Typing has the usual aids:

  • Enter keeps the indent. After { it adds one level. Between {} the closing bracket gets its own line.
  • An opening bracket or quote gets its closing one, or wraps the selection.
  • A typed closing bracket or quote steps over the one that is there.
  • Backspace between a pair removes both.

The bracket that matches the one at the caret has a box (--rf-code-bracket).

Word wrap

With word-wrap (or Alt+Z, or code::set_word_wrap), a line that is wider than the editor breaks into rows. A row breaks after a space when it can, else inside a long word. Nothing scrolls sideways. Up and Down move by rows, so they can stay in one long line. Alt+Z also sets the word-wrap property, so CSS and bindings see it; code::word_wrap reads it.

The rows are counted in characters: a character is one cell and a tab is four. With the mono font this is exact. With another font a row can be a little wider or narrower than the editor.

What it costs: when wrap turns on or the width changes, one pass over the text counts the rows of each line. After an edit only the changed lines are counted again. With wrap off nothing of this runs.

Events and the clipboard

Copy, cut and paste work with no app code in a window with AppWindow (and in the C API's rfRun): the editor gives the copied text to the UI as a clipboard request, rf-app puts it on the clipboard, and pasted text comes back to the editor. With many carets, copy gives one line per caret (empty carets copy their whole lines), and a paste with as many lines as carets gives each caret its line; else every caret gets all of it. A big paste is one edit. On Linux the selection is also the primary selection, and a middle click pastes it.

The editor still sends CodeEvent::Copy, Cut and Paste (action on-clipboard), so an app can show a message. An app that keeps the clipboard itself turns this off with ui.set_clipboard_keys(false) and answers the events, as this example does (its clipboard is a String):

// from: crates/renderfi/examples/guide_code.rs#code-events
/// The app's part: saving, breakpoints and language services. Call it
/// with every action of the editor (event "emit"). Copy and paste work by
/// themselves in a window (rf-app serves the clipboard); this app keeps
/// the clipboard itself, a `String`, so it turned that off with
/// `ui.set_clipboard_keys(false)`.
pub fn on_action(ui: &mut Ui, src: NodeId, a: &Action, clipboard: &mut String) {
    if !a.name.starts_with("src.") {
        return;
    }
    for event in code::take_events(ui, src) {
        match event {
            // (only for an app that keeps the clipboard itself)
            CodeEvent::Copy(text) | CodeEvent::Cut(text) => *clipboard = text,
            CodeEvent::Paste => code::paste(ui, src, clipboard),
            CodeEvent::Save => {
                let text = code::text(ui, src).unwrap_or_default();
                ui.set_data("src.status", format!("saved {} bytes", text.len()));
            }
            CodeEvent::GutterClick { line } => code::set_markers(ui, src, vec![Marker { line, kind: MarkerKind::Breakpoint }]),
            CodeEvent::Completion { .. } | CodeEvent::Hover { .. } | CodeEvent::Signature { .. } | CodeEvent::Definition { .. } => {
                language_service(ui, src, &event)
            }
            _ => {}
        }
    }
}

Find and replace

Ctrl+F (Cmd+F on macOS) opens the find bar at the top right of the editor, over the text. The bar comes with the editor: no app code is needed. It needs the widgets in the UI (Widgets::install with Widgets::attach, or an app that gives its input to Widgets::input).

  • Find. The selected text (on one line) fills the field. Typing searches at once and shows every match in the text and on the scroll bar. The count shows 3 of 12. When no match is selected, it shows ? of 12. It can also show No results, or why a regex is wrong.
  • Next and previous. Enter and F3 go to the next match, Shift+Enter and Shift+F3 to the one before. At the end the search goes round. The arrow buttons do the same.
  • Options. Match case (Aa, Alt+C), whole word (ab, Alt+W) and regex (.*, Alt+R). They are toggle buttons (role checkbox, checked).
  • Replace. Ctrl+H (Cmd+Alt+F) shows the replace field, and so does the arrow at the left of the bar. Enter in the replace field (or Replace) replaces the selected match and goes to the next. Ctrl+Alt+Enter (or All) replaces every match as one undo step. In a regex replacement, $1 is group 1 and $$ is a dollar sign. A read-only editor has no replace field.
  • Go to line. Ctrl+G shows a line field in the same place. Type 42, or 42:7 for a column. The editor shows the line while you type. Enter goes there and closes the bar.
  • Closing. Escape (in the bar or in the text) closes the bar. The matches go and the focus goes back to the text. The next Ctrl+F shows the last search again.

The bar keeps the caret's line out from under it: the editor scrolls so that the selected match is below the bar. For a screen reader the bar is a group named Find. The fields are a searchbox and text boxes with labels. The buttons have names with their keys. The count is a status, so a screen reader reads it when it changes.

Each part has a ::part() name, so a skin styles it like any widget:

part what it is
find-bar the bar. With the replace field it has the class replace, with the line field goto
find-row, replace-row, goto-row its rows
find-input, replace-input, goto-input the fields (find-input gets the class no-results or error)
find-toggle case, find-toggle word, find-toggle regex the options (:checked)
find-button prev, next, close, replace, all the buttons
find-count the count
find-expand the arrow that shows the replace field
code-editor::part(find-bar) { background-color: #1e1e1e; border-color: #454545 }
code-find-toggle:checked { border-color: #007fd4 }

The default look uses the popup colors of the editor: --rf-code-popup, --rf-code-popup-fg and --rf-code-popup-border. It also uses the theme variables of the widgets: --rf-field, --rf-accent and --rf-line.

An app with a find bar of its own sets find-bar="none". The keys then only send on-find (find, replace, goto) and CodeEvent::Find or CodeEvent::GoToLine. The apps/code example does this. The search also works from code, with or without the bar:

// from: crates/renderfi/examples/guide_code.rs#code-find
/// Find with a regex, then replace every match as one undo step.
pub fn rename_parameter(ui: &mut Ui, src: NodeId) -> usize {
    let options = FindOptions { regex: true, case_sensitive: true, whole_word: true };
    let found = code::find(ui, src, r"w|width", options).expect("a valid regex");
    assert_eq!(found, 2);
    code::replace_all(ui, src, "width")
}

code::find searches as plain text or as a regex. find_next, find_position, replace_next and replace_all do the rest. Widgets::open_find_bar and Widgets::close_find_bar open and close the bar from code, and Widgets::find_bar gives its nodes. The regex engine is rf_syntax::regex: no backtracking (a lazy DFA finds the lines with a match, a Pike VM the match), with classes, groups, alternation, anchors, \b and repeats. Matches stay on one line.

Folding, markers and diagnostics

  • Folding. The arrows in the gutter fold a block: from a line whose brackets stay open to the line before the closing bracket, or by indentation for Python, XML and Markdown (the grammar says which). code::set_fold_ranges gives ranges of your own (a language server's folding ranges); fold, unfold, fold_all, unfold_all and folded work from code. Folded lines take no layout and no time.
  • Markers. code::set_markers puts breakpoints, bookmarks, git changes (added, modified, deleted) and the current line of a debugger in the gutter. A click on the marker column sends CodeEvent::GutterClick.
  • Diagnostics. code::set_diagnostics draws squiggly lines (errors, warnings, info; hints get a thin line) and shows the message when the pointer rests on them.

Markers, diagnostics, folds and find matches move with the text when it changes.

Popups

The editor has four popups: the completion list, the doc of the selected item, signature help and the hover tooltip with its picture. They are nodes in the top layer, not drawings of the editor. So the editor's box and the scroll containers around it never cut them.

  • The list. It shows twelve rows. More items scroll, with the normal scroll bar. The selected row stays in view. The list has one width for all its items, from its longest item (between 220 and 560 pixels). So its width stays the same while you type and scroll.
  • The doc. The doc of the selected item is a small window of its own beside the list: right of it, else left of it, else under it. It has its own size limits (400 by 300 pixels) and scrolls. So a long doc never changes the size of the list. Ctrl+Space while the list is open hides the doc window and shows it again.
  • Rich text. A doc is Markdown-like text. Each line is a paragraph. A line can be a heading (#) or a list item (-, *, 1.), and ``` starts and ends a code block. In a line, `code` is code, `bold` is bold, `italic` is italic, and a link in Markdown form shows its text in the link color. The doc of a property from rf-complete has a short head (the name, the kind and the default), then the values of an enum as a short list, then the description.
  • Signature help and tooltips have the same look. Their doc is rich text too.
  • Placing. A list that has no room below its line opens above it. While it is open it stays on that side, so it does not jump while you type. Every popup stays inside the window.
  • Keys and focus. The keys stay with the editor: Up, Down, Page Up and Page Down move in the list, Enter and Tab put the item in, and Escape closes it. A click on a row puts that item in. A drag of the scroll bar scrolls the list. The editor keeps the focus. When the focus goes away, the popups close. When their line scrolls out of view, they close too.

The popups need the widgets in the UI, as the find bar does. They are parts of the editor:

part what it is
popup every popup. It also has the class of what it shows: completion, signature or hover (so code-editor::part(completion) is the list)
popup-list the rows: a scroll container (max-height sets how many rows show)
popup-row a row of the list (class selected)
popup-icon, popup-swatch the mark of the item's kind, or its color square
popup-label, popup-detail the text of the item, and the text at its right
popup-details the doc window beside the list
popup-line, popup-text the line of signature help and its pieces (class active for the current parameter)
popup-doc the doc under the line of signature help or a tooltip
popup-para, popup-code a paragraph (class heading or item) and a code block of a doc
popup-picture the picture of a tooltip
code-editor::part(completion) { border-radius: 8 }
code-editor::part(popup-list) { max-height: 160 }
code-editor::part(popup-details) { max-width: 520 }

The default look uses the editor's variables: --rf-code-popup, --rf-code-popup-fg, --rf-code-popup-border, --rf-code-popup-selected and --rf-code-popup-radius. The popups are a general mechanism of rf-widgets: another native widget gives its popups the same way (rf_widgets::overlay, Widgets::register_overlays). A spec can have a list, a width, a doc and details for the window beside it.

Themes

The editor reads CSS variables, with the dark theme's colors as fallbacks. Token colors are --rf-code-keyword, --rf-code-type, --rf-code-function, --rf-code-macro, --rf-code-string, --rf-code-escape, --rf-code-number, --rf-code-constant, --rf-code-comment, --rf-code-operator, --rf-code-punctuation, --rf-code-variable, --rf-code-property, --rf-code-tag, --rf-code-attribute, --rf-code-heading, --rf-code-emphasis, --rf-code-link and --rf-code-invalid. The editor's parts are --rf-code-bg, --rf-code-fg, --rf-code-gutter, --rf-code-line-number, --rf-code-line-number-active, --rf-code-current-line, --rf-code-selection, --rf-code-caret, --rf-code-match, --rf-code-match-current, --rf-code-bracket, --rf-code-indent-guide, --rf-code-fold, --rf-code-error, --rf-code-warning, --rf-code-info, --rf-code-hint, --rf-code-added, --rf-code-modified, --rf-code-deleted, --rf-code-breakpoint, --rf-code-popup and a few more.

rf_syntax::theme::DARK and LIGHT hold all of them: LIGHT.css(":root") is a stylesheet for your theme sheet. The Markdown viewer colors its code blocks with the same variables.

:root { --rf-code-keyword: #d73a49; --rf-code-string: #032f62; --rf-code-bg: #fafbfc }

Languages

Built in: Rust, C and C++, JSON, CSS, XML (RFML, HTML, SVG), Markdown, GLSL, HLSL and WGSL, Python, and JavaScript and TypeScript. A grammar is a small data file: states with regex rules (the longest match wins), word lists, and the comment and bracket characters that folding and Ctrl+/ use. The tokenizer keeps the state at the end of each line, so an edit tokenizes from the changed line only until a line ends in the same state as before.

// from: crates/renderfi/examples/guide_code.rs#code-grammar
/// A grammar is a small data file: states with regex rules and word lists.
const INI: &str = r#"
name INI
aliases ini cfg
comment ;
constant true false
state main
  ;.*                 comment
  \[[^\]]*\]          heading
  [A-Za-z_][\w.]*(?=\s*=)  property
  =                   operator
  "[^"]*"             string
  [0-9]+(\.[0-9]+)?   number
  [A-Za-z_]\w*        word
"#;

pub fn add_ini_grammar() {
    let grammar = rf_syntax::Grammar::parse(INI).expect("a valid grammar");
    rf_syntax::register(grammar);
    // every editor and Markdown code block can now color INI files
    assert!(rf_syntax::grammar("cfg").is_some());
}

The format is described in rf_syntax::grammar; the built-in files are in crates/rf-syntax/src/grammars.

Editor services

Everything a language server gives goes through the editor's API, so an LSP client plugs in without changes to the editor: rf-lsp does (see Language servers). The editor asks with events; the app answers.

the editor sends the app answers with
CodeEvent::Completion { offset, trigger }: a word started, a trigger character, or Ctrl+Space code::set_completions: items with a label, kind (the icon), detail, insert text and filter text, and the range they replace (the list's, or the item's own: replace_start, replace_after). Typing goes on filtering the list (fuzzy); Enter or Tab puts the item in and sends CodeEvent::CompletionAccepted { index }. An item can also have a doc (shown beside the list while the item is selected), a color (a square in the place of the icon) and caret_back (the caret goes that many bytes before the end of the inserted text: 1 for name="")
CodeEvent::Hover { offset }: the pointer rests code::set_hover(range, text): shown in a tooltip, with the diagnostics there. code::set_hover_picture adds a picture over the text: an image of the UI or an SVG, at a size you give
code::set_line_decorator: a LineDecorator names the color values and the numbers of a line. A color gets a square before it, and a click on the square opens the color picker. A number can be dragged sideways. See Colors and Numbers
CodeEvent::Signature { offset, trigger }: ( or , was typed code::set_signature: the signature with the current parameter in color
CodeEvent::Definition { offset }: Alt+click (or Ctrl+click) or F12 code::go_to_line or code::set_selections on the definition
CodeEvent::Change: the range replaced (bytes, line and byte column, and UTF-16 columns) and the new text, in the order applied textDocument/didChange with incremental changes
code::set_diagnostics, set_semantic_tokens (colors that win over the tokenizer), set_fold_ranges, apply_edits (formatting and code actions, one undo step), set_inlay_hints

LSP counts columns in UTF-16 code units. Change events carry both; code::pos_utf16 and code::offset_utf16 convert a place either way, and code::utf16_col and col_from_utf16 do it for one line's text.

// from: crates/renderfi/examples/guide_code.rs#code-services
/// What a language server does, made of fixed answers: an LSP client
/// (rf-lsp) has the same shape. It gets the request, asks the server,
/// and answers with the code:: functions.
pub fn language_service(ui: &mut Ui, src: NodeId, request: &CodeEvent) {
    match *request {
        CodeEvent::Completion { offset, .. } => {
            // the word being typed is replaced by the item chosen
            let start = code::with_doc(ui, src, |d| d.word_at(offset).0).unwrap();
            let items = vec![
                CompletionItem { detail: "fn(f32, f32) -> f32".into(), ..CompletionItem::new("area", CompletionKind::Function) },
                CompletionItem::new("as_ref", CompletionKind::Method),
            ];
            code::set_completions(ui, src, Some(Completions { items, start, end: None }));
        }
        CodeEvent::Hover { offset } => {
            let (a, b) = code::with_doc(ui, src, |d| d.word_at(offset)).unwrap();
            code::set_hover(ui, src, (a, b), "fn area(w: f32, h: f32) -> f32");
        }
        CodeEvent::Signature { .. } => {
            let label = "area(w: f32, h: f32) -> f32".to_string();
            code::set_signature(ui, src, Some(SignatureHelp { label, params: vec![(5, 11), (13, 19)], active: 0, doc: String::new() }));
        }
        CodeEvent::Definition { .. } => code::go_to_line(ui, src, 0),
        _ => {}
    }
}

/// LSP counts columns in UTF-16 code units: a change event has both.
/// This makes the `contentChanges` entry of `textDocument/didChange`.
pub fn lsp_change(event: &CodeEvent) -> Option<String> {
    let CodeEvent::Change(c) = event else { return None };
    Some(format!(
        r#"{{"range":{{"start":{{"line":{},"character":{}}},"end":{{"line":{},"character":{}}}}},"text":{:?}}}"#,
        c.start.line, c.start_utf16, c.end.line, c.end_utf16, c.text
    ))
}

/// A formatter's edits (or `textDocument/formatting`) are one undo step.
/// Positions from a server convert with `code::offset_utf16`.
pub fn format_document(ui: &mut Ui, src: NodeId) {
    let at = code::offset_utf16(ui, src, 1, 4);
    code::apply_edits(ui, src, vec![TextEdit::new(at, at + 5, "(w * h)")]);
    // semantic tokens color ranges over the tokenizer
    code::set_semantic_tokens(ui, src, vec![SemanticToken { start: Pos::new(1, 5), end: Pos::new(1, 6), kind: rf_syntax::Kind::Variable }]);
}

Inlay hints are kept and moved with edits, but not drawn yet.

Completion for RFML and CSS

rf-complete gives the editor code completion ("intellisense") for RFML markup and CSS. It reads the UI that the app runs. Nothing is a fixed list:

what completes where it comes from
element types with their docs: built-in, rf-widgets, widgets of the app or a plugin, components the type registry of the Ui
the attributes of each type, with kind, default, enum words and doc the type registry
CSS properties and their values the style properties of the registry, and the shorthands the CSS parser splits
var(--name) names, classes, ids, ::part() names the loaded stylesheets and the running tree
action names for on-* attributes, data paths for {...} the running tree, Ui::data_paths, and names the app gives
image, font, markup and CSS paths the asset source (Ui::asset_list)

A widget can be registered while the app runs. It completes from the next request on, because a registration makes a new registry and the provider then makes its catalog again.

// from: crates/renderfi/examples/guide_code.rs#code-complete
const SHEET_EDITOR: &str = r##"
<box class="app">
  <code-editor id="sheet" class="grow" language="css" on-change="sheet.change" on-request="sheet.ask"/>
</box>"##;

/// Completion, hover docs, color squares and image previews for an editor
/// that holds CSS (`Language::Markup` for RFML). Once, when the editor is
/// there:
pub fn start_assist(ui: &mut Ui, editor: NodeId) -> Assist {
    let mut assist = Assist::new();
    assist.attach(ui, editor, Language::Css);
    assist
}

/// With every action of the editor (event "emit"). The requests are
/// answered from the registry, the stylesheets and the assets of the UI.
/// This app applies the text as a stylesheet when it changes, so the
/// assist looks at the stylesheets again.
pub fn on_sheet_action(ui: &mut Ui, assist: &mut Assist, editor: NodeId) {
    let mut changed = false;
    for event in code::take_events(ui, editor) {
        match event {
            CodeEvent::Change(_) | CodeEvent::Resync => changed = true,
            // a completion list, a hover doc, an image preview
            other => {
                assist.handle(ui, editor, &other);
            }
        }
    }
    if changed {
        let text = code::text(ui, editor).unwrap_or_default();
        if ui.set_stylesheet("edited", &text).is_ok() {
            assist.refresh(ui);
        }
    }
}

Assist::attach sets three things on the editor:

  • completion-triggers: the characters that ask for a list.
  • completion-word-chars: the characters that are part of a word. A list stays open over the - of align-items.
  • The line decorator, for colors and numbers.

Some apps keep their Widgets themselves and do not call Widgets::attach. Such an app calls handle_with(ui, &mut widgets, editor, &event).

In markup

place the list
after < The closing tag of the open element comes first. Then the element types. The nodes that a widget makes for itself are left out.
after </ The open elements, the innermost first.
inside a tag The attributes of the type that the tag does not have yet, then the CSS properties. Every element takes CSS properties as attributes. An item puts in name="" with the caret between the quotes. Then the values show. A bool can stand alone.
in a value The words of an enum: align-items=" shows flex-start, center and the others. true and false for a bool. Colors for a color. Units after a number: 12px, 12%. Asset paths for src, icon and href. Class names for class. Action names for on-*.
in style="..." and in a <style> block As in CSS.
in {...} The data paths.

In CSS

place the list
a selector Types, also the part types such as slider-thumb. Classes after . and ids after #. Pseudo-classes after : and pseudo-elements after ::. The parts of a widget or component in widget::part(. At-rules after @.
a property name The CSS properties, each with its kind. -- shows the custom properties.
a value The words of the property. Then var(), calc() and the other functions. Then inherit, initial and unset.
a color value "Pick a color...", the color functions, the variables that are colors, and the named colors. Each color has its square.
after a number The units.
in var( The custom properties with their values.
in url( The image files. In @font-face: the font files.

The doc of an item shows beside the list. The tooltip shows the doc of the thing under the pointer: a tag, an attribute, a property, a value, a pseudo-class or a --variable.

Colors

Every color value has a small square before it, filled with the color. Light and dark squares show through a color with alpha. These values get a square:

  • hex colors: #rgb, #rgba, #rrggbb, #rrggbbaa
  • rgb(), hsl(), hwb(), oklch(), oklab() and color-mix()
  • color names
  • a var() whose value at the root is a color

The squares follow the text as you type. They are drawn only. The text, its columns and the events of the editor are the same with and without them.

A click on a square opens the color picker under it. Each pick is written over the value in the text. The value keeps its notation:

  • A hex color stays hex. If no digit is lost, the short form stays. Capital letters stay capital.
  • rgb(1, 2, 3) keeps its commas.
  • hsl(), hwb() and oklch() stay what they are.
  • A name or a var() becomes hex.

The value keeps its alpha. All picks of one picker are one undo step.

The picker's text field takes typed colors: hex, rgb(), hsl(), hwb(), oklch() and color names. It also takes hsb(h s% b%), which is the picker's own model.

"Pick a color..." in a completion list puts #808080 in and opens the picker on it.

Numbers

A number in a CSS value or in a number attribute can be dragged like a number field. Press on it and move sideways.

  • Four pixels are one step of the last digit: 12 moves by 1, and 0.50 moves by 0.01.
  • Shift makes ten steps.
  • The unit stays.
  • A drag is one undo step.
  • Each step is a change event. An app that applies its stylesheet on each change shows the drag live.

A click without a drag puts the caret there. A drag that starts beside the number selects text. Assist::set_number_drag(false) turns the drag off.

Image previews

Put the pointer on the name in src="...", icon="..." or url(...) and let it rest. The tooltip shows the picture, with its size in pixels and its format.

The picture is found the way the app finds it:

  1. An SVG that the UI has under that name: Ui::add_svg, the icons of the widgets.
  2. An image that the UI has: Ui::set_image, a loaded image, a file that an <image> shows.
  3. A file of the asset source, decoded with the UI's own decoders.

The longer side of the preview is between 48 and 256 pixels. A small icon is drawn larger by a whole factor, so its pixels stay sharp. A big picture is drawn smaller.

A file can be missing or broken. Then the tooltip shows the reason: img/nope.png: no such file in the assets.

The provider alone

Assist is glue. The work is in rf_complete::Provider: a text and a place go in, a list or a doc comes out. It needs no editor. The language server uses it too.

// from: crates/renderfi/examples/guide_code.rs#code-provider
/// The provider alone: what fits after `<slider value="3" `, and the doc
/// of the tag.
pub fn what_fits(ui: &Ui) -> Vec<String> {
    let mut provider = Provider::new();
    let text = "<slider value=\"3\" ";
    let list = provider.complete(ui, Language::Markup, text, text.len()).expect("the attributes of a slider");
    let doc = provider.hover(ui, Language::Markup, text, 3).expect("the doc of the tag");
    assert!(doc.text.starts_with("<slider>"));
    // "min", "max", "step", "on-change", ... and every CSS property
    list.items.into_iter().map(|item| item.label).collect()
}

More parts of the crate:

  • Provider::scanner gives the scanner that finds the colors and numbers of a line.
  • rf_complete::color reads and writes the color notations.
  • Provider::image_at makes an image preview.

For another language, give the editor a decorator of your own. code::set_line_decorator takes a LineDecorator. The decorator names the color values and numbers of one line. Its recolor writes a picked color back.

What it costs

  • An app with no editor pays nothing, because the crate is not in the app. An editor with no decorator checks one None per line.
  • Nothing runs per frame. A request reads at most 64 KiB of text before the caret. It costs the same in a small file and in a huge file.
  • The catalog of the registry is made once per registry and kept. When a stylesheet is replaced, the names of the stylesheets are read again.
  • The decorator is asked for the lines in view. The answer is kept while the text of the line stays the same. Lines longer than 2000 bytes get no decorations.

Measured on a Ryzen in release mode (cargo test --release -p rf-complete --test editor -- --nocapture numbers):

what time
the catalog of a registry with the widgets (165 types, 197 CSS properties), once per registry 7 ms
a list of values, at the end of a file of 200,000 lines 0.08 ms
the list of all CSS properties 0.08 ms
the list of all tags 0.02 ms
the list of the attributes of a tag 0.10 ms
the colors and numbers of one line 0.5 µs
a painted frame of the 200,000 line file, with color squares 0.024 ms
the same frame with no decorator 0.021 ms

Completion for script code

An editor can show script code: a <script> section of markup, or a script file of a script host (plugin.as). Then the host of that code answers the requests of the editor. It gives the completion list, the doc beside the list and on hover, and signature help. renderfi has no language of its own. The host knows its language and the code that runs.

// from: crates/rf-complete/tests/editor.rs#attach-script
    // the editor shows the code of a script section (or a script file of a
    // host: ScriptTarget::File); the host of the code answers its requests,
    // as `assist.handle` gets them
    let id = t.ui.scripts()[0].id;
    t.app.assist.attach_script(&mut t.ui, css, renderfi::ScriptTarget::Section(id));

attach_script makes . and : ask for a list. ( and , ask for signature help by themselves. The error marks stay the app's: it puts the section's diagnostics into the editor, as before. In C, rfCodeEditorAttachScript does the same, and rfCodeEditorNextEvent answers the requests. The AngelScript host completes from its engine. In a widget class it also gives the callbacks that are missing, as method skeletons. See editor help.

Language servers

rf-lsp connects editors to language servers: programs such as rust-analyzer or clangd that know a language. A server gives diagnostics, completion, hover text, signature help, definitions, references, semantic colors, inlay hints, formatting, rename and fixes ("code actions"). The client speaks the Language Server Protocol (LSP) with each server and puts the answers into the editors through the code:: functions above.

// from: crates/renderfi/examples/guide_code.rs#code-lsp
/// Language servers for the editors of an app (rf-lsp). The config has
/// the built-in servers (used when their program is on PATH), then the
/// app's `lsp.toml`, then the folder's `.lsp.toml`.
pub fn start_servers(folder: &Path, wake: impl Fn() + Send + Sync + 'static) -> Lsp {
    let (config, problems) = Config::load("my-editor", Some(folder));
    for p in problems {
        eprintln!("{p}");
    }
    let mut lsp = Lsp::new(config);
    lsp.add_folder(folder);
    // a server answered on another thread: wake the event loop
    // (rf_platform::Waker::wake), then call after_frame
    lsp.set_wake_callback(wake);
    lsp
}

/// A file is in the editor (from `ui.load_file`): its server gets it.
/// False when no server takes its language.
pub fn file_loaded(ui: &mut Ui, lsp: &mut Lsp, src: NodeId, file: &Path, text: &str) -> bool {
    code::set_text(ui, src, text);
    lsp.open(ui, src, file)
}

/// Every editor action: the events go to the server first. It sends the
/// changes and takes the requests it can answer.
pub fn on_editor_action(ui: &mut Ui, lsp: &mut Lsp, src: NodeId) {
    for event in code::take_events(ui, src) {
        if !lsp.handle(ui, src, &event) {
            language_service(ui, src, &event);
        }
    }
}

/// After each frame (and when the wake callback ran): the answers go into
/// the editors; the app does what only it can do.
pub fn after_frame(ui: &mut Ui, lsp: &mut Lsp, status: &mut String) {
    lsp.update(ui);
    for event in lsp.take_events() {
        match event {
            // a definition in a file that is not open: open it in a tab,
            // and when it is in, `lsp.reveal(ui, tab_editor, &place)`
            LspEvent::Show(place) => *status = format!("open {}", place.path.display()),
            LspEvent::Message { text, .. } => *status = text,
            _ => {}
        }
    }
}

What goes where:

the user the client the server's answer goes to
types didChange with the changed ranges, one message per update for all changes
saves (Ctrl+S) didSave
a word starts, ., Ctrl+Space completion the completion list. Each item replaces its own range. When an item goes in, resolve gets its imports
rests the pointer hover the tooltip
types ( or , signatureHelp the signature popup
Alt+click, F12 definition the selection, or LspEvent::Show for another file
lsp.goto(.., Goto::References) (or Declaration, TypeDefinition) references LspEvent::Locations
lsp.format formatting (or rangeFormatting for a selection) the text, as one undo step
lsp.prepare_rename, then lsp.rename prepareRename, rename LspEvent::RenameReady, then every open file the rename touches (one undo step each)
lsp.code_actions, then lsp.apply_code_action codeAction, codeAction/resolve LspEvent::CodeActions, then the edits
diagnostics (publishDiagnostics), semantic tokens (whole, then deltas) and inlay hints. The editor keeps the hints but does not draw them yet

lsp.status_text(editor) is the state of the editor's server in a few words, such as rust-analyzer: indexing 40%, for a status bar. LspEvent::Status says it changed. Messages of a server (window/showMessage) come as LspEvent::Message.

Nothing waits

  • Each server is a child process (std::process). Worker threads write to its input, read its output and parse the JSON. The UI thread only builds small messages and applies answers.
  • An answer for an old text is dropped: a hover after typing, signature help, semantic tokens. A request that is no longer wanted is cancelled ($/cancelRequest): a second completion request cancels the first.
  • Completion shows something at once. At the same word, the last list shows before the server answers. A new word (not after . or ::) shows the last list of names. The server's answer then replaces the list. Typing filters the list in the editor. The server is asked again only when it said that its list is incomplete.
  • Columns: the client asks for UTF-8 columns, which are the editor's own. When a server only counts UTF-16, the client converts with the editor's helpers.
  • A server can end without being asked (a crash). It then starts again after 0.5 s. Each crash in a row doubles the wait, up to 30 s. The new process gets the open files again. After 6 crashes in a row, the server stays off (State::Failed).

Measured on a Ryzen in release mode:

  • A typed character and its didChange cost 12 µs on the UI thread. This is the same in a file of 100,000 lines and in a small file.
  • From Ctrl+Space to the list on screen: 2 ms with the test server.
  • clangd answers a hover in 2 ms. It sends the first diagnostics of a small file 65 ms after the file opens.

Which server runs

The built-in servers:

server languages
rust-analyzer Rust
clangd C, C++, Objective-C
pyright, then pylsp Python
typescript-language-server TypeScript, JavaScript
vscode-css-language-server CSS, SCSS, Less
vscode-json-language-server JSON
glsl_analyzer GLSL

If a server's program is not on PATH, the server does not run. The file's extension picks the language.

Config::load(app, folder) reads lsp.toml from the app's settings folder (~/.config/APP on Linux, %APPDATA%\APP on Windows, ~/Library/Application Support/APP on macOS) and then .lsp.toml from the folder:

# a server of your own (servers from files come before the built-in ones)
[server.my-glsl]
command = "/opt/glsl/bin/server"
args = ["--stdio"]
languages = ["glsl"]
# JSON: the initializationOptions of initialize
options = {"strict": true}
# JSON: what workspace/configuration answers
settings = {"glsl": {"version": 460}}

# turn a built-in server off
[server.pylsp]
enabled = false

# more file extensions for a language
[extensions]
shader = "glsl"

The folder's file can change languages, options, settings and enabled, but not command or args: opening a folder never runs a program that the folder names.

The code app

cargo run --release -p code -- FOLDER opens a folder with language servers: a file tree, tabs, live diagnostics, completion, hover, F12 (a definition in another file opens in a tab, through Ui::load_file), References, Rename, Format and Fixes in the tool bar, and the server's state in the status bar. Without a folder it shows the sample project in the binary, with the word-list service.

A language server for RFML and CSS

rf-lsp is also a server. The program rfml-language-server gives other editors what the code editor has: VS Code, Neovim, Helix, Zed and every editor with an LSP client. It answers from the same provider as the code editor (Completion for RFML and CSS). It talks on stdin and stdout.

cargo install --path crates/rf-lsp/server
rfml-language-server --assets assets --components assets/components.rfml --css assets/theme.css
option meaning
--assets DIR The asset folder. Image, font, markup and CSS paths complete from it. Default: the workspace folder that the editor names.
--components FILE A markup file with <component> definitions. The components complete as tags. Can be given more than once.
--css FILE A stylesheet. Its variables, classes and parts complete. Can be given more than once.
--plugins PATH A folder of plugins (each *.rfplugin in it and in its direct subfolders) or one manifest. The plugins are loaded, so their widgets complete; a library file that changes is loaded again before the next request. Can be given more than once. See plugins.md.
--plugin-list FILE A text file with one plugin folder or manifest per line, relative to the file.
the editor asks the server answers
textDocument/completion The lists of the code editor. An attribute is a snippet with the caret between its quotes. In VS Code the values show right after.
textDocument/hover The docs. For an image path: the picture (a file of the asset folder), its size and its format.
textDocument/documentColor Every color value of the document. The editor draws its own color squares.
textDocument/colorPresentation The texts for a color that the editor's picker picked. The notation of the value comes first, then hex, rgb(), hsl(), hwb() and oklch().
textDocument/signatureHelp For a script file of a script host (its extension, such as .as): the signature of the call, from the host. Completion and hover of such a file come from the host too. See editor help.

The editor sends the whole text with each change. The open documents work together:

  • An open CSS document is a stylesheet of the server's UI. Its variables complete in the other documents. A text with an error keeps the sheet of before.
  • The classes and ids of the open markup documents complete in CSS selectors.

In Neovim, this starts the server for a buffer:

vim.lsp.start({ name = "rfml", cmd = { "rfml-language-server" }, root_dir = vim.fn.getcwd() })

In VS Code, use an extension that starts a language server from a command, and give it rfml-language-server for the languages css and xml (or rfml).

The program knows the element types of rf-widgets and of the plugins it loads (--plugins). An app with widgets and components of its own can also serve its own registry. It makes its Ui as always. Then it calls rf_lsp::serve::run in place of opening a window, for example when it is started with --language-server:

// from: crates/renderfi/examples/guide_code.rs#code-serve
/// An app as the language server of its own widgets and components. Make
/// the `Ui` as always, then serve on stdin and stdout in place of a
/// window. True: the editor ended the session in the right way.
pub fn serve_own_registry(ui: &mut Ui) -> std::io::Result<bool> {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    rf_lsp::serve::run(ui, &mut stdin.lock(), &mut stdout.lock())
}

From C

rfLanguageServerConfigure reads a config file and sets the workspace folder, rfLanguageServerSetWakeCallback wakes your event loop, rfCodeEditorStartLanguageServer gives an editor's file to its server and rfCodeEditorStopLanguageServer takes it back. rfCodeEditorNextEvent gives each event to the server too, and rfUpdate applies the answers. rfCodeEditorGetLanguageServerStatus is the text for a status bar. Definitions in other files, references, rename, format and fixes are Rust only for now.

Big files

Measured on a Ryzen in release mode (cargo run --release -p rf-widgets --example code_bench -- --all), each step is the input and one frame (styles, layout, the editor's paint and the display list):

lines open typing Enter caret down wheel step Ctrl+D typing at 200 carets find a regex
10,000 0.8 ms 0.07 ms 0.15 ms 0.07 ms 0.07 ms 0.09 ms 0.9 ms 1.5 ms
100,000 3 ms 0.07 ms 0.14 ms 0.07 ms 0.07 ms 0.11 ms 0.9 ms 14 ms
1,000,000 33 ms 0.08 ms 0.16 ms 0.06 ms 0.07 ms 0.10 ms 1.0 ms 134 ms
  • Opening tokenizes what is in view; the rest is tokenized on idle frames, 4 ms at a time (a million lines take about 0.7 s in all). Lines past that point are colored from a guess until the pass gets there.
  • Only the lines in view are laid out and painted. A line is laid out once and kept in the engine's text cache.
  • Lines longer than 10,000 bytes are laid out up to there.

From C

rfCodeEditorRegister adds the type; rfCodeEditorSetText, rfCodeEditorGetText, rfCodeEditorSetLanguage, rfCodeEditorSetDiagnostics, rfCodeEditorSetMarkers, rfCodeEditorSetFoldRanges, rfCodeEditorFold, rfCodeEditorPaste and rfCodeEditorApplyEdits set what the Rust API sets, and rfCodeEditorNextEvent reads the events (call it when an on-* action of the editor arrives). See C and bindings.

Not yet

  • Tab stops (a tab is four spaces wide wherever it is).
  • Drawing inlay hints; snippets with placeholders in completions.
  • Several languages in one file (a script in HTML, code in Markdown fences: shown as one color).
  • Matches that span lines in find.