Skip to main content

taut/
code_editor.rs

1//! Code editor: source code, config files, anything line-based.
2//! [`ui.code_editor(&mut code, "Source")`](Ui::code_editor), where `code` is a [`CodeEditor`]
3//! the app keeps: the text and the editing state (cursors, undo, folds).
4//!
5//! Fast at any file size. The text is one `String`, with each line's start offset kept beside
6//! it: an edit re-finds the lines it touched and shifts the rest. Only visible rows are
7//! described (as [`Ui::rows`] does for a large list), a box per run of one colour. Colouring a
8//! line needs what was left open before it (a block comment, a multi-line string): that is kept
9//! per line, computed only up to the visible lines, and after an edit recomputed only until it
10//! matches the old value again.
11//!
12//! A language's syntax is plain data ([`Syntax`]): keywords, type names, comment and string
13//! syntax. A few languages are built in; an app writes rules for others the same way.
14use crate::color::Color;
15use crate::event::{Cursor, Key, Mods};
16use crate::id::Id;
17use crate::layout::{Align, Flow, Length};
18use crate::platform::Clipboard;
19use crate::text::{Font, cluster};
20use crate::text_edit::{in_word, step, word, word_edge};
21use crate::theme::Theme;
22use crate::ui::{Icon, Response, Stroke, Ui};
23use crate::widgets::{CROSS, DOWN, RIGHT};
24use std::ops::Range;
25use std::time::Duration;
26
27/// Undo depth.
28const HISTORY: usize = 500;
29/// An edit at more places than this re-indexes every line, not line by line.
30const MANY: usize = 64;
31/// How many lines away a matching bracket is searched for.
32const PAIRED_WITHIN: usize = 2000;
33/// Line-end state: inside a block comment.
34const IN_COMMENT: u8 = 1;
35/// Opening brackets, each with its closing one.
36const BRACKETS: [(char, char); 3] = [('(', ')'), ('[', ']'), ('{', '}')];
37/// The up arrow, for the find-previous button.
38const UP: Icon = Icon::line("M4 9.5 8 5.5 12 9.5");
39
40/// A code token's kind, for its colour.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum TokenKind {
43    /// Identifiers, punctuation, and anything else.
44    Plain,
45    /// A keyword: `fn`, `if`, `return`.
46    Keyword,
47    /// A type name: `u32`, `String`.
48    Type,
49    /// A number: `42`, `0xff`, `1.5`.
50    Number,
51    /// A string literal.
52    String,
53    /// A comment.
54    Comment,
55}
56
57impl TokenKind {
58    /// Its colour in a theme.
59    pub fn color(self, theme: &Theme) -> Color {
60        match self {
61            TokenKind::Plain => theme.text,
62            TokenKind::Keyword => theme.accent,
63            TokenKind::Type => theme.blue,
64            TokenKind::Number => theme.amber,
65            TokenKind::String => theme.green,
66            TokenKind::Comment => theme.text_faint,
67        }
68    }
69}
70
71/// A string syntax of a language.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct StringSyntax {
74    /// Opening and closing delimiters. (A backslash escapes the next character.)
75    pub delimiters: [&'static str; 2],
76    /// It may span lines. (Else a line end ends it, closed or not.)
77    pub multiline: bool,
78    /// It holds one character, or one escape: `'a'`, `'\n'`. A delimiter not closed right after
79    /// is no literal (Rust's `'a`, a lifetime).
80    pub char_literal: bool,
81}
82
83/// A language's syntax for highlighting, and what indents the next line: plain data, so an app
84/// writes rules for its own language the same way.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub struct Syntax {
87    /// Keywords.
88    pub keywords: &'static [&'static str],
89    /// Built-in type names.
90    pub types: &'static [&'static str],
91    /// A capitalized word is a type name too.
92    pub capitalized_types: bool,
93    /// Line comment start; "" for none.
94    pub line_comment: &'static str,
95    /// Block comment start and end; "" for none.
96    pub block_comment: [&'static str; 2],
97    /// String syntaxes. Where two start alike, the longer first.
98    pub strings: &'static [StringSyntax],
99    /// Line-end characters after which Enter indents one more step.
100    pub indent_after: &'static str,
101}
102
103impl Syntax {
104    /// No highlighting: every token is plain.
105    pub const PLAIN: Syntax = Syntax { keywords: &[], types: &[], capitalized_types: false, line_comment: "", block_comment: ["", ""], strings: &[], indent_after: "([{" };
106    /// Rust.
107    pub const RUST: Syntax = Syntax {
108        keywords: &[
109            "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut",
110            "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while",
111        ],
112        types: &["bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64"],
113        capitalized_types: true,
114        line_comment: "//",
115        block_comment: ["/*", "*/"],
116        strings: &[StringSyntax { delimiters: ["\"", "\""], multiline: true, char_literal: false }, StringSyntax { delimiters: ["'", "'"], multiline: false, char_literal: true }],
117        indent_after: "([{",
118    };
119    /// C and C++.
120    pub const C: Syntax = Syntax {
121        keywords: &[
122            "auto",
123            "break",
124            "case",
125            "catch",
126            "class",
127            "const",
128            "continue",
129            "default",
130            "delete",
131            "do",
132            "else",
133            "enum",
134            "extern",
135            "false",
136            "for",
137            "goto",
138            "if",
139            "inline",
140            "namespace",
141            "new",
142            "nullptr",
143            "private",
144            "protected",
145            "public",
146            "return",
147            "sizeof",
148            "static",
149            "struct",
150            "switch",
151            "template",
152            "this",
153            "throw",
154            "true",
155            "try",
156            "typedef",
157            "union",
158            "using",
159            "virtual",
160            "volatile",
161            "while",
162        ],
163        types: &["bool", "char", "double", "float", "int", "long", "short", "signed", "size_t", "unsigned", "void"],
164        capitalized_types: false,
165        line_comment: "//",
166        block_comment: ["/*", "*/"],
167        strings: &[StringSyntax { delimiters: ["\"", "\""], multiline: false, char_literal: false }, StringSyntax { delimiters: ["'", "'"], multiline: false, char_literal: true }],
168        indent_after: "([{",
169    };
170    /// Python.
171    pub const PYTHON: Syntax = Syntax {
172        keywords: &[
173            "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",
174            "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",
175        ],
176        types: &["bool", "bytes", "dict", "float", "int", "list", "object", "set", "str", "tuple"],
177        capitalized_types: true,
178        line_comment: "#",
179        block_comment: ["", ""],
180        strings: &[
181            StringSyntax { delimiters: ["\"\"\"", "\"\"\""], multiline: true, char_literal: false },
182            StringSyntax { delimiters: ["'''", "'''"], multiline: true, char_literal: false },
183            StringSyntax { delimiters: ["\"", "\""], multiline: false, char_literal: false },
184            StringSyntax { delimiters: ["'", "'"], multiline: false, char_literal: false },
185        ],
186        indent_after: "([{:",
187    };
188    /// JavaScript, TypeScript and JSON.
189    pub const JAVASCRIPT: Syntax = Syntax {
190        keywords: &[
191            "async",
192            "await",
193            "break",
194            "case",
195            "catch",
196            "class",
197            "const",
198            "continue",
199            "debugger",
200            "default",
201            "delete",
202            "do",
203            "else",
204            "export",
205            "extends",
206            "false",
207            "finally",
208            "for",
209            "function",
210            "if",
211            "import",
212            "in",
213            "instanceof",
214            "interface",
215            "let",
216            "new",
217            "null",
218            "of",
219            "return",
220            "static",
221            "super",
222            "switch",
223            "this",
224            "throw",
225            "true",
226            "try",
227            "type",
228            "typeof",
229            "undefined",
230            "var",
231            "void",
232            "while",
233            "yield",
234        ],
235        types: &["any", "boolean", "never", "number", "object", "string", "unknown"],
236        capitalized_types: true,
237        line_comment: "//",
238        block_comment: ["/*", "*/"],
239        strings: &[
240            StringSyntax { delimiters: ["`", "`"], multiline: true, char_literal: false },
241            StringSyntax { delimiters: ["\"", "\""], multiline: false, char_literal: false },
242            StringSyntax { delimiters: ["'", "'"], multiline: false, char_literal: false },
243        ],
244        indent_after: "([{",
245    };
246
247    /// Highlights one line. Pushes onto `pieces` each run's end (bytes from the line start) and
248    /// kind. `open` is the state before the line (0 at the text's start); returns the state at
249    /// its end, for the next line. (This is all a code block shown elsewhere needs:
250    /// [`TokenKind::color`] colours each piece.)
251    pub fn line(&self, line: &str, open: u8, pieces: &mut Vec<(usize, TokenKind)>) -> u8 {
252        self.read(line, open, Some(pieces))
253    }
254
255    /// Scans a line: returns its end state, and its pieces if asked.
256    fn read(&self, line: &str, mut open: u8, mut pieces: Option<&mut Vec<(usize, TokenKind)>>) -> u8 {
257        let mut at = 0;
258        while at < line.len() {
259            let (end, sort, after) = self.piece(line, at, open, pieces.is_some());
260            if let Some(pieces) = pieces.as_deref_mut() {
261                join(pieces, end, sort);
262            }
263            (at, open) = (end, after);
264        }
265        open
266    }
267
268    /// The token of `line` starting at byte `at` in state `open`: its end, kind, and the state
269    /// after it. (`named`: words are looked up; else only skipped.)
270    fn piece(&self, line: &str, at: usize, open: u8, named: bool) -> (usize, TokenKind, u8) {
271        let rest = &line[at..];
272        if open == IN_COMMENT {
273            return self.comment_end(line, at);
274        }
275        if let Some(quote) = self.strings.get((open as usize).wrapping_sub(2)) {
276            return close(rest, quote.delimiters[1]).map_or((line.len(), TokenKind::String, if quote.multiline { open } else { 0 }), |end| (at + end, TokenKind::String, 0));
277        }
278        let first = rest.as_bytes()[0];
279        if first.is_ascii_digit() {
280            return (at + number(rest), TokenKind::Number, 0);
281        }
282        if first == b'_' || first.is_ascii_alphabetic() || first >= 0x80 {
283            let end = at + word_end(rest);
284            return (end, if named { self.sort_of(&line[at..end]) } else { TokenKind::Plain }, 0);
285        }
286        if !self.line_comment.is_empty() && rest.starts_with(self.line_comment) {
287            return (line.len(), TokenKind::Comment, 0);
288        }
289        if !self.block_comment[0].is_empty() && rest.starts_with(self.block_comment[0]) {
290            return self.comment_end(line, at + self.block_comment[0].len());
291        }
292        match self.strings.iter().position(|quote| rest.starts_with(quote.delimiters[0])) {
293            Some(found) => self.quoted(line, at, found),
294            None => (at + self.plain_end(rest), TokenKind::Plain, 0),
295        }
296    }
297
298    /// The token a block comment makes from byte `from` of `line`: its end, and whether it is
299    /// still open after the line.
300    fn comment_end(&self, line: &str, from: usize) -> (usize, TokenKind, u8) {
301        let mark = self.block_comment[1];
302        match line[from..].find(mark).filter(|_| !mark.is_empty()) {
303            Some(end) => (from + end + mark.len(), TokenKind::Comment, 0),
304            None => (line.len(), TokenKind::Comment, IN_COMMENT),
305        }
306    }
307
308    /// The token string syntax `quotes[found]` makes, opening at byte `at` of `line`.
309    fn quoted(&self, line: &str, at: usize, found: usize) -> (usize, TokenKind, u8) {
310        let quote = self.strings[found];
311        let from = at + quote.delimiters[0].len();
312        let rest = &line[from..];
313        if quote.char_literal {
314            // One character, or a backslash escape (up to `\u{10ffff}`), then the closing
315            // delimiter: else it was no literal.
316            let kept = rest.strip_prefix('\\').map_or(0, |after| 1 + cluster(after));
317            let inside = if kept > 0 { rest[kept..].find(quote.delimiters[1]).filter(|end| *end <= 9).map(|end| kept + end) } else { Some(cluster(rest)) };
318            let closed = inside.filter(|inside| *inside > 0 && rest[*inside..].starts_with(quote.delimiters[1]));
319            return closed.map_or((from, TokenKind::Plain, 0), |inside| (from + inside + quote.delimiters[1].len(), TokenKind::String, 0));
320        }
321        match close(rest, quote.delimiters[1]) {
322            Some(end) => (from + end, TokenKind::String, 0),
323            None => (line.len(), TokenKind::String, if quote.multiline { found as u8 + 2 } else { 0 }),
324        }
325    }
326
327    /// A word's kind: keyword, type name, or neither.
328    fn sort_of(&self, word: &str) -> TokenKind {
329        if self.keywords.contains(&word) {
330            TokenKind::Keyword
331        } else if self.types.contains(&word) || self.capitalized_types && word.starts_with(char::is_uppercase) {
332            TokenKind::Type
333        } else {
334            TokenKind::Plain
335        }
336    }
337
338    /// The end of the plain run at the start of `rest`: past its first character, up to
339    /// anything that could start a word, number, comment or string.
340    fn plain_end(&self, rest: &str) -> usize {
341        let marks = [self.line_comment, self.block_comment[0]].into_iter().chain(self.strings.iter().map(|quote| quote.delimiters[0]));
342        let mut firsts = [0u8; 8];
343        let mut count = 0;
344        for mark in marks.filter_map(|mark| mark.as_bytes().first()).take(8) {
345            (firsts[count], count) = (*mark, count + 1);
346        }
347        let starts = |byte: &u8| byte.is_ascii_alphanumeric() || *byte == b'_' || *byte >= 0x80 || firsts[..count].contains(byte);
348        1 + rest.as_bytes()[1..].iter().position(starts).unwrap_or(rest.len() - 1)
349    }
350}
351
352/// Appends a piece; merges it with the last if of the same kind.
353fn join(pieces: &mut Vec<(usize, TokenKind)>, end: usize, sort: TokenKind) {
354    match pieces.last_mut() {
355        Some(last) if last.1 == sort => last.0 = end,
356        _ => pieces.push((end, sort)),
357    }
358}
359
360/// The end of the first `mark` in `rest`, skipping escaped ones; `None` if there is none.
361fn close(rest: &str, mark: &str) -> Option<usize> {
362    let (bytes, mark) = (rest.as_bytes(), mark.as_bytes());
363    let mut at = 0;
364    while at < bytes.len() && !mark.is_empty() {
365        if bytes[at..].starts_with(mark) {
366            return Some(at + mark.len());
367        }
368        at += if bytes[at] == b'\\' { 2 } else { 1 };
369    }
370    None
371}
372
373/// The length of the number at the start of `rest`: digits, letters and `_` (`0x1f`, `10u8`,
374/// `1_000`), and a point followed by a digit (`1.5`; `1..5` is two).
375fn number(rest: &str) -> usize {
376    let bytes = rest.as_bytes();
377    let goes_on = |at: usize| bytes[at].is_ascii_alphanumeric() || bytes[at] == b'_' || bytes[at] == b'.' && bytes.get(at + 1).is_some_and(u8::is_ascii_digit);
378    (1..bytes.len()).find(|at| !goes_on(*at)).unwrap_or(bytes.len())
379}
380
381/// The length of the word at the start of `rest`: letters, digits and `_`, any script.
382fn word_end(rest: &str) -> usize {
383    rest.bytes().position(|byte| !(byte.is_ascii_alphanumeric() || byte == b'_' || byte >= 0x80)).unwrap_or(rest.len())
384}
385
386/// The column width of a piece starting at column `from`: one per character, a tab to the next
387/// multiple of `tab`.
388fn columns(text: &str, from: u32, tab: u32) -> u32 {
389    text.chars().fold(from, |column, letter| if letter == '\t' { (column / tab + 1) * tab } else { column + 1 }) - from
390}
391
392/// The byte length of a line's leading indent.
393fn indent_len(line: &str) -> usize {
394    line.len() - line.trim_start_matches([' ', '\t']).len()
395}
396
397/// The closing bracket for an opening one.
398fn closer(open: char) -> Option<char> {
399    BRACKETS.iter().find(|(opens, _)| *opens == open).map(|(_, closes)| *closes)
400}
401
402/// Where a text position moves when `edits` are made (each a replaced range and its new text,
403/// in order, in pre-edit offsets): along with the text before it. Inside a replaced range, it
404/// goes to the end of the replacement.
405fn moved(at: usize, edits: &[(Range<usize>, String)]) -> usize {
406    let mut shift = 0isize;
407    for (range, with) in edits {
408        if at < range.start || at == range.start && range.start < range.end {
409            break;
410        }
411        if at < range.end {
412            return range.start.saturating_add_signed(shift) + with.len();
413        }
414        shift += with.len() as isize - range.len() as isize;
415    }
416    at.saturating_add_signed(shift)
417}
418
419/// A stable insertion sort by `key`, for short lists (cursors: usually few).
420fn in_order<T>(list: &mut [T], key: impl Fn(&T) -> usize) {
421    for at in 1..list.len() {
422        let mut to = at;
423        while to > 0 && key(&list[to - 1]) > key(&list[to]) {
424            list.swap(to - 1, to);
425            to -= 1;
426        }
427    }
428}
429
430/// Where a line wraps to fit rows so many columns wide: for each row after the first, its start
431/// byte and column. After the last space that fits; with none, before the first character that
432/// doesn't.
433struct Breaks<'a> {
434    letters: std::str::CharIndices<'a>,
435    width: u32,
436    tab: u32,
437    column: u32,
438    /// The current row's start, and its last space: each as byte and column.
439    from: (usize, u32),
440    space: Option<(usize, u32)>,
441}
442
443impl<'a> Breaks<'a> {
444    fn new(line: &'a str, width: u32, tab: u32) -> Self {
445        Breaks { letters: line.char_indices(), width: width.max(1), tab, column: 0, from: (0, 0), space: None }
446    }
447}
448
449impl Iterator for Breaks<'_> {
450    type Item = (usize, u32);
451    fn next(&mut self) -> Option<(usize, u32)> {
452        for (at, letter) in self.letters.by_ref() {
453            let after = if letter == '\t' { (self.column / self.tab + 1) * self.tab } else { self.column + 1 };
454            // A space that doesn't fit hangs past the edge: the row breaks after it.
455            let over = letter != ' ' && after - self.from.1 > self.width && at > self.from.0;
456            let broken = over.then(|| self.space.filter(|(space, _)| *space > self.from.0).unwrap_or((at, self.column)));
457            self.space = if letter == ' ' { Some((at + 1, after)) } else { self.space.filter(|_| broken.is_none()) };
458            self.column = after;
459            if let Some(start) = broken {
460                self.from = start;
461                return Some(start);
462            }
463        }
464        None
465    }
466}
467
468/// A cursor and its selection anchor, in bytes: the text between is selected.
469#[derive(Clone, Copy, Debug, Default, PartialEq)]
470struct Sel {
471    cursor: usize,
472    anchor: usize,
473    /// The column it keeps while moving up and down rows.
474    column: Option<u32>,
475}
476
477impl Sel {
478    fn at(at: usize) -> Sel {
479        Sel { cursor: at, anchor: at, column: None }
480    }
481    fn range(&self) -> Range<usize> {
482        self.cursor.min(self.anchor)..self.cursor.max(self.anchor)
483    }
484}
485
486/// One change, undone as one: at each of some places (in pre-change offsets) what went and what
487/// came; and the cursors before and after.
488struct Change {
489    edits: Vec<(usize, String, String)>,
490    before: Vec<Sel>,
491    after: Vec<Sel>,
492    /// It was typed, so typing right after it undoes with it.
493    typed: bool,
494}
495
496/// The find bar: open, and whether replacing too; search and replacement text; match case, and
497/// whole words.
498#[derive(Default)]
499struct Finding {
500    open: bool,
501    replacing: bool,
502    words: String,
503    with: String,
504    case: bool,
505    whole: bool,
506    /// Focus goes to its box when next described.
507    focus: bool,
508    /// The total match count, as of the search and text (as one hash); and the selected match's
509    /// index (0 for none), as of the selection's start.
510    counted: (u64, usize, (usize, usize)),
511}
512
513/// A code editor's state ([`Ui::code_editor`]): the text and the editing state. Kept by the
514/// app, one per editor, as a [`Table`](crate::Table) is.
515///
516/// ```
517/// use taut::{CodeEditor, Syntax};
518/// let mut code = CodeEditor::new("fn main() {}\n", &Syntax::RUST);
519/// code.wrap = true; // long lines go on to the next row, in place of scrolling sideways
520/// assert_eq!(code.text(), "fn main() {}\n");
521/// assert_eq!(code.cursor(), (1, 1)); // line and column of the cursor, counted from 1
522/// ```
523pub struct CodeEditor {
524    /// Highlighting: [`Syntax::RUST`], or the app's own; [`Syntax::PLAIN`] highlights nothing.
525    pub syntax: &'static Syntax,
526    /// Wraps long lines instead of scrolling sideways.
527    pub wrap: bool,
528    /// Tab width in columns; also the indent width.
529    pub tab_width: usize,
530    /// Tab indents with a tab character instead of spaces.
531    pub hard_tabs: bool,
532    text: String,
533    /// Each line's start byte; each line's width in columns; and the widest, once computed
534    /// since the last change.
535    starts: Vec<u32>,
536    widths: Vec<u32>,
537    widest: Option<u32>,
538    /// The text uses CRLF line ends.
539    returns: bool,
540    /// Each line's start state, for highlighting (see `open_at`): correct for lines before
541    /// `sure`; and for those before `kept`, from the first line after `edited` whose recomputed
542    /// start state matches the old one.
543    states: Vec<u8>,
544    sure: usize,
545    kept: usize,
546    edited: usize,
547    /// For wrapping, each line's row count at `wrapped_at` columns (0: no wrapping). And where
548    /// lines wrap or fold, each line's first row, and the total row count after the last line;
549    /// empty when each line is one row.
550    wraps: Vec<u16>,
551    wrapped_at: u32,
552    tops: Vec<u32>,
553    tops_stale: bool,
554    /// Folded line ranges: first and last line of each, in order. (The line before the first
555    /// stands for them.)
556    folds: Vec<[u32; 2]>,
557    /// The cursors, the primary first.
558    sels: Vec<Sel>,
559    changes: Vec<Change>,
560    /// How many of the last changes are undone now.
561    undone: usize,
562    /// Counts every change to the text.
563    version: u64,
564    /// The tab width and rules all of the above was computed with (the app may change them).
565    made_for: (usize, Syntax),
566    finding: Finding,
567    /// The go-to-line bar, if open: its text, and whether focus goes to it when next described.
568    going: Option<(String, bool)>,
569    /// For the box: its id, and its measuring id; its room (width and height); when its cursor
570    /// last moved (it blinks from then); whether to scroll the primary cursor into view; the
571    /// pointer's click count; and that Escape had nothing to do, so Tab moves on.
572    id: Id,
573    measured: Id,
574    view: [f32; 2],
575    moved: Duration,
576    reveal: bool,
577    clicks: u8,
578    escaped: bool,
579    /// The bracket pair at the primary cursor, as of a version and position.
580    paired: (u64, usize, Option<[usize; 2]>),
581    /// The last highlighted line's pieces, which line, and as of which version.
582    pieces: Vec<(usize, TokenKind)>,
583    coloured: (u64, usize),
584}
585
586impl std::fmt::Debug for CodeEditor {
587    /// Its length in bytes and lines, and its settings; not the text.
588    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589        let lines = self.starts.len().max(1);
590        f.debug_struct("CodeEditor")
591            .field("bytes", &self.text.len())
592            .field("lines", &lines)
593            .field("wrap", &self.wrap)
594            .field("tab_width", &self.tab_width)
595            .field("hard_tabs", &self.hard_tabs)
596            .finish_non_exhaustive()
597    }
598}
599
600impl Default for CodeEditor {
601    fn default() -> Self {
602        CodeEditor::new("", &Syntax::PLAIN)
603    }
604}
605
606impl CodeEditor {
607    /// The text to edit, and its highlighting rules.
608    pub fn new(text: impl Into<String>, rules: &'static Syntax) -> CodeEditor {
609        let mut code = CodeEditor {
610            syntax: rules,
611            wrap: false,
612            tab_width: 4,
613            hard_tabs: false,
614            text: text.into(),
615            starts: Vec::new(),
616            widths: Vec::new(),
617            widest: None,
618            returns: false,
619            states: Vec::new(),
620            sure: 1,
621            kept: 1,
622            edited: 0,
623            wraps: Vec::new(),
624            wrapped_at: 0,
625            tops: Vec::new(),
626            tops_stale: false,
627            folds: Vec::new(),
628            sels: vec![Sel::at(0)],
629            changes: Vec::new(),
630            undone: 0,
631            version: 0,
632            made_for: (4, *rules),
633            finding: Finding::default(),
634            going: None,
635            id: 0,
636            measured: 0,
637            view: [0.0; 2],
638            moved: Duration::ZERO,
639            reveal: false,
640            clicks: 1,
641            escaped: false,
642            paired: (u64::MAX, 0, None),
643            pieces: Vec::new(),
644            coloured: (u64::MAX, 0),
645        };
646        code.index();
647        code
648    }
649
650    /// The current text.
651    pub fn text(&self) -> &str {
652        &self.text
653    }
654    /// Replaces all the text: the undo history is cleared and the cursor goes to the start.
655    pub fn set_text(&mut self, text: impl Into<String>) {
656        (self.text, self.sels, self.undone, self.version) = (text.into(), vec![Sel::at(0)], 0, self.version + 1);
657        self.changes.clear();
658        self.index();
659    }
660    /// The primary cursor's line and column, both from 1 (column in characters).
661    pub fn cursor(&self) -> (usize, usize) {
662        let at = self.sels[0].cursor;
663        let line = self.line_of(at);
664        (line + 1, self.text[self.starts[line] as usize..at].chars().count() + 1)
665    }
666    /// Puts the cursor at the start of a line (from 1), to be scrolled into view.
667    pub fn go_to_line(&mut self, line: usize) {
668        let line = line.clamp(1, self.starts.len()) - 1;
669        let (start, end) = self.line_ends(line);
670        self.sels = vec![Sel::at(start + indent_len(&self.text[start..end]))];
671        self.unfold_cursors();
672        self.reveal = true;
673    }
674
675    // ---- the lines ----
676
677    /// Indexes every line's start and width from scratch: for a new text, or after a change too
678    /// large to patch line by line.
679    fn index(&mut self) {
680        self.starts.clear();
681        self.widths.clear();
682        let tab = self.tab_width.max(1) as u32;
683        let mut from = 0;
684        for (at, _) in self.text.match_indices('\n') {
685            self.starts.push(from as u32);
686            self.widths.push(columns(self.text[from..at].trim_end_matches('\r'), 0, tab));
687            from = at + 1;
688        }
689        self.starts.push(from as u32);
690        self.widths.push(columns(&self.text[from..], 0, tab));
691        self.returns = self.text.find('\n').is_some_and(|at| self.text[..at].ends_with('\r'));
692        self.states.clear();
693        self.states.resize(self.starts.len(), 0);
694        (self.sure, self.kept, self.edited, self.widest) = (1, 1, 0, None);
695        (self.made_for, self.wrapped_at, self.tops_stale) = ((self.tab_width, *self.syntax), 0, true);
696        self.folds.clear();
697        self.wraps.clear();
698    }
699
700    /// The line containing byte `at`.
701    fn line_of(&self, at: usize) -> usize {
702        self.starts.partition_point(|start| *start as usize <= at) - 1
703    }
704    /// Line `line`'s start and end (before its line end).
705    fn line_ends(&self, line: usize) -> (usize, usize) {
706        let start = self.starts[line] as usize;
707        let end = self.starts.get(line + 1).map_or(self.text.len(), |next| *next as usize - 1);
708        (start, if self.text[start..end].ends_with('\r') { end - 1 } else { end })
709    }
710    /// Line `line`'s text, without its line end.
711    fn line_text(&self, line: usize) -> &str {
712        let (start, end) = self.line_ends(line);
713        &self.text[start..end]
714    }
715
716    /// Re-indexes after `removed` bytes from `at` were replaced by `added`: the touched lines
717    /// are re-found and the rest shifted, with everything kept per line.
718    fn relines(&mut self, at: usize, removed: usize, added: usize) {
719        let (first, last) = (self.line_of(at), self.line_of(at + removed));
720        let shift = added as i64 - removed as i64;
721        let end = self.starts.get(last + 1).map_or(self.text.len() as i64, |next| *next as i64 - 1 + shift) as usize;
722        let (from, tab) = (self.starts[first] as usize, self.tab_width.max(1) as u32);
723        // The lines now in place of those.
724        let mut found: Vec<(u32, u32)> = Vec::new();
725        let mut start = from;
726        for (at, _) in self.text[from..end].match_indices('\n') {
727            found.push((start as u32, columns(self.text[start..from + at].trim_end_matches('\r'), 0, tab)));
728            start = from + at + 1;
729        }
730        found.push((start as u32, columns(self.text[start..end].trim_end_matches('\r'), 0, tab)));
731        let new = found.len();
732        self.starts.splice(first..=last, found.iter().map(|line| line.0));
733        self.widths.splice(first..=last, found.iter().map(|line| line.1));
734        for start in &mut self.starts[first + new..] {
735            *start = (*start as i64 + shift) as u32;
736        }
737        self.relined(first, last, new);
738    }
739
740    /// Patches the per-line state after lines `first` to `last` became `new` lines.
741    fn relined(&mut self, first: usize, last: usize, new: usize) {
742        let shift = new as isize - (last + 1 - first) as isize;
743        let along = |line: usize| if line > last { line.saturating_add_signed(shift) } else { line };
744        self.states.splice(first + 1..=last, std::iter::repeat_n(0, new - 1));
745        // Start states are correct up to the first touched line; after the touched lines they
746        // may well match again.
747        self.edited = if self.sure > self.edited { first + new - 1 } else { along(self.edited).max(first + new - 1) };
748        self.kept = if self.kept > last + 1 { along(self.kept) } else { self.kept.min(first + 1) };
749        self.sure = self.sure.min(first + 1);
750        if self.wrapped_at > 0 {
751            let rows: Vec<u16> = (first..first + new).map(|line| self.rows_of(line)).collect();
752            self.wraps.splice(first..=last, rows);
753        }
754        // A fold whose lines, or whose standing line, were touched is unfolded.
755        self.folds.retain(|fold| (fold[1] as usize) < first || fold[0] as usize > last + 1);
756        for fold in &mut self.folds {
757            *fold = fold.map(|line| along(line as usize) as u32);
758        }
759        (self.widest, self.tops_stale) = (None, true);
760    }
761
762    /// Line `line`'s row count when wrapping at `wrapped_at` columns.
763    fn rows_of(&self, line: usize) -> u16 {
764        Breaks::new(self.line_text(line), self.wrapped_at, self.tab_width.max(1) as u32).count().saturating_add(1).min(u16::MAX as usize) as u16
765    }
766
767    /// Syncs the per-line state with the app's settings, which may have changed: tab width,
768    /// rules, and wrapping at `width` columns.
769    fn fit(&mut self, width: u32) {
770        if self.made_for.0 != self.tab_width {
771            self.index();
772        }
773        if self.made_for.1 != *self.syntax {
774            (self.made_for.1, self.sure, self.kept, self.coloured) = (*self.syntax, 1, 1, (u64::MAX, 0));
775        }
776        let wrap = if self.wrap { width.max(8) } else { 0 };
777        if wrap == self.wrapped_at {
778            return;
779        }
780        (self.wrapped_at, self.tops_stale) = (wrap, true);
781        self.wraps.clear();
782        if wrap > 0 {
783            self.wraps = (0..self.starts.len()).map(|line| self.rows_of(line)).collect();
784        }
785    }
786
787    /// The widest line, in columns.
788    fn widest(&mut self) -> u32 {
789        let widths = &self.widths;
790        *self.widest.get_or_insert_with(|| widths.iter().copied().max().unwrap_or(0))
791    }
792
793    // ---- rows: what the box shows of the lines ----
794
795    /// Recomputes each line's first row, where it differs from its line number.
796    fn tops(&mut self) {
797        if !std::mem::take(&mut self.tops_stale) {
798            return;
799        }
800        self.tops.clear();
801        if self.wraps.is_empty() && self.folds.is_empty() {
802            return;
803        }
804        let (mut top, mut fold) = (0u32, 0);
805        for line in 0..self.starts.len() {
806            self.tops.push(top);
807            fold += self.folds.get(fold).is_some_and(|run| run[1] < line as u32) as usize;
808            let hidden = self.folds.get(fold).is_some_and(|run| run[0] <= line as u32);
809            top += if hidden { 0 } else { self.wraps.get(line).map_or(1, |rows| *rows as u32) };
810        }
811        self.tops.push(top);
812    }
813    /// The row count.
814    fn row_count(&self) -> usize {
815        self.tops.last().map_or(self.starts.len(), |rows| *rows as usize)
816    }
817    /// The row line `line` starts at.
818    fn top_of(&self, line: usize) -> usize {
819        self.tops.get(line).map_or(line, |top| *top as usize)
820    }
821    /// The line of row `row`.
822    fn line_at(&self, row: usize) -> usize {
823        match self.tops.is_empty() {
824            true => row.min(self.starts.len() - 1),
825            false => self.tops.partition_point(|top| *top as usize <= row).saturating_sub(1).min(self.starts.len() - 1),
826        }
827    }
828    /// Row `row`: its line, its byte range, and its start column.
829    fn row_span(&self, row: usize) -> (usize, usize, usize, u32) {
830        let line = self.line_at(row);
831        let (start, end) = self.line_ends(line);
832        if self.wraps.is_empty() {
833            return (line, start, end, 0);
834        }
835        let part = row.saturating_sub(self.top_of(line));
836        let mut breaks = Breaks::new(&self.text[start..end], self.wrapped_at, self.tab_width.max(1) as u32);
837        let from = if part == 0 { (0, 0) } else { breaks.nth(part - 1).unwrap_or((end - start, 0)) };
838        let to = breaks.next().map_or(end, |next| start + next.0);
839        (line, start + from.0, to, from.1)
840    }
841    /// The row byte `at` shows in, and its column within that row.
842    fn place(&self, at: usize) -> (usize, u32) {
843        let line = self.line_of(at);
844        let start = self.starts[line] as usize;
845        let tab = self.tab_width.max(1) as u32;
846        let column = columns(&self.text[start..at], 0, tab);
847        if self.wraps.is_empty() {
848            return (self.top_of(line), column);
849        }
850        let end = self.line_ends(line).1;
851        let before = Breaks::new(&self.text[start..end], self.wrapped_at, tab).take_while(|(byte, _)| start + byte <= at);
852        let (part, from) = before.fold((0, 0), |(part, _), (_, from)| (part + 1, from));
853        (self.top_of(line) + part, column - from)
854    }
855    /// The position in row `row` at `column`, or the row's end. (A row a line wraps after ends
856    /// before its last character: the position after it is the next row's.)
857    fn at_column(&self, row: usize, column: u32) -> usize {
858        let (line, from, to, start) = self.row_span(row);
859        let last = to == self.line_ends(line).1;
860        let (mut at, mut went, tab) = (from, start, self.tab_width.max(1) as u32);
861        while at < to {
862            let next = at + cluster(&self.text[at..to]);
863            went += columns(&self.text[at..next], went, tab);
864            if went > start + column || next == to && !last {
865                break;
866            }
867            at = next;
868        }
869        at
870    }
871
872    // ---- folding ----
873
874    /// A line's indent depth in columns; `None` for a blank line.
875    fn depth(&self, line: usize) -> Option<u32> {
876        let text = self.line_text(line);
877        let indent = indent_len(text);
878        (indent < text.len()).then(|| columns(&text[..indent], 0, self.tab_width.max(1) as u32))
879    }
880    /// The last line of the block line `line` starts, if it starts one: the following lines
881    /// indented further, up to the last non-blank one. (The next non-blank line is searched
882    /// only a few lines on.)
883    fn block(&self, line: usize) -> Option<usize> {
884        let depth = self.depth(line)?;
885        let next = (line + 1..self.starts.len().min(line + 64)).find_map(|next| self.depth(next).map(|deeper| (next, deeper)))?;
886        if next.1 <= depth {
887            return None;
888        }
889        let after = (next.0..self.starts.len()).find(|later| self.depth(*later).is_some_and(|deeper| deeper <= depth)).unwrap_or(self.starts.len());
890        (line + 1..after).rev().find(|inside| self.depth(*inside).is_some())
891    }
892    /// Folds the block line `line` starts (with any folds inside), or unfolds it if folded.
893    /// Returns whether there was such a block.
894    fn fold(&mut self, line: usize) -> bool {
895        if let Some(run) = self.folds.iter().position(|run| run[0] as usize == line + 1) {
896            self.folds.remove(run);
897            self.tops_stale = true;
898            return true;
899        }
900        let Some(last) = self.block(line) else { return false };
901        let run = [line as u32 + 1, last as u32];
902        self.folds.retain(|inner| inner[1] < run[0] || inner[0] > run[1]);
903        let at = self.folds.partition_point(|before| before[0] < run[0]);
904        self.folds.insert(at, run);
905        self.tops_stale = true;
906        // A cursor in the folded lines moves to the end of the standing line.
907        let shows = self.line_ends(line).1;
908        let inside: Vec<bool> = self.sels.iter().map(|sel| (line + 1..=last).contains(&self.line_of(sel.cursor))).collect();
909        for (sel, inside) in self.sels.iter_mut().zip(inside) {
910            if inside {
911                *sel = Sel::at(shows);
912            }
913        }
914        self.merge();
915        true
916    }
917    /// Unfolds whatever a cursor entered.
918    fn unfold_cursors(&mut self) {
919        let lines: Vec<usize> = self.sels.iter().map(|sel| self.line_of(sel.cursor)).collect();
920        let before = self.folds.len();
921        self.folds.retain(|run| !lines.iter().any(|line| (run[0] as usize..=run[1] as usize).contains(line)));
922        self.tops_stale |= self.folds.len() != before;
923    }
924
925    // ---- colours ----
926
927    /// Line `line`'s start state (see [`Syntax::line`]): scanned on from the last known line,
928    /// and after an edit only until it matches again.
929    fn open_at(&mut self, line: usize) -> u8 {
930        while self.sure <= line {
931            let at = self.sure;
932            let open = self.syntax.read(self.line_text(at - 1), self.states[at - 1], None);
933            if at > self.edited && at < self.kept && self.states[at] == open {
934                self.sure = self.kept;
935                continue;
936            }
937            self.states[at] = open;
938            self.sure += 1;
939        }
940        self.kept = self.kept.max(self.sure);
941        self.states[line]
942    }
943    /// Highlights line `line` into `pieces`, unless it was the last highlighted.
944    fn colour(&mut self, line: usize) {
945        if self.coloured == (self.version, line) {
946            return;
947        }
948        let open = self.open_at(line);
949        self.pieces.clear();
950        let (start, end) = self.line_ends(line);
951        self.syntax.read(&self.text[start..end], open, Some(&mut self.pieces));
952        self.coloured = (self.version, line);
953    }
954
955    /// The bracket matching the one at the primary cursor (after it, else before), where both
956    /// are code, not in a comment or string: both positions. Searched up to `PAIRED_WITHIN`
957    /// lines away.
958    fn paired(&mut self) -> Option<[usize; 2]> {
959        let at = self.sels[0].cursor;
960        if self.paired.0 == self.version && self.paired.1 == at {
961            return self.paired.2;
962        }
963        let before = self.text[..at].chars().next_back().map(|letter| (at - letter.len_utf8(), letter));
964        let after = self.text[at..].chars().next().map(|letter| (at, letter));
965        let found = [after, before].into_iter().flatten().find_map(|(at, letter)| self.partner(at, letter).map(|other| [at, other]));
966        self.paired = (self.version, at, found);
967        found
968    }
969    /// The position of the bracket matching `letter` at byte `at`.
970    fn partner(&mut self, at: usize, letter: char) -> Option<usize> {
971        let (open, close) = *BRACKETS.iter().find(|(open, close)| *open == letter || *close == letter)?;
972        let (forward, home) = (letter == open, self.line_of(at));
973        if !self.is_code(home, at) {
974            return None;
975        }
976        let mut depth = 0usize;
977        let lines: Vec<usize> = if forward { (home..self.starts.len().min(home + PAIRED_WITHIN)).collect() } else { (home.saturating_sub(PAIRED_WITHIN)..=home).rev().collect() };
978        for line in lines {
979            if let Some(found) = self.pair_in(line, at, [open, close], forward, &mut depth) {
980                return Some(found);
981            }
982        }
983        None
984    }
985    /// Whether byte `at` of line `line` is code: not in a comment or string.
986    fn is_code(&mut self, line: usize, at: usize) -> bool {
987        self.colour(line);
988        let start = self.starts[line] as usize;
989        let piece = self.pieces.partition_point(|(end, _)| *end <= at - start);
990        self.pieces.get(piece).is_some_and(|(_, sort)| *sort == TokenKind::Plain)
991    }
992    /// Scans line `line`'s code for the bracket matching the one at `at`, forward or back,
993    /// tracking nesting depth of its kind.
994    fn pair_in(&mut self, line: usize, at: usize, [open, close]: [char; 2], forward: bool, depth: &mut usize) -> Option<usize> {
995        self.colour(line);
996        let start = self.starts[line] as usize;
997        let mut letters: Vec<(usize, char)> = Vec::new();
998        let mut from = 0;
999        for (end, sort) in self.pieces.iter().copied() {
1000            let piece = &self.text[start + from..start + end];
1001            letters.extend(piece.char_indices().filter(|(_, letter)| *letter == open || *letter == close).filter(|_| sort == TokenKind::Plain).map(|(byte, letter)| (start + from + byte, letter)));
1002            from = end;
1003        }
1004        if !forward {
1005            letters.reverse();
1006        }
1007        for (byte, letter) in letters.into_iter().filter(|(byte, _)| if forward { *byte > at } else { *byte < at }) {
1008            match letter == open && forward || letter == close && !forward {
1009                true => *depth += 1,
1010                false if *depth == 0 => return Some(byte),
1011                false => *depth -= 1,
1012            }
1013        }
1014        None
1015    }
1016
1017    // ---- changing the text ----
1018
1019    /// Makes one change, undone as one: each of `edits` replaces a range of the text (in order,
1020    /// non-overlapping). With `carets`, a cursor goes into each replacement, that many bytes
1021    /// in; else cursors move with the text.
1022    fn change(&mut self, edits: Vec<(Range<usize>, String)>, carets: Option<Vec<usize>>, typed: bool) {
1023        if edits.iter().all(|(range, with)| range.is_empty() && with.is_empty()) {
1024            return;
1025        }
1026        let before = self.sels.clone();
1027        let written: Vec<(usize, String, String)> = edits.iter().map(|(range, with)| (range.start, self.text[range.clone()].to_string(), with.clone())).collect();
1028        self.apply(&edits);
1029        if let Some(carets) = carets {
1030            self.sels = self.carets(&edits, &carets);
1031            self.merge();
1032        }
1033        self.changes.truncate(self.changes.len() - self.undone);
1034        self.undone = 0;
1035        // Consecutive typed letters undo together, a word at a time.
1036        let after = self.sels.clone();
1037        match self.changes.last_mut().filter(|last| typed && last.typed && joins(last, &written)) {
1038            Some(last) => {
1039                last.edits[0].2.push_str(&written[0].2);
1040                last.after = after;
1041            }
1042            None => self.changes.push(Change { edits: written, before, after, typed }),
1043        }
1044        if self.changes.len() > HISTORY {
1045            self.changes.remove(0);
1046        }
1047    }
1048
1049    /// The cursors after `edits`: one in each replacement, `carets` bytes into it.
1050    fn carets(&self, edits: &[(Range<usize>, String)], carets: &[usize]) -> Vec<Sel> {
1051        let mut shift = 0isize;
1052        let mut sels = Vec::with_capacity(edits.len());
1053        for ((range, with), caret) in edits.iter().zip(carets) {
1054            sels.push(Sel::at(range.start.saturating_add_signed(shift) + caret));
1055            shift += with.len() as isize - range.len() as isize;
1056        }
1057        sels
1058    }
1059
1060    /// Applies each replacement (in order, non-overlapping, in current offsets), re-indexes the
1061    /// lines, and moves the cursors.
1062    fn apply(&mut self, edits: &[(Range<usize>, String)]) {
1063        let many = edits.len() > MANY;
1064        for (range, with) in edits.iter().rev() {
1065            self.text.replace_range(range.clone(), with);
1066            if !many {
1067                self.relines(range.start, range.len(), with.len());
1068            }
1069        }
1070        if many {
1071            self.index();
1072        }
1073        for sel in &mut self.sels {
1074            (sel.cursor, sel.anchor) = (moved(sel.cursor, edits), moved(sel.anchor, edits));
1075        }
1076        self.version += 1;
1077    }
1078
1079    /// Undoes the last change, or (`again`) redoes the last undone one.
1080    fn undo(&mut self, again: bool) {
1081        let at = if again { self.changes.len() - self.undone } else { self.changes.len().wrapping_sub(self.undone + 1) };
1082        let Some(change) = self.changes.get(at).filter(|_| !again || self.undone > 0) else { return };
1083        let mut shift = 0isize;
1084        let mut edits = Vec::with_capacity(change.edits.len());
1085        for (place, removed, added) in &change.edits {
1086            let (from, to) = if again { (removed, added) } else { (added, removed) };
1087            let start = if again { *place } else { place.saturating_add_signed(shift) };
1088            edits.push((start..start + from.len(), to.clone()));
1089            shift += added.len() as isize - removed.len() as isize;
1090        }
1091        let sels = if again { change.after.clone() } else { change.before.clone() };
1092        self.apply(&edits);
1093        self.sels = sels;
1094        self.undone = if again { self.undone - 1 } else { self.undone + 1 };
1095        self.unfold_cursors();
1096    }
1097
1098    /// Edits at every cursor as `make` says: the range to replace, its replacement, and the
1099    /// cursor's offset into it. (Where two cursors' ranges meet, the first's edit wins.)
1100    fn each(&mut self, typed: bool, make: impl Fn(&CodeEditor, &Sel) -> (Range<usize>, String, usize)) {
1101        let mut made: Vec<(Range<usize>, String, usize)> = self.sels.iter().map(|sel| make(self, sel)).collect();
1102        in_order(&mut made, |(range, ..)| range.start);
1103        let (mut edits, mut carets, mut end) = (Vec::with_capacity(made.len()), Vec::with_capacity(made.len()), 0);
1104        for (nth, (range, with, caret)) in made.into_iter().enumerate() {
1105            if nth == 0 || range.start >= end {
1106                end = range.end;
1107                edits.push((range, with));
1108                carets.push(caret);
1109            }
1110        }
1111        self.change(edits, Some(carets), typed);
1112    }
1113
1114    /// Inserts typed or pasted text at every cursor, replacing each selection. (Its line ends
1115    /// become the text's own.)
1116    fn put(&mut self, text: &str, typed: bool) {
1117        let with: String = text.replace("\r\n", "\n").replace('\r', "\n");
1118        let with = if self.returns { with.replace('\n', "\r\n") } else { with };
1119        self.each(typed, |_, sel| (sel.range(), with.clone(), with.len()));
1120    }
1121
1122    /// What Enter inserts for a cursor: a line end and the line's indent; after a block opener,
1123    /// one step more; with the matching closing bracket right after the cursor, that bracket on
1124    /// its own line below.
1125    fn line_break(&self, sel: &Sel) -> (Range<usize>, String, usize) {
1126        let range = sel.range();
1127        let start = self.starts[self.line_of(range.start)] as usize;
1128        let typed = &self.text[start..range.start];
1129        let indent = &typed[..indent_len(typed)];
1130        let last = typed.trim_end().chars().next_back();
1131        let ending = if self.returns { "\r\n" } else { "\n" };
1132        let mut with = format!("{ending}{indent}");
1133        if !last.is_some_and(|last| self.syntax.indent_after.contains(last)) {
1134            let caret = with.len();
1135            return (range, with, caret);
1136        }
1137        with.push_str(&self.indent_step(indent.len() as u32));
1138        let caret = with.len();
1139        if last.and_then(closer).is_some_and(|close| self.text[range.end..].starts_with(close)) {
1140            with.push_str(&format!("{ending}{indent}"));
1141        }
1142        (range, with, caret)
1143    }
1144
1145    /// What Tab inserts at column `column`: a tab, or spaces to the next stop.
1146    fn indent_step(&self, column: u32) -> String {
1147        let tab = self.tab_width.max(1);
1148        if self.hard_tabs { "\t".into() } else { " ".repeat(tab - column as usize % tab) }
1149    }
1150
1151    /// The lines the cursors' selections touch, in order, each once. (A selection ending at a
1152    /// line's start doesn't take that line.)
1153    fn selected_lines(&self) -> Vec<usize> {
1154        let mut lines = Vec::new();
1155        for range in self.sels.iter().map(Sel::range) {
1156            let ends_a_line = range.end > range.start && self.starts[self.line_of(range.end)] as usize == range.end;
1157            let last = self.line_of(if ends_a_line { range.end - 1 } else { range.end });
1158            lines.extend(self.line_of(range.start)..=last);
1159        }
1160        in_order(&mut lines, |line| *line);
1161        lines.dedup();
1162        lines
1163    }
1164
1165    /// Tab: indents the selected lines, if any selection spans lines; else inserts an indent at
1166    /// each cursor.
1167    fn indent(&mut self) {
1168        let spans = self.sels.iter().any(|sel| self.line_of(sel.cursor) != self.line_of(sel.anchor));
1169        if !spans {
1170            return self.each(true, |code, sel| {
1171                let range = sel.range();
1172                let start = code.starts[code.line_of(range.start)] as usize;
1173                let step = code.indent_step(columns(&code.text[start..range.start], 0, code.tab_width.max(1) as u32));
1174                let caret = step.len();
1175                (range, step, caret)
1176            });
1177        }
1178        let edits = self.selected_lines().into_iter().filter(|line| !self.line_text(*line).trim().is_empty()).map(|line| {
1179            let start = self.starts[line] as usize;
1180            (start..start, if self.hard_tabs { "\t".to_string() } else { " ".repeat(self.tab_width.max(1)) })
1181        });
1182        let edits = edits.collect();
1183        self.change(edits, None, false);
1184    }
1185
1186    /// Shift+Tab: removes one indent step from each cursor's line.
1187    fn outdent(&mut self) {
1188        let edits = self.selected_lines().into_iter().map(|line| {
1189            let (start, text) = (self.starts[line] as usize, self.line_text(line));
1190            let spaces = text.bytes().take(self.tab_width.max(1)).take_while(|byte| *byte == b' ').count();
1191            (start..start + if text.starts_with('\t') { 1 } else { spaces }, String::new())
1192        });
1193        let edits = edits.filter(|(range, _)| !range.is_empty()).collect();
1194        self.change(edits, None, false);
1195    }
1196
1197    /// What Backspace (or `forward`, Delete) removes at a cursor: the selection, else a
1198    /// character (with Ctrl a word); and in a space indent, back to the last stop.
1199    fn doomed(&self, sel: &Sel, forward: bool, words: bool) -> Range<usize> {
1200        let at = sel.cursor;
1201        if !sel.range().is_empty() {
1202            return sel.range();
1203        }
1204        let start = self.starts[self.line_of(at)] as usize;
1205        let lead = &self.text[start..at];
1206        if !forward && !words && !lead.is_empty() && lead.bytes().all(|byte| byte == b' ') {
1207            let tab = self.tab_width.max(1);
1208            return at - ((lead.len() - 1) % tab + 1)..at;
1209        }
1210        let other = if words { word(&self.text, at, forward) } else { step(&self.text, at, forward) };
1211        at.min(other)..at.max(other)
1212    }
1213
1214    // ---- the keyboard ----
1215
1216    /// Handles a key; returns whether the box took it. `page` is the visible row count.
1217    fn key(&mut self, key: Key, mods: Mods, page: usize, clipboard: &mut dyn Clipboard) -> bool {
1218        self.escaped = false;
1219        if key == Key::Escape && mods == Mods::NONE {
1220            return self.escape();
1221        }
1222        if self.edit_key(key, mods, clipboard) || self.bar_key(key, mods) {
1223            return true;
1224        }
1225        if mods.ctrl && mods.alt && matches!(key, Key::Up | Key::Down) {
1226            return self.add_cursor(key == Key::Up);
1227        }
1228        if mods.ctrl && mods.alt && key == Key::Char('f') {
1229            let line = self.line_of(self.sels[0].cursor);
1230            return self.fold(line) || self.fold_around(line);
1231        }
1232        self.go(key, mods, page)
1233    }
1234
1235    /// Escape: closes an open bar, or reduces several cursors to one. With nothing to do it is
1236    /// not taken, and Tab after it moves focus on.
1237    fn escape(&mut self) -> bool {
1238        if self.finding.open || self.going.is_some() {
1239            (self.finding.open, self.going) = (false, None);
1240            return true;
1241        }
1242        if self.sels.len() > 1 {
1243            self.sels.truncate(1);
1244            return true;
1245        }
1246        self.escaped = true;
1247        false
1248    }
1249
1250    /// Keys that edit the text or use the clipboard; returns whether this was one.
1251    fn edit_key(&mut self, key: Key, mods: Mods, clipboard: &mut dyn Clipboard) -> bool {
1252        let plain = !mods.ctrl && !mods.alt;
1253        match key {
1254            Key::Backspace | Key::Delete if !mods.alt => self.each(false, |code, sel| (code.doomed(sel, key == Key::Delete, mods.ctrl), String::new(), 0)),
1255            Key::Enter if plain => self.each(true, CodeEditor::line_break),
1256            Key::Tab if plain && mods.shift => self.outdent(),
1257            Key::Tab if plain => self.indent(),
1258            Key::Char('a') if mods == Mods::CTRL => self.sels = vec![Sel { cursor: self.text.len(), anchor: 0, column: None }],
1259            Key::Char('c') if mods == Mods::CTRL => self.copy(clipboard),
1260            Key::Char('x') if mods == Mods::CTRL => {
1261                self.copy(clipboard);
1262                self.each(false, |_, sel| (sel.range(), String::new(), 0));
1263            }
1264            Key::Char('v') if mods == Mods::CTRL => clipboard.get().iter().for_each(|pasted| self.put(pasted, false)),
1265            Key::Char('z' | 'y') if mods.ctrl && !mods.alt => self.undo(mods.shift || key == Key::Char('y')),
1266            _ => return false,
1267        }
1268        true
1269    }
1270
1271    /// Copies the cursors' selections, a line each: nothing if none select anything.
1272    fn copy(&self, clipboard: &mut dyn Clipboard) {
1273        let mut ranges: Vec<Range<usize>> = self.sels.iter().map(Sel::range).filter(|range| !range.is_empty()).collect();
1274        in_order(&mut ranges, |range| range.start);
1275        if !ranges.is_empty() {
1276            clipboard.set(&ranges.into_iter().map(|range| &self.text[range]).collect::<Vec<_>>().join("\n"));
1277        }
1278    }
1279
1280    /// Keys that open the bars or step through matches; returns whether this was one.
1281    fn bar_key(&mut self, key: Key, mods: Mods) -> bool {
1282        match key {
1283            Key::Char('f' | 'h') if mods == Mods::CTRL => self.open_finding(key == Key::Char('h')),
1284            Key::Char('g') if mods == Mods::CTRL => self.going = Some((String::new(), true)),
1285            Key::F(3) if !mods.ctrl && !mods.alt => self.find_next(mods.shift),
1286            _ => return false,
1287        }
1288        true
1289    }
1290
1291    /// Opens the find bar (and, `replacing`, replace) with the selection in it, if on one line.
1292    fn open_finding(&mut self, replacing: bool) {
1293        let picked = &self.text[self.sels[0].range()];
1294        if !picked.is_empty() && !picked.contains('\n') {
1295            self.finding.words = picked.to_string();
1296        }
1297        (self.finding.open, self.finding.replacing, self.finding.focus) = (true, replacing, true);
1298    }
1299
1300    /// Ctrl+Alt+Up/Down: adds a cursor a row above the top one or below the bottom one, at the
1301    /// primary's column.
1302    fn add_cursor(&mut self, up: bool) -> bool {
1303        let edge = self.sels.iter().map(|sel| sel.cursor).fold(if up { usize::MAX } else { 0 }, |edge, at| if up { edge.min(at) } else { edge.max(at) });
1304        let column = self.sels[0].column.unwrap_or_else(|| self.place(self.sels[0].cursor).1);
1305        self.tops();
1306        let (to, _) = self.row_away(edge, if up { -1 } else { 1 }, Some(column));
1307        if to != edge {
1308            self.sels.push(Sel { column: Some(column), ..Sel::at(to) });
1309        }
1310        true
1311    }
1312
1313    /// Cursor movement keys (with Shift, selecting); returns whether this was one.
1314    fn go(&mut self, key: Key, mods: Mods, page: usize) -> bool {
1315        if mods.alt || !matches!(key, Key::Left | Key::Right | Key::Up | Key::Down | Key::Home | Key::End | Key::PageUp | Key::PageDown) {
1316            return false;
1317        }
1318        self.tops();
1319        for at in 0..self.sels.len() {
1320            let sel = self.sels[at];
1321            let (to, column) = self.went(&sel, key, mods, page);
1322            self.sels[at] = Sel { cursor: to, anchor: if mods.shift { sel.anchor } else { to }, column };
1323        }
1324        self.merge();
1325        self.unfold_cursors();
1326        true
1327    }
1328
1329    /// Where a key moves a cursor, and the column it then keeps.
1330    fn went(&self, sel: &Sel, key: Key, mods: Mods, page: usize) -> (usize, Option<u32>) {
1331        let (at, picked, text) = (sel.cursor, sel.range(), self.text.as_str());
1332        let (start, end) = self.line_ends(self.line_of(at));
1333        let lead = start + indent_len(&text[start..end]);
1334        let to = match key {
1335            Key::Left | Key::Right if mods.ctrl => word(text, at, key == Key::Right),
1336            Key::Left if !mods.shift && !picked.is_empty() => picked.start,
1337            Key::Right if !mods.shift && !picked.is_empty() => picked.end,
1338            Key::Left | Key::Right => step(text, at, key == Key::Right),
1339            Key::Home if mods.ctrl => 0,
1340            Key::End if mods.ctrl => text.len(),
1341            // Home goes to the line's first non-blank character, and from there to the line
1342            // start.
1343            Key::Home => [lead, start][(at == lead) as usize],
1344            Key::End => end,
1345            Key::Up | Key::Down => return self.row_away(at, if key == Key::Up { -1 } else { 1 }, sel.column),
1346            _ => return self.row_away(at, if key == Key::PageUp { -(page as isize) } else { page as isize }, sel.column),
1347        };
1348        (to, None)
1349    }
1350
1351    /// The position `rows` up or down from `at` (before the first row: the start; past the
1352    /// last: the end), at `column`, else at `at`'s column.
1353    fn row_away(&self, at: usize, rows: isize, column: Option<u32>) -> (usize, Option<u32>) {
1354        let (row, across) = self.place(at);
1355        let want = column.unwrap_or(across);
1356        match row.checked_add_signed(rows) {
1357            None => (0, Some(want)),
1358            Some(to) if to >= self.row_count() => (self.text.len(), Some(want)),
1359            Some(to) => (self.at_column(to, want), Some(want)),
1360        }
1361    }
1362
1363    /// Merges cursors that overlap or touch.
1364    fn merge(&mut self) {
1365        let mut at = 1;
1366        while at < self.sels.len() {
1367            let (one, other) = (self.sels[at].range(), at);
1368            let over = (0..at).find(|before| {
1369                let two = self.sels[*before].range();
1370                let (low, high) = (one.start.max(two.start), one.end.min(two.end));
1371                low < high || low == high && (one.is_empty() || two.is_empty())
1372            });
1373            let Some(before) = over else {
1374                at += 1;
1375                continue;
1376            };
1377            let (kept, both) = (self.sels[before], self.sels[before].range().start.min(one.start)..self.sels[before].range().end.max(one.end));
1378            let forward = kept.cursor >= kept.anchor;
1379            self.sels[before] = Sel { cursor: if forward { both.end } else { both.start }, anchor: if forward { both.start } else { both.end }, column: kept.column };
1380            self.sels.remove(other);
1381        }
1382    }
1383
1384    /// Folds the nearest block around line `line` that starts above it.
1385    fn fold_around(&mut self, line: usize) -> bool {
1386        let Some(depth) = (0..=line).rev().find_map(|inside| self.depth(inside)) else { return false };
1387        let outer = (0..line).rev().find(|above| self.depth(*above).is_some_and(|outer| outer < depth));
1388        outer.is_some_and(|outer| self.fold(outer))
1389    }
1390
1391    // ---- the pointer ----
1392
1393    /// A press at byte `at`, the `clicks`th in a row: one places the cursor, two select the
1394    /// word, three the line. With Shift the anchor stays; with Alt a cursor is added. Or (not
1395    /// `first`) the pointer is dragged there.
1396    fn point(&mut self, at: usize, clicks: u8, first: bool, mods: Mods) {
1397        if !first {
1398            self.sels[0].cursor = self.dragged(at);
1399            return;
1400        }
1401        self.clicks = clicks;
1402        if mods.alt {
1403            self.sels.insert(0, Sel::at(at));
1404            return self.merge();
1405        }
1406        let anchor = self.sels[0].anchor;
1407        let picked = match clicks {
1408            _ if mods.shift => Sel { cursor: at, anchor, column: None },
1409            2 => Sel { cursor: word_edge(&self.text, at, true), anchor: word_edge(&self.text, at, false), column: None },
1410            3.. => self.whole_line(at),
1411            _ => Sel::at(at),
1412        };
1413        self.sels = vec![picked];
1414    }
1415    /// Where a drag to byte `at` moves the primary cursor: by character, by word after a double
1416    /// click, by line after a triple one.
1417    fn dragged(&self, at: usize) -> usize {
1418        let forward = at >= self.sels[0].anchor;
1419        match self.clicks {
1420            2 => word_edge(&self.text, at, forward),
1421            3.. if forward => self.whole_line(at).cursor,
1422            3.. => self.starts[self.line_of(at)] as usize,
1423            _ => at,
1424        }
1425    }
1426    /// The whole line containing byte `at`, with its line end.
1427    fn whole_line(&self, at: usize) -> Sel {
1428        let line = self.line_of(at);
1429        let end = self.starts.get(line + 1).map_or(self.text.len(), |next| *next as usize);
1430        Sel { cursor: end, anchor: self.starts[line] as usize, column: None }
1431    }
1432
1433    // ---- finding ----
1434
1435    /// The first match starting at or after byte `from` and ending by `to`: case-sensitive or
1436    /// not, whole word or not.
1437    fn next_match(&self, from: usize, to: usize) -> Option<Range<usize>> {
1438        let (words, mut at) = (self.finding.words.as_str(), from);
1439        while at < to && !words.is_empty() {
1440            let rest = &self.text[at..to];
1441            let (start, long) = if self.finding.case { rest.find(words).map(|start| (start, words.len()))? } else { any_case(rest, words)? };
1442            let found = at + start..at + start + long;
1443            let alone = !self.finding.whole || !in_word(&self.text, step(&self.text, found.start, false)) || found.start == 0;
1444            if alone && (!self.finding.whole || !in_word(&self.text, found.end)) {
1445                return Some(found);
1446            }
1447            at = found.start + cluster(&self.text[found.start..]);
1448        }
1449        None
1450    }
1451
1452    /// Selects the next match after the primary cursor (or before, `back`), wrapping around the
1453    /// text; and scrolls to it.
1454    fn find_next(&mut self, back: bool) {
1455        let picked = self.sels[0].range();
1456        let found = match back {
1457            false => self.next_match(picked.end, self.text.len()).or_else(|| self.next_match(0, picked.end)),
1458            true => self.last_match(picked.start).or_else(|| self.last_match(self.text.len())),
1459        };
1460        if let Some(found) = found {
1461            self.sels = vec![Sel { cursor: found.end, anchor: found.start, column: None }];
1462            self.unfold_cursors();
1463            self.reveal = true;
1464        }
1465    }
1466    /// The last match ending by byte `to`.
1467    fn last_match(&self, to: usize) -> Option<Range<usize>> {
1468        let mut last = None;
1469        let mut from = 0;
1470        while let Some(found) = self.next_match(from, to) {
1471            from = found.start + cluster(&self.text[found.start..]);
1472            last = Some(found);
1473        }
1474        last
1475    }
1476
1477    /// Replaces the selection with the replacement text, if it is a match; then finds the next.
1478    fn replace_one(&mut self) {
1479        let picked = self.sels[0].range();
1480        if !picked.is_empty() && self.next_match(picked.start, picked.end) == Some(picked.clone()) {
1481            let with = self.finding.with.clone();
1482            let caret = with.len();
1483            self.change(vec![(picked, with)], Some(vec![caret]), false);
1484        }
1485        self.find_next(false);
1486    }
1487    /// Replaces every match, as one change.
1488    fn replace_all(&mut self) {
1489        let mut edits = Vec::new();
1490        let mut from = 0;
1491        while let Some(found) = self.next_match(from, self.text.len()) {
1492            from = found.end.max(found.start + 1);
1493            edits.push((found, self.finding.with.clone()));
1494        }
1495        self.change(edits, None, false);
1496    }
1497
1498    /// The total match count, and the selected match's index (0 for none). Recounted only when
1499    /// the search, text or selection changed.
1500    fn count(&mut self) -> (usize, usize) {
1501        let picked = self.sels[0].range();
1502        let key = crate::id::hash((&self.finding.words, self.finding.case, self.finding.whole, self.version));
1503        if self.finding.counted.0 != key {
1504            self.finding.counted = (key, self.matches_before(self.text.len()), (0, usize::MAX));
1505        }
1506        if self.finding.counted.2.1 != picked.start {
1507            let place = if self.next_match(picked.start, picked.end) == Some(picked.clone()) { self.matches_before(picked.end) } else { 0 };
1508            self.finding.counted.2 = (place, picked.start);
1509        }
1510        (self.finding.counted.1, self.finding.counted.2.0)
1511    }
1512    /// The number of matches ending by byte `to`.
1513    fn matches_before(&self, to: usize) -> usize {
1514        let (mut count, mut from) = (0, 0);
1515        while let Some(found) = self.next_match(from, to) {
1516            (count, from) = (count + 1, found.end.max(found.start + 1));
1517        }
1518        count
1519    }
1520}
1521
1522/// Whether a typed change right after `last` undoes with it: both insert one or more letters at
1523/// one place, the second right after the first, and the first didn't end a word where the
1524/// second starts one.
1525fn joins(last: &Change, edits: &[(usize, String, String)]) -> bool {
1526    let ([(at, removed, added)], [(was, _, before)]) = (edits, last.edits.as_slice()) else { return false };
1527    removed.is_empty() && *was + before.len() == *at && (!before.ends_with(char::is_whitespace) || added.starts_with(char::is_whitespace))
1528}
1529
1530/// The first case-insensitive match of `needle` in `hay`: its start, and its length in `hay`.
1531fn any_case(hay: &str, needle: &str) -> Option<(usize, usize)> {
1532    if needle.is_ascii() {
1533        let (bytes, wanted) = (hay.as_bytes(), needle.as_bytes());
1534        let first = wanted[0].to_ascii_lowercase();
1535        let found = (0..(bytes.len() + 1).saturating_sub(wanted.len())).find(|at| bytes[*at].to_ascii_lowercase() == first && bytes[*at..*at + wanted.len()].eq_ignore_ascii_case(wanted));
1536        return found.map(|at| (at, wanted.len()));
1537    }
1538    hay.char_indices().find_map(|(at, _)| alike(&hay[at..], needle).map(|long| (at, long)))
1539}
1540
1541/// The bytes of `hay` matching `needle` at its start, case-insensitive.
1542fn alike(hay: &str, needle: &str) -> Option<usize> {
1543    let mut letters = hay.char_indices();
1544    for wanted in needle.chars() {
1545        let (_, letter) = letters.next()?;
1546        if !letter.to_lowercase().eq(wanted.to_lowercase()) {
1547            return None;
1548        }
1549    }
1550    Some(letters.next().map_or(hay.len(), |(at, _)| at))
1551}
1552
1553/// A code editor's metrics, computed each run: its font, row and font line heights, column
1554/// width, line number gutter width, and the text's x start.
1555#[derive(Clone, Copy)]
1556struct Sizes {
1557    font: Font,
1558    row: f32,
1559    line: f32,
1560    column: f32,
1561    numbers: f32,
1562    text: f32,
1563}
1564
1565/// Code editor.
1566impl Ui {
1567    /// A code editor showing `code`'s text, highlighted by `code.rules`, with line numbers in a
1568    /// gutter on the left. It fills its room. `hint` is its screen reader name. `changed` is
1569    /// set when the user edits the text.
1570    ///
1571    /// Keys, besides those of every text box: Tab and Shift+Tab indent and outdent the selected
1572    /// lines (Escape, then Tab, moves focus on); Enter keeps the indent. Ctrl+F finds, Ctrl+H
1573    /// replaces, F3 and Shift+F3 find next and previous, Ctrl+G goes to a line.
1574    /// Ctrl+Alt+Up/Down add a cursor, as does Alt+click; Escape leaves one. Ctrl+Alt+F folds or
1575    /// unfolds the cursor's block, as does a click on the marker by its line number. Files of
1576    /// any length open, scroll and edit instantly: only what is visible is described and
1577    /// highlighted.
1578    pub fn code_editor(&mut self, code: &mut CodeEditor, hint: &str) -> Response {
1579        let t = self.theme;
1580        let sizes = self.code_sizes(code);
1581        if let Some(room) = self.rooms.get(&code.measured) {
1582            code.view = [room[0], room[1]];
1583        }
1584        code.fit(((code.view[0] - sizes.text - sizes.column) / sizes.column).max(0.0) as u32);
1585        code.tops();
1586        let edge = if code.id != 0 && self.focus == code.id { t.accent } else { t.line_strong };
1587        self.column().grow().min(0.0, 3.0 * sizes.row).fill(t.panel).border(edge, 1.0).radius(t.radius).clip().open();
1588        let id = self.id("code");
1589        code.id = id;
1590        let mut state = self.interact(id);
1591        let version = code.version;
1592        if state.focused {
1593            self.code_input(code, &state, sizes);
1594        } else if state.hovered {
1595            self.set_cursor(Cursor::Text);
1596        }
1597        self.find_bar(code);
1598        self.go_bar(code);
1599        if std::mem::take(&mut code.reveal) {
1600            self.reveal_code(code, id, sizes);
1601        }
1602        self.code_view(code, &state, sizes, hint);
1603        self.close();
1604        state.changed = code.version != version;
1605        self.edit_menu(&state, false);
1606        state
1607    }
1608
1609    /// This run's metrics.
1610    fn code_sizes(&mut self, code: &CodeEditor) -> Sizes {
1611        let font = self.theme.font.mono();
1612        let line = self.text.metrics(font, self.scale).height().ceil();
1613        let column = self.text.measure(" ", font, self.scale, None).max(1.0);
1614        let digits = (code.starts.len().ilog10() + 1).max(2) as f32;
1615        let numbers = (digits * column + 26.0).ceil();
1616        Sizes { font, row: line.max((font.size * 1.45).round()), line, column, numbers, text: numbers + 6.0 }
1617    }
1618
1619    /// Feeds pointer and keys to a focused code editor.
1620    fn code_input(&mut self, code: &mut CodeEditor, state: &Response, sizes: Sizes) {
1621        // A selection asked for by a screen reader, or the app (`select_all`), first.
1622        if self.edit.id == state.id && std::mem::take(&mut self.edit.reveal) {
1623            code.sels = vec![Sel { cursor: self.edit.cursor.min(code.text.len()), anchor: self.edit.anchor.min(code.text.len()), column: None }];
1624        }
1625        if std::mem::take(&mut self.select_all) {
1626            code.sels = vec![Sel { cursor: code.text.len(), anchor: 0, column: None }];
1627        }
1628        let was = (code.version, code.sels.clone());
1629        self.code_pointer(code, state, sizes);
1630        let page = ((code.view[1] / sizes.row) as usize).saturating_sub(1).max(1);
1631        let Ui { input, clipboard, .. } = self;
1632        input.strokes.retain(|stroke| match stroke {
1633            Stroke::Key(key, mods) => !code.key(*key, *mods, page, clipboard.as_mut()),
1634            Stroke::Text(typed) => {
1635                code.escaped = false;
1636                code.put(typed, true);
1637                false
1638            }
1639        });
1640        if was != (code.version, code.sels.clone()) {
1641            (code.moved, code.reveal, self.again) = (self.now, true, true);
1642        }
1643        // The box stands for the edited text: the context menu, and screen reader selection,
1644        // use it.
1645        let primary = code.sels[0];
1646        (self.edit.id, self.edit.secret, self.edit.cursor, self.edit.anchor) = (state.id, false, primary.cursor, primary.anchor);
1647        self.takes_tab = if code.escaped { 0 } else { state.id };
1648    }
1649
1650    /// The pointer in a code editor: on the text it places the cursor (dragging selects); on
1651    /// the gutter it selects the line, or on a fold marker folds the block.
1652    fn code_pointer(&mut self, code: &mut CodeEditor, state: &Response, sizes: Sizes) {
1653        let Some(whole) = self.visible_boxes.scrollers.iter().find(|scroller| scroller.id == state.id).map(|scroller| scroller.rect) else { return };
1654        let Some(p) = self.input.pointer else { return };
1655        code.tops();
1656        let offset = self.scrolls.get(&state.id).copied().unwrap_or_default();
1657        let on_numbers = p.x - whole.x < sizes.numbers;
1658        if state.hovered {
1659            self.set_cursor(if on_numbers { Cursor::Arrow } else { Cursor::Text });
1660        }
1661        if !state.pressed {
1662            return;
1663        }
1664        let first = self.input.pressed[0] && state.hovered;
1665        let row = (((p.y - whole.y + offset[1]) / sizes.row).max(0.0) as usize).min(code.row_count() - 1);
1666        if first && on_numbers {
1667            return self.number_pressed(code, row, p.x - whole.x > sizes.numbers - 16.0);
1668        }
1669        let at = self.code_at_x(code, row, p.x - whole.x + offset[0] - sizes.text, sizes);
1670        code.point(at, self.input.clicks, first, self.input.mods);
1671    }
1672
1673    /// A click on the gutter at row `row`: on the fold marker it folds or unfolds the line's
1674    /// block; elsewhere it selects the line.
1675    fn number_pressed(&mut self, code: &mut CodeEditor, row: usize, on_mark: bool) {
1676        let line = code.line_at(row);
1677        if on_mark && code.fold(line) {
1678            return;
1679        }
1680        let picked = code.whole_line(code.starts[line] as usize);
1681        code.sels = vec![picked];
1682        code.clicks = 3;
1683    }
1684
1685    /// The position in row `row` nearest `x` units from its text start.
1686    fn code_at_x(&mut self, code: &CodeEditor, row: usize, x: f32, sizes: Sizes) -> usize {
1687        let (_, from, to, start) = code.row_span(row);
1688        let (mut at, mut left) = (from, 0.0);
1689        while at < to {
1690            let next = at + cluster(&code.text[at..to]);
1691            let right = self.code_x(code, from, next, start, sizes);
1692            if x < (left + right) / 2.0 {
1693                return at;
1694            }
1695            (at, left) = (next, right);
1696        }
1697        to
1698    }
1699
1700    /// The x of byte `at` from its row's text start, the row starting at byte `from` and column
1701    /// `start`. ASCII characters are one column each, tabs go to their stop, anything else is
1702    /// measured.
1703    fn code_x(&mut self, code: &CodeEditor, from: usize, at: usize, start: u32, sizes: Sizes) -> f32 {
1704        self.code_x_on(code, (0.0, start), from, at, sizes).0
1705    }
1706
1707    /// The same, continuing from byte `from` at `x` and column `column`: so each piece of a
1708    /// long row is placed without rescanning from the row start. Returns byte `at`'s x and
1709    /// column.
1710    fn code_x_on(&mut self, code: &CodeEditor, (mut x, mut column): (f32, u32), from: usize, at: usize, sizes: Sizes) -> (f32, u32) {
1711        let tab = code.tab_width.max(1) as u32;
1712        for (nth, piece) in code.text[from..at].split('\t').enumerate() {
1713            if nth > 0 {
1714                let stop = (column / tab + 1) * tab;
1715                (x, column) = (x + (stop - column) as f32 * sizes.column, stop);
1716            }
1717            let wide = if piece.is_ascii() { piece.len() as f32 * sizes.column } else { self.text.measure(piece, sizes.font, self.scale, None) };
1718            (x, column) = (x + wide, column + piece.chars().count() as u32);
1719        }
1720        (x, column)
1721    }
1722
1723    /// Scrolls so the primary cursor is in view.
1724    fn reveal_code(&mut self, code: &mut CodeEditor, id: Id, sizes: Sizes) {
1725        let [wide, high] = code.view;
1726        if high <= 0.0 {
1727            return;
1728        }
1729        code.unfold_cursors();
1730        code.tops();
1731        let at = code.sels[0].cursor;
1732        let (row, _) = code.place(at);
1733        let (_, from, _, start) = code.row_span(row);
1734        let x = sizes.text + self.code_x(code, from, at, start, sizes);
1735        let mut offset = self.scrolls.get(&id).copied().unwrap_or_default();
1736        let top = row as f32 * sizes.row;
1737        offset[1] = offset[1].min(top).max(top + sizes.row - high);
1738        offset[0] = offset[0].min(x - sizes.text).max(x + 2.0 * sizes.column - wide).max(0.0);
1739        match offset == [0.0; 2] {
1740            true => self.scrolls.remove(&id),
1741            false => self.scrolls.insert(id, offset),
1742        };
1743    }
1744
1745    /// The find and replace bar, while open.
1746    fn find_bar(&mut self, code: &mut CodeEditor) {
1747        if !code.finding.open {
1748            return;
1749        }
1750        let (t, words) = (self.theme, self.code_words);
1751        self.column().pad(6.0).gap(6.0).fill(t.raised).open();
1752        self.wrapping_row().gap(6.0).open();
1753        self.el().w(Length::Px(200.0)).open();
1754        if std::mem::take(&mut code.finding.focus) {
1755            let field = self.next_id();
1756            self.set_focus(field);
1757            self.select_all();
1758        }
1759        let field = self.text_box(&mut code.finding.words, words[0]);
1760        self.close();
1761        let back = self.icon_button(UP, words[9]).clicked;
1762        let next = self.icon_button(DOWN, words[8]).clicked;
1763        let (count, place) = code.count();
1764        self.note(&format!("{place} {} {count}", words[7]));
1765        self.toggle(&mut code.finding.case, words[2]);
1766        self.toggle(&mut code.finding.whole, words[3]);
1767        let shut = self.icon_button(CROSS, words[10]).clicked;
1768        self.close();
1769        let with = code.finding.replacing && self.replace_row(code);
1770        self.close();
1771        let in_bar = field.focused || with;
1772        let keyed = |ui: &mut Ui, mods: Mods| in_bar && ui.key(Key::Enter, mods) || ui.key(Key::F(3), mods);
1773        if field.changed {
1774            code.sels = vec![Sel::at(code.sels[0].range().start)];
1775            code.find_next(false);
1776        } else if back || keyed(self, Mods::SHIFT) {
1777            code.find_next(true);
1778        } else if next || keyed(self, Mods::NONE) {
1779            code.find_next(false);
1780        }
1781        if shut || in_bar && self.key(Key::Escape, Mods::NONE) {
1782            code.finding.open = false;
1783            self.set_focus(code.id);
1784        }
1785    }
1786
1787    /// The replace row of the bar. Returns whether its box has focus.
1788    fn replace_row(&mut self, code: &mut CodeEditor) -> bool {
1789        let words = self.code_words;
1790        self.wrapping_row().gap(6.0).open();
1791        self.el().w(Length::Px(200.0)).open();
1792        let field = self.text_box(&mut code.finding.with, words[1]);
1793        self.close();
1794        let one = self.button(words[4]).clicked;
1795        let all = self.button(words[5]).clicked;
1796        self.close();
1797        if one {
1798            code.replace_one();
1799        }
1800        if all {
1801            code.replace_all();
1802        }
1803        field.focused
1804    }
1805
1806    /// The go-to-line bar, while open.
1807    fn go_bar(&mut self, code: &mut CodeEditor) {
1808        let Some((mut typed, focus)) = code.going.take() else { return };
1809        let t = self.theme;
1810        self.row().pad(6.0).gap(6.0).fill(t.raised).open();
1811        self.el().w(Length::Px(140.0)).open();
1812        if focus {
1813            let field = self.next_id();
1814            self.set_focus(field);
1815        }
1816        let field = self.text_box(&mut typed, self.code_words[6]);
1817        self.close();
1818        let shut = self.icon_button(CROSS, self.code_words[10]).clicked;
1819        self.close();
1820        let go = field.focused && self.key(Key::Enter, Mods::NONE);
1821        if go && let Ok(line) = typed.trim().parse::<usize>() {
1822            code.go_to_line(line);
1823            code.moved = self.now;
1824        }
1825        if go || shut || field.focused && self.key(Key::Escape, Mods::NONE) {
1826            return self.set_focus(code.id);
1827        }
1828        code.going = Some((typed, false));
1829    }
1830
1831    /// The scrolling area with the visible rows; and what screen readers get of it.
1832    fn code_view(&mut self, code: &mut CodeEditor, state: &Response, sizes: Sizes, hint: &str) {
1833        let wide = if code.wrap { 0.0 } else { sizes.text + (code.widest() + 2) as f32 * sizes.column };
1834        self.el().key("code").grow().scroll().scroll_x().align(Align::Start, Align::Spread).sense().focusable().open();
1835        // Screen readers get a text box with all its text, the cursor position in characters,
1836        // and its line of how many.
1837        if self.listening {
1838            self.tell_text(state, hint, &code.text);
1839            let letters = |at: usize| code.text[..at].chars().count() as u32;
1840            self.tell_caret([letters(code.sels[0].anchor), letters(code.sels[0].cursor)]);
1841            self.tell_position(code.line_of(code.sels[0].cursor) + 1, code.starts.len());
1842        }
1843        self.column().min(wide, 0.0).open();
1844        code.tops();
1845        code.measured = self.next_id();
1846        let caret = state.focused && self.window_focused && self.blink(code.moved);
1847        let rows = self.rows(code.row_count(), sizes.row);
1848        let line = code.line_of(code.sels[0].cursor);
1849        let paired = if state.focused { code.paired() } else { None };
1850        for row in rows {
1851            self.code_row(code, row, line, [state.focused, caret], paired, sizes);
1852        }
1853        self.close();
1854        self.close();
1855        self.close();
1856    }
1857
1858    /// One row: its selections, matches and bracket pair, its highlighted text, its cursors,
1859    /// and over it all, its line number. `line` is the primary cursor's; `shows` says whether
1860    /// the box has focus, and whether the cursor shows now (it blinks).
1861    fn code_row(&mut self, code: &mut CodeEditor, row: usize, line: usize, shows: [bool; 2], paired: Option<[usize; 2]>, sizes: Sizes) {
1862        let t = self.theme;
1863        let (this, from, to, start) = code.row_span(row);
1864        let ends = to == code.line_ends(this).1;
1865        self.el().flow(Flow::Stack).fill(if this == line { t.hover } else { Color::NONE }).open();
1866        // Behind the text: selections, matches, the bracket pair.
1867        let picked = t.accent.with_alpha(if shows[0] { 0.35 } else { 0.2 });
1868        for range in code.sels.iter().map(Sel::range).filter(|range| !range.is_empty() && range.start <= to && range.end > from).collect::<Vec<_>>() {
1869            let left = self.code_x(code, from, range.start.max(from), start, sizes);
1870            let right = if range.end > to { self.code_x(code, from, to, start, sizes) + if ends { sizes.column } else { 0.0 } } else { self.code_x(code, from, range.end, start, sizes) };
1871            self.code_mark(left, right - left, sizes, picked, false);
1872        }
1873        let mut found = from;
1874        while let Some(range) = code.finding.open.then(|| code.next_match(found, to)).flatten() {
1875            let (left, right) = (self.code_x(code, from, range.start, start, sizes), self.code_x(code, from, range.end, start, sizes));
1876            self.code_mark(left, right - left, sizes, t.amber.with_alpha(0.3), false);
1877            found = range.end.max(range.start + 1);
1878        }
1879        for at in paired.into_iter().flatten().filter(|at| (from..to).contains(at)) {
1880            let left = self.code_x(code, from, at, start, sizes);
1881            self.code_mark(left, sizes.column, sizes, t.text_dim, true);
1882        }
1883        self.code_letters(code, this, [from, to], start, sizes);
1884        // The cursors: the primary where the input method's window goes, the others as marks.
1885        for (nth, sel) in code.sels.iter().enumerate().filter(|(_, sel)| sel.cursor >= from && (sel.cursor < to || sel.cursor == to && ends)) {
1886            let x = sizes.text + self.code_x(code, from, sel.cursor, start, sizes);
1887            let blinks = shows[0] && shows[1];
1888            // The primary is a text box only while the box has focus: the focused text box's
1889            // cursor is watched for blinking.
1890            match nth {
1891                0 => _ = self.el().text("", sizes.font, t.text).select(shows[0].then_some([0, 0]), blinks).place((Align::Start, Align::Center)).offset(x, 0.0).show(),
1892                _ => _ = self.el().size(1.0, sizes.line).fill(if blinks { t.text } else { Color::NONE }).place((Align::Start, Align::Center)).offset(x, 0.0).show(),
1893            }
1894        }
1895        self.code_numbers(code, this, from == code.starts[this] as usize, line, sizes);
1896        self.close();
1897    }
1898
1899    /// A mark behind a row's text, `left` units from its text start and so wide: filled, or
1900    /// (`ring`) outlined.
1901    fn code_mark(&mut self, left: f32, wide: f32, sizes: Sizes, color: Color, ring: bool) {
1902        let mark = self.el().size(wide.max(1.0), sizes.row).offset(sizes.text + left, 0.0);
1903        match ring {
1904            true => mark.border(color, 1.0).radius(2.0).show(),
1905            false => mark.fill(color).show(),
1906        };
1907    }
1908
1909    /// A row's text, from byte `ends[0]` to `ends[1]` of line `line` (the row starting at
1910    /// column `start`): a box per run of one colour, placed where it starts.
1911    fn code_letters(&mut self, code: &mut CodeEditor, line: usize, [from, to]: [usize; 2], start: u32, sizes: Sizes) {
1912        let t = self.theme;
1913        code.colour(line);
1914        let base = code.starts[line] as usize;
1915        // Where the last piece went, and its byte: each piece is placed from there.
1916        let (mut begun, mut went) = (base, (0.0, start, from));
1917        for nth in 0..code.pieces.len() {
1918            let (end, sort) = code.pieces[nth];
1919            let (low, high) = (begun.max(from), (base + end).min(to).max(begun.max(from)));
1920            begun = base + end;
1921            // Each piece between tabs on its own: a tab is space, up to its stop.
1922            for (at, piece) in between_tabs(&code.text, low, high) {
1923                let (x, column) = self.code_x_on(code, (went.0, went.1), went.2, at, sizes);
1924                went = (x, column, at);
1925                self.el().text(piece, sizes.font, sort.color(&t)).select(None, false).place((Align::Start, Align::Center)).offset(sizes.text + x, 0.0).show();
1926            }
1927        }
1928    }
1929
1930    /// The line number, at the row's left however far it is scrolled sideways, over what
1931    /// scrolls under it; and beside it, for a line starting a block, the fold marker. Only a
1932    /// line's first row shows these (`first`).
1933    fn code_numbers(&mut self, code: &CodeEditor, line: usize, first: bool, current: usize, sizes: Sizes) {
1934        let t = self.theme;
1935        let across = self.scrolls.get(&code.id).map_or(0.0, |offset| offset[0]);
1936        self.row().size(sizes.numbers, sizes.row).fill(t.panel).offset(across, 0.0).pad((0.0, 0.0, 4.0, 0.0)).gap(2.0).align(Align::End, Align::Center).open();
1937        if first {
1938            let mut digits = [0u8; 20];
1939            let shown = number_text(line + 1, &mut digits);
1940            self.el().text(shown, sizes.font, if line == current { t.text } else { t.text_faint }).show();
1941        }
1942        let folded = code.folds.iter().any(|run| run[0] as usize == line + 1);
1943        match first && (folded || code.block(line).is_some()) {
1944            true => _ = self.el().icon(if folded { RIGHT } else { DOWN }, 12.0, t.text_faint).show(),
1945            false => _ = self.el().size(12.0, 12.0).show(),
1946        }
1947        self.close();
1948    }
1949}
1950
1951/// The non-empty pieces of `text` from byte `from` to `to` between its tabs, each with its
1952/// start byte.
1953fn between_tabs(text: &str, from: usize, to: usize) -> impl Iterator<Item = (usize, &str)> {
1954    let pieces = text[from..to].split('\t').scan(from, |at, piece| Some((std::mem::replace(at, *at + piece.len() + 1), piece)));
1955    pieces.filter(|(_, piece)| !piece.is_empty())
1956}
1957
1958/// A number written into `digits`, as text.
1959fn number_text(mut number: usize, digits: &mut [u8; 20]) -> &str {
1960    let mut at = digits.len();
1961    loop {
1962        at -= 1;
1963        digits[at] = b'0' + (number % 10) as u8;
1964        number /= 10;
1965        if number == 0 {
1966            break;
1967        }
1968    }
1969    std::str::from_utf8(&digits[at..]).unwrap_or("")
1970}
1971
1972#[cfg(test)]
1973mod tests {
1974    use super::*;
1975    use crate::platform::LocalClipboard;
1976
1977    /// The text with `|` at each cursor and `[` `]` around each selection.
1978    fn shown(code: &CodeEditor) -> String {
1979        let mut marks: Vec<(usize, char)> = Vec::new();
1980        for sel in &code.sels {
1981            match sel.range().is_empty() {
1982                true => marks.push((sel.cursor, '|')),
1983                false => marks.extend([(sel.range().start, '['), (sel.range().end, ']')]),
1984            }
1985        }
1986        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
1987        let mut text = code.text.clone();
1988        for (at, mark) in marks {
1989            text.insert(at, mark);
1990        }
1991        text
1992    }
1993
1994    /// Presses keys in a windowless code editor, and types.
1995    fn keys(code: &mut CodeEditor, keys: &[(Key, Mods)]) {
1996        let mut clipboard = LocalClipboard::default();
1997        for (key, mods) in keys {
1998            code.key(*key, *mods, 10, &mut clipboard);
1999        }
2000    }
2001    const NONE: Mods = Mods::NONE;
2002    const SHIFT: Mods = Mods::SHIFT;
2003    const CTRL: Mods = Mods::CTRL;
2004
2005    /// What every line keeps, recomputed from scratch: as it must be after any edit.
2006    fn same_as_afresh(code: &CodeEditor) {
2007        let afresh = CodeEditor::new(code.text.clone(), code.syntax);
2008        assert_eq!((&code.starts, &code.widths), (&afresh.starts, &afresh.widths), "the lines of {:?}", code.text);
2009    }
2010
2011    #[test]
2012    fn a_line_is_coloured_by_the_rules() {
2013        let mut pieces = Vec::new();
2014        let open = Syntax::RUST.line("let x: u32 = 0x1f; // done", 0, &mut pieces);
2015        assert_eq!(open, 0);
2016        let sorts: Vec<(&str, TokenKind)> = {
2017            let line = "let x: u32 = 0x1f; // done";
2018            let mut from = 0;
2019            pieces.iter().map(|(end, sort)| (&line[std::mem::replace(&mut from, *end)..*end], *sort)).collect()
2020        };
2021        assert_eq!(
2022            sorts,
2023            [
2024                ("let", TokenKind::Keyword),
2025                (" x: ", TokenKind::Plain),
2026                ("u32", TokenKind::Type),
2027                (" = ", TokenKind::Plain),
2028                ("0x1f", TokenKind::Number),
2029                ("; ", TokenKind::Plain),
2030                ("// done", TokenKind::Comment)
2031            ]
2032        );
2033        // A multi-line string and a block comment stay open and close on a later line.
2034        pieces.clear();
2035        assert_eq!(Syntax::RUST.line("let s = \"one", 0, &mut pieces), 2);
2036        pieces.clear();
2037        assert_eq!(Syntax::RUST.line("two\"; /* three", 2, &mut pieces), IN_COMMENT);
2038        assert_eq!(pieces, [(4, TokenKind::String), (6, TokenKind::Plain), (14, TokenKind::Comment)]);
2039        pieces.clear();
2040        assert_eq!(Syntax::RUST.line("four */ x", IN_COMMENT, &mut pieces), 0);
2041        assert_eq!(pieces, [(7, TokenKind::Comment), (9, TokenKind::Plain)]);
2042        // A character literal is a string, a lifetime is not; an escaped delimiter doesn't
2043        // close.
2044        pieces.clear();
2045        Syntax::RUST.line("f::<'a>('\\'', 'b', \"\\\"\")", 0, &mut pieces);
2046        assert_eq!(pieces, [(8, TokenKind::Plain), (12, TokenKind::String), (14, TokenKind::Plain), (17, TokenKind::String), (19, TokenKind::Plain), (23, TokenKind::String), (24, TokenKind::Plain)]);
2047        // Python's triple quotes span lines, its single ones don't.
2048        pieces.clear();
2049        assert_eq!(Syntax::PYTHON.line("x = \"\"\"doc", 0, &mut pieces), 2);
2050        assert_eq!(Syntax::PYTHON.line("y = 'no end", 0, &mut pieces), 0);
2051    }
2052
2053    #[test]
2054    fn lines_are_kept_right_through_every_edit() {
2055        let mut code = CodeEditor::new("one\ntwo\r\nthree\n\tfour", &Syntax::PLAIN);
2056        same_as_afresh(&code);
2057        assert_eq!(code.widths, [3, 3, 5, 8]);
2058        for (at, removed, added) in [(0, 0, "zero\n"), (5, 4, ""), (2, 3, "a\nb\nc"), (0, 0, ""), (4, 6, "\r\n\r\n")] {
2059            let at = at.min(code.text.len());
2060            let end = (at + removed).min(code.text.len());
2061            code.change(vec![(at..end, added.to_string())], None, false);
2062            same_as_afresh(&code);
2063        }
2064        // And a change at more places than are patched one by one.
2065        let edits: Vec<_> = (0..100).map(|n| (0..0, format!("{n}\n"))).take(1).collect();
2066        code.change(edits, None, false);
2067        let many: Vec<(Range<usize>, String)> = (0..code.text.len()).step_by(2).map(|at| (at..at, "\n".to_string())).filter(|(range, _)| code.text.is_char_boundary(range.start)).collect();
2068        code.change(many, None, false);
2069        same_as_afresh(&code);
2070    }
2071
2072    #[test]
2073    fn what_is_left_open_is_read_only_as_far_as_needed_and_again_only_until_it_agrees() {
2074        let mut lines: Vec<String> = (0..1000).map(|n| format!("let x{n} = {n};")).collect();
2075        lines[10] = "/* a comment".into();
2076        lines[12] = "that ends */".into();
2077        let mut code = CodeEditor::new(lines.join("\n"), &Syntax::RUST);
2078        assert_eq!(code.open_at(11), IN_COMMENT);
2079        assert_eq!(code.sure, 12, "no further than asked");
2080        assert_eq!(code.open_at(900), 0);
2081        assert_eq!(code.sure, 901);
2082        // An edit far above: rescanned from there until it matches, and no further.
2083        let at = code.starts[3] as usize;
2084        code.change(vec![(at..at, "1".into())], None, false);
2085        assert_eq!(code.sure, 4);
2086        assert_eq!(code.open_at(800), 0);
2087        assert_eq!(code.sure, 901, "it agreed again at once, and kept the rest");
2088        // An edit opening a comment: everything after it is inside.
2089        code.change(vec![(at..at, "/*".into())], None, false);
2090        assert_eq!(code.open_at(5), IN_COMMENT);
2091        assert_eq!(code.open_at(800), 0, "the comment ends at line 12");
2092        assert_eq!(code.open_at(11), IN_COMMENT);
2093        // Each state is what scanning every line from the start gives.
2094        let mut open = 0;
2095        for line in 0..code.starts.len() {
2096            assert_eq!(code.open_at(line), open, "line {line}");
2097            open = code.syntax.read(code.line_text(line), open, None);
2098        }
2099    }
2100
2101    #[test]
2102    fn enter_keeps_the_indent_and_tab_indents() {
2103        let mut code = CodeEditor::new("fn main() {}", &Syntax::RUST);
2104        code.sels = vec![Sel::at(11)];
2105        keys(&mut code, &[(Key::Enter, NONE)]);
2106        assert_eq!(shown(&code), "fn main() {\n    |\n}", "after a bracket that opens, a step further; the closing one under");
2107        code.put("let x = 1;", true);
2108        keys(&mut code, &[(Key::Enter, NONE)]);
2109        assert_eq!(shown(&code), "fn main() {\n    let x = 1;\n    |\n}");
2110        keys(&mut code, &[(Key::Backspace, NONE)]);
2111        assert_eq!(shown(&code), "fn main() {\n    let x = 1;\n|\n}", "Backspace in spaces goes back a stop");
2112        keys(&mut code, &[(Key::Tab, NONE), (Key::Char('a'), CTRL), (Key::Tab, NONE)]);
2113        assert_eq!(code.text, "    fn main() {\n        let x = 1;\n    \n    }", "Tab indents every line selected, but blank ones");
2114        keys(&mut code, &[(Key::Tab, SHIFT), (Key::Tab, SHIFT)]);
2115        assert_eq!(code.text, "fn main() {\nlet x = 1;\n\n}");
2116        code.hard_tabs = true;
2117        code.sels = vec![Sel::at(12)];
2118        keys(&mut code, &[(Key::Tab, NONE)]);
2119        assert_eq!(shown(&code), "fn main() {\n\t|let x = 1;\n\n}");
2120        keys(&mut code, &[(Key::Char('z'), CTRL)]);
2121        assert_eq!(shown(&code), "fn main() {\n|let x = 1;\n\n}");
2122    }
2123
2124    #[test]
2125    fn several_cursors_type_and_move_together() {
2126        let mut code = CodeEditor::new("one\ntwo\nthree", &Syntax::PLAIN);
2127        keys(&mut code, &[(Key::Down, Mods { ctrl: true, alt: true, shift: false }), (Key::Down, Mods { ctrl: true, alt: true, shift: false })]);
2128        assert_eq!(shown(&code), "|one\n|two\n|three");
2129        code.put("- ", true);
2130        assert_eq!(shown(&code), "- |one\n- |two\n- |three");
2131        keys(&mut code, &[(Key::End, NONE), (Key::Left, SHIFT)]);
2132        assert_eq!(shown(&code), "- on[e]\n- tw[o]\n- thre[e]");
2133        keys(&mut code, &[(Key::Char('x'), CTRL), (Key::Char('z'), CTRL)]);
2134        assert_eq!(shown(&code), "- on[e]\n- tw[o]\n- thre[e]", "undone, the cursors are back as they were");
2135        keys(&mut code, &[(Key::Home, NONE), (Key::Escape, NONE)]);
2136        assert_eq!(shown(&code), "|- one\n- two\n- three", "Escape leaves the main cursor: the first");
2137        // Overlapping cursors merge.
2138        code.sels = vec![Sel::at(1), Sel::at(2)];
2139        keys(&mut code, &[(Key::Home, NONE)]);
2140        assert_eq!(code.sels.len(), 1);
2141    }
2142
2143    #[test]
2144    fn rows_follow_wrapping_and_folding() {
2145        let mut code = CodeEditor::new("fn a() {\n    one two three four five\n    six\n}\nend", &Syntax::RUST);
2146        code.wrap = true;
2147        code.fit(12);
2148        code.tops();
2149        assert_eq!(code.wraps, [1, 3, 1, 1, 1]);
2150        assert_eq!(code.row_count(), 7);
2151        let spans: Vec<&str> = (0..7).map(|row| code.row_span(row)).map(|(_, from, to, _)| &code.text[from..to]).collect();
2152        assert_eq!(spans, ["fn a() {", "    one two ", "three four ", "five", "    six", "}", "end"]);
2153        // Down keeps its column across rows of one line.
2154        code.sels = vec![Sel::at(code.starts[1] as usize + 5)];
2155        keys(&mut code, &[(Key::Down, NONE)]);
2156        assert_eq!(code.place(code.sels[0].cursor), (2, 5));
2157        // Folding hides the block's lines; a cursor in them moves to the standing line.
2158        assert!(code.fold(0));
2159        code.tops();
2160        assert_eq!(code.row_count(), 3);
2161        assert_eq!((code.line_at(1), code.line_at(2)), (3, 4));
2162        assert_eq!(code.sels[0].cursor, 8);
2163        keys(&mut code, &[(Key::Down, NONE)]);
2164        assert_eq!(code.line_of(code.sels[0].cursor), 3, "Down goes past what is folded");
2165        // An edit on a fold's standing line unfolds it.
2166        code.sels = vec![Sel::at(2)];
2167        code.put("x", true);
2168        assert!(code.folds.is_empty());
2169        same_as_afresh(&code);
2170    }
2171
2172    #[test]
2173    fn find_and_replace_with_case_and_whole_words() {
2174        let mut code = CodeEditor::new("Cat cat catalog\ncat", &Syntax::PLAIN);
2175        code.finding.words = "cat".into();
2176        assert_eq!(code.count(), (4, 0));
2177        code.finding.whole = true;
2178        assert_eq!(code.count(), (3, 0));
2179        code.finding.case = true;
2180        assert_eq!(code.count(), (2, 0));
2181        keys(&mut code, &[(Key::F(3), NONE)]);
2182        assert_eq!(shown(&code), "Cat [cat] catalog\ncat");
2183        assert_eq!(code.count(), (2, 1));
2184        keys(&mut code, &[(Key::F(3), NONE), (Key::F(3), NONE)]);
2185        assert_eq!(shown(&code), "Cat [cat] catalog\ncat", "it goes round");
2186        keys(&mut code, &[(Key::F(3), SHIFT)]);
2187        assert_eq!(shown(&code), "Cat cat catalog\n[cat]");
2188        code.finding.with = "dog".into();
2189        code.replace_one();
2190        assert_eq!(shown(&code), "Cat [cat] catalog\ndog");
2191        code.finding.case = false;
2192        code.replace_all();
2193        assert_eq!(code.text, "dog dog catalog\ndog");
2194        keys(&mut code, &[(Key::Char('z'), CTRL)]);
2195        assert_eq!(code.text, "Cat cat catalog\ndog", "replacing all is undone as one");
2196        // Non-ASCII letters are found case-insensitively.
2197        code.set_text("Ärger ärger");
2198        (code.finding.words, code.finding.whole) = ("ÄRGER".into(), false);
2199        assert_eq!(code.count().0, 2);
2200    }
2201
2202    #[test]
2203    fn brackets_pair_only_in_code() {
2204        let mut code = CodeEditor::new("f(a, \"(\", [b]) // )\n{\n  g()\n}", &Syntax::RUST);
2205        code.sels = vec![Sel::at(1)];
2206        assert_eq!(code.paired(), Some([1, 13]));
2207        code.sels = vec![Sel::at(14)];
2208        assert_eq!(code.paired(), Some([13, 1]), "the one before the cursor, where none is after it");
2209        code.sels = vec![Sel::at(20)];
2210        assert_eq!(code.paired(), Some([20, 28]), "over lines");
2211        code.sels = vec![Sel::at(6)];
2212        assert_eq!(code.paired(), None, "a bracket in a quote pairs with nothing");
2213    }
2214
2215    #[test]
2216    fn the_pointer_selects_by_letter_word_and_line() {
2217        let mut code = CodeEditor::new("one two\nthree", &Syntax::PLAIN);
2218        code.point(5, 1, true, NONE);
2219        code.point(10, 1, false, NONE);
2220        assert_eq!(shown(&code), "one t[wo\nth]ree");
2221        code.point(5, 2, true, NONE);
2222        assert_eq!(shown(&code), "one [two]\nthree");
2223        code.point(5, 3, true, NONE);
2224        assert_eq!(shown(&code), "[one two\n]three");
2225        code.point(10, 1, true, NONE);
2226        code.point(1, 1, true, Mods { alt: true, ..NONE });
2227        assert_eq!(code.sels.len(), 2, "a press with Alt is one cursor more");
2228        code.point(2, 1, true, Mods { alt: true, ..NONE });
2229        assert_eq!(code.sels.len(), 3);
2230    }
2231}