JFLib

28. Rich text and code editors: ui.richtext, ui.code_editor#

Two ready-made editors keep their document in a model of their own (not one String as the text boxes do): RichDoc -- paragraphs of formatted runs -- and CodeDoc -- lines. Both models carry their selection and an undo history (ui::History), so the app only keeps the document and draws the widget every frame. A shared core (ed_core.rs) gives them the keys of the text boxes (grapheme clusters, words, Home / End, PgUp / PgDn, Ctrl+A / C / X / V / Z / Y), IME and magnifier caret (ime_pos; the composition of IBus / Wayland is drawn at the caret) and a K_TEXTBOX record for screen readers and scripts. apps/editortest shows both (tests/*.uis, --test model for the models).

Rich text.

// once (init): fonts of the app's own become families of documents and of the toolbar
let f = ui.text.load_mem(SERIF, 0);
if f >= 0 { ui.font_register("DejaVu Serif", 400, false, f as u32); }
// the document: build it, or load it
self.doc = RichDoc::from_paras(vec![
    Para::new().with("Title", Fmt::default()).attrs(RA_LEFT, LS_NONE, 0, PS_H1),
    Para::new().with("Some ", Fmt::default()).with("bold", Fmt::bold()).with(" text.", Fmt::default()),
    Para::plain("an item").attrs(RA_LEFT, LS_BULLET, 0, PS_NORMAL),
]);
let doc = RichDoc::from_json(&saved).unwrap_or_default();

// in frame: an optional toolbar, then the editor filling its place (ids ID_ED .. ID_ED + 5)
ui.richtext_toolbar(ID_TOOLS, ID_ED, &mut self.doc, RTB_ALL);   // ids ID_TOOLS .. + 149
ui.next_size(-1, -1);
if ui.richtext(ID_ED, &mut self.doc, 0) & EV_ACT != 0 { self.dirty = true; }
if let Some(url) = ui.richtext_link(ID_ED) { ui.open_url(&url); } // Ctrl+click on a link

// saving: JSON keeps everything, HTML and plain text for others
let json = self.doc.to_json();
let html = self.doc.to_html();
let text = self.doc.to_plain();          // with list markers ("• ", "1. ")
  • Characters (Fmt): bold, italic, underline, strike (RF_*), colour, highlight, size (tenths of a point), font family (font_register families, "monospace", else ui.font_load), a link. Paragraphs (Para): alignment RA_LEFT / CENTER / RIGHT / JUSTIFY, lists LS_BULLET / LS_NUMBER with a level 0..8 (•, ◦, ▪ and 1., a., i. by level), styles PS_H1..H3, PS_QUOTE. Without a selection a format applies to what is typed next.
  • Editing from code goes through the document (each call one undo step): insert_text, insert_paras, delete, split, toggle(RF_BOLD), set_color, set_size, set_font, set_link (on the link at the caret, "" removes it), set_align, toggle_list, indent, set_style; undo / redo / is_dirty / mark_saved. The attribute fields of a Para may be set directly while building a document (not undoable).
  • Keys: Ctrl+B / I / U, Ctrl+Shift+X (strike), Ctrl+Space (clear), Ctrl+K (link flyout), Ctrl+L / E / R / J (alignment), Ctrl+Shift+8 / 7 (lists), Tab / Shift+Tab (list level), Ctrl+1 / 2 / 3 / 0 (headings, body), Ctrl+] / [ (size), Ctrl+Shift+V (paste text only); Enter in an empty list item ends the list, Backspace at an item's start makes it body text.
  • Clipboard: text (list markers when several paragraphs are copied) and HTML; the HTML holds the exact fragment as JSON in a comment, so copy and paste between richtexts keep every attribute; HTML from browsers and office programs is read (RichDoc::from_html).
  • Flags: RT_READONLY (select, copy; a click opens a link), RT_NO_FRAME, RT_OPEN_LINKS (the editor calls open_url itself), RT_TAB (Tab inserts a tab outside lists), RT_PLAIN_PASTE. High contrast replaces the document's colours by the scheme's.

Code.

// once: the font (as for consoles) and the document
let f = ui.text.load_mem(MONO, 0);
if f >= 0 { ui.mono_font_set(f as u32); }
self.code = CodeDoc::from_text(&text);
self.code.tab_width = 4;               // use_tabs = true indents with tabs
self.hl = Highlighter::for_name("main.rs");   // rust(), json(), ini(), toml(), markdown(), javascript(), css(), html(), wat(), plain()

// in frame: the editor fills its place (ids ID_CODE .. ID_CODE + 15)
ui.next_size(-1, -1);
if ui.code_editor(ID_CODE, &mut self.code, &self.hl, 0) & EV_ACT != 0 { self.dirty = true; }
let st = ui.code_status(ID_CODE);      // line / column of the caret, find matches
ui.text(TS_CAPTION, &format!("Zeile {}, Spalte {}", st.line, st.col));
// saving
let text = self.code.text();
  • The editor shows line numbers, the current line, the bracket pair at the caret (outside strings and comments), a find / replace bar (Ctrl+F / Ctrl+H, incremental, case, whole word, F3 / Shift+F3, Enter / Shift+Enter, "Alle ersetzen" as one undo step); ui.code_find(id, query, replace) opens it from a menu. Enter keeps the indentation (one level more after an opener, the closer of {} on a line of its own), a typed closer on a blank line goes out a level, Tab / Shift+Tab indent the selected lines, Ctrl+/ toggles line comments, Alt+Up / Down move lines, Home toggles first non-blank / column 0, Ctrl+C / X without a selection take the line.
  • Large files: only the visible lines are laid out and highlighted; the editor keeps the state each line starts in and follows CodeDoc::changes_since, so an edit re-highlights only until the old states agree again. 100 000 lines scroll and edit at the speed of a short file (apps/editortest/tests/code_bench.uis).
  • Long lines (minified JSON / JS, logs): of a line of 4 KB and more only the part in view is drawn; the editor keeps checkpoints of its columns and its tokens, and after an edit works them again only near it (tokens from 4 KB before the edit to where the old ones agree again). Typing, moving the caret, selecting, scrolling sideways and find stay well under a millisecond or two per pass on a line of 100 000 characters and on a 1 MB single-line file (apps/editortest/tests/code_longline.uis). A construct that decides by looking more than 4 KB ahead (Markdown emphasis waiting for its closer) catches up when the whole line is highlighted again (another start state or grammar). The editor has no soft wrap; very long lines scroll sideways.
  • Highlighting: a Grammar is a list of Rules tried at each position (line comments, blocks with nesting, strings with escapes and multi-line, word lists, numbers, punctuation, Custom functions) plus a few switches (identifiers before ( are functions, capitalised ones types). An app's own language is a static Grammar and Highlighter::new(&MY_GRAMMAR). h.line(text, state, &mut tokens) is the engine itself (tests, other views).
  • Colours: ui.code_theme() follows the UI (light / dark syntax colours on the text box colours, the high-contrast scheme's few colours with keywords bold); ui.code_theme_set(Some(CodeTheme::dark())) fixes them, ui.code_font_size(pt) sets the size.
  • Flags: CE_READONLY, CE_NO_GUTTER, CE_NO_FRAME, CE_NO_FIND, CE_NO_LINE.
  • Tests: the record of the editor is a text box (expect #3000 text "fn main() {\n "), beyond 64 KB it holds the visible lines. Mouse tests need wait 1000 between clicks on the same editor, else they count as a double click.

Diagnostics (a checker's or compiler's messages) belong to the document:

// after a change (or a pause in typing): lines and columns from 1 as compilers print them
if ui.code_editor(ID_CODE, &mut self.code, &self.hl, CE_MARKS) & EV_ACT != 0 {
    let d: Vec<Diag> = script::check(&self.code.text()).iter()
        .map(|x| Diag::new(x.line as usize, x.col as usize, x.end_col as usize,
                           if x.error { DIAG_ERROR } else { DIAG_WARNING }, &x.msg))
        .collect();
    self.code.set_diagnostics(&d);
    ui.repass();                       // the editor drew the old ones in this pass
}
let st = ui.code_status(ID_CODE);      // st.diags: errors / warnings / infos, st.diag: at the caret
if let Some(d) = ui.code_diag(ID_CODE) { self.status = format!("{}:{}: {}", d.line, d.col, d.msg); }
  • Diag::new(line, col, end_col, severity, msg) marks a part of a line (Diag::span one over lines); columns count characters (a tab is one), the end is exclusive, an end at or before the start marks one character, a column past the line's end its end. Severities DIAG_ERROR, DIAG_WARNING, DIAG_INFO. The positions are those of the text as it is when they are set (a check on another thread: drop its result when doc.revision() changed meanwhile).

  • The editor draws wavy underlines in the severity's colour (CodeTheme::diag; code_theme() takes the UI's critical / warning / info colours) and, on the line where one starts, a marker in a gutter column of their own: a filled circle with a cross, a triangle, an "i" -- shapes, so high contrast and colour-blind readers tell them apart. The column is there while the document has diagnostics; CE_MARKS keeps it, so the text does not move when they come and go. The pointer over an underline or a marker shows the messages as a tooltip ("Fehler: …", most severe first); F8 / Shift+F8 move the caret to the next / previous one (round the end; without diagnostics F8 stays the window's key for the splitters); the ones at the caret are also a K_TEXT record at its line for screen readers.

  • They follow the edits (typing, Enter, deleting, block indent, comments, moved lines, undo / redo) until the app sets new ones: text before a change keeps its place, text after it shifts, a diagnostic whose text was replaced shrinks to what is left of it and is dropped when nothing is, typed text at its edges stays outside. So a check may come later (after a pause in typing) without squiggles sliding off their words. Where they are now: diagnostics() / diagnostic(i) (a problems list), diagnostics_at(pos), next_diagnostic(pos, back), diagnostic_counts().

  • Only the visible lines' diagnostics are drawn, an underline is one command however long it is: 100 000 lines with 13 000 diagnostics scroll and edit at the speed of a short file (apps/editortest/tests/code_diag.uis: hover, F8, edits, checking while typing, shots).

  • Highlighter::jfs() (for_name("x.jfs")) highlights JFScript's language: keywords, true / false / nil, numbers (1_000, 0xFF, 0b101, 1.5e-3), // and /* */, strings with escapes and ${…} whose code is highlighted too (the delimiters are SY_META, so their braces match as a bracket pair). A grammar of one's own gets such strings with Rule::Interp { open, close, start }. editortest --test model compares it token by token with script::tokens.

  • The web's languages (view-source, developer tools): Highlighter::javascript(), css(), html() and wat() (for_name of js / mjs / cjs, css, html / htm / xhtml / xml / svg, wat / wast; the grammars JAVASCRIPT, CSS, HTML, WAT):

    • JavaScript: keywords (a member after . never is one: p.catch(..) is a call), true / null / undefined / NaN, strings with escapes, regular expressions where an expression may start (SY_STRING; a / b stays a division), template strings over lines whose ${…} holds highlighted code (delimiters SY_META, braces inside count), numbers (1n, 0x1F, 1_000), calls, capitalised names as types, // and /* */.
    • CSS: selectors (.class SY_TYPE, #id SY_CONST, :hover / ::before SY_META), at-rules (SY_KEYWORD), blocks over lines with their properties (SY_KEY), numbers with units and %, #fff colours (SY_NUMBER), functions (calc(, url(), !important, nested rules; minified sheets highlight the same.
    • HTML (also XML and SVG): tags over lines (names SY_KEYWORD, attributes SY_KEY, values with or without quotes SY_STRING), comments, CDATA, <!DOCTYPE> / <?xml?> (SY_META), character references (SY_ESCAPE), a lone < as text. The content of <script> is highlighted as JavaScript and that of <style> as CSS up to their end tag, which ends them whatever is open (as a browser does).
    • WAT: module fields and block keywords, instructions (SY_FUNC: i32.add, local.get, call), value and reference types, $names (SY_META), numbers, strings, ;; and nested (; ;) comments.

    Two rules make such languages: Rule::Nest { open, close, kind, inner } highlights the text between two delimiters with another grammar's rules (an HTML tag, a template string and its ${…}; close counts only outside the inner grammar's strings and comments), and Rule::Element { name, tag, inner } an element whose content is another language. The line state then holds the inner grammar's state (three levels: a page, its script's template string, the code in its ${…}). editortest --test model checks tokens and states across lines of all four and the long-line checkpoints of a minified page, script and style sheet.

