BlueGit

ict rusty-teams

fix(composer): code padding, links with ports, undo order

- Code padding is one em space, never real indentation: pasted and
  split code keeps its leading spaces, copies and HTML leave it out
- Forward Delete at a line end joins without the next marker; Delete
  inside padding deletes the first content character; stray padding a
  join leaves in code content is removed
- host:port and localhost links are schemeless and become https; a
  refused link shows an inline error in the link field
- Any text edit drops format undo and redo steps, so undo stays in order

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
9712d24d372cc68e630f5e0a44b170d6ba24105c
Parent
31afb34e
3 files changed +264 −29
crates/app/src/views/composer.rs +94 −12
@@ -10,8 +10,8 @@ use gpui_kit::assets::IconName;
10 10 use gpui_kit::component::{
11 11 ActiveTheme as _, h_flex,
12 12 input::{
13 Backspace, Copy, Cut, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent,
14 InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
13 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
14 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16 16 },
17 17 tooltip::Tooltip,
@@ -187,6 +187,7 @@ struct Conversion {
187 187 struct LinkEditor {
188 188 range: Range<usize>,
189 189 field: Entity<InputState>,
190 refused: bool,
190 191 }
191 192
192 193 type DraftDecorations = (
@@ -425,6 +426,8 @@ impl Composer {
425 426 self.refresh_style(cx);
426 427 return;
427 428 }
429 self.format_undo.clear();
430 self.format_redo.clear();
428 431 if replaying && let Some(snapshot) = self.snapshot_for(&value) {
429 432 self.draft = snapshot;
430 433 self.pending_style = None;
@@ -556,6 +559,10 @@ impl Composer {
556 559 window: &mut Window,
557 560 cx: &mut Context<Self>,
558 561 ) {
562 if !edits.is_empty() {
563 self.format_undo.clear();
564 self.format_redo.clear();
565 }
559 566 self.input.update(cx, |state, cx| {
560 567 let edited = !edits.is_empty();
561 568 if edited {
@@ -816,7 +823,11 @@ impl Composer {
816 823 state.focus(window, cx);
817 824 state.select_all(window, cx);
818 825 });
819 self.link_editor = Some(LinkEditor { range, field });
826 self.link_editor = Some(LinkEditor {
827 range,
828 field,
829 refused: false,
830 });
820 831 cx.notify();
821 832 }
822 833
@@ -830,7 +841,11 @@ impl Composer {
830 841 } else if let Some(url) = link_url(&typed) {
831 842 url
832 843 } else {
833 self.link_editor = Some(editor);
844 self.link_editor = Some(LinkEditor {
845 refused: true,
846 ..editor
847 });
848 cx.notify();
834 849 return;
835 850 };
836 851 self.focus(window, cx);
@@ -890,6 +905,20 @@ impl Composer {
890 905 }
891 906 }
892 907
908 fn delete_forward(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
909 let selection = self.selection(cx);
910 if !selection.is_empty() {
911 return false;
912 }
913 match self.draft.delete_forward(selection.start) {
914 Some(cursor) => {
915 self.commit(Some(cursor), window, cx);
916 true
917 }
918 None => false,
919 }
920 }
921
893 922 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
894 923 let selection = self.selection(cx);
895 924 if !self.draft.indent(selection, outdent) {
@@ -901,12 +930,10 @@ impl Composer {
901 930
902 931 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
903 932 let selection = self.selection(cx);
904 let Some(text) = self.draft.text().get(selection.clone()).map(str::to_owned) else {
905 return false;
906 };
907 if text.is_empty() {
933 if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {
908 934 return false;
909 935 }
936 let text = self.draft.plain_slice(selection.clone());
910 937 let lines = self.draft.slice(selection);
911 938 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
912 939 text.clone(),
@@ -1678,6 +1705,7 @@ impl Composer {
1678 1705 placement,
1679 1706 format_toolbar::Mode::Link {
1680 1707 field: &editor.field,
1708 refused: editor.refused,
1681 1709 on_apply: Rc::new(move |window, cx| {
1682 1710 composer
1683 1711 .update(cx, |this, cx| this.apply_link(window, cx))
@@ -2021,6 +2049,11 @@ impl Render for Composer {
2021 2049 cx.stop_propagation();
2022 2050 }
2023 2051 }))
2052 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2053 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2054 cx.stop_propagation();
2055 }
2056 }))
2024 2057 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2025 2058 if this.link_editor.is_some() {
2026 2059 this.close_link_editor(window, cx);
@@ -2490,12 +2523,61 @@ mod tests {
2490 2523 assert!(typist.draft().marks().is_empty());
2491 2524 typist.press("ctrl-y");
2492 2525 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2493 typist.press("end");
2526 }
2527
2528 #[gpui_kit::test]
2529 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
2530 use teams_core::{FormatState, MarkKind};
2531
2532 let mut typist = typist(cx);
2533 typist.type_text("hello");
2534 typist.press("shift-left shift-left ctrl-b end");
2494 2535 typist.type_text(" x");
2495 typist.press("ctrl-z");
2536 typist.press("backspace backspace");
2496 2537 assert_eq!(typist.value(), "hello");
2497 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2498 2538 typist.press("ctrl-z");
2539 assert_ne!(typist.value(), "hello");
2540 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2541 }
2542
2543 #[gpui_kit::test]
2544 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
2545 let mut typist = typist(cx);
2546 typist.type_text("```");
2547 typist.press("enter");
2548 typist.type_text("a");
2549 typist.press("enter");
2550 typist.type_text("b");
2551 typist.press("up end delete");
2552 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
2553 }
2554
2555 #[gpui_kit::test]
2556 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
2557 let mut typist = typist(cx);
2558 typist.type_text("```");
2559 typist.press("enter");
2560 typist.type_text(" x");
2561 typist.press("ctrl-a ctrl-c");
2562 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
2563 assert_eq!(text.as_deref(), Some(" x"));
2564 }
2565
2566 #[gpui_kit::test]
2567 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
2568 let mut typist = typist(cx);
2569 typist.type_text("docs");
2570 typist.press("ctrl-a ctrl-k");
2571 typist.type_text("javascript:alert(1)");
2572 typist.press("enter");
2573 let composer = typist.composer.clone();
2574 assert!(typist.cx.update(|cx| {
2575 composer
2576 .read(cx)
2577 .link_editor
2578 .as_ref()
2579 .is_some_and(|editor| editor.refused)
2580 }));
2499 2581 assert!(typist.draft().marks().is_empty());
2500 2582 }
2501 2583
@@ -2517,7 +2599,7 @@ mod tests {
2517 2599 .cx
2518 2600 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
2519 2601 typist.press("ctrl-v");
2520 assert_eq!(typist.value(), " :) **x**");
2602 assert_eq!(typist.value(), "\u{2003}:) **x**");
2521 2603 let composer = typist.composer.clone();
2522 2604 assert!(
2523 2605 typist
@@ -10,8 +10,8 @@ use gpui_kit::assets::IconName;
10use gpui_kit::component::{
10use gpui_kit::component::{
11 ActiveTheme as _, h_flex,
11 ActiveTheme as _, h_flex,
12 input::{
12 input::{
13 Backspace, Copy, Cut, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent,
13 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
14 InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
14 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16 },
16 },
17 tooltip::Tooltip,
17 tooltip::Tooltip,
@@ -187,6 +187,7 @@ struct Conversion {
187struct LinkEditor {
187struct LinkEditor {
188 range: Range<usize>,
188 range: Range<usize>,
189 field: Entity<InputState>,
189 field: Entity<InputState>,
190 refused: bool,
190}
191}
191
192
192type DraftDecorations = (
193type DraftDecorations = (
@@ -425,6 +426,8 @@ impl Composer {
425 self.refresh_style(cx);
426 self.refresh_style(cx);
426 return;
427 return;
427 }
428 }
429 self.format_undo.clear();
430 self.format_redo.clear();
428 if replaying && let Some(snapshot) = self.snapshot_for(&value) {
431 if replaying && let Some(snapshot) = self.snapshot_for(&value) {
429 self.draft = snapshot;
432 self.draft = snapshot;
430 self.pending_style = None;
433 self.pending_style = None;
@@ -556,6 +559,10 @@ impl Composer {
556 window: &mut Window,
559 window: &mut Window,
557 cx: &mut Context<Self>,
560 cx: &mut Context<Self>,
558 ) {
561 ) {
562 if !edits.is_empty() {
563 self.format_undo.clear();
564 self.format_redo.clear();
565 }
559 self.input.update(cx, |state, cx| {
566 self.input.update(cx, |state, cx| {
560 let edited = !edits.is_empty();
567 let edited = !edits.is_empty();
561 if edited {
568 if edited {
@@ -816,7 +823,11 @@ impl Composer {
816 state.focus(window, cx);
823 state.focus(window, cx);
817 state.select_all(window, cx);
824 state.select_all(window, cx);
818 });
825 });
819 self.link_editor = Some(LinkEditor { range, field });
826 self.link_editor = Some(LinkEditor {
827 range,
828 field,
829 refused: false,
830 });
820 cx.notify();
831 cx.notify();
821 }
832 }
822
833
@@ -830,7 +841,11 @@ impl Composer {
830 } else if let Some(url) = link_url(&typed) {
841 } else if let Some(url) = link_url(&typed) {
831 url
842 url
832 } else {
843 } else {
833 self.link_editor = Some(editor);
844 self.link_editor = Some(LinkEditor {
845 refused: true,
846 ..editor
847 });
848 cx.notify();
834 return;
849 return;
835 };
850 };
836 self.focus(window, cx);
851 self.focus(window, cx);
@@ -890,6 +905,20 @@ impl Composer {
890 }
905 }
891 }
906 }
892
907
908 fn delete_forward(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
909 let selection = self.selection(cx);
910 if !selection.is_empty() {
911 return false;
912 }
913 match self.draft.delete_forward(selection.start) {
914 Some(cursor) => {
915 self.commit(Some(cursor), window, cx);
916 true
917 }
918 None => false,
919 }
920 }
921
893 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
922 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
894 let selection = self.selection(cx);
923 let selection = self.selection(cx);
895 if !self.draft.indent(selection, outdent) {
924 if !self.draft.indent(selection, outdent) {
@@ -901,12 +930,10 @@ impl Composer {
901
930
902 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
931 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
903 let selection = self.selection(cx);
932 let selection = self.selection(cx);
904 let Some(text) = self.draft.text().get(selection.clone()).map(str::to_owned) else {
933 if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {
905 return false;
906 };
907 if text.is_empty() {
908 return false;
934 return false;
909 }
935 }
936 let text = self.draft.plain_slice(selection.clone());
910 let lines = self.draft.slice(selection);
937 let lines = self.draft.slice(selection);
911 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
938 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
912 text.clone(),
939 text.clone(),
@@ -1678,6 +1705,7 @@ impl Composer {
1678 placement,
1705 placement,
1679 format_toolbar::Mode::Link {
1706 format_toolbar::Mode::Link {
1680 field: &editor.field,
1707 field: &editor.field,
1708 refused: editor.refused,
1681 on_apply: Rc::new(move |window, cx| {
1709 on_apply: Rc::new(move |window, cx| {
1682 composer
1710 composer
1683 .update(cx, |this, cx| this.apply_link(window, cx))
1711 .update(cx, |this, cx| this.apply_link(window, cx))
@@ -2021,6 +2049,11 @@ impl Render for Composer {
2021 cx.stop_propagation();
2049 cx.stop_propagation();
2022 }
2050 }
2023 }))
2051 }))
2052 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2053 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2054 cx.stop_propagation();
2055 }
2056 }))
2024 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2057 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2025 if this.link_editor.is_some() {
2058 if this.link_editor.is_some() {
2026 this.close_link_editor(window, cx);
2059 this.close_link_editor(window, cx);
@@ -2490,12 +2523,61 @@ mod tests {
2490 assert!(typist.draft().marks().is_empty());
2523 assert!(typist.draft().marks().is_empty());
2491 typist.press("ctrl-y");
2524 typist.press("ctrl-y");
2492 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2525 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2493 typist.press("end");
2526 }
2527
2528 #[gpui_kit::test]
2529 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
2530 use teams_core::{FormatState, MarkKind};
2531
2532 let mut typist = typist(cx);
2533 typist.type_text("hello");
2534 typist.press("shift-left shift-left ctrl-b end");
2494 typist.type_text(" x");
2535 typist.type_text(" x");
2495 typist.press("ctrl-z");
2536 typist.press("backspace backspace");
2496 assert_eq!(typist.value(), "hello");
2537 assert_eq!(typist.value(), "hello");
2497 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2498 typist.press("ctrl-z");
2538 typist.press("ctrl-z");
2539 assert_ne!(typist.value(), "hello");
2540 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2541 }
2542
2543 #[gpui_kit::test]
2544 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
2545 let mut typist = typist(cx);
2546 typist.type_text("```");
2547 typist.press("enter");
2548 typist.type_text("a");
2549 typist.press("enter");
2550 typist.type_text("b");
2551 typist.press("up end delete");
2552 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
2553 }
2554
2555 #[gpui_kit::test]
2556 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
2557 let mut typist = typist(cx);
2558 typist.type_text("```");
2559 typist.press("enter");
2560 typist.type_text(" x");
2561 typist.press("ctrl-a ctrl-c");
2562 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
2563 assert_eq!(text.as_deref(), Some(" x"));
2564 }
2565
2566 #[gpui_kit::test]
2567 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
2568 let mut typist = typist(cx);
2569 typist.type_text("docs");
2570 typist.press("ctrl-a ctrl-k");
2571 typist.type_text("javascript:alert(1)");
2572 typist.press("enter");
2573 let composer = typist.composer.clone();
2574 assert!(typist.cx.update(|cx| {
2575 composer
2576 .read(cx)
2577 .link_editor
2578 .as_ref()
2579 .is_some_and(|editor| editor.refused)
2580 }));
2499 assert!(typist.draft().marks().is_empty());
2581 assert!(typist.draft().marks().is_empty());
2500 }
2582 }
2501
2583
@@ -2517,7 +2599,7 @@ mod tests {
2517 .cx
2599 .cx
2518 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
2600 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
2519 typist.press("ctrl-v");
2601 typist.press("ctrl-v");
2520 assert_eq!(typist.value(), " :) **x**");
2602 assert_eq!(typist.value(), "\u{2003}:) **x**");
2521 let composer = typist.composer.clone();
2603 let composer = typist.composer.clone();
2522 assert!(
2604 assert!(
2523 typist
2605 typist
crates/app/src/views/format_toolbar.rs +23 −4
@@ -124,6 +124,7 @@ pub enum Mode<'a> {
124 124 },
125 125 Link {
126 126 field: &'a Entity<InputState>,
127 refused: bool,
127 128 on_apply: ApplyHandler,
128 129 },
129 130 }
@@ -193,8 +194,8 @@ fn bar(state: &dyn Fn(FormatButton) -> FormatState, on_press: PressHandler) -> D
193 194 row
194 195 }
195 196
196 fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
197 h_flex()
197 fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
198 let row = h_flex()
198 199 .gap(px(BUTTON_GAP * 2.))
199 200 .items_center()
200 201 .child(
@@ -203,7 +204,11 @@ fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
203 204 .h(px(BUTTON))
204 205 .rounded(px(6.))
205 206 .border_1()
206 .border_color(theme::accent())
207 .border_color(if refused {
208 theme::red()
209 } else {
210 theme::accent()
211 })
207 212 .bg(theme::surface())
208 213 .child(Input::new(field).appearance(false).bordered(false)),
209 214 )
@@ -228,7 +233,17 @@ fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
228 233 cx.stop_propagation();
229 234 })
230 235 .on_click(move |_, window, cx| on_apply(window, cx)),
236 );
237 v_flex().child(row).when(refused, |editor| {
238 editor.child(
239 div()
240 .pt(px(4.))
241 .px(px(2.))
242 .text_size(px(11.5))
243 .text_color(theme::red_soft())
244 .child("Only http, https and mailto links"),
231 245 )
246 })
232 247 }
233 248
234 249 fn arrow(offset: Pixels) -> impl IntoElement {
@@ -261,7 +276,11 @@ fn arrow(offset: Pixels) -> impl IntoElement {
261 276 pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
262 277 let content = match mode {
263 278 Mode::Bar { state, on_press } => bar(state, on_press),
264 Mode::Link { field, on_apply } => link_editor(field, on_apply),
279 Mode::Link {
280 field,
281 refused,
282 on_apply,
283 } => link_editor(field, refused, on_apply),
265 284 };
266 285 deferred(
267 286 anchored()
@@ -124,6 +124,7 @@ pub enum Mode<'a> {
124 },
124 },
125 Link {
125 Link {
126 field: &'a Entity<InputState>,
126 field: &'a Entity<InputState>,
127 refused: bool,
127 on_apply: ApplyHandler,
128 on_apply: ApplyHandler,
128 },
129 },
129}
130}
@@ -193,8 +194,8 @@ fn bar(state: &dyn Fn(FormatButton) -> FormatState, on_press: PressHandler) -> D
193 row
194 row
194}
195}
195
196
196fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
197fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
197 h_flex()
198 let row = h_flex()
198 .gap(px(BUTTON_GAP * 2.))
199 .gap(px(BUTTON_GAP * 2.))
199 .items_center()
200 .items_center()
200 .child(
201 .child(
@@ -203,7 +204,11 @@ fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
203 .h(px(BUTTON))
204 .h(px(BUTTON))
204 .rounded(px(6.))
205 .rounded(px(6.))
205 .border_1()
206 .border_1()
206 .border_color(theme::accent())
207 .border_color(if refused {
208 theme::red()
209 } else {
210 theme::accent()
211 })
207 .bg(theme::surface())
212 .bg(theme::surface())
208 .child(Input::new(field).appearance(false).bordered(false)),
213 .child(Input::new(field).appearance(false).bordered(false)),
209 )
214 )
@@ -228,7 +233,17 @@ fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
228 cx.stop_propagation();
233 cx.stop_propagation();
229 })
234 })
230 .on_click(move |_, window, cx| on_apply(window, cx)),
235 .on_click(move |_, window, cx| on_apply(window, cx)),
236 );
237 v_flex().child(row).when(refused, |editor| {
238 editor.child(
239 div()
240 .pt(px(4.))
241 .px(px(2.))
242 .text_size(px(11.5))
243 .text_color(theme::red_soft())
244 .child("Only http, https and mailto links"),
231 )
245 )
246 })
232}
247}
233
248
234fn arrow(offset: Pixels) -> impl IntoElement {
249fn arrow(offset: Pixels) -> impl IntoElement {
@@ -261,7 +276,11 @@ fn arrow(offset: Pixels) -> impl IntoElement {
261pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
276pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
262 let content = match mode {
277 let content = match mode {
263 Mode::Bar { state, on_press } => bar(state, on_press),
278 Mode::Bar { state, on_press } => bar(state, on_press),
264 Mode::Link { field, on_apply } => link_editor(field, on_apply),
279 Mode::Link {
280 field,
281 refused,
282 on_apply,
283 } => link_editor(field, refused, on_apply),
265 };
284 };
266 deferred(
285 deferred(
267 anchored()
286 anchored()
crates/core/src/draft.rs +147 −13
@@ -12,7 +12,7 @@ const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12 12 const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13 13 const INDENT: &str = "\u{2003}\u{2003}";
14 14 const QUOTE_MARKER: &str = "\u{2003}";
15 const CODE_MARKER: &str = " ";
15 const CODE_MARKER: &str = "\u{2003}";
16 16 const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
17 17 const FENCE: &str = "```";
18 18 const MARKDOWN_INDENT: usize = 2;
@@ -652,6 +652,67 @@ impl Draft {
652 652 }
653 653 }
654 654
655 /// Forward Delete next to a marker: at a line end it joins the next line without its
656 /// marker; inside a marker it deletes the first character of the content instead.
657 pub fn delete_forward(&mut self, cursor: usize) -> Option<usize> {
658 self.journal = Journal::default();
659 let index = self.line_at(cursor);
660 let line = self.line_ranges()[index].clone();
661 let content = self.content_range(index);
662 if cursor >= line.start && cursor < content.start {
663 let next = self.text[content.start..]
664 .chars()
665 .next()
666 .filter(|character| *character != '\n');
667 match next {
668 Some(character) => {
669 self.splice(content.start..content.start + character.len_utf8(), "", &[]);
670 }
671 None if index + 1 < self.lines.len() => {
672 let next_content = self.content_range(index + 1);
673 self.splice(content.end..next_content.start, "", &[]);
674 }
675 None => return Some(content.start),
676 }
677 return Some(self.repair(content.start));
678 }
679 if cursor != line.end || index + 1 >= self.lines.len() {
680 return None;
681 }
682 let next_marker = self.marker_range(index + 1);
683 if next_marker.is_empty() {
684 return None;
685 }
686 self.splice(cursor..next_marker.end, "", &[]);
687 Some(self.repair(cursor))
688 }
689
690 /// The text of `range` without list, quote and code markers in front of whole lines
691 /// and without code padding, for the plain clipboard.
692 pub fn plain_slice(&self, range: Range<usize>) -> String {
693 let mut plain = String::with_capacity(range.len());
694 for (index, line) in self.line_ranges().into_iter().enumerate() {
695 if line.end < range.start || line.start > range.end {
696 continue;
697 }
698 let marker = self.marker_range(index);
699 let skip_marker = matches!(self.lines[index], LineKind::Code(_));
700 let start = if skip_marker {
701 range.start.max(marker.end)
702 } else {
703 range.start.max(line.start)
704 };
705 let end = range.end.min(line.end);
706 if start < end {
707 plain.push_str(&self.text[start..end]);
708 }
709 if line.end < range.end && line.end < self.text.len() {
710 plain.push('\n');
711 }
712 }
713 plain
714 }
715
655 716 /// Backspace at the start of a formatted line drops (or lifts) its format.
656 717 pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {
657 718 self.journal = Journal::default();
@@ -1117,6 +1178,23 @@ impl Draft {
1117 1178 }
1118 1179 }
1119 1180
1181 /// Padding merged into a code line's content by a join or a cross-line delete.
1182 fn drop_stray_padding(&mut self, index: usize, mut cursor: usize) -> usize {
1183 loop {
1184 let content = self.content_range(index);
1185 let Some(offset) = self.text[content.clone()].find(CODE_MARKER) else {
1186 return cursor;
1187 };
1188 let stray = content.start + offset..content.start + offset + CODE_MARKER.len();
1189 self.splice(stray.clone(), "", &[]);
1190 if cursor >= stray.end {
1191 cursor -= CODE_MARKER.len();
1192 } else if cursor > stray.start {
1193 cursor = stray.start;
1194 }
1195 }
1196 }
1197
1120 1198 /// Lines whose marker was edited away become text; numbered items are renumbered; code
1121 1199 /// lines get their padding back.
1122 1200 fn repair(&mut self, mut cursor: usize) -> usize {
@@ -1126,10 +1204,11 @@ impl Draft {
1126 1204 continue;
1127 1205 }
1128 1206 if matches!(kind, LineKind::Code(_)) {
1129 let start = self.line_ranges()[index].start;
1130 if !self.text[start..].starts_with(CODE_MARKER) {
1131 cursor = self.replace_marker(start..start, CODE_MARKER, cursor);
1207 let line = self.line_ranges()[index].clone();
1208 if !self.text[line.start..].starts_with(CODE_MARKER) {
1209 cursor = self.replace_marker(line.start..line.start, CODE_MARKER, cursor);
1132 1210 }
1211 cursor = self.drop_stray_padding(index, cursor);
1133 1212 continue;
1134 1213 }
1135 1214 let line = self.line_ranges()[index].clone();
@@ -1244,15 +1323,16 @@ pub fn link_url(text: &str) -> Option<String> {
1244 1323 if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
1245 1324 return Some(text.to_owned());
1246 1325 }
1247 let scheme = text
1248 .split_once(':')
1249 .map(|(scheme, _)| scheme)
1250 .filter(|scheme| {
1251 scheme.starts_with(|character: char| character.is_ascii_alphabetic())
1252 && scheme
1253 .chars()
1254 .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character))
1255 });
1326 let scheme = text.split_once(':').filter(|(scheme, rest)| {
1327 let host_and_port = scheme.contains('.')
1328 || scheme.eq_ignore_ascii_case("localhost")
1329 || rest.starts_with(|character: char| character.is_ascii_digit());
1330 !host_and_port
1331 && scheme.starts_with(|character: char| character.is_ascii_alphabetic())
1332 && scheme
1333 .chars()
1334 .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character))
1335 });
1256 1336 scheme.is_none().then(|| format!("https://{text}"))
1257 1337 }
1258 1338
@@ -2135,6 +2215,60 @@ mod tests {
2135 2215 assert!(draft.in_code(draft.text().len()));
2136 2216 }
2137 2217
2218 #[test]
2219 fn code_indentation_is_kept_on_paste_split_and_send() {
2220 let mut draft = typed_draft("```py");
2221 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2222 let pasted = "def f():\n return 1";
2223 let mut next = draft.text().to_owned();
2224 next.insert_str(cursor, pasted);
2225 draft.apply_edit(&next, cursor + pasted.len(), None);
2226 assert_eq!(
2227 draft.to_html(),
2228 "<pre class=\"language-py\">def f():\n return 1</pre>"
2229 );
2230 let mut split = Draft::from_markdown("```\n a b\n```");
2231 let after_a = CODE_MARKER.len() + " a".len();
2232 split.break_line(after_a, false).unwrap();
2233 assert_eq!(split.to_html(), "<pre> a\n b</pre>");
2234 }
2235
2236 #[test]
2237 fn delete_never_moves_padding_into_code() {
2238 let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");
2239 let end_of_first = draft.line_ranges()[0].end;
2240 assert_eq!(draft.delete_forward(end_of_first), Some(end_of_first));
2241 assert_eq!(draft.to_html(), "<pre>let a = 1;let b = 2;</pre>");
2242 let cursor = draft.delete_forward(0).unwrap();
2243 assert_eq!(cursor, CODE_MARKER.len());
2244 assert_eq!(draft.to_html(), "<pre>et a = 1;let b = 2;</pre>");
2245 let mut selected = Draft::from_markdown("```\nx = 1\ny = 2\n```");
2246 let second = selected.line_ranges()[1].start;
2247 let mut next = selected.text().to_owned();
2248 next.replace_range(0..second + CODE_MARKER.len(), "");
2249 selected.apply_edit(&next, 0, None);
2250 assert_eq!(selected.to_html(), "<pre>y = 2</pre>");
2251 }
2252
2253 #[test]
2254 fn plain_copies_leave_code_padding_out() {
2255 let draft = Draft::from_markdown("```\n a\nb\n```");
2256 assert_eq!(draft.plain_slice(0..draft.text().len()), " a\nb");
2257 }
2258
2259 #[test]
2260 fn host_and_port_links_are_schemeless() {
2261 assert_eq!(
2262 link_url("localhost:3000"),
2263 Some("https://localhost:3000".into())
2264 );
2265 assert_eq!(
2266 link_url("example.com:8080/x"),
2267 Some("https://example.com:8080/x".into())
2268 );
2269 assert_eq!(link_url("javascript:alert(1)"), None);
2270 }
2271
2138 2272 #[test]
2139 2273 fn journal_merges_edits_into_ranges_of_the_old_text() {
2140 2274 let mut draft = Draft::plain("a **b** c");
@@ -12,7 +12,7 @@ const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
12const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13const INDENT: &str = "\u{2003}\u{2003}";
13const INDENT: &str = "\u{2003}\u{2003}";
14const QUOTE_MARKER: &str = "\u{2003}";
14const QUOTE_MARKER: &str = "\u{2003}";
15const CODE_MARKER: &str = " ";
15const CODE_MARKER: &str = "\u{2003}";
16const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
16const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
17const FENCE: &str = "```";
17const FENCE: &str = "```";
18const MARKDOWN_INDENT: usize = 2;
18const MARKDOWN_INDENT: usize = 2;
@@ -652,6 +652,67 @@ impl Draft {
652 }
652 }
653 }
653 }
654
654
655 /// Forward Delete next to a marker: at a line end it joins the next line without its
656 /// marker; inside a marker it deletes the first character of the content instead.
657 pub fn delete_forward(&mut self, cursor: usize) -> Option<usize> {
658 self.journal = Journal::default();
659 let index = self.line_at(cursor);
660 let line = self.line_ranges()[index].clone();
661 let content = self.content_range(index);
662 if cursor >= line.start && cursor < content.start {
663 let next = self.text[content.start..]
664 .chars()
665 .next()
666 .filter(|character| *character != '\n');
667 match next {
668 Some(character) => {
669 self.splice(content.start..content.start + character.len_utf8(), "", &[]);
670 }
671 None if index + 1 < self.lines.len() => {
672 let next_content = self.content_range(index + 1);
673 self.splice(content.end..next_content.start, "", &[]);
674 }
675 None => return Some(content.start),
676 }
677 return Some(self.repair(content.start));
678 }
679 if cursor != line.end || index + 1 >= self.lines.len() {
680 return None;
681 }
682 let next_marker = self.marker_range(index + 1);
683 if next_marker.is_empty() {
684 return None;
685 }
686 self.splice(cursor..next_marker.end, "", &[]);
687 Some(self.repair(cursor))
688 }
689
690 /// The text of `range` without list, quote and code markers in front of whole lines
691 /// and without code padding, for the plain clipboard.
692 pub fn plain_slice(&self, range: Range<usize>) -> String {
693 let mut plain = String::with_capacity(range.len());
694 for (index, line) in self.line_ranges().into_iter().enumerate() {
695 if line.end < range.start || line.start > range.end {
696 continue;
697 }
698 let marker = self.marker_range(index);
699 let skip_marker = matches!(self.lines[index], LineKind::Code(_));
700 let start = if skip_marker {
701 range.start.max(marker.end)
702 } else {
703 range.start.max(line.start)
704 };
705 let end = range.end.min(line.end);
706 if start < end {
707 plain.push_str(&self.text[start..end]);
708 }
709 if line.end < range.end && line.end < self.text.len() {
710 plain.push('\n');
711 }
712 }
713 plain
714 }
715
655 /// Backspace at the start of a formatted line drops (or lifts) its format.
716 /// Backspace at the start of a formatted line drops (or lifts) its format.
656 pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {
717 pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {
657 self.journal = Journal::default();
718 self.journal = Journal::default();
@@ -1117,6 +1178,23 @@ impl Draft {
1117 }
1178 }
1118 }
1179 }
1119
1180
1181 /// Padding merged into a code line's content by a join or a cross-line delete.
1182 fn drop_stray_padding(&mut self, index: usize, mut cursor: usize) -> usize {
1183 loop {
1184 let content = self.content_range(index);
1185 let Some(offset) = self.text[content.clone()].find(CODE_MARKER) else {
1186 return cursor;
1187 };
1188 let stray = content.start + offset..content.start + offset + CODE_MARKER.len();
1189 self.splice(stray.clone(), "", &[]);
1190 if cursor >= stray.end {
1191 cursor -= CODE_MARKER.len();
1192 } else if cursor > stray.start {
1193 cursor = stray.start;
1194 }
1195 }
1196 }
1197
1120 /// Lines whose marker was edited away become text; numbered items are renumbered; code
1198 /// Lines whose marker was edited away become text; numbered items are renumbered; code
1121 /// lines get their padding back.
1199 /// lines get their padding back.
1122 fn repair(&mut self, mut cursor: usize) -> usize {
1200 fn repair(&mut self, mut cursor: usize) -> usize {
@@ -1126,10 +1204,11 @@ impl Draft {
1126 continue;
1204 continue;
1127 }
1205 }
1128 if matches!(kind, LineKind::Code(_)) {
1206 if matches!(kind, LineKind::Code(_)) {
1129 let start = self.line_ranges()[index].start;
1207 let line = self.line_ranges()[index].clone();
1130 if !self.text[start..].starts_with(CODE_MARKER) {
1208 if !self.text[line.start..].starts_with(CODE_MARKER) {
1131 cursor = self.replace_marker(start..start, CODE_MARKER, cursor);
1209 cursor = self.replace_marker(line.start..line.start, CODE_MARKER, cursor);
1132 }
1210 }
1211 cursor = self.drop_stray_padding(index, cursor);
1133 continue;
1212 continue;
1134 }
1213 }
1135 let line = self.line_ranges()[index].clone();
1214 let line = self.line_ranges()[index].clone();
@@ -1244,15 +1323,16 @@ pub fn link_url(text: &str) -> Option<String> {
1244 if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
1323 if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
1245 return Some(text.to_owned());
1324 return Some(text.to_owned());
1246 }
1325 }
1247 let scheme = text
1326 let scheme = text.split_once(':').filter(|(scheme, rest)| {
1248 .split_once(':')
1327 let host_and_port = scheme.contains('.')
1249 .map(|(scheme, _)| scheme)
1328 || scheme.eq_ignore_ascii_case("localhost")
1250 .filter(|scheme| {
1329 || rest.starts_with(|character: char| character.is_ascii_digit());
1251 scheme.starts_with(|character: char| character.is_ascii_alphabetic())
1330 !host_and_port
1252 && scheme
1331 && scheme.starts_with(|character: char| character.is_ascii_alphabetic())
1253 .chars()
1332 && scheme
1254 .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character))
1333 .chars()
1255 });
1334 .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character))
1335 });
1256 scheme.is_none().then(|| format!("https://{text}"))
1336 scheme.is_none().then(|| format!("https://{text}"))
1257}
1337}
1258
1338
@@ -2135,6 +2215,60 @@ mod tests {
2135 assert!(draft.in_code(draft.text().len()));
2215 assert!(draft.in_code(draft.text().len()));
2136 }
2216 }
2137
2217
2218 #[test]
2219 fn code_indentation_is_kept_on_paste_split_and_send() {
2220 let mut draft = typed_draft("```py");
2221 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2222 let pasted = "def f():\n return 1";
2223 let mut next = draft.text().to_owned();
2224 next.insert_str(cursor, pasted);
2225 draft.apply_edit(&next, cursor + pasted.len(), None);
2226 assert_eq!(
2227 draft.to_html(),
2228 "<pre class=\"language-py\">def f():\n return 1</pre>"
2229 );
2230 let mut split = Draft::from_markdown("```\n a b\n```");
2231 let after_a = CODE_MARKER.len() + " a".len();
2232 split.break_line(after_a, false).unwrap();
2233 assert_eq!(split.to_html(), "<pre> a\n b</pre>");
2234 }
2235
2236 #[test]
2237 fn delete_never_moves_padding_into_code() {
2238 let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");
2239 let end_of_first = draft.line_ranges()[0].end;
2240 assert_eq!(draft.delete_forward(end_of_first), Some(end_of_first));
2241 assert_eq!(draft.to_html(), "<pre>let a = 1;let b = 2;</pre>");
2242 let cursor = draft.delete_forward(0).unwrap();
2243 assert_eq!(cursor, CODE_MARKER.len());
2244 assert_eq!(draft.to_html(), "<pre>et a = 1;let b = 2;</pre>");
2245 let mut selected = Draft::from_markdown("```\nx = 1\ny = 2\n```");
2246 let second = selected.line_ranges()[1].start;
2247 let mut next = selected.text().to_owned();
2248 next.replace_range(0..second + CODE_MARKER.len(), "");
2249 selected.apply_edit(&next, 0, None);
2250 assert_eq!(selected.to_html(), "<pre>y = 2</pre>");
2251 }
2252
2253 #[test]
2254 fn plain_copies_leave_code_padding_out() {
2255 let draft = Draft::from_markdown("```\n a\nb\n```");
2256 assert_eq!(draft.plain_slice(0..draft.text().len()), " a\nb");
2257 }
2258
2259 #[test]
2260 fn host_and_port_links_are_schemeless() {
2261 assert_eq!(
2262 link_url("localhost:3000"),
2263 Some("https://localhost:3000".into())
2264 );
2265 assert_eq!(
2266 link_url("example.com:8080/x"),
2267 Some("https://example.com:8080/x".into())
2268 );
2269 assert_eq!(link_url("javascript:alert(1)"), None);
2270 }
2271
2138 #[test]
2272 #[test]
2139 fn journal_merges_edits_into_ranges_of_the_old_text() {
2273 fn journal_merges_edits_into_ranges_of_the_old_text() {
2140 let mut draft = Draft::plain("a **b** c");
2274 let mut draft = Draft::plain("a **b** c");