JFLib

Rich-text and code editors#

ui/ed_core.rs#

Source: lib/ui/ed_core.rs

ed_core -- the editing core of the editors with a text model of their own: richtext
(rich_edit.rs) and code_editor (code_edit.rs)

  TextPos { line, byte }               a place in a document of lines (code) or paragraphs
                                       (rich text): the line and a UTF-8 byte offset in it
  TextSel { anchor, caret }            a selection (anchor == caret: the caret alone)
  (crate) EdView                       what the caret moves need of a widget: the lines'
                                       texts and their visual rows (byte ranges, caret x, y)
  (crate) ed_key(view, sel, prefx, key, page, tab) -> EdAct   what an editing key does:
                                       the caret moves (grapheme clusters, words, rows with
                                       a preferred x, pages, the document; Shift selects),
                                       the range Backspace / Delete remove (+Ctrl: words), Enter,
                                       Tab, clipboard and undo chords; None: not an editing key
  (crate) word_range(text, byte)       the word a double click selects (a run of blanks or of
                                       punctuation as one)
  (crate) Ui::ed_key_first / ed_key_take / ed_caret_on   the key queue past the reservation
                                       of the focused editor, the caret blink

Both widgets take the edit state of the text boxes while they have the focus (edit.rs
ed_hold / ed_drop): the key filter of app-level key() then hides their editing keys,
textbox_selection / textbox_select and a screen reader's selection (Act::Select) work on the
text of their K_TEXTBOX record, the caret reaches magnifiers and the IME through ime_pos.
Keys follow the text boxes: Left / Right (+Ctrl words, +Shift select), Up / Down at the
preferred x, PgUp / PgDn by the view height, Home / End on the visual row (Ctrl: the
document), Backspace / Delete (+Ctrl words), Ctrl+A / C / X / V, Ctrl+Z undo, Ctrl+Y /
Ctrl+Shift+Z redo, Shift+Delete cut, Ctrl+Insert copy, Shift+Insert paste.  Right-to-left the
arrows follow the text (rtl_text_key, applied by the caller).
  • struct TextPos a place in a document: the line (code) or paragraph (rich text) and a UTF-8 byte offset into its text
    • line: usize
    • byte: usize

impl TextPos

  • const fn new(line: usize, byte: usize) -> TextPos the place byte of line line

  • struct TextSel a selection: the anchor stays where it began, the caret moves (equal: no selection)

    • anchor: TextPos
    • caret: TextPos

impl TextSel

  • const fn at(p: TextPos) -> TextSel the caret alone at p
  • const fn new(anchor: TextPos, caret: TextPos) -> TextSel from anchor to caret
  • fn is_empty(&self) -> bool anchor == caret: no text selected
  • fn start(&self) -> TextPos the earlier end
  • fn end(&self) -> TextPos the later end
  • fn range(&self) -> (TextPos, TextPos) (start, end)

ui/rich_doc.rs#

Source: lib/ui/rich_doc.rs

rich_doc -- the document of ui.richtext: paragraphs of formatted runs, the selection and the
undo history (ui::History); JSON, HTML (rich_html.rs) and plain text

  RichDoc::new() / from_plain(s) / from_paras(v) / from_json(s) / from_html(s)
  doc.to_json() / to_html() / to_plain() (list markers) / text() (paragraphs joined by '\n')
  doc.paras() / para(i) / selection() / set_selection(sel) / revision()
  editing at the selection (each one undoable step): insert_text(s), insert_paras(frag)
  (paste), delete(a, b), split() (Enter), toggle(RF_*), set_color / set_bg / set_size /
  set_font / set_link / clear_format, set_align(RA_*), toggle_list(LS_*), indent(delta),
  set_style(PS_*); with an empty selection the character formats apply to the text typed
  next (current_fmt shows them)
  doc.undo() / redo() / can_undo() / can_redo() / undo_label() / is_dirty() / mark_saved()

  Fmt { flags RF_BOLD | RF_ITALIC | RF_UNDER | RF_STRIKE, color, bg, size (1/10 pt),
        font (family), link }      0 / "" = the editor's default
  Para { align RA_*, list LS_*, level 0..8, style PS_* } + its text and runs

JSON ("jfrich" 1):
  {"jfrich":1,"font":"","size":11,"paras":[{"align":"center","list":"bullet","level":1,
   "style":"h1","runs":[{"t":"Hallo ","b":1},{"t":"Welt","i":1,"u":1,"s":1,"color":"#c00000",
   "bg":"#ffff00","size":14.5,"font":"DejaVu Serif","link":"https://example.org"}],
   "mark":{"b":1}}]}
(attributes at their default are left out; "mark" is the format of an empty paragraph).