Language services, breakpoints and folding. A language plugs into the editor with a CodeAssist (like Highlighter for colours): completion items, hover texts and signature help; every method has a default that offers nothing. What needs the app -- go to a definition, rename, format, toggle a breakpoint -- comes back as events.

struct Jfs;                                   // JFScript's services for .jfs
impl CodeAssist for Jfs {
    fn complete(&mut self, doc: &CodeDoc, at: TextPos, _explicit: bool) -> Option<CompList> {
        let c = script::ls::complete(&doc.text(), doc.flat(at) as u32, &script::ls::CompleteCx::default());
        let items = c.items.into_iter()
            .map(|i| CompItem { label: i.label, detail: i.detail, doc: i.doc, kind: CI_FUNCTION, insert: String::new() })
            .collect();
        Some(CompList { start: doc.unflat(c.start as usize), items })
    }
    fn hover(&mut self, doc: &CodeDoc, at: TextPos) -> Option<String> {
        script::ls::hover(&doc.text(), doc.flat(at) as u32, &script::ls::CompleteCx::default()).map(|h| h.text())
    }
}

// in frame: folding ranges from the language after a change, then the editor with the services
if self.folds_rev != Some(self.code.revision()) {
    let f: Vec<(usize, usize)> = script::ls::folding(&self.code.text()).iter()
        .map(|x| (x.line as usize - 1, x.end as usize - 1)).collect();
    self.code.set_fold_ranges(&f);            // lines from 0: first stays, first + 1 ..= last fold
    self.folds_rev = Some(self.code.revision());
}
ui.next_size(-1, -1);
ui.code_editor_with(ID_CODE, &mut self.code, &Highlighter::jfs(), Some(&mut Jfs), CE_BREAKPOINTS);
for e in ui.code_events(ID_CODE) {
    match e {
        CodeEv::Definition(p) => self.jump_to_definition(p),          // Ctrl+click, F12
        CodeEv::Rename(p) => self.ask_new_name(p),                   // F2
        CodeEv::Format => {                                           // Shift+Alt+F
            if let Ok(f) = script::fmt::format(&self.code.text()) {
                self.code.replace_text(&f, "Formatieren");           // one undo step
            }
        }
        CodeEv::Breakpoint(line) => self.toggle_breakpoint(line),     // a click in the column
    }
}
// a rename's edits as one undo step
let edits: Vec<TextEdit> = script::ls::rename(&text, pos, "count")?.iter()
    .map(|e| TextEdit::new(doc.unflat(e.start as usize), doc.unflat(e.end as usize), &e.text)).collect();
