From 132843e3fecf6c4efc4b4fe60c722aeed22fe647 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 22:42:41 +0000 Subject: [PATCH] text editor: the host may take Tab, word and paragraph stops, word deletes and Copy's HTML TextEditorHost gains defaulted hooks: tab (Tab and Shift+Tab, for a list level or the next cell), caret_stop (Cmd+arrows by word, Ctrl+Up/Down by paragraph off the Mac), delete_word, and copy_html, offered beside the plain text on Copy and Cut. Hosts without them keep the editor's own rules. The canvas editor keeps Shift+Tab for its host instead of letting it move focus out of the session. Co-Authored-By: Claude Opus 5.5 --- crates/text/src/ui/editor.rs | 70 +++++++++++++++++++++---- crates/text/src/ui/editor/edits.rs | 44 +++++++++++++++- crates/text/tests/it/editor.rs | 83 +++++++++++++++++++++++++++++- 3 files changed, 184 insertions(+), 13 deletions(-) diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index 1f38633778..8b859b8674 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -377,6 +377,43 @@ pub trait TextEditorHost { fn style_key(&mut self, _key: StyleKey, _selection: TextSelection) -> bool { false } + + /// Take Tab (`back`: Shift+Tab) in the canvas editor, at a paragraph's start or wherever the app gives it a meaning + /// (a list level, the next table cell), and return the selection after it. `None` (the default): Tab types a tab + /// character and Shift+Tab does nothing. + fn tab(&mut self, _selection: TextSelection, _back: bool) -> Option { + None + } + + /// The next caret stop of `stop` from `offset` toward the text's end (`forward`) or start, for the app's own word + /// or paragraph rules. `None` (the default): a word move goes to the next [`word_boundary`], and a paragraph move + /// is a line move. + fn caret_stop(&mut self, _offset: usize, _stop: CaretStop, _forward: bool) -> Option { + None + } + + /// Delete by word (Ctrl+Backspace and Ctrl+Delete, Alt on the Mac) with the app's own rules, and return the + /// selection after it. `None` (the default): the selection goes, or without one the text to the next + /// [`word_boundary`]. + fn delete_word(&mut self, _selection: TextSelection, _forward: bool) -> Option { + None + } + + /// `selection` as HTML, offered beside its plain text by Copy and Cut so the formatting pastes along. `None` (the + /// default) offers the plain text only. + fn copy_html(&mut self, _selection: TextSelection) -> Option { + None + } +} + +/// A unit a caret move goes by ([`TextEditorHost::caret_stop`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CaretStop { + /// Cmd+Left and Cmd+Right (Alt on the Mac). + Word, + /// Ctrl+Up and Ctrl+Down off the Mac. + Paragraph, } /// The style of the editor: the selection fill, the caret's two strokes and the marked text's underline. @@ -514,7 +551,8 @@ impl Outcome for TextEditorOutput { /// - Keys: Left and Right by char (a selection collapses to its edge), with Cmd or Alt by word, Up and Down by /// line, Cmd+Up and Cmd+Down to the text's start or end, Home and End to the line's edges, Shift extends any of /// them. Backspace and Delete by char, Alt by word, Cmd+Backspace to the line start. Cmd+A all, Cmd+C, Cmd+X and -/// Cmd+V the clipboard. Enter a line break; Cmd+Enter commits; Esc commits or cancels; Cmd+. cancels; +/// Cmd+V the clipboard. The host may give Tab and Shift+Tab, the word and paragraph stops, the word deletes and +/// Copy's HTML its own rules ([`TextEditorHost::tab`] and the hooks after it). Enter a line break; Cmd+Enter commits; Esc commits or cancels; Cmd+. cancels; /// Cmd+T asks the host for its Character panel. In a form field ([`mode`](Self::mode)) Tab and Shift+Tab end the /// session toward the next or previous field, a press that moves focus away commits, and in a one-line field Enter commits. The /// [`TextEditorCommand`]s format. In vertical text the arrows turn with the flow, the formatting keys too: Alt+Up @@ -677,8 +715,8 @@ fn show_i_beam(cx: &mut Cx<'_, TextEditor<'_>>, phase: &PressPhase, vertical: bo } /// Applies one pass's editor steps to `edits` in order: typing, the marked text, moves, deletes, selections, the edit -/// commands and the commands keys fired. Returns the text a Copy or Cut put on the clipboard, and whether a command -/// asked for the character panel. +/// commands and the commands keys fired. Returns what a Copy or Cut put on the clipboard, and whether a command asked +/// for the character panel. fn apply_steps( edits: &mut Edits<'_>, steps: Vec>, @@ -686,8 +724,8 @@ fn apply_steps( masked: bool, pasted: Option<&str>, fallback: Rect, -) -> (Option, bool) { - let mut copied: Option = None; +) -> (Option>, bool) { + let mut copied: Option> = None; let mut ending: Option> = None; let mut character_panel = false; for step in steps { @@ -723,7 +761,11 @@ fn apply_steps( EditorInput::Newline { .. } if edits.session.preedit.is_none() && mode.multiline() => { edits.done.changed |= edits.insert_text("\n", EditKind::Typed); } - EditorInput::Tab if mode.takes_tab() => edits.done.changed |= edits.insert_text("\t", EditKind::Typed), + EditorInput::Tab if mode.takes_tab() => { + if !edits.host_tab(false) { + edits.done.changed |= edits.insert_text("\t", EditKind::Typed); + } + } EditorInput::Move(step, mods) => edits.motion(step, mods), EditorInput::Delete { forward, by, .. } => edits.done.changed |= edits.delete(forward, by), EditorInput::DeleteSurrounding { before, after, unit, .. } => edits.done.changed |= edits.delete_around(before, after, unit), @@ -734,9 +776,9 @@ fn apply_steps( edits.selection = TextSelection::new(char_at(&lines, anchor), caret).with_affinity(hit_affinity(&lines, caret, focus.line)); } EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(), - EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.selected_text(), + EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.copied(), EditorInput::Edit(EditCommand::Cut) if !masked => { - copied = edits.selected_text(); + copied = edits.copied(); edits.done.changed |= edits.delete_selection(); } EditorInput::Edit(EditCommand::Paste) => { @@ -883,6 +925,14 @@ impl Component for TextEditor<'_> { } } } + // The canvas editor keeps Shift+Tab beside the Tab it types, for the host to take (an outdent); it never moves + // the focus out of the session. + if mode.takes_tab() { + cx.claim(SHIFT_TAB); + if cx.take_claimed(SHIFT_TAB) && edits.session.preedit.is_none() { + edits.host_tab(true); + } + } if edits.done.commit || edits.done.cancel || edits.done.next || edits.done.previous { edits.end_composition(); @@ -897,8 +947,8 @@ impl Component for TextEditor<'_> { let vertical = edits.host.vertical(); *cx.memory::() = session; - if let Some(text) = copied { - cx.clipboard().put(&[ClipItem::Text(text.into())]); + if let Some(items) = copied { + cx.clipboard().put(&items); } show_i_beam(cx, &press.phase, vertical); if done.changed { diff --git a/crates/text/src/ui/editor/edits.rs b/crates/text/src/ui/editor/edits.rs index c395822de5..2e2ece5a6d 100644 --- a/crates/text/src/ui/editor/edits.rs +++ b/crates/text/src/ui/editor/edits.rs @@ -7,7 +7,9 @@ use std::ops::Range; use craft_behavior::kurbo::Point; use craft_behavior::{Granularity, MoveMods, NavMove, SurroundingUnit}; -use super::{CaretAffinity, ClickRuns, EditKind, TextEditorCommand, TextEditorHost, TextSelection, hit_affinity}; +use craft_ui::runtime::commands::ClipItem; + +use super::{CaretAffinity, CaretStop, ClickRuns, EditKind, TextEditorCommand, TextEditorHost, TextSelection, hit_affinity}; use crate::quotes::{QuoteStyle, smart_quotes}; /// What the editor keeps between passes of one editing session. @@ -236,6 +238,35 @@ impl Edits<'_> { (!range.is_empty()).then(|| char_slice(self.host.text(), &range)) } + /// What Copy and Cut put on the clipboard: the selected chars, with the host's HTML of them beside; + /// `None` with an empty selection. + pub fn copied(&mut self) -> Option> { + let text = self.selected_text()?; + let html = self.host.copy_html(self.selection); + Some(html.into_iter().map(|html| ClipItem::Html(html.into())).chain([ClipItem::Text(text.into())]).collect()) + } + + /// Lets the host take Tab or Shift+Tab ([`TextEditorHost::tab`]); `false` when it doesn't. + pub fn host_tab(&mut self, back: bool) -> bool { + self.clamp_selection(); + let selection = self.selection; + let Some(changed) = self.host_edit(|host| host.tab(selection, back)) else { return false }; + self.done.changed |= changed; + true + } + + /// Runs an edit the host made itself and adopts the selection it left; whether the text changed, or `None` when + /// the host made none. An edit ends a live composition first, so the host never edits around marked text. + fn host_edit(&mut self, edit: impl FnOnce(&mut dyn TextEditorHost) -> Option) -> Option { + let before = fingerprint(self.host.text()); + self.end_composition(); + let selection = edit(&mut *self.host)?; + self.session.word = None; + self.selection = selection; + self.clamp_selection(); + Some(fingerprint(self.host.text()) != before) + } + /// Delete the selection ([`EditKind::Deleted`]); the caller has copied it. pub fn delete_selection(&mut self) -> bool { let range = self.clamped(); @@ -362,7 +393,7 @@ impl Edits<'_> { NavMove::Back | NavMove::Forward => { let forward = step == NavMove::Forward; if mods.by != Granularity::Unit { - word_boundary(&text, caret, forward) + self.host.caret_stop(caret, CaretStop::Word, forward).unwrap_or_else(|| word_boundary(&text, caret, forward)) } else if !range.is_empty() && !mods.extend { if forward { range.end } else { range.start } } else if forward { @@ -373,8 +404,12 @@ impl Edits<'_> { } NavMove::Up | NavMove::Down => { let up = step == NavMove::Up; + // Ctrl+Up and Ctrl+Down off the Mac: the arrow's lead with no unit of its own. + let by_paragraph = mods.lead && mods.by == Granularity::Unit; if matches!(mods.by, Granularity::Paragraph | Granularity::Document) { if up { 0 } else { chars } + } else if let Some(offset) = by_paragraph.then(|| self.host.caret_stop(caret, CaretStop::Paragraph, !up)).flatten() { + offset } else { let (offset, side) = self.host.line_step(caret, self.selection.affinity, if up { -1 } else { 1 }); affinity = side; @@ -407,6 +442,11 @@ impl Edits<'_> { /// Backspace or Delete. pub fn delete(&mut self, forward: bool, by: Granularity) -> bool { self.clamp_selection(); + let selection = self.selection; + if by == Granularity::Word + && let Some(changed) = self.host_edit(|host| host.delete_word(selection, forward)) { + return changed; + } let text = self.host.text().to_owned(); let chars = text.chars().count(); let range = self.clamped(); diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index caea2b0423..08736d2caa 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -11,7 +11,7 @@ use craft_behavior::CancelReason; use craft_behavior::CanvasView; use craft_behavior::kurbo::Point; use craft_text::quotes::QuoteStyle; -use craft_text::ui::editor::{CaretLine, EditKind, EditorEnd, EditorMode, HostCx, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection}; +use craft_text::ui::editor::{CaretLine, CaretStop, EditKind, EditorEnd, EditorMode, HostCx, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection}; use craft_ui::buttons::Button; use craft_ui::canvas::{Canvas, CanvasTool, ToolAction, ToolContext, ToolHost, ToolKey, ToolPath, ToolPointer, tool_pass}; use craft_ui::contract::{Bind, FacesCx as _, Props as _, Show as _, ShowContainer as _}; @@ -49,6 +49,11 @@ struct Host { replacement: Option, /// A replacement may retain a nonempty selection independently of its inserted range. replacement_selection: Option, + /// The host's own keys: Tab at a paragraph start, stops at spaces and line breaks, a word delete to the text's + /// end, and bold HTML for Copy. + own_keys: bool, + /// The Tabs the host took, `true` for Shift+Tab. + tabs: Vec, } /// The chars of one line. @@ -199,6 +204,41 @@ impl TextEditorHost for Host { self.styles.push(key); self.formats } + + fn tab(&mut self, selection: TextSelection, back: bool) -> Option { + let start = selection.caret == 0 || self.text.chars().nth(selection.caret - 1) == Some('\n'); + (self.own_keys && start).then(|| { + self.tabs.push(back); + selection + }) + } + + fn caret_stop(&mut self, offset: usize, stop: CaretStop, forward: bool) -> Option { + if !self.own_keys { + return None; + } + let edge = if stop == CaretStop::Word { ' ' } else { '\n' }; + let chars: Vec = self.text.chars().collect(); + Some(if forward { + (offset + 1..chars.len()).find(|&at| chars[at - 1] == edge).unwrap_or(chars.len()) + } else { + (1..offset).rev().find(|&at| chars[at - 1] == edge).unwrap_or(0) + }) + } + + fn delete_word(&mut self, selection: TextSelection, forward: bool) -> Option { + if !self.own_keys || !forward { + return None; + } + let start = selection.range().start; + self.text = self.text.chars().take(start).collect(); + Some(TextSelection::caret_at(start)) + } + + fn copy_html(&mut self, selection: TextSelection) -> Option { + let range = selection.range(); + self.own_keys.then(|| format!("{}", self.text.chars().skip(range.start).take(range.len()).collect::())) + } } struct Session { @@ -612,6 +652,47 @@ fn field_modes_end_on_enter_tab_and_shift_tab_but_not_while_composing() { assert!(canvas.ends.borrow().is_empty(), "Tab does not end a canvas session"); } +/// A host may give the editing keys its own meaning: Tab and Shift+Tab at a paragraph start are the host's and type +/// nothing, while Tab elsewhere still types; Ctrl+arrows stop where the host's word and paragraph rules say; a word +/// delete is the host's edit; Copy still offers the plain text beside the host's HTML. +#[trial] +fn a_host_takes_tab_the_word_keys_and_rich_copy() { + let host = Host { text: "ab.cd ef\ngh".to_owned(), own_keys: true, ..Host::default() }; + let mut editor = session_on(host, None, false, EditorMode::Canvas, false); + editor.fixture.os(craft_host::target::Os::Linux); + editor.focus(); + let ctrl = Modifiers::COMMAND; + let caret = |editor: &Session| editor.selection.borrow().caret; + *editor.selection.borrow_mut() = TextSelection::caret_at(11); + editor.fixture.settle(); + editor.fixture.key(Key::ArrowUp, ctrl).settle(); + assert_eq!(caret(&editor), 9, "Ctrl+Up goes to the host's paragraph start, not a line up"); + editor.fixture.key(Key::Tab, Modifiers::NONE).settle(); + editor.fixture.key(Key::Tab, Modifiers::SHIFT).settle(); + assert_eq!(editor.host.borrow().tabs, [false, true], "the host takes Tab and Shift+Tab at a paragraph start"); + assert_eq!(editor.text(), "ab.cd ef\ngh", "a Tab the host takes types nothing"); + + let mut stops = Vec::new(); + for _ in 0..2 { + editor.fixture.key(Key::ArrowLeft, ctrl).settle(); + stops.push(caret(&editor)); + } + assert_eq!(stops, [6, 0], "the host's word stops, not the editor's punctuation stop"); + editor.fixture.key(Key::ArrowDown, ctrl).settle(); + assert_eq!(caret(&editor), 9, "Ctrl+Down goes to the host's next paragraph"); + editor.fixture.key(Key::Delete, ctrl).settle(); + assert_eq!((editor.text().as_str(), caret(&editor)), ("ab.cd ef\n", 9), "a word delete is the host's edit"); + + editor.fixture.key(Key::ArrowLeft, Modifiers::NONE).key(Key::Tab, Modifiers::NONE).settle(); + assert_eq!(editor.text(), "ab.cd ef\t\n", "Tab the host leaves types a tab"); + assert_eq!(editor.host.borrow().tabs.len(), 2); + + // The fixture's clipboard is egui's, which keeps only the text of an offer: the HTML beside it must not cost it. + editor.fixture.key(Key::A, ctrl).settle(); + editor.fixture.frame(vec![Event::Copy]); + assert_eq!(editor.fixture.copied().to_vec(), ["ab.cd ef\t\n".to_owned()], "Copy offers the plain text beside the host's HTML"); +} + /// A masked editor puts nothing on the clipboard for Copy or Cut, and a Cut keeps the text; the same editor /// unmasked copies the selection. #[trial]