Positions are TextPos { line: paragraph, byte: UTF-8 offset into the paragraph's text };
a paragraph holds no '\n'.  An edit replaces a range of whole paragraphs (ParaEdit: old and
new paragraphs, the selection before and after), so undo restores text, formats and
paragraph attributes alike; typing and repeated Backspace / Delete merge into one step.
/// Fmt::flags: bold
RF_BOLD: u8 = 1
/// Fmt::flags: italic
RF_ITALIC: u8 = 2
/// Fmt::flags: underlined
RF_UNDER: u8 = 4
/// Fmt::flags: struck through
RF_STRIKE: u8 = 8
/// every flag
RF_ALL: u8 = 15
/// Para::align: start (left)
RA_LEFT: u8 = 0
/// Para::align: centred
RA_CENTER: u8 = 1
/// Para::align: end (right)
RA_RIGHT: u8 = 2
/// both edges (the last row of a paragraph stays left)
RA_JUSTIFY: u8 = 3
/// Para::list: no list
LS_NONE: u8 = 0
/// a bulleted list item (•, ◦, ▪ by level)
LS_BULLET: u8 = 1
/// a numbered list item (1., a., i. by level)
LS_NUMBER: u8 = 2
/// Para::style: body text
PS_NORMAL: u8 = 0
/// headings (bold, larger)
PS_H1: u8 = 1
/// Para::style: heading 2
PS_H2: u8 = 2
/// Para::style: heading 3
PS_H3: u8 = 3
/// a quotation (indented, a bar on the left, the secondary text colour)
PS_QUOTE: u8 = 4
/// the deepest Para::level
LEVEL_MAX: u8 = 8
  • struct Fmt the format of a run of characters; zero / empty fields take the editor's defaults
    • flags: u8 -- RF_BOLD | RF_ITALIC | RF_UNDER | RF_STRIKE
    • color: u32 -- text colour 0xAARRGGBB (0: the theme's text colour)
    • bg: u32 -- highlight colour behind the text (0: none)
    • size: u16 -- size in tenths of a point (0: the document's size)
    • font: String -- font family ("": the document's font)
    • link: String -- link target ("": not a link)

impl Fmt

  • fn flags(flags: u8) -> Fmt the default format with these flags

  • fn bold() -> Fmt bold

  • fn italic() -> Fmt italic

  • struct Para a paragraph: its text (no '\n') with runs of formats, and its attributes. The attribute fields may be set directly while building a document (not undoable; RichDoc's setters are).

    • mark: Fmt -- the format of the paragraph's end: typing into the empty paragraph takes it
    • align: u8 -- RA_*
    • list: u8 -- LS_*
    • level: u8 -- indent / list level 0..LEVEL_MAX
    • style: u8 -- PS_*

impl Para

  • fn new() -> Para an empty body paragraph

  • fn plain(text: &str) -> Para a paragraph of unformatted text ('\n' and '\r' are dropped)

  • fn with(mut self, text: &str, fmt: Fmt) -> Para builder: text in a format appended

  • fn attrs(mut self, align: u8, list: u8, level: u8, style: u8) -> Para builder: the attributes

  • fn push(&mut self, text: &str, fmt: &Fmt) append text in a format ('\n' and '\r' are dropped)

  • fn text(&self) -> &str the paragraph's text (no '\n')

  • fn len(&self) -> usize the text's length in bytes

  • fn is_empty(&self) -> bool no text

  • fn runs(&self) -> impl Iterator<Item = (&str, &Fmt)> + '_ the runs: (text, format)

  • fn spans(&self) -> impl Iterator<Item = (usize, usize, &Fmt)> + '_ the runs as (start, end, format)

  • fn version(&self) -> u32 changes with every edit of the paragraph (layout caches)

  • fn fmt_at(&self, byte: usize) -> &Fmt the format of the character at byte (the last one at the end; the mark when empty)

  • fn typing_fmt(&self, byte: usize) -> Fmt the format typing at byte takes: the character before it (at the start: the first character; empty: the mark); a link ends at its end

  • struct RichDoc the document of ui.richtext (see the module header)

    • font: String -- the document's font family ("": the UI font)
    • size: u16 -- the document's size in tenths of a point (0: 11 pt)

impl RichDoc

  • fn new() -> RichDoc one empty paragraph

  • fn from_paras(mut paras: Vec<Para>) -> RichDoc paragraphs (an empty list: one empty paragraph); the caret at the start

  • fn from_plain(s: &str) -> RichDoc unformatted text: a paragraph per line

  • fn paras(&self) -> &[Para] the content (no history)

  • fn para(&self, i: usize) -> &Para paragraph i (clamped to the last one)

  • fn para_count(&self) -> usize the number of paragraphs (at least 1)

  • fn revision(&self) -> u64 counts the changes of the content (edits, undo, redo; not the selection)

  • fn selection(&self) -> TextSel the selection (the caret: anchor == caret)

  • fn set_selection(&mut self, sel: TextSel) move the selection (clamped to the text, not undoable)

  • fn clamp(&self, p: TextPos) -> TextPos p inside the document, on a character boundary

  • fn end(&self) -> TextPos the end of the document

  • fn text(&self) -> String the text: the paragraphs joined by '\n' (no list markers)

  • fn flat(&self, p: TextPos) -> usize the byte offset of p in text()

  • fn unflat(&self, f: usize) -> TextPos the position of byte offset f of text()

  • fn text_range(&self, a: TextPos, b: TextPos) -> String the text between a and b (paragraphs joined by '\n')

  • fn paras_range(&self, a: TextPos, b: TextPos) -> Vec<Para> the paragraphs between a and b (the first and the last cut there), with attributes

  • fn selected_text(&self) -> String the selected text

  • fn selected_paras(&self) -> Vec<Para> the selected paragraphs (a fragment for the clipboard)

  • fn current_para(&self) -> &Para the paragraph with the caret

  • fn current_fmt(&self) -> Fmt the format typing takes now (a format chosen without a selection, else the text's at the caret); with a selection: its first character's, the flags all of it has

  • fn can_undo(&self) -> bool there is a step to undo

  • fn can_redo(&self) -> bool there is a step to redo

  • fn undo_label(&self) -> Option<&str> the label of the step undo takes back ("Fett", "Schreiben" ...)

  • fn redo_label(&self) -> Option<&str> the label of the step redo does again

  • fn undo(&mut self) -> bool take the last step back -> false: nothing to undo

  • fn redo(&mut self) -> bool do the last undone step again -> false: nothing to redo

  • fn is_dirty(&self) -> bool the content differs from the state of the last mark_saved

  • fn mark_saved(&mut self) the content is saved now (is_dirty false until the next change)

  • fn clear_history(&mut self) forget the undo steps

  • fn group_begin(&mut self, label: &str) the next edits are one undo step (until group_end)

  • fn group_end(&mut self) close the step of group_begin

  • fn insert_text(&mut self, s: &str) -> bool replace the selection by text (a paragraph per line) in the current format

  • fn insert_paras(&mut self, frag: &[Para]) -> bool replace the selection by paragraphs (a paste): several keep their attributes, one is inserted into the paragraph at the caret

  • fn delete_selection(&mut self) -> bool remove the selection

  • fn delete(&mut self, a: TextPos, b: TextPos) -> bool remove a..b (the caret goes to a)

  • fn split(&mut self) -> bool Enter: split the paragraph at the caret (the selection is replaced). In an empty list item the list ends instead (a nested one moves out a level); after a heading the new paragraph is body text.

  • fn toggle(&mut self, flag: u8) -> bool RF_BOLD / RF_ITALIC / RF_UNDER / RF_STRIKE on (when not all of the selection has it) or off

  • fn set_flags(&mut self, flags: u8, on: bool) -> bool set (on) or clear flags

  • fn set_color(&mut self, argb: u32) -> bool the text colour (0: the theme's)

  • fn set_bg(&mut self, argb: u32) -> bool the highlight colour (0: none)

  • fn set_size(&mut self, tenths: u16) -> bool the size in tenths of a point (0: the document's)

  • fn set_font(&mut self, family: &str) -> bool the font family ("": the document's)

  • fn clear_format(&mut self) -> bool back to the default format (links stay)

  • fn set_align(&mut self, align: u8) -> bool RA_* for the selected paragraphs

  • fn toggle_list(&mut self, kind: u8) -> bool LS_BULLET / LS_NUMBER: the selected paragraphs become such list items, or plain paragraphs when all of them already are

  • fn set_list(&mut self, kind: u8) -> bool LS_* without toggling

  • fn indent(&mut self, delta: i32) -> bool one level deeper (delta 1) or out (-1), 0..LEVEL_MAX

  • fn set_style(&mut self, style: u8) -> bool PS_* for the selected paragraphs

  • fn set_paras(&mut self, paras: Vec<Para>) -> bool replace the whole content (one undo step)

  • fn to_json(&self) -> String the document as JSON (see the module header)

  • fn from_json(s: &str) -> Option<RichDoc> a document from to_json's JSON (None: not such a document)

  • fn to_plain(&self) -> String the text with list markers ("• ", "1. ") and two blanks of indent per level

  • fn list_marks(paras: &[Para]) -> Vec<Option<String>> the list marker of every paragraph ("•", "◦", "▪", "1.", "a.", "i." by level; None: no list item). Numbers count the items of a level; a paragraph outside a list or an item of another kind starts again.

ui/rich_html.rs#

Source: lib/ui/rich_html.rs

rich_html -- RichDoc as HTML and back

  doc.to_html() -> String          a fragment: <div style="white-space:pre-wrap"> with <p>,
                                   <h1>..<h3>, <blockquote>, nested <ul> / <ol> (<li>), and
                                   per run <a href>, <span style="color / background-color /
                                   font-size / font-family">, <b>, <i>, <u>, <s>
  RichDoc::from_html(s) -> RichDoc a tolerant reader of what browsers and office programs
                                   put on the clipboard: blocks (p, div, h1..h6, li, ul / ol
                                   nesting, blockquote, pre, tr, br), inline formats (b /
                                   strong, i / em, u / ins, s / strike / del, a href, font,
                                   code, CSS in style attributes: color, background(-color),
                                   font-weight, font-style, text-decoration, font-size in
                                   pt / px / em / % / keywords, font-family, text-align),
                                   entities; script, style and head are skipped
  (crate) clip_html(paras, font, size) the clipboard's HTML: to_html plus the fragment as
                                   JSON in a comment (<!--jfrich ...-->), so a paste into a
                                   richtext keeps every attribute exactly
  (crate) html_read(s) -> HRead   the same reader for the Markdown / HTML viewer
                                   (md_doc.rs): the paragraphs and, by paragraph, what a
                                   viewer shows besides them -- rules, images and form fields
                                   (U+FFFC in the text), preformatted blocks and their
                                   language, the heading level, the quotation depth, table
                                   rows and their cells, the numbers of list items, task
                                   boxes; the forms and their fields (md_doc.rs "Forms").
                                   It reads the element tree of the HTML (md_dom.rs): the
                                   tags as the tree has them, elements with the hidden
                                   attribute or display:none left out
  (crate) dom_read(dom) / dom_para(dom, l)   the same for a tree of a document (MdDoc::html,
                                   its changes): the paragraphs, fields and forms know their
                                   elements; one block element's paragraph read again

Style sheets (the viewer's reader only; RichDoc::from_html takes the style attributes as
before): the <style> elements of the tree (media screen / all, type text/css) and the
<link rel="stylesheet"> elements whose text the app gave (MdDoc::set_sheet: a link reads
nothing by itself) in document order give rules -- selectors of md_dom.rs (tag, *, #id,
.class, [attr], descendant and child) with declarations; comments, at-rules and rules whose selector is not in the subset
are left out.  An element's style is the cascade: the declarations of the rules that match
by specificity and source order, its style attribute's, then the !important ones the same
way (of each property the last).  The text's properties are inherited as the formats are
(colour, weight, style, decoration, size, family, alignment); a link takes the link colour
unless a rule for it gives one.  A block element (and ul, ol, nav, form ...) whose style
gives margins, padding, borders (width, a visible style -- drawn solid -- and colour, per
side) or a background gets a box (md_doc.rs MdBox; its background is the box's, not the
text's).  display:none hides.  Rules are indexed by the id, class or tag their subject needs;
matching has a budget proportional to the tree and the sheets (then no rule matches), at
most RULES_MAX rules.

Whitespace outside <pre> / white-space:pre* collapses as in browsers; a paragraph is a
block or the text between two <br>.  Nesting is capped (NEST_MAX open blocks, formats and
lists: deeper tags count as text-level), so no input costs more than linear time.

impl RichDoc

  • fn to_html(&self) -> String the document as an HTML fragment (see rich_html.rs)
  • fn from_html(s: &str) -> RichDoc a document from HTML (see rich_html.rs); a fragment of a richtext's clipboard is taken exactly

ui/rich_edit.rs#

Source: lib/ui/rich_edit.rs

rich_edit -- ui.richtext: a rich-text editor over a RichDoc (rich_doc.rs), and its toolbar

  ui.richtext(id, &mut doc, RT_*) -> EV_*   the editor, filling the place it gets (natural
       480 x 240 DIP; next_size(-1, -1) fills): the paragraphs wrapped at the width
       (text::segment line breaks, grapheme clusters inside a word too long), runs in their
       fonts (bold / italic: the family's faces, else synthetic), colours, highlight,
       underline / strike, links in the accent colour, alignment (justify spreads the
       blanks), bulleted / numbered lists by level, headings, quotations; a scroll bar.
       EV_ACT: the content changed this frame; EV_FOCUS while focused; EV_COMMIT: the focus
       left.  Ids id .. id + 5 (id + 1 the scroll bar, id + 2 .. 5 the link flyout).
       RT_READONLY: select and copy only (a click opens a link); RT_NO_FRAME: no box;
       RT_OPEN_LINKS: the editor opens an activated http, https or mailto link with open_url
       itself (other links only reach the app); RT_TAB: Tab
       outside a list inserts a tab (else Tab moves the focus on); RT_PLAIN_PASTE: paste
       only text.
  ui.richtext_toolbar(id, editor, &mut doc, RTB_*) -> EV_ACT when it changed doc
       undo / redo, paragraph style, font family (registered families: font_register),
       size, bold / italic / underline / strike, text and highlight colour, link, alignment,
       lists, indent, clear format; the buttons show the state at the caret and give the
       focus back to the editor (ids id .. id + 149)
  ui.richtext_link(id) -> Option<String>   a link the user activated (Ctrl+click, a click
       when read-only, Ctrl+Enter on it), taken once (in a pass: in the window being built
       when it has the editor; outside the passes: in any window)
  ui.richtext_link_dialog(id)              open the editor's link flyout (as Ctrl+K)

Every window keeps its editors' views (WinParts::rich): an editor of the same id in two
windows scrolls and lays out by itself.

Keys (besides those of ed_core.rs): Ctrl+B / I / U bold, italic, underline, Ctrl+Shift+X
strike, Ctrl+Space clear format, Ctrl+K link, Ctrl+L / E / R / J alignment, Ctrl+Shift+8 /
Ctrl+Shift+L bullets, Ctrl+Shift+7 numbers, Ctrl+1 / 2 / 3 headings, Ctrl+0 body text,
Ctrl+] / Ctrl+[ size up / down, Tab / Shift+Tab a list level in / out, Enter a new
paragraph (in an empty list item: the list ends), Backspace at the start of a list item:
the item becomes body text, Ctrl+Shift+V paste text only, Esc drops the focus.  With no
selection a format applies to what is typed next.
Clipboard: CLIP_TEXT (list markers when several paragraphs are copied) and CLIP_HTML
(rich_html.rs: HTML with the exact fragment as JSON in a comment); a paste takes HTML when
there is some (any program's), else the text.  Undo: the document's History (rich_doc.rs).
Accessibility: a K_TEXTBOX record (label: the text, value / max: caret / anchor as byte
offsets into it) as text boxes have, a K_LINK record per visible link; the caret goes to
ime_pos (IME, magnifiers); the editor takes the text boxes' edit state while focused
(ed_hold), so a screen reader can select.  Right-to-left the text keeps its order (as in
text boxes); bidirectional reordering inside a paragraph is not done.

Layout: a paragraph is laid out once per version (Para::version, its attributes, the
width, dpi, text scale and document font); the rows are cached per editor.  Only the
visible paragraphs are drawn.
/// richtext flags: select and copy only
RT_READONLY: u32 = 1
/// no text box frame
RT_NO_FRAME: u32 = 2
/// the editor opens activated http, https and mailto links itself (open_url)
RT_OPEN_LINKS: u32 = 4
/// Tab outside a list inserts a tab
RT_TAB: u32 = 8
/// a paste takes only the text
RT_PLAIN_PASTE: u32 = 16
/// richtext_toolbar groups: undo / redo
RTB_HISTORY: u32 = 1
/// paragraph style, font family, size
RTB_STYLE: u32 = 2
/// bold, italic, underline, strike
RTB_CHARS: u32 = 4
/// text and highlight colour
RTB_COLOR: u32 = 8
/// link
RTB_LINK: u32 = 16
/// alignment
RTB_ALIGN: u32 = 32
/// lists and indent
RTB_LISTS: u32 = 64
/// clear format
RTB_CLEAR: u32 = 128
/// every group
RTB_ALL: u32 = 255

impl Ui

  • fn richtext(&mut self, id: u32, doc: &mut RichDoc, flags: u32) -> u32 ui_richtext(id, doc, RT_*) -> EV_* (see the module header)
  • fn richtext_toolbar(&mut self, id: u32, editor: u32, doc: &mut RichDoc, groups: u32) -> u32 ui_richtext_toolbar(id, editor, doc, RTB_*) -> EV_ACT when it changed doc (see the module header)

ui/code_doc.rs#

Source: lib/ui/code_doc.rs

code_doc -- the document of ui.code_editor: lines of text, the selection, undo (ui::History),
the indentation settings and the edits of a code editor

  CodeDoc::new() / from_text(s)       ('\r\n', '\r' and '\n' end lines)
  doc.text() / line_count() / line(i) / lines() / selection() / set_selection(sel)
  doc.revision()                      counts content changes (edits, undo, redo)
  edits (each one undoable step; typing and repeated Backspace / Delete merge):
    replace(a, b, s) / insert(s) / delete(a, b) / newline(openers) (auto-indent: the line's
    indentation, one level more after an opener, a closer right of the caret on a line of
    its own) / type_text(s) (a closer typed on a blank line goes one level out) / indent(delta)
    (block indent / unindent of the selected lines) / tab() / back_tab() /
    toggle_comment(prefix) / replace_all(q, rep, FIND_*) / replace_next(q, rep, FIND_*)
  find: find_all(q, FIND_*) / find_next(from, q, FIND_*, backwards) (FIND_CASE matches the
    case, FIND_WORD whole words)
  doc.undo() / redo() / can_undo() / can_redo() / undo_label() / is_dirty() / mark_saved()
  tab_width (1..16, default 4), use_tabs (indent with tabs instead of blanks)
  col_of(line, byte) / byte_at_col(line, col)   visual columns (tabs to the next stop,
  wide East Asian characters two)
  diagnostics (a checker's or compiler's messages, drawn by the editor):
    set_diagnostics(&[Diag]) / clear_diagnostics() / diagnostics() -> Vec<Diag> /
    diagnostic(i) / diagnostic_count() / diagnostic_counts() -> [errors, warnings, infos] /
    diagnostics_at(pos) (most severe first) / next_diagnostic(pos, back) (wrapping)
  breakpoints and a debugger's current line (the gutter column of CE_BREAKPOINTS; lines
    from 0): set_breakpoints(&[(line, BP_ON | BP_DISABLED | BP_COND)]) / breakpoints() /
    breakpoint(line) / set_exec_line(Some(line)) / exec_line()
  folding (ranges from a language's services; lines from 0): set_fold_ranges(&[(first,
    last)]) / fold_ranges() / fold_at(line) / set_folded(line, on) / toggle_fold(line) /
    fold_all(on) / fold_around(line) / is_hidden(line) / reveal(line) / visible_lines() /
    row_of_line(line) / line_of_row(row) / visible_line(line, down)
  several changes as one undo step: apply_edits(&[TextEdit], label) (a rename's edits),
    replace_text(text, label) (a formatter's result: only the lines that differ change, the
    caret keeps its place among the non-blank characters)

An edit replaces a range of whole lines (LineEdit: old and new lines, the selection before
and after); each change is also kept in a short journal (changes_since) that the editor's
highlighting states and the find results follow without starting again from the top.

Diagnostics follow every change of the text (edits, undo, redo) until the app sets new
ones: when lines change, the old and new lines are compared -- the same number of lines
line by line (one line moved by Alt+Up / Down: as a move), else as one replaced part from
the first to the last difference.  Text before a change keeps its positions, text after it
shifts; a diagnostic whose text was replaced shrinks to what is left of it and is dropped
when nothing is (one that marks a point stays at the change).  Typed text at a diagnostic's
edge stays outside it.  So squiggles stay under their words while the user types, until
the next check replaces them.  Breakpoints, the execution line and folding ranges follow
the same way by their lines (a line counts as the point at its start); an edit inside the
hidden lines of a folded range unfolds it.  None of them is part of the undo history.
/// find: match the case
FIND_CASE: u8 = 1
/// find: whole words only
FIND_WORD: u8 = 2
/// find_all stops after this many matches
FIND_MAX: usize = 100_000
  • struct LineChange a change of the lines: first .. first + old became first .. first + new (at revision rev)
    • rev: u64
    • first: usize
    • old: usize
    • new: usize
/// Diag::severity: an error
DIAG_ERROR: u8 = 0
/// a warning
DIAG_WARNING: u8 = 1
/// a note, a hint (higher values count as this too)
DIAG_INFO: u8 = 2
  • struct Diag a diagnostic of a code editor: a part of the text in lines and columns from 1 as compilers report them (columns count characters, a tab is one; the end is exclusive, an end at or before the start marks the one character at the start, past a line's end the end of the line), a severity DIAG_* and the message (see the module header)
    • line: usize -- where it starts (from 1)
    • col: usize
    • end_line: usize -- where it ends (exclusive)
    • end_col: usize
    • severity: u8 -- DIAG_ERROR, DIAG_WARNING, DIAG_INFO
    • msg: String

impl Diag

  • fn new(line: usize, col: usize, end_col: usize, severity: u8, msg: &str) -> Diag a part of one line: line:col .. line:end_col
  • fn span(line: usize, col: usize, end_line: usize, end_col: usize, severity: u8, msg: &str) -> Diag line:col .. end_line:end_col
/// a breakpoint's look (CodeDoc::set_breakpoints): set
BP_ON: u8 = 0
/// a breakpoint that is there but off (a ring)
BP_DISABLED: u8 = 1
/// a breakpoint with a condition (a bar across it)
BP_COND: u8 = 2
  • struct TextEdit a change of a CodeDoc's text: a .. b becomes text (CodeDoc::apply_edits)
    • a: TextPos
    • b: TextPos
    • text: String

impl TextEdit

  • fn new(a: TextPos, b: TextPos, text: &str) -> TextEdit

  • struct CodeDoc the document of ui.code_editor (see the module header)

    • tab_width: u8 -- columns between tab stops (1..16)
    • use_tabs: bool -- indent with tabs (else with blanks)

impl CodeDoc

  • fn new() -> CodeDoc one empty line
  • fn from_text(s: &str) -> CodeDoc a text: a line per '\n' ('\r\n' and '\r' too)
  • fn from_lines(mut lines: Vec<String>) -> CodeDoc lines (an empty list: one empty line); they must not hold '\n'
  • fn text(&self) -> String the text: the lines joined by '\n'
  • fn line_count(&self) -> usize the number of lines (at least 1)
  • fn line(&self, i: usize) -> &str line i (clamped to the last one), without its '\n'
  • fn lines(&self) -> &[String] every line
  • fn revision(&self) -> u64 counts the content changes (edits, undo, redo)
  • fn changes_since(&self, rev: u64) -> Option<&[LineChange]> the changes after revision rev, oldest first (None: the journal no longer reaches back that far -- start again)
  • fn selection(&self) -> TextSel the selection (the caret: anchor == caret)
  • fn set_selection(&mut self, sel: TextSel) move the selection (clamped, not undoable)
  • fn clamp(&self, p: TextPos) -> TextPos p inside the document, on a character boundary
  • fn end(&self) -> TextPos the end of the document
  • fn text_range(&self, a: TextPos, b: TextPos) -> String the text between a and b
  • fn selected_text(&self) -> String the selected text (lines joined by '\n')
  • fn flat(&self, p: TextPos) -> usize the byte offset of p in text()
  • fn unflat(&self, f: usize) -> TextPos the position of byte offset f of text()
  • fn col_of(&self, line: usize, byte: usize) -> usize the visual column of byte in a line (tabs to the next stop, wide characters 2)
  • fn byte_at_col(&self, line: usize, col: usize) -> usize the byte of the cluster boundary nearest to column col
  • fn can_undo(&self) -> bool there is a step to undo
  • fn can_redo(&self) -> bool there is a step to redo
  • fn undo_label(&self) -> Option<&str> the label of the step undo takes back
  • fn redo_label(&self) -> Option<&str> the label of the step redo does again
  • fn undo(&mut self) -> bool take the last step back -> false: nothing to undo
  • fn redo(&mut self) -> bool do the last undone step again -> false: nothing to redo
  • fn is_dirty(&self) -> bool the content differs from the state of the last mark_saved
  • fn mark_saved(&mut self) the content is saved now
  • fn clear_history(&mut self) forget the undo steps
  • fn replace(&mut self, a: TextPos, b: TextPos, s: &str) -> TextPos replace a..b by s; the caret after it -> the end of s
  • fn insert(&mut self, s: &str) -> TextPos replace the selection by s (a paste)
  • fn delete(&mut self, a: TextPos, b: TextPos) -> bool remove a..b
  • fn indentation(&self, line: usize) -> &str the leading blanks of a line
  • fn indent_unit(&self) -> String one level of indentation (a tab or tab_width blanks)
  • fn type_text(&mut self, s: &str, closers: &str) -> bool typed text replaces the selection; a closer of closers typed as the first character of a blank line takes one level of indentation away
  • fn newline(&mut self, openers: &str) -> bool Enter: a line break with the line's indentation; after an opener of openers (the last non-blank character before the caret) one level more, and when its closer follows the caret, that goes to a line of its own
  • fn tab(&mut self) -> bool Tab: the selected lines one level in (several lines selected), else the indentation up to the next tab stop at the caret (replacing the selection)
  • fn back_tab(&mut self) -> bool Shift+Tab: the selected lines (or the caret's) one level out
  • fn indent(&mut self, delta: i32) -> bool the selected lines (a selection ending at a line start leaves that line out) one level in (delta > 0) or out; the selection follows its text
  • fn toggle_comment(&mut self, prefix: &str) -> bool line comments on (when not every selected non-blank line has one) or off
  • fn move_lines(&mut self, delta: i32) -> bool Alt+Up / Alt+Down: the selected lines move one line up (delta < 0) or down
  • fn find_all(&self, q: &str, opts: u8) -> Vec<(TextPos, TextPos)> every match of q (FIND_CASE, FIND_WORD), at most FIND_MAX
  • fn find_lines(&self, q: &str, opts: u8, first: usize, n: usize) -> Vec<(TextPos, TextPos)> the matches of q in lines first .. first + n
  • fn find_next(&self, from: TextPos, q: &str, opts: u8, backwards: bool) -> Option<(TextPos, TextPos)> the next match after from (backwards: the last one before it), wrapping around
  • fn sel_is_match(&self, q: &str, opts: u8) -> bool the selection is a match of q
  • fn replace_next(&mut self, q: &str, rep: &str, opts: u8) -> bool replace the selection when it is a match, then select the next match -> replaced
  • fn replace_all(&mut self, q: &str, rep: &str, opts: u8) -> usize replace every match (one undo step) -> how many
  • fn set_diagnostics(&mut self, d: &[Diag]) replace the diagnostics (Diag positions, clamped to the text); from now on they follow the edits until the next call (see the module header)
  • fn clear_diagnostics(&mut self) no diagnostics
  • fn diagnostics(&self) -> Vec<Diag> the diagnostics where they are now, by position
  • fn diagnostic_count(&self) -> usize the number of diagnostics
  • fn diagnostic(&self, i: usize) -> Option<Diag> diagnostic i (0 .. diagnostic_count(), by position) where it is now
  • fn diagnostic_counts(&self) -> [usize; 3] the number of errors, warnings and infos (DIAG_* order)
  • fn diagnostics_at(&self, p: TextPos) -> Vec<Diag> the diagnostics at p (their part holds p, its end included; a point: its character), most severe first
  • fn next_diagnostic(&self, p: TextPos, back: bool) -> Option<TextPos> the start of the first diagnostic after p (back: the last one before p), round the end of the text; None without diagnostics
  • fn set_breakpoints(&mut self, bps: &[(usize, u8)]) the breakpoints: (line from 0, BP_*), drawn in the gutter column of CE_BREAKPOINTS (the app keeps the real ones: a click there is CodeEv::Breakpoint); they follow the edits with their lines until the next call
  • fn breakpoints(&self) -> &[(usize, u8)] the breakpoints where they are now, by line
  • fn breakpoint(&self, line: usize) -> Option<u8> the breakpoint of a line
  • fn set_exec_line(&mut self, line: Option<usize>) the line a debugger stopped at (None: none), drawn marked with an arrow in the breakpoints' column; it follows the edits
  • fn exec_line(&self) -> Option<usize> the line of set_exec_line where it is now
  • fn set_fold_ranges(&mut self, ranges: &[(usize, usize)]) the folding ranges (first, last) with lines from 0 (a language's services give them): line first stays, first + 1 ..= last fold away. A range that starts on the line of a folded one stays folded; ranges follow the edits, and an edit inside the hidden lines of a folded range unfolds it
  • fn fold_count(&self) -> usize the number of folding ranges
  • fn fold_ranges(&self) -> Vec<(usize, usize, bool)> the folding ranges where they are now: (first, last, folded)
  • fn fold_at(&self, line: usize) -> Option<(usize, bool)> the range that starts at line: (last, folded)
  • fn set_folded(&mut self, line: usize, folded: bool) -> bool fold (folded) or unfold the range that starts at line -> changed
  • fn toggle_fold(&mut self, line: usize) -> bool fold or unfold the range that starts at line -> changed
  • fn fold_all(&mut self, folded: bool) every range folded (true) or unfolded
  • fn fold_around(&self, line: usize) -> Option<(usize, usize)> the innermost range that holds line (its first line counts): (first, last)
  • fn is_hidden(&self, line: usize) -> bool line is hidden in a folded range
  • fn reveal(&mut self, line: usize) -> bool unfold every range that hides line -> changed
  • fn visible_lines(&self) -> usize the lines that are not hidden
  • fn row_of_line(&self, line: usize) -> usize the visible row of a line (counting only lines that are not hidden; a hidden line: the row of its fold's first line)
  • fn line_of_row(&self, row: usize) -> usize the line of a visible row
  • fn visible_line(&self, line: usize, down: bool) -> usize the nearest line that is not hidden from line on, downwards (down) or upwards
  • fn apply_edits(&mut self, edits: &[TextEdit], label: &str) -> bool several changes as one undo step named label: the edits (positions in the text before any of them, in any order, not overlapping) replace their parts; the selection follows the text (inside a replaced part: to its new end) -> false when nothing changed or two edits overlap. Rename and format of a language service go through here
  • fn replace_text(&mut self, text: &str, label: &str) -> bool the whole text becomes text as one undo step; only the lines that differ change (the diagnostics, breakpoints and folds of the others stay), and the caret keeps its place among the characters that are no blanks (so after a formatter it stays at its token) -> changed

ui/highlight.rs#

Source: lib/ui/highlight.rs

highlight -- syntax highlighting for ui.code_editor: a small engine of token rules, the
built-in grammars (Rust, JSON, INI, TOML, a Markdown subset, JFS: the scripts of
JFScript; JavaScript, CSS, HTML with its scripts and styles, WAT: the text format of
WebAssembly) and the colours of the tokens

  Highlighter::rust() / json() / ini() / toml() / markdown() / jfs() / plain()
  Highlighter::javascript() / css() / html() / wat()   (E10: view-source, developer tools)
  Highlighter::for_name(s)            by name or file extension ("rs", "json", "ini", "cfg",
                                      "toml", "md", "jfs", "js", "css", "html", "xml", "svg",
                                      "wat", a path); plain() for anything else
  Highlighter::new(&GRAMMAR)          an app's own grammar (a static Grammar of Rules)
  h.line(text, state, &mut tokens) -> state   the tokens of one line (SY_* kinds, byte
                                      ranges; the plain text between them is SY_TEXT) from
                                      the state the line before ended in; 0 = nothing open
  h.tokens(text) -> Vec<Vec<Token>>   every line of a text (tests)
  CodeTheme::light() / dark() / high_contrast(&HcColors), ui.code_theme()   the colours of
                                      the tokens and the editor (gutter, current line,
                                      selection, bracket match, find matches, diagnostics,
                                      breakpoints, a debugger's current line)

A grammar is a list of rules tried in order at every position: line comments, blocks (from
open to close, nested or not, optionally only at a line start: Markdown fences), strings
(escapes, multi-line or not), strings with code inside (Interp: the ${..} of JFS, whose
code the same rules highlight), Rust raw strings, word lists, numbers, punctuation and
functions of its own (Custom: JSON keys, Rust char literals / lifetimes / attributes, INI
sections and keys, Markdown headings, lists, emphasis and links), parts with rules of their
own (Nest: HTML's tags, JavaScript's template strings and their ${..}) and elements whose
content is another language (Element: HTML's <script> and <style>).  Where no rule matches,
an identifier is read whole: before '(' a function (calls), before '!' a macro (macros),
capitalised a type (caps_types).  A construct still open at a line end is the line's end
state: rule index + 1, the nesting depth (bits 8..15) and a Rust raw string's '#' count
(bits 16..31); inside a Nest or an Element the inner grammar's state in bits 8..31 (so
three levels: HTML, a script's template string, its ${..}); the editor keeps a state per
line and highlights only the visible lines.
/// token kinds: plain text
SY_TEXT: u8 = 0
/// token kinds: keywords
SY_KEYWORD: u8 = 1
/// types (lists, capitalised names)
SY_TYPE: u8 = 2
/// functions, macros
SY_FUNC: u8 = 3
/// strings, character literals
SY_STRING: u8 = 4
/// numbers, dates
SY_NUMBER: u8 = 5
/// comments, Markdown quotations
SY_COMMENT: u8 = 6
/// true / false / null, enum constants
SY_CONST: u8 = 7
/// operators, brackets, separators
SY_PUNCT: u8 = 8
/// attributes, lifetimes, preprocessor lines
SY_META: u8 = 9
/// JSON / INI / TOML keys
SY_KEY: u8 = 10
/// Markdown headings, INI / TOML sections
SY_HEADING: u8 = 11
/// Markdown *emphasis*
SY_EMPH: u8 = 12
/// Markdown **strong**
SY_STRONG: u8 = 13
/// links, URLs
SY_LINK: u8 = 14
/// Markdown code spans and blocks
SY_CODE: u8 = 15
/// escape sequences in strings
SY_ESCAPE: u8 = 16
/// the number of kinds
SY_COUNT: usize = 17
  • struct Token a highlighted part of a line: bytes start .. end

    • start: usize
    • end: usize
    • kind: u8
  • enum Rule a rule of a grammar (see the module header)

    • LineComment(&'static str) -- from the text to the end of the line: a comment
    • Block { open: &'static str, close: &'static str, kind: u8, nested: bool, bol: bool } -- from open to close (nested: opens inside count; bol: open and close only at the start of a line, after blanks -- the whole line belongs to it); may span lines
    • Str { open: &'static str, close: &'static str, escape: bool, multi: bool, kind: u8 } -- a string from open to close; escape: a backslash takes the next character (SY_ESCAPE); multi: may span lines
    • RawStr -- Rust raw strings: r"..", r#".."#, br".." (may span lines)
    • Interp { open: &'static str, close: &'static str, start: &'static str } -- a string with code inside (interpolation), on one line: from open to close, a backslash takes the next character (\u{..} its hex digits and brace; SY_ESCAPE); from start (ending with '{') to the '}' that closes it (braces inside count) the grammar's rules highlight code, the two delimiters SY_META
    • Words(&'static [&'static str], u8) -- identifiers of a list
    • Number -- number literals: 12, 0x1F, 0b101, 0o17, 1_000, 1.5e-3, suffixes (u8, f32)
    • Custom(fn(&str, usize, bool) -> Option<(usize, u8)>) -- a function of its own: (line, position, at the line start after blanks) -> (bytes, kind)
    • Punct(&'static str) -- single characters
    • Nest { open: &'static str, close: &'static str, kind: u8, inner: &'static Grammar } -- a part with rules of its own: from open to close (may span lines), the two delimiters kind, the text between them highlighted by inner's rules (HTML's tags, the ${..} of JavaScript's template strings); close counts only outside inner's strings and comments, and with close "}" the braces inside count
    • Element { name: &'static str, tag: &'static Grammar, inner: &'static Grammar } -- an element whose content is another language (HTML's script and style): the start tag from '<' and name (ASCII case-insensitive, then a blank, '/' or '>') to its '>' on the same line ('<' and '>' SY_PUNCT, the rest by tag's rules), then the content up to "</" and name (case-insensitive, wherever it stands) by inner's rules; may span lines; the end tag is the grammar's own again
  • struct Grammar a language (see the module header)

    • name: &'static str
    • exts: &'static [&'static str] -- file extensions (lower case, without the dot)
    • rules: &'static [Rule]
    • ident: &'static str -- characters inside identifiers besides letters, digits and '_'
    • calls: bool -- an identifier before '(' is a function
    • macros: bool -- an identifier before '!' is a macro (Rust)
    • caps_types: bool -- capitalised identifiers are types
    • comment: &'static str -- the line comment of Ctrl+/ ("": none)
    • openers: &'static str -- Enter after one of these indents one level more
    • closers: &'static str -- one of these typed on a blank line goes one level out
    • pairs: &'static str -- the bracket pairs the editor matches: "()[]{}"
  • struct Highlighter the highlighter of a grammar (see the module header)

impl Highlighter

  • const fn new(g: &'static Grammar) -> Highlighter an app's own grammar

  • const fn plain() -> Highlighter plain text: no tokens

  • const fn rust() -> Highlighter Rust

  • const fn json() -> Highlighter JSON (and JSONC comments)

  • const fn ini() -> Highlighter INI files

  • const fn toml() -> Highlighter TOML

  • const fn markdown() -> Highlighter a Markdown subset

  • const fn jfs() -> Highlighter the scripting language of JFScript (.jfs, JFNetworker's scripts)

  • const fn javascript() -> Highlighter JavaScript (template strings over lines with their ${..}, regular expressions)

  • const fn css() -> Highlighter CSS (selectors, at-rules, properties, values with units and colours, nested rules)

  • const fn html() -> Highlighter HTML (also XML and SVG): tags, attributes, comments, entities, doctype; the content of <script> as JavaScript and of <style> as CSS

  • const fn wat() -> Highlighter WAT, the text format of WebAssembly (modules, instructions, $names, types)

  • fn for_name(s: &str) -> Highlighter by name or extension, also of a path ("rs", "Rust", "x/y.toml"); plain() for others

  • fn grammar(&self) -> &'static Grammar the grammar (comment prefix, openers, closers, bracket pairs)

  • fn name(&self) -> &'static str the grammar's name ("Rust", "JSON" ...)

  • fn line(&self, t: &str, state: u32, out: &mut Vec<Token>) -> u32 the tokens of one line from the state of the line before -> the state at its end

  • fn tokens(&self, text: &str) -> Vec<Vec<Token>> the tokens of every line of a text (tests)

  • static RUST: Grammar Rust

  • static JSON: Grammar JSON (comments of JSONC too)

  • static INI: Grammar INI files (; and # comments at a line start, [sections], key = value, key: value)

  • static TOML: Grammar TOML

  • static MARKDOWN: Grammar a Markdown subset: headings, quotations, rules, lists, fenced code, code spans, emphasis, strong, links, escapes, HTML comments

  • static JFS: Grammar the scripting language of JFScript (.jfs): calls before '(' are functions, the delimiters of ${..} in strings SY_META

  • static JAVASCRIPT: Grammar JavaScript: keywords, constants, strings, template strings over lines (their ${..} with SY_META delimiters, code inside), regular expressions (SY_STRING), numbers (also 1n, 0x.., 1_000), // and /* */ comments; calls before '(' are functions, capitalised names types, a member after '.' never a keyword

  • static CSS: Grammar CSS: selectors (.class SY_TYPE, #id SY_CONST, :pseudo SY_META), at-rules (SY_KEYWORD), blocks over lines with properties (SY_KEY), numbers with units, #colours (SY_NUMBER), functions, !important, strings, /* */ comments; nested rules

  • static HTML: Grammar HTML (XML and SVG too): tags over lines (names SY_KEYWORD, attributes SY_KEY, values SY_STRING, '<' and '>' SY_PUNCT), comments, CDATA (SY_CODE), <!DOCTYPE> and <?xml?> (SY_META), character references (SY_ESCAPE); the content of <script> highlighted as JavaScript and of <style> as CSS up to its end tag

  • static WAT: Grammar WAT, the text format of WebAssembly: module fields and block keywords (SY_KEYWORD), instructions (SY_FUNC: i32.add, local.get, call ...), value and reference types (SY_TYPE), $names (SY_META), numbers, strings, ;; and nested (; ;) comments

  • static PLAIN: Grammar plain text: no tokens

  • struct CodeTheme the colours of a code editor (0xAARRGGBB); bold / italic: a bit per SY_* kind

    • bg: u32
    • fg: u32
    • gutter_bg: u32
    • gutter_fg: u32
    • gutter_cur: u32 -- the current line's number
    • line_hl: u32 -- the current line's background
    • sel: u32 -- the selection (focused / not focused)
    • sel_inactive: u32
    • sel_text: u32 -- the selected text (0: the tokens keep their colours)
    • bracket: u32 -- the frame around a matching bracket pair
    • find: u32 -- the find matches and the current one
    • find_cur: u32
    • find_frame: bool -- find matches framed instead of filled (high contrast)
    • caret: u32
    • tokens: [u32; SY_COUNT]
    • bold: u32
    • italic: u32
    • diag: [u32; 3] -- the wavy underlines and gutter markers of errors, warnings and infos (DIAG_* order)
    • breakpoint: u32 -- breakpoints in the gutter
    • exec_line: u32 -- the background of a debugger's current line (the editor's background: a frame in exec_mark instead) and its arrow in the gutter
    • exec_mark: u32

impl CodeTheme

  • fn light() -> CodeTheme on a light background (the colours of GitHub's light theme)
  • fn dark() -> CodeTheme on a dark background (the colours of GitHub's dark theme)
  • fn high_contrast(c: &plat::HcColors) -> CodeTheme the colours of a high-contrast scheme: few colours, keywords and headings bold; diagnostics in the text, link and highlight colours (the gutter markers' shapes tell them apart too)

impl crate::Ui

  • fn code_theme(&self) -> CodeTheme the code editors' colours for the UI's theme: dark / light syntax colours on the UI's text box colours (accent selection, diagnostics in its critical / warning / info colours), or the high-contrast scheme's colours

ui/code_edit.rs#

Source: lib/ui/code_edit.rs

code_edit -- ui.code_editor: a code editor over a CodeDoc (code_doc.rs) with syntax
highlighting (highlight.rs)

  ui.code_editor(id, &mut doc, &hl, CE_*) -> EV_*   the editor, filling the place it gets
       (natural 560 x 320 DIP; next_size(-1, -1) fills): line numbers, the monospace font
       of mono_font_set (else the system's), tabs to tab_width, the current line, the
       bracket pair at the caret, a find / replace bar, scroll bars.  Only the visible lines
       are laid out and highlighted (the editor keeps each line's start state and follows
       the document's change journal), so a file of 100 000 lines scrolls as fast as a
       short one; of a long line only the part in view (code_long.rs keeps the columns and
       tokens of long lines and works them again near an edit only), so typing in a line of
       1 MB is as fast as in a short one.  EV_ACT: the text changed; EV_FOCUS while
       focused; EV_COMMIT: the focus left.  Ids id .. id + 15 (id + 1 / + 2 the scroll bars,
       + 3 .. 13 the find bar).
       CE_READONLY: select, copy and find only; CE_NO_GUTTER: no line numbers;
       CE_NO_FRAME: no box; CE_NO_FIND: no find bar; CE_NO_LINE: no current-line highlight;
       CE_MARKS: the gutter keeps its column of diagnostic markers while there are none;
       CE_BREAKPOINTS: a column for breakpoints at the gutter's left (also there while the
       document has breakpoints or an execution line); CE_FOLDS: the folding column stays
       while the document has no folding ranges
  ui.code_editor_with(id, &mut doc, &hl, Some(&mut assist), CE_*)   the same with a
       language's services (code_assist.rs: completion popup, hover tooltips, signature
       help); ids id + 14 (the completion list) and id + 15 are the editor's too
  ui.code_events(id) -> Vec<CodeEv>   what the user asked for in the editor's last pass:
       Definition(pos) (Ctrl+click, F12), Rename(pos) (F2), Format (Shift+Alt+F),
       Breakpoint(line) (a click in the breakpoints' column); the app answers (a jump,
       CodeDoc::apply_edits / replace_text as one undo step, set_breakpoints);
       ui.code_popup_item(id) the completion item the list has chosen (None: closed)
  ui.code_find(id, query, replace)   open the find bar (replace: with the replace row) with
       a query; the editor selects the first match from the caret on
  ui.code_reveal(id, line)   scroll line (from 0) into view in the editor's next pass, in the
       middle when it was not in view, the folds hiding it opened -- without the keyboard
       focus, the caret or the selection (a debugger's execution line)
  ui.code_status(id) -> CodeStatus   line and column of the caret (from 1), the matches
       and the current one, the lines tokenized in the last frame, the document's
       diagnostics per severity and the severity of the one at the caret, the completion
       list's items and choice, whether signature help is open, the lines folded away
  ui.code_diag(id) -> Option<Diag>   the (most severe) diagnostic at the caret, its message
  ui.code_theme_set(Some(theme))     the colours of every code editor (None: code_theme())
  ui.code_font_size(pt)              the size of the code editors' font (default 10 pt)

Every window keeps the state of its editors (WinParts::code): an editor of the same id in two
windows scrolls, finds and pops up by itself.  code_find and code_reveal made in a window's
pass are for that window's editor (when it has one of the id), else (outside the passes:
App::command) for the first editor of the id that is built; code_status, code_diag,
code_events and code_popup_item read the window being built's editor, else the first window's
(the main window first) that has one.

Diagnostics (CodeDoc::set_diagnostics; they follow the edits, code_doc.rs) are wavy
underlines below their text in the colour of their severity (infos below warnings below
errors; a point or the end of a line: one cell) and a marker in the gutter's first column on
the line where one starts (the most severe: a filled circle with a cross, a triangle, an
"i" -- shapes, not only colours, also in high contrast).  The column is there while the
document has diagnostics (CE_MARKS: always, so the text does not move).  The pointer over an
underline or a marker shows the messages as a tooltip ("Fehler: ...", most severe first);
the ones at the caret are in code_status / code_diag and a K_TEXT record at the caret's line
for screen readers (after the editor's record: the app's post-modifiers stay the editor's).
Only the diagnostics of the visible lines are looked at (binary search by position), an
underline is one command however long it is.

Keys (besides those of ed_core.rs): Tab / Shift+Tab indent / unindent (several lines: the
block), Enter a line break with the indentation (one level more after an opener), a closer
typed on a blank line goes one level out, Backspace in leading blanks back to the previous
tab stop, Home toggles between the first non-blank and column 0, Ctrl+C / Ctrl+X without a
selection the whole line, Ctrl+/ line comments, Alt+Up / Alt+Down move the lines, Ctrl+Up /
Ctrl+Down scroll, Ctrl+F find, Ctrl+H replace, F3 / Shift+F3 (Enter / Shift+Enter in the
find box) the next / previous match, F8 / Shift+F8 the caret to the start of the next /
previous diagnostic (round the end; without diagnostics F8 stays the window's key for the
splitters), Esc closes the find bar (else drops the focus),
Ctrl+Tab (read-only: Tab) moves the focus on.  Mouse: click, drag, Shift+click, double
click a word, a click or drag in the gutter selects lines, the wheel (Shift: sideways).
Accessibility: a K_TEXTBOX record with the text (beyond 64 KB: the visible lines) and the
caret / anchor as byte offsets into it, ime_pos for IME and magnifiers, the edit state of
the text boxes while focused (ed_hold).

Language services (code_editor_with; code_assist.rs has the popups): Ctrl+Space opens the
completion list (typing a word or a trigger character opens it too), Ctrl+Shift+Space
signature help, the pointer resting on a word shows the assist's hover text (after the
diagnostics there), F12 / Ctrl+click, F2 and Shift+Alt+F are CodeEv.  The gutter from the
left: breakpoints (CE_BREAKPOINTS: a filled circle, a ring when disabled, a bar across it
with a condition; the execution line an arrow there and a marked background), diagnostic
markers, line numbers, folding (a chevron on the first line of each of the document's
folding ranges: a click folds / unfolds; Ctrl+Shift+[ / ] at the caret's line).  Folded
lines are left out of the view (rows count only the visible lines), the caret skips them
(Up / Down / Left / Right / PgUp / PgDn), find steps over their matches, a "⋯" box after a
folded line unfolds it on a click, and an edit inside them or the caret landing there (an
app's set_selection, undo) unfolds them.  Without folds a row is a line, so 100 000 lines
stay as fast as before.
/// code_editor flags: select, copy and find only
CE_READONLY: u32 = 1
/// no line numbers
CE_NO_GUTTER: u32 = 2
/// no text box frame
CE_NO_FRAME: u32 = 4
/// no find bar
CE_NO_FIND: u32 = 8
/// no highlight of the current line
CE_NO_LINE: u32 = 16
/// the gutter keeps its column of diagnostic markers while the document has none
CE_MARKS: u32 = 32
/// the gutter's column of breakpoints (a click there: CodeEv::Breakpoint)
CE_BREAKPOINTS: u32 = 64
/// the gutter keeps its folding column while the document has no folding ranges
CE_FOLDS: u32 = 128
  • struct CodeStatus what code_status reports
    • line: usize -- the caret's line and column (from 1; columns with tabs expanded)
    • col: usize
    • matches: usize -- the find bar's matches (0: none or closed) and the current one (from 1; 0: none)
    • current: usize
    • hl_lines: usize -- the lines tokenized for highlighting states in the editor's last frame (the visible lines are tokenized again to draw them, not counted)
    • lines: usize -- the number of lines
    • diags: [usize; 3] -- the document's diagnostics: errors, warnings, infos (DIAG_* order)
    • diag: Option<u8> -- the severity (DIAG_*) of the most severe diagnostic at the caret (ui.code_diag: the diagnostic with its message)
    • popup: usize -- the items the completion list shows (0: closed) and the chosen one (from 0)
    • popup_sel: usize
    • sig: bool -- signature help is open
    • hidden: usize -- the lines folded away

impl Ui

  • fn code_theme_set(&mut self, theme: Option<CodeTheme>) the colours of every code editor (None: code_theme(), following the UI's theme)
  • fn code_font_size(&mut self, pt: f32) the size of the code editors' font in points (0: 10 pt)
  • fn code_find(&mut self, id: u32, query: &str, replace: bool) open the find bar of code editor id with a query (replace: with the replace row); the editor selects the first match from its caret on. Called in a window's pass: that window's editor (when it has one of the id); else (App::command, a window without one) the first editor of the id built next
  • fn code_reveal(&mut self, id: u32, line: usize) scroll code editor id so that line (from 0) is in view in its next pass: in the middle of the view when it was not in it (no scroll when it was), the folded ranges that hide it unfolded. The keyboard focus, the caret and the selection stay as they are: a debugger shows the execution line while the page or its toolbar keeps the keyboard (CodeDoc::set_exec_line marks it). A later request for the same editor replaces it. Called in a window's pass: that window's editor (when it has one of the id); else (App::command, a window without one) the first editor of the id built next
  • fn code_status(&self, id: u32) -> CodeStatus the caret, the find matches, the lines tokenized and the diagnostics in code editor id's last frame (of the window being built; outside the passes, or when that window has none of the id, the first window's that has one, the main window first)
  • fn code_diag(&self, id: u32) -> Option<Diag> the most severe diagnostic at the caret of code editor id in its last frame (its message for a status bar)
  • fn code_events(&self, id: u32) -> Vec<CodeEv> what the user asked of code editor id in its last pass (go to definition, rename, format, a breakpoint's click)
  • fn code_popup_item(&self, id: u32) -> Option<CompItem> the item the completion list of code editor id has chosen (None: closed)
  • fn code_editor(&mut self, id: u32, doc: &mut CodeDoc, h: &Highlighter, flags: u32) -> u32 ui_code_editor(id, doc, hl, CE_*) -> EV_* (see the module header)
  • fn code_editor_with(&mut self, id: u32, doc: &mut CodeDoc, h: &Highlighter, mut assist: Option<&mut dyn CodeAssist>, flags: u32) -> u32 code_editor with a language's services (completion, hover, signature help; see the module header and code_assist.rs)

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