doc.apply_edits(&edits, "Umbenennen");
  • The completion list opens while a word is typed (once per word: one without items keeps it closed until the word ends), after a character of triggers() (.) and on Ctrl+Space; it filters as one types (the labels that start with the typed part, matching case first), Up / Down / PgUp / PgDn choose, Enter / Tab / a click insert (the word from CompList::start to the end of the word at the caret becomes the item, one undo step; Enter after a word typed out in full just breaks the line), Esc closes. A row shows a badge for the kind (CI_FUNCTION, CI_METHOD, CI_VARIABLE, CI_KEYWORD ..: a letter in the token colour of the kind), the label in the code font and the detail; the chosen item's doc stands under the rows. ui.code_popup_item(id) and CodeStatus::popup tell what it shows.
  • Hover: the pointer resting on a word asks hover once per word and revision; the text (lines by \n, wrapped at 72 characters) follows the diagnostics in the editor's tooltip. Signature help opens when ( or , is typed and on Ctrl+Shift+Space, follows the caret (the active parameter bold and underlined) and closes outside a call or on Esc. The popups are drawn on the popup layer inside the window in the code theme's colours (high contrast too) and are records for screen readers (K_LIST id + 14 with a K_LISTITEM per visible row, the chosen one selected; K_TEXT "label – parameter – doc"); scripts find rows as listitem:"split – s.split(sep, n)".
  • Breakpoints belong to the app: a click in the column of CE_BREAKPOINTS is CodeEv::Breakpoint(line), doc.set_breakpoints(&[(line, BP_ON | BP_DISABLED | BP_COND)]) draws them (a filled circle, a ring, a bar across), doc.set_exec_line(Some(line)) marks a debugger's line (an arrow and CodeTheme::exec_line); both follow edits like diagnostics. ui.code_reveal(id, line) scrolls the line into view in the editor's next pass (into the middle when it was not in view; the folds hiding it open) without taking the keyboard focus or moving the caret: a debugger shows where it stopped while the page or its toolbar keeps the keyboard (apps/editortest, tests/code_reveal.uis).
  • Folding: ranges from the language (set_fold_ranges; one that starts where a folded one did stays folded), a chevron per range in a column after the numbers (CE_FOLDS keeps it), a click or Ctrl+Shift+[ / ] folds and unfolds, fold_all. Folded lines are out of the view, the caret's moves and find's steps; a "..." box after the line unfolds it; an edit inside or the caret put there by the app (set_selection, undo) unfolds, folding around the caret moves it to the range's first line. Without ranges a row is a line: 100 000 lines stay as fast as before (tests/code_ide.uis benches 80 000 lines with 10 000 folded functions).
  • Tests: apps/editortest/tests/code_assist.uis and code_ide.uis (cmd 906 switches JFScript's services on for JFS), --test model group ide.

Source: docs/GUIDE.md in the JFLib repository.