fix(composer): no padding characters, one undo history
- Draft text holds only content and visible list markers; list levels, the quote gap and code padding are line indents, so em spaces in code survive and copies carry no hidden characters - The composer keeps one history of text and format steps and drives Ctrl+Z / Ctrl+Y itself; typing and deleting runs merge into a step - tel: and other unknown schemes are refused; only a host or localhost before the colon counts as host:port - The link field's refused state clears on the next edit; plain_slice removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1,5 +1,5 @@
1
1
use std::cell::Cell;
2
use std::collections::{HashMap, HashSet, VecDeque};
2
use std::collections::{HashMap, HashSet};
3
3
use std::ops::Range;
4
4
use std::path::PathBuf;
5
5
use std::rc::Rc;
@@ -51,7 +51,7 @@ const POPUP_ROW_HEIGHT: f32 = 44.;
51
51
const DEMO_UPLOAD_STEPS: u8 = 10;
52
52
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
53
53
const DEMO_FAILURE_STEP: u8 = 6;
54
const SNAPSHOT_LIMIT: usize = 100;
54
const HISTORY_LIMIT: usize = 200;
55
55
const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);
56
56
const KEY_CONTEXT: &str = "Composer";
57
57
@@ -184,10 +184,26 @@ struct Conversion {
184
184
restore: Vec<Edit>,
185
185
}
186
186
187
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188
enum StepKind {
189
Typing { after_space: bool },
190
Deleting,
191
Other,
192
}
193
194
/// One state of the composer's own undo history: text, tokens, formatting and selection.
195
struct HistoryStep {
196
draft: Draft,
197
tokens: Vec<(Range<usize>, InlineToken)>,
198
selection: Range<usize>,
199
kind: StepKind,
200
}
201
187
202
struct LinkEditor {
188
203
range: Range<usize>,
189
204
field: Entity<InputState>,
190
205
refused: bool,
206
_edits: Subscription,
191
207
}
192
208
193
209
type DraftDecorations = (
@@ -214,10 +230,8 @@ pub struct Composer {
214
230
draft: Draft,
215
231
decorations: DraftDecorations,
216
232
pending_style: Option<TypingStyle>,
217
snapshots: VecDeque<Draft>,
218
format_undo: Vec<(Draft, Draft)>,
219
format_redo: Vec<(Draft, Draft)>,
220
replaying_history: bool,
233
history: Vec<HistoryStep>,
234
history_index: usize,
221
235
pasted_markdown: Option<String>,
222
236
paste_hint: Option<Task<()>>,
223
237
copied: Option<(String, Vec<DraftLine>)>,
@@ -291,6 +305,27 @@ fn candidate_subtitle(candidate: &MentionCandidate) -> String {
291
305
}
292
306
}
293
307
308
fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {
309
if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {
310
return StepKind::Typing {
311
after_space: typed.is_whitespace(),
312
};
313
}
314
let removed = previous.len().saturating_sub(value.len());
315
let one_char_removed = removed > 0
316
&& previous.is_char_boundary(cursor)
317
&& previous
318
.get(cursor..cursor + removed)
319
.is_some_and(|gone| gone.chars().count() == 1 && gone != "\n")
320
&& previous.get(..cursor) == value.get(..cursor)
321
&& previous.get(cursor + removed..) == value.get(cursor..);
322
if one_char_removed {
323
StepKind::Deleting
324
} else {
325
StepKind::Other
326
}
327
}
328
294
329
fn looks_like_url(text: &str) -> bool {
295
330
["https://", "http://", "www."]
296
331
.iter()
@@ -342,10 +377,13 @@ impl Composer {
342
377
draft: Draft::default(),
343
378
decorations,
344
379
pending_style: None,
345
snapshots: VecDeque::new(),
346
format_undo: Vec::new(),
347
format_redo: Vec::new(),
348
replaying_history: false,
380
history: vec![HistoryStep {
381
draft: Draft::default(),
382
tokens: Vec::new(),
383
selection: 0..0,
384
kind: StepKind::Other,
385
}],
386
history_index: 0,
349
387
pasted_markdown: None,
350
388
paste_hint: None,
351
389
copied: None,
@@ -419,27 +457,18 @@ impl Composer {
419
457
420
458
fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
421
459
let state = self.input.read(cx);
422
let (value, cursor) = (state.value().to_string(), state.cursor());
460
let (value, input_cursor) = (state.value().to_string(), state.cursor());
423
461
let previous = std::mem::replace(&mut self.previous_value, value.clone());
424
let replaying = std::mem::take(&mut self.replaying_history);
425
462
if value == self.draft.text() {
426
463
self.refresh_style(cx);
427
464
return;
428
465
}
429
self.format_undo.clear();
430
self.format_redo.clear();
431
if replaying && let Some(snapshot) = self.snapshot_for(&value) {
432
self.draft = snapshot;
433
self.pending_style = None;
434
self.refresh_style(cx);
435
return;
436
}
466
let kind = step_kind(&previous, &value, input_cursor);
437
467
let typing = self.pending_style.take();
438
let cursor = self.draft.apply_edit(&value, cursor, typing.as_ref());
439
self.commit(Some(cursor), window, cx);
440
if replaying {
441
return;
442
}
468
let cursor = self.draft.apply_edit(&value, input_cursor, typing.as_ref());
469
let edits = self.draft.take_edits();
470
self.apply_to_input(edits, cursor..cursor, window, cx);
471
self.record(kind, cx);
443
472
if let Some(pasted) = self.pasted_markdown.take()
444
473
&& self.convert_paste(&pasted, cursor, window, cx)
445
474
{
@@ -504,6 +533,7 @@ impl Composer {
504
533
let edits = self.draft.take_edits();
505
534
let restore = reverse_edits(&edits, before.text());
506
535
self.apply_to_input(edits, cursor..cursor, window, cx);
536
self.record(StepKind::Other, cx);
507
537
self.conversion = Some(Conversion {
508
538
value: self.draft.text().to_owned(),
509
539
cursor,
@@ -550,6 +580,7 @@ impl Composer {
550
580
None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),
551
581
};
552
582
self.apply_to_input(edits, selection, window, cx);
583
self.record(StepKind::Other, cx);
553
584
}
554
585
555
586
fn apply_to_input(
@@ -559,10 +590,6 @@ impl Composer {
559
590
window: &mut Window,
560
591
cx: &mut Context<Self>,
561
592
) {
562
if !edits.is_empty() {
563
self.format_undo.clear();
564
self.format_redo.clear();
565
}
566
593
self.input.update(cx, |state, cx| {
567
594
let edited = !edits.is_empty();
568
595
if edited {
@@ -578,30 +605,80 @@ impl Composer {
578
605
self.draft.take_edits();
579
606
}
580
607
self.previous_value = value;
581
self.remember_snapshot();
582
608
self.refresh_style(cx);
583
609
}
584
610
585
fn remember_snapshot(&mut self) {
586
if self
587
.snapshots
588
.back()
589
.is_some_and(|last| last.text() == self.draft.text())
590
{
591
self.snapshots.pop_back();
611
/// Adds the current state as an undo step. Typing and deleting runs merge into one step;
612
/// a typed space ends a typing step.
613
fn record(&mut self, kind: StepKind, cx: &App) {
614
let state = self.input.read(cx);
615
let step = HistoryStep {
616
draft: self.draft.clone(),
617
tokens: state
618
.tokens()
619
.iter()
620
.map(|span| (span.range(), span.token().clone()))
621
.collect(),
622
selection: state.selected_range(),
623
kind,
624
};
625
let at_end = self.history_index + 1 == self.history.len();
626
let merges = at_end
627
&& match (self.history.last().map(|last| last.kind), kind) {
628
(Some(StepKind::Typing { after_space: false }), StepKind::Typing { .. }) => true,
629
(
630
Some(StepKind::Typing { after_space: true }),
631
StepKind::Typing { after_space },
632
) => after_space,
633
(Some(StepKind::Deleting), StepKind::Deleting) => true,
634
_ => false,
635
};
636
if merges {
637
if let Some(last) = self.history.last_mut() {
638
*last = step;
639
}
640
return;
592
641
}
593
self.snapshots.push_back(self.draft.clone());
594
if self.snapshots.len() > SNAPSHOT_LIMIT {
595
self.snapshots.pop_front();
642
self.history.truncate(self.history_index + 1);
643
self.history.push(step);
644
if self.history.len() > HISTORY_LIMIT {
645
self.history.remove(0);
596
646
}
647
self.history_index = self.history.len() - 1;
597
648
}
598
649
599
fn snapshot_for(&self, value: &str) -> Option<Draft> {
600
self.snapshots
601
.iter()
602
.rev()
603
.find(|snapshot| snapshot.text() == value)
604
.cloned()
650
/// Ctrl+Z / Ctrl+Y move through the composer's own history; the input's is never used.
651
fn step_history(&mut self, back: bool, window: &mut Window, cx: &mut Context<Self>) {
652
let target = if back {
653
self.history_index.checked_sub(1)
654
} else {
655
Some(self.history_index + 1).filter(|index| *index < self.history.len())
656
};
657
let Some(target) = target else {
658
return;
659
};
660
self.history_index = target;
661
let step = &self.history[target];
662
let mut content = InputContent::new(step.draft.text().to_owned());
663
for (range, token) in &step.tokens {
664
if let Ok(next) = content.clone().with_token(range.clone(), token.clone()) {
665
content = next;
666
}
667
}
668
let (draft, selection) = (step.draft.clone(), step.selection.clone());
669
self.input.update(cx, |state, cx| {
670
state.set_value(content, window, cx);
671
state.set_selected_range(selection, cx);
672
});
673
self.previous_value = draft.text().to_owned();
674
self.draft = draft;
675
self.pending_style = None;
676
self.conversion = None;
677
self.paste_hint = None;
678
self.refresh_style(cx);
679
self.update_emoji(cx);
680
self.update_mention(cx);
681
cx.notify();
605
682
}
606
683
607
684
fn refresh_style(&mut self, cx: &mut Context<Self>) {
@@ -609,8 +686,10 @@ impl Composer {
609
686
let (text, ranges) = &self.decorations;
610
687
text.set(style.text, cx);
611
688
ranges.set(style.ranges, cx);
612
self.input
613
.update(cx, |state, cx| state.set_hanging_indents(style.markers, cx));
689
self.input.update(cx, |state, cx| {
690
state.set_line_indents(style.indents, cx);
691
state.set_hanging_indents(style.markers, cx);
692
});
614
693
}
615
694
616
695
fn load_draft(
@@ -633,10 +712,9 @@ impl Composer {
633
712
self.paste_hint = None;
634
713
self.link_editor = None;
635
714
self.toolbar_dismissed = None;
636
self.snapshots.clear();
637
self.format_undo.clear();
638
self.format_redo.clear();
639
self.remember_snapshot();
715
self.history.clear();
716
self.history_index = 0;
717
self.record(StepKind::Other, cx);
640
718
self.refresh_style(cx);
641
719
}
642
720
@@ -670,64 +748,12 @@ impl Composer {
670
748
self.draft = conversion.before;
671
749
self.pending_style = None;
672
750
self.apply_to_input(conversion.restore, cursor..cursor, window, cx);
751
self.record(StepKind::Other, cx);
673
752
self.undone_value = Some(self.input.read(cx).value().to_string());
674
753
self.update_emoji(cx);
675
754
true
676
755
}
677
756
678
/// A format-only change is an undo step of its own; the input's history has no record of it.
679
fn record_format(&mut self, before: Draft, cx: &mut Context<Self>) {
680
if before != self.draft {
681
self.format_undo.push((before, self.draft.clone()));
682
if self.format_undo.len() > SNAPSHOT_LIMIT {
683
self.format_undo.remove(0);
684
}
685
self.format_redo.clear();
686
}
687
self.remember_snapshot();
688
self.refresh_style(cx);
689
}
690
691
fn step_format(&mut self, undo: bool, cx: &mut Context<Self>) -> bool {
692
let (from, to) = if undo {
693
(&mut self.format_undo, &mut self.format_redo)
694
} else {
695
(&mut self.format_redo, &mut self.format_undo)
696
};
697
let matches = from
698
.last()
699
.is_some_and(|(before, after)| *(if undo { after } else { before }) == self.draft);
700
if !matches {
701
return false;
702
}
703
let Some(step) = from.pop() else {
704
return false;
705
};
706
self.draft = if undo { step.0.clone() } else { step.1.clone() };
707
to.push(step);
708
self.pending_style = None;
709
self.remember_snapshot();
710
self.refresh_style(cx);
711
cx.notify();
712
true
713
}
714
715
/// Undo and Redo set `replaying_history` for the Change they cause; a second deferral runs
716
/// after that Change, so the flag never outlives an undo with nothing to undo.
717
fn begin_history_replay(&mut self, cx: &mut Context<Self>) {
718
self.replaying_history = true;
719
self.conversion = None;
720
self.paste_hint = None;
721
let composer = cx.entity().downgrade();
722
cx.defer(move |cx| {
723
cx.defer(move |cx| {
724
composer
725
.update(cx, |this, _| this.replaying_history = false)
726
.ok();
727
});
728
});
729
}
730
731
757
fn selection(&self, cx: &App) -> Range<usize> {
732
758
self.input.read(cx).selected_range()
733
759
}
@@ -747,10 +773,10 @@ impl Composer {
747
773
pending.toggle(kind, &self.draft.style_at(cursor));
748
774
self.pending_style = (!pending.is_empty()).then_some(pending);
749
775
} else {
750
let before = self.draft.clone();
751
776
self.draft.toggle(selection, kind);
752
777
self.draft.take_edits();
753
self.record_format(before, cx);
778
self.record(StepKind::Other, cx);
779
self.refresh_style(cx);
754
780
}
755
781
cx.notify();
756
782
}
@@ -823,10 +849,19 @@ impl Composer {
823
849
state.focus(window, cx);
824
850
state.select_all(window, cx);
825
851
});
852
let edits = cx.subscribe(&field, |this, _, event: &InputEvent, cx| {
853
if matches!(event, InputEvent::Change)
854
&& let Some(editor) = this.link_editor.as_mut()
855
{
856
editor.refused = false;
857
cx.notify();
858
}
859
});
826
860
self.link_editor = Some(LinkEditor {
827
861
range,
828
862
field,
829
863
refused: false,
864
_edits: edits,
830
865
});
831
866
cx.notify();
832
867
}
@@ -855,13 +890,13 @@ impl Composer {
855
890
self.commit(Some(end), window, cx);
856
891
}
857
892
} else {
858
let before = self.draft.clone();
859
893
self.draft.set_link(editor.range.clone(), &url);
860
894
self.draft.take_edits();
861
self.record_format(before, cx);
895
self.refresh_style(cx);
862
896
self.input.update(cx, |state, cx| {
863
897
state.set_selected_range(editor.range.clone(), cx)
864
898
});
899
self.record(StepKind::Other, cx);
865
900
self.toolbar_dismissed = Some(editor.range);
866
901
}
867
902
cx.notify();
@@ -933,7 +968,7 @@ impl Composer {
933
968
if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {
934
969
return false;
935
970
}
936
let text = self.draft.plain_slice(selection.clone());
971
let text = self.draft.text()[selection.clone()].to_owned();
937
972
let lines = self.draft.slice(selection);
938
973
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
939
974
text.clone(),
@@ -1973,20 +2008,16 @@ impl Render for Composer {
1973
2008
}
1974
2009
}))
1975
2010
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
1976
.capture_action(cx.listener(|this, _: &Undo, _, cx| {
1977
if this.link_editor.is_some() {
1978
} else if this.step_format(true, cx) {
2011
.capture_action(cx.listener(|this, _: &Undo, window, cx| {
2012
if this.link_editor.is_none() {
2013
this.step_history(true, window, cx);
1979
2014
cx.stop_propagation();
1980
} else {
1981
this.begin_history_replay(cx);
1982
2015
}
1983
2016
}))
1984
.capture_action(cx.listener(|this, _: &Redo, _, cx| {
1985
if this.link_editor.is_some() {
1986
} else if this.step_format(false, cx) {
2017
.capture_action(cx.listener(|this, _: &Redo, window, cx| {
2018
if this.link_editor.is_none() {
2019
this.step_history(false, window, cx);
1987
2020
cx.stop_propagation();
1988
} else {
1989
this.begin_history_replay(cx);
1990
2021
}
1991
2022
}))
1992
2023
.capture_action(cx.listener(|this, _: &Copy, _, cx| {
@@ -2415,7 +2446,7 @@ mod tests {
2415
2446
typist.type_text("- a");
2416
2447
typist.press("enter tab");
2417
2448
typist.type_text("b");
2418
assert_eq!(typist.value(), "• a\n\u{2003}\u{2003}◦ b");
2449
assert_eq!(typist.value(), "• a\n◦ b");
2419
2450
typist.press("shift-tab");
2420
2451
assert_eq!(typist.value(), "• a\n• b");
2421
2452
}
@@ -2579,6 +2610,51 @@ mod tests {
2579
2610
.is_some_and(|editor| editor.refused)
2580
2611
}));
2581
2612
assert!(typist.draft().marks().is_empty());
2613
typist.type_text("x");
2614
assert!(typist.cx.update(|cx| {
2615
composer
2616
.read(cx)
2617
.link_editor
2618
.as_ref()
2619
.is_some_and(|editor| !editor.refused)
2620
}));
2621
}
2622
2623
#[gpui_kit::test]
2624
fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
2625
use teams_core::{FormatState, LineKind, MarkKind};
2626
2627
let mut typist = typist(cx);
2628
typist.type_text("hello");
2629
typist.press("ctrl-a ctrl-b");
2630
let composer = typist.composer.clone();
2631
typist.act(|window, cx| {
2632
composer.update(cx, |composer, cx| {
2633
composer.press_format(super::super::FormatButton::Bulleted, window, cx)
2634
})
2635
});
2636
assert_eq!(typist.value(), "• hello");
2637
typist.press("ctrl-z");
2638
assert_eq!(typist.value(), "hello");
2639
assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
2640
typist.press("ctrl-z");
2641
assert!(typist.draft().marks().is_empty());
2642
assert_eq!(typist.draft().lines(), [LineKind::Text]);
2643
}
2644
2645
#[gpui_kit::test]
2646
fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
2647
use teams_core::{FormatState, MarkKind};
2648
2649
let mut typist = typist(cx);
2650
typist.type_text("hello");
2651
typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
2652
assert_eq!(typist.value(), "");
2653
typist.press("ctrl-y");
2654
assert_eq!(typist.value(), "hello");
2655
assert!(typist.draft().marks().is_empty());
2656
typist.press("ctrl-y");
2657
assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
2582
2658
}
2583
2659
2584
2660
#[gpui_kit::test]
@@ -2599,7 +2675,7 @@ mod tests {
2599
2675
.cx
2600
2676
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
2601
2677
typist.press("ctrl-v");
2602
assert_eq!(typist.value(), "\u{2003}:) **x**");
2678
assert_eq!(typist.value(), ":) **x**");
2603
2679
let composer = typist.composer.clone();
2604
2680
assert!(
2605
2681
typist
@@ -1,5 +1,5 @@1
use std::cell::Cell;1
use std::cell::Cell;2
use std::collections::{HashMap, HashSet, VecDeque};2
use std::collections::{HashMap, HashSet};3
use std::ops::Range;3
use std::ops::Range;4
use std::path::PathBuf;4
use std::path::PathBuf;5
use std::rc::Rc;5
use std::rc::Rc;@@ -51,7 +51,7 @@ const POPUP_ROW_HEIGHT: f32 = 44.;51
const DEMO_UPLOAD_STEPS: u8 = 10;51
const DEMO_UPLOAD_STEPS: u8 = 10;52
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);52
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);53
const DEMO_FAILURE_STEP: u8 = 6;53
const DEMO_FAILURE_STEP: u8 = 6;54
const SNAPSHOT_LIMIT: usize = 100;54
const HISTORY_LIMIT: usize = 200;55
const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);55
const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);56
const KEY_CONTEXT: &str = "Composer";56
const KEY_CONTEXT: &str = "Composer";57
57
@@ -184,10 +184,26 @@ struct Conversion {184
restore: Vec<Edit>,184
restore: Vec<Edit>,185
}185
}186
186
187
#[derive(Debug, Clone, Copy, PartialEq, Eq)]188
enum StepKind {189
Typing { after_space: bool },190
Deleting,191
Other,192
}193
194
/// One state of the composer's own undo history: text, tokens, formatting and selection.195
struct HistoryStep {196
draft: Draft,197
tokens: Vec<(Range<usize>, InlineToken)>,198
selection: Range<usize>,199
kind: StepKind,200
}201
187
struct LinkEditor {202
struct LinkEditor {188
range: Range<usize>,203
range: Range<usize>,189
field: Entity<InputState>,204
field: Entity<InputState>,190
refused: bool,205
refused: bool,206
_edits: Subscription,191
}207
}192
208
193
type DraftDecorations = (209
type DraftDecorations = (@@ -214,10 +230,8 @@ pub struct Composer {214
draft: Draft,230
draft: Draft,215
decorations: DraftDecorations,231
decorations: DraftDecorations,216
pending_style: Option<TypingStyle>,232
pending_style: Option<TypingStyle>,217
snapshots: VecDeque<Draft>,233
history: Vec<HistoryStep>,218
format_undo: Vec<(Draft, Draft)>,234
history_index: usize,219
format_redo: Vec<(Draft, Draft)>,220
replaying_history: bool,221
pasted_markdown: Option<String>,235
pasted_markdown: Option<String>,222
paste_hint: Option<Task<()>>,236
paste_hint: Option<Task<()>>,223
copied: Option<(String, Vec<DraftLine>)>,237
copied: Option<(String, Vec<DraftLine>)>,@@ -291,6 +305,27 @@ fn candidate_subtitle(candidate: &MentionCandidate) -> String {291
}305
}292
}306
}293
307
308
fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {309
if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {310
return StepKind::Typing {311
after_space: typed.is_whitespace(),312
};313
}314
let removed = previous.len().saturating_sub(value.len());315
let one_char_removed = removed > 0316
&& previous.is_char_boundary(cursor)317
&& previous318
.get(cursor..cursor + removed)319
.is_some_and(|gone| gone.chars().count() == 1 && gone != "\n")320
&& previous.get(..cursor) == value.get(..cursor)321
&& previous.get(cursor + removed..) == value.get(cursor..);322
if one_char_removed {323
StepKind::Deleting324
} else {325
StepKind::Other326
}327
}328
294
fn looks_like_url(text: &str) -> bool {329
fn looks_like_url(text: &str) -> bool {295
["https://", "http://", "www."]330
["https://", "http://", "www."]296
.iter()331
.iter()@@ -342,10 +377,13 @@ impl Composer {342
draft: Draft::default(),377
draft: Draft::default(),343
decorations,378
decorations,344
pending_style: None,379
pending_style: None,345
snapshots: VecDeque::new(),380
history: vec![HistoryStep {346
format_undo: Vec::new(),381
draft: Draft::default(),347
format_redo: Vec::new(),382
tokens: Vec::new(),348
replaying_history: false,383
selection: 0..0,384
kind: StepKind::Other,385
}],386
history_index: 0,349
pasted_markdown: None,387
pasted_markdown: None,350
paste_hint: None,388
paste_hint: None,351
copied: None,389
copied: None,@@ -419,27 +457,18 @@ impl Composer {419
457
420
fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {458
fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {421
let state = self.input.read(cx);459
let state = self.input.read(cx);422
let (value, cursor) = (state.value().to_string(), state.cursor());460
let (value, input_cursor) = (state.value().to_string(), state.cursor());423
let previous = std::mem::replace(&mut self.previous_value, value.clone());461
let previous = std::mem::replace(&mut self.previous_value, value.clone());424
let replaying = std::mem::take(&mut self.replaying_history);425
if value == self.draft.text() {462
if value == self.draft.text() {426
self.refresh_style(cx);463
self.refresh_style(cx);427
return;464
return;428
}465
}429
self.format_undo.clear();466
let kind = step_kind(&previous, &value, input_cursor);430
self.format_redo.clear();431
if replaying && let Some(snapshot) = self.snapshot_for(&value) {432
self.draft = snapshot;433
self.pending_style = None;434
self.refresh_style(cx);435
return;436
}437
let typing = self.pending_style.take();467
let typing = self.pending_style.take();438
let cursor = self.draft.apply_edit(&value, cursor, typing.as_ref());468
let cursor = self.draft.apply_edit(&value, input_cursor, typing.as_ref());439
self.commit(Some(cursor), window, cx);469
let edits = self.draft.take_edits();440
if replaying {470
self.apply_to_input(edits, cursor..cursor, window, cx);441
return;471
self.record(kind, cx);442
}443
if let Some(pasted) = self.pasted_markdown.take()472
if let Some(pasted) = self.pasted_markdown.take()444
&& self.convert_paste(&pasted, cursor, window, cx)473
&& self.convert_paste(&pasted, cursor, window, cx)445
{474
{@@ -504,6 +533,7 @@ impl Composer {504
let edits = self.draft.take_edits();533
let edits = self.draft.take_edits();505
let restore = reverse_edits(&edits, before.text());534
let restore = reverse_edits(&edits, before.text());506
self.apply_to_input(edits, cursor..cursor, window, cx);535
self.apply_to_input(edits, cursor..cursor, window, cx);536
self.record(StepKind::Other, cx);507
self.conversion = Some(Conversion {537
self.conversion = Some(Conversion {508
value: self.draft.text().to_owned(),538
value: self.draft.text().to_owned(),509
cursor,539
cursor,@@ -550,6 +580,7 @@ impl Composer {550
None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),580
None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),551
};581
};552
self.apply_to_input(edits, selection, window, cx);582
self.apply_to_input(edits, selection, window, cx);583
self.record(StepKind::Other, cx);553
}584
}554
585
555
fn apply_to_input(586
fn apply_to_input(@@ -559,10 +590,6 @@ impl Composer {559
window: &mut Window,590
window: &mut Window,560
cx: &mut Context<Self>,591
cx: &mut Context<Self>,561
) {592
) {562
if !edits.is_empty() {563
self.format_undo.clear();564
self.format_redo.clear();565
}566
self.input.update(cx, |state, cx| {593
self.input.update(cx, |state, cx| {567
let edited = !edits.is_empty();594
let edited = !edits.is_empty();568
if edited {595
if edited {@@ -578,30 +605,80 @@ impl Composer {578
self.draft.take_edits();605
self.draft.take_edits();579
}606
}580
self.previous_value = value;607
self.previous_value = value;581
self.remember_snapshot();582
self.refresh_style(cx);608
self.refresh_style(cx);583
}609
}584
610
585
fn remember_snapshot(&mut self) {611
/// Adds the current state as an undo step. Typing and deleting runs merge into one step;586
if self612
/// a typed space ends a typing step.587
.snapshots613
fn record(&mut self, kind: StepKind, cx: &App) {588
.back()614
let state = self.input.read(cx);589
.is_some_and(|last| last.text() == self.draft.text())615
let step = HistoryStep {590
{616
draft: self.draft.clone(),591
self.snapshots.pop_back();617
tokens: state618
.tokens()619
.iter()620
.map(|span| (span.range(), span.token().clone()))621
.collect(),622
selection: state.selected_range(),623
kind,624
};625
let at_end = self.history_index + 1 == self.history.len();626
let merges = at_end627
&& match (self.history.last().map(|last| last.kind), kind) {628
(Some(StepKind::Typing { after_space: false }), StepKind::Typing { .. }) => true,629
(630
Some(StepKind::Typing { after_space: true }),631
StepKind::Typing { after_space },632
) => after_space,633
(Some(StepKind::Deleting), StepKind::Deleting) => true,634
_ => false,635
};636
if merges {637
if let Some(last) = self.history.last_mut() {638
*last = step;639
}640
return;592
}641
}593
self.snapshots.push_back(self.draft.clone());642
self.history.truncate(self.history_index + 1);594
if self.snapshots.len() > SNAPSHOT_LIMIT {643
self.history.push(step);595
self.snapshots.pop_front();644
if self.history.len() > HISTORY_LIMIT {645
self.history.remove(0);596
}646
}647
self.history_index = self.history.len() - 1;597
}648
}598
649
599
fn snapshot_for(&self, value: &str) -> Option<Draft> {650
/// Ctrl+Z / Ctrl+Y move through the composer's own history; the input's is never used.600
self.snapshots651
fn step_history(&mut self, back: bool, window: &mut Window, cx: &mut Context<Self>) {601
.iter()652
let target = if back {602
.rev()653
self.history_index.checked_sub(1)603
.find(|snapshot| snapshot.text() == value)654
} else {604
.cloned()655
Some(self.history_index + 1).filter(|index| *index < self.history.len())656
};657
let Some(target) = target else {658
return;659
};660
self.history_index = target;661
let step = &self.history[target];662
let mut content = InputContent::new(step.draft.text().to_owned());663
for (range, token) in &step.tokens {664
if let Ok(next) = content.clone().with_token(range.clone(), token.clone()) {665
content = next;666
}667
}668
let (draft, selection) = (step.draft.clone(), step.selection.clone());669
self.input.update(cx, |state, cx| {670
state.set_value(content, window, cx);671
state.set_selected_range(selection, cx);672
});673
self.previous_value = draft.text().to_owned();674
self.draft = draft;675
self.pending_style = None;676
self.conversion = None;677
self.paste_hint = None;678
self.refresh_style(cx);679
self.update_emoji(cx);680
self.update_mention(cx);681
cx.notify();605
}682
}606
683
607
fn refresh_style(&mut self, cx: &mut Context<Self>) {684
fn refresh_style(&mut self, cx: &mut Context<Self>) {@@ -609,8 +686,10 @@ impl Composer {609
let (text, ranges) = &self.decorations;686
let (text, ranges) = &self.decorations;610
text.set(style.text, cx);687
text.set(style.text, cx);611
ranges.set(style.ranges, cx);688
ranges.set(style.ranges, cx);612
self.input689
self.input.update(cx, |state, cx| {613
.update(cx, |state, cx| state.set_hanging_indents(style.markers, cx));690
state.set_line_indents(style.indents, cx);691
state.set_hanging_indents(style.markers, cx);692
});614
}693
}615
694
616
fn load_draft(695
fn load_draft(@@ -633,10 +712,9 @@ impl Composer {633
self.paste_hint = None;712
self.paste_hint = None;634
self.link_editor = None;713
self.link_editor = None;635
self.toolbar_dismissed = None;714
self.toolbar_dismissed = None;636
self.snapshots.clear();715
self.history.clear();637
self.format_undo.clear();716
self.history_index = 0;638
self.format_redo.clear();717
self.record(StepKind::Other, cx);639
self.remember_snapshot();640
self.refresh_style(cx);718
self.refresh_style(cx);641
}719
}642
720
@@ -670,64 +748,12 @@ impl Composer {670
self.draft = conversion.before;748
self.draft = conversion.before;671
self.pending_style = None;749
self.pending_style = None;672
self.apply_to_input(conversion.restore, cursor..cursor, window, cx);750
self.apply_to_input(conversion.restore, cursor..cursor, window, cx);751
self.record(StepKind::Other, cx);673
self.undone_value = Some(self.input.read(cx).value().to_string());752
self.undone_value = Some(self.input.read(cx).value().to_string());674
self.update_emoji(cx);753
self.update_emoji(cx);675
true754
true676
}755
}677
756
678
/// A format-only change is an undo step of its own; the input's history has no record of it.679
fn record_format(&mut self, before: Draft, cx: &mut Context<Self>) {680
if before != self.draft {681
self.format_undo.push((before, self.draft.clone()));682
if self.format_undo.len() > SNAPSHOT_LIMIT {683
self.format_undo.remove(0);684
}685
self.format_redo.clear();686
}687
self.remember_snapshot();688
self.refresh_style(cx);689
}690
691
fn step_format(&mut self, undo: bool, cx: &mut Context<Self>) -> bool {692
let (from, to) = if undo {693
(&mut self.format_undo, &mut self.format_redo)694
} else {695
(&mut self.format_redo, &mut self.format_undo)696
};697
let matches = from698
.last()699
.is_some_and(|(before, after)| *(if undo { after } else { before }) == self.draft);700
if !matches {701
return false;702
}703
let Some(step) = from.pop() else {704
return false;705
};706
self.draft = if undo { step.0.clone() } else { step.1.clone() };707
to.push(step);708
self.pending_style = None;709
self.remember_snapshot();710
self.refresh_style(cx);711
cx.notify();712
true713
}714
715
/// Undo and Redo set `replaying_history` for the Change they cause; a second deferral runs716
/// after that Change, so the flag never outlives an undo with nothing to undo.717
fn begin_history_replay(&mut self, cx: &mut Context<Self>) {718
self.replaying_history = true;719
self.conversion = None;720
self.paste_hint = None;721
let composer = cx.entity().downgrade();722
cx.defer(move |cx| {723
cx.defer(move |cx| {724
composer725
.update(cx, |this, _| this.replaying_history = false)726
.ok();727
});728
});729
}730
731
fn selection(&self, cx: &App) -> Range<usize> {757
fn selection(&self, cx: &App) -> Range<usize> {732
self.input.read(cx).selected_range()758
self.input.read(cx).selected_range()733
}759
}@@ -747,10 +773,10 @@ impl Composer {747
pending.toggle(kind, &self.draft.style_at(cursor));773
pending.toggle(kind, &self.draft.style_at(cursor));748
self.pending_style = (!pending.is_empty()).then_some(pending);774
self.pending_style = (!pending.is_empty()).then_some(pending);749
} else {775
} else {750
let before = self.draft.clone();751
self.draft.toggle(selection, kind);776
self.draft.toggle(selection, kind);752
self.draft.take_edits();777
self.draft.take_edits();753
self.record_format(before, cx);778
self.record(StepKind::Other, cx);779
self.refresh_style(cx);754
}780
}755
cx.notify();781
cx.notify();756
}782
}@@ -823,10 +849,19 @@ impl Composer {823
state.focus(window, cx);849
state.focus(window, cx);824
state.select_all(window, cx);850
state.select_all(window, cx);825
});851
});852
let edits = cx.subscribe(&field, |this, _, event: &InputEvent, cx| {853
if matches!(event, InputEvent::Change)854
&& let Some(editor) = this.link_editor.as_mut()855
{856
editor.refused = false;857
cx.notify();858
}859
});826
self.link_editor = Some(LinkEditor {860
self.link_editor = Some(LinkEditor {827
range,861
range,828
field,862
field,829
refused: false,863
refused: false,864
_edits: edits,830
});865
});831
cx.notify();866
cx.notify();832
}867
}@@ -855,13 +890,13 @@ impl Composer {855
self.commit(Some(end), window, cx);890
self.commit(Some(end), window, cx);856
}891
}857
} else {892
} else {858
let before = self.draft.clone();859
self.draft.set_link(editor.range.clone(), &url);893
self.draft.set_link(editor.range.clone(), &url);860
self.draft.take_edits();894
self.draft.take_edits();861
self.record_format(before, cx);895
self.refresh_style(cx);862
self.input.update(cx, |state, cx| {896
self.input.update(cx, |state, cx| {863
state.set_selected_range(editor.range.clone(), cx)897
state.set_selected_range(editor.range.clone(), cx)864
});898
});899
self.record(StepKind::Other, cx);865
self.toolbar_dismissed = Some(editor.range);900
self.toolbar_dismissed = Some(editor.range);866
}901
}867
cx.notify();902
cx.notify();@@ -933,7 +968,7 @@ impl Composer {933
if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {968
if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {934
return false;969
return false;935
}970
}936
let text = self.draft.plain_slice(selection.clone());971
let text = self.draft.text()[selection.clone()].to_owned();937
let lines = self.draft.slice(selection);972
let lines = self.draft.slice(selection);938
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(973
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(939
text.clone(),974
text.clone(),@@ -1973,20 +2008,16 @@ impl Render for Composer {1973
}2008
}1974
}))2009
}))1975
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))2010
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))1976
.capture_action(cx.listener(|this, _: &Undo, _, cx| {2011
.capture_action(cx.listener(|this, _: &Undo, window, cx| {1977
if this.link_editor.is_some() {2012
if this.link_editor.is_none() {1978
} else if this.step_format(true, cx) {2013
this.step_history(true, window, cx);1979
cx.stop_propagation();2014
cx.stop_propagation();1980
} else {1981
this.begin_history_replay(cx);1982
}2015
}1983
}))2016
}))1984
.capture_action(cx.listener(|this, _: &Redo, _, cx| {2017
.capture_action(cx.listener(|this, _: &Redo, window, cx| {1985
if this.link_editor.is_some() {2018
if this.link_editor.is_none() {1986
} else if this.step_format(false, cx) {2019
this.step_history(false, window, cx);1987
cx.stop_propagation();2020
cx.stop_propagation();1988
} else {1989
this.begin_history_replay(cx);1990
}2021
}1991
}))2022
}))1992
.capture_action(cx.listener(|this, _: &Copy, _, cx| {2023
.capture_action(cx.listener(|this, _: &Copy, _, cx| {@@ -2415,7 +2446,7 @@ mod tests {2415
typist.type_text("- a");2446
typist.type_text("- a");2416
typist.press("enter tab");2447
typist.press("enter tab");2417
typist.type_text("b");2448
typist.type_text("b");2418
assert_eq!(typist.value(), "• a\n\u{2003}\u{2003}◦ b");2449
assert_eq!(typist.value(), "• a\n◦ b");2419
typist.press("shift-tab");2450
typist.press("shift-tab");2420
assert_eq!(typist.value(), "• a\n• b");2451
assert_eq!(typist.value(), "• a\n• b");2421
}2452
}@@ -2579,6 +2610,51 @@ mod tests {2579
.is_some_and(|editor| editor.refused)2610
.is_some_and(|editor| editor.refused)2580
}));2611
}));2581
assert!(typist.draft().marks().is_empty());2612
assert!(typist.draft().marks().is_empty());2613
typist.type_text("x");2614
assert!(typist.cx.update(|cx| {2615
composer2616
.read(cx)2617
.link_editor2618
.as_ref()2619
.is_some_and(|editor| !editor.refused)2620
}));2621
}2622
2623
#[gpui_kit::test]2624
fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {2625
use teams_core::{FormatState, LineKind, MarkKind};2626
2627
let mut typist = typist(cx);2628
typist.type_text("hello");2629
typist.press("ctrl-a ctrl-b");2630
let composer = typist.composer.clone();2631
typist.act(|window, cx| {2632
composer.update(cx, |composer, cx| {2633
composer.press_format(super::super::FormatButton::Bulleted, window, cx)2634
})2635
});2636
assert_eq!(typist.value(), "• hello");2637
typist.press("ctrl-z");2638
assert_eq!(typist.value(), "hello");2639
assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);2640
typist.press("ctrl-z");2641
assert!(typist.draft().marks().is_empty());2642
assert_eq!(typist.draft().lines(), [LineKind::Text]);2643
}2644
2645
#[gpui_kit::test]2646
fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {2647
use teams_core::{FormatState, MarkKind};2648
2649
let mut typist = typist(cx);2650
typist.type_text("hello");2651
typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");2652
assert_eq!(typist.value(), "");2653
typist.press("ctrl-y");2654
assert_eq!(typist.value(), "hello");2655
assert!(typist.draft().marks().is_empty());2656
typist.press("ctrl-y");2657
assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);2582
}2658
}2583
2659
2584
#[gpui_kit::test]2660
#[gpui_kit::test]@@ -2599,7 +2675,7 @@ mod tests {2599
.cx2675
.cx2600
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));2676
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));2601
typist.press("ctrl-v");2677
typist.press("ctrl-v");2602
assert_eq!(typist.value(), "\u{2003}:) **x**");2678
assert_eq!(typist.value(), ":) **x**");2603
let composer = typist.composer.clone();2679
let composer = typist.composer.clone();2604
assert!(2680
assert!(2605
typist2681
typist@@ -9,12 +9,27 @@ use crate::theme;
9
9
const CODE_PILL_RADIUS: f32 = 4.;
10
10
const CODE_BLOCK_RADIUS: f32 = 6.;
11
11
const QUOTE_BAR_WIDTH: f32 = 3.;
12
const QUOTE_INDENT: f32 = 12.;
13
const CODE_INDENT: f32 = 10.;
14
const LIST_LEVEL_INDENT: f32 = 18.;
12
15
13
16
/// How the composer paints a draft: text styles, fills and the list markers to hang under.
14
17
pub struct DraftStyle {
15
18
pub text: Vec<TextDecoration>,
16
19
pub ranges: Vec<RangeDecoration>,
17
20
pub markers: Vec<Range<usize>>,
21
pub indents: Vec<(usize, Pixels)>,
22
}
23
24
fn line_indent(kind: &LineKind) -> f32 {
25
match kind {
26
LineKind::Text => 0.,
27
LineKind::Quote => QUOTE_INDENT,
28
LineKind::Code(_) => CODE_INDENT,
29
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {
30
LIST_LEVEL_INDENT * f32::from(*depth)
31
}
32
}
18
33
}
19
34
20
35
fn color(color: Hsla) -> HighlightStyle {
@@ -65,6 +80,13 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
65
80
let mut text = Vec::new();
66
81
let mut ranges = Vec::new();
67
82
let mut markers = Vec::new();
83
let indents = draft
84
.line_ranges()
85
.into_iter()
86
.zip(draft.lines())
87
.map(|(line, kind)| (line.start, px(line_indent(kind))))
88
.filter(|(_, indent)| *indent > px(0.))
89
.collect();
68
90
for mark in draft.marks() {
69
91
let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
70
92
if mark.kind == MarkKind::Code {
@@ -134,6 +156,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
134
156
text,
135
157
ranges,
136
158
markers,
159
indents,
137
160
}
138
161
}
139
162
@@ -157,10 +180,7 @@ mod tests {
157
180
fn list_markers_hang_and_code_gets_a_pill() {
158
181
let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");
159
182
let style = draft_style(&draft, "Mono".into());
160
assert_eq!(
161
style.markers,
162
[draft.marker_range(0), draft.marker_range(1)]
163
);
183
assert_eq!(style.markers, [draft.marker_range(0)]);
164
184
assert_eq!(
165
185
style
166
186
.ranges
@@ -171,6 +191,22 @@ mod tests {
171
191
);
172
192
}
173
193
194
#[test]
195
fn nesting_quotes_and_code_become_line_indents() {
196
let draft = Draft::from_markdown("- a\n - b\n> q\n```\nx\n```");
197
let style = draft_style(&draft, "Mono".into());
198
let starts = draft.line_ranges();
199
assert_eq!(
200
style.indents,
201
[
202
(starts[1].start, gpui_kit::px(18.)),
203
(starts[2].start, gpui_kit::px(12.)),
204
(starts[3].start, gpui_kit::px(10.)),
205
]
206
);
207
assert!(!draft.text().contains('\u{2003}'));
208
}
209
174
210
#[test]
175
211
fn a_code_block_covers_its_empty_last_line_before_text() {
176
212
let draft = Draft::from_lines(&[
@@ -9,12 +9,27 @@ use crate::theme;9
const CODE_PILL_RADIUS: f32 = 4.;9
const CODE_PILL_RADIUS: f32 = 4.;10
const CODE_BLOCK_RADIUS: f32 = 6.;10
const CODE_BLOCK_RADIUS: f32 = 6.;11
const QUOTE_BAR_WIDTH: f32 = 3.;11
const QUOTE_BAR_WIDTH: f32 = 3.;12
const QUOTE_INDENT: f32 = 12.;13
const CODE_INDENT: f32 = 10.;14
const LIST_LEVEL_INDENT: f32 = 18.;12
15
13
/// How the composer paints a draft: text styles, fills and the list markers to hang under.16
/// How the composer paints a draft: text styles, fills and the list markers to hang under.14
pub struct DraftStyle {17
pub struct DraftStyle {15
pub text: Vec<TextDecoration>,18
pub text: Vec<TextDecoration>,16
pub ranges: Vec<RangeDecoration>,19
pub ranges: Vec<RangeDecoration>,17
pub markers: Vec<Range<usize>>,20
pub markers: Vec<Range<usize>>,21
pub indents: Vec<(usize, Pixels)>,22
}23
24
fn line_indent(kind: &LineKind) -> f32 {25
match kind {26
LineKind::Text => 0.,27
LineKind::Quote => QUOTE_INDENT,28
LineKind::Code(_) => CODE_INDENT,29
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {30
LIST_LEVEL_INDENT * f32::from(*depth)31
}32
}18
}33
}19
34
20
fn color(color: Hsla) -> HighlightStyle {35
fn color(color: Hsla) -> HighlightStyle {@@ -65,6 +80,13 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {65
let mut text = Vec::new();80
let mut text = Vec::new();66
let mut ranges = Vec::new();81
let mut ranges = Vec::new();67
let mut markers = Vec::new();82
let mut markers = Vec::new();83
let indents = draft84
.line_ranges()85
.into_iter()86
.zip(draft.lines())87
.map(|(line, kind)| (line.start, px(line_indent(kind))))88
.filter(|(_, indent)| *indent > px(0.))89
.collect();68
for mark in draft.marks() {90
for mark in draft.marks() {69
let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));91
let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));70
if mark.kind == MarkKind::Code {92
if mark.kind == MarkKind::Code {@@ -134,6 +156,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {134
text,156
text,135
ranges,157
ranges,136
markers,158
markers,159
indents,137
}160
}138
}161
}139
162
@@ -157,10 +180,7 @@ mod tests {157
fn list_markers_hang_and_code_gets_a_pill() {180
fn list_markers_hang_and_code_gets_a_pill() {158
let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");181
let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");159
let style = draft_style(&draft, "Mono".into());182
let style = draft_style(&draft, "Mono".into());160
assert_eq!(183
assert_eq!(style.markers, [draft.marker_range(0)]);161
style.markers,162
[draft.marker_range(0), draft.marker_range(1)]163
);164
assert_eq!(184
assert_eq!(165
style185
style166
.ranges186
.ranges@@ -171,6 +191,22 @@ mod tests {171
);191
);172
}192
}173
193
194
#[test]195
fn nesting_quotes_and_code_become_line_indents() {196
let draft = Draft::from_markdown("- a\n - b\n> q\n```\nx\n```");197
let style = draft_style(&draft, "Mono".into());198
let starts = draft.line_ranges();199
assert_eq!(200
style.indents,201
[202
(starts[1].start, gpui_kit::px(18.)),203
(starts[2].start, gpui_kit::px(12.)),204
(starts[3].start, gpui_kit::px(10.)),205
]206
);207
assert!(!draft.text().contains('\u{2003}'));208
}209
174
#[test]210
#[test]175
fn a_code_block_covers_its_empty_last_line_before_text() {211
fn a_code_block_covers_its_empty_last_line_before_text() {176
let draft = Draft::from_lines(&[212
let draft = Draft::from_lines(&[@@ -10,9 +10,6 @@ use crate::spans::Span;
10
10
pub const MAX_DEPTH: u8 = 2;
11
11
const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12
12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13
const INDENT: &str = "\u{2003}\u{2003}";
14
const QUOTE_MARKER: &str = "\u{2003}";
15
const CODE_MARKER: &str = "\u{2003}";
16
13
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
17
14
const FENCE: &str = "```";
18
15
const MARKDOWN_INDENT: usize = 2;
@@ -622,8 +619,7 @@ impl Draft {
622
619
LineKind::Quote => {
623
620
self.splice(cursor..cursor, "\n", &[]);
624
621
self.lines[index + 1] = LineKind::Quote;
625
self.splice(cursor + 1..cursor + 1, QUOTE_MARKER, &[]);
626
Some(cursor + 1 + QUOTE_MARKER.len())
622
Some(cursor + 1)
627
623
}
628
624
LineKind::Code(_) => {
629
625
let last_of_block = self.lines.get(index + 1) != Some(&kind);
@@ -632,7 +628,7 @@ impl Draft {
632
628
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
633
629
}
634
630
self.splice(cursor..cursor, "\n", &[]);
635
Some(self.repair(cursor + 1))
631
Some(cursor + 1)
636
632
}
637
633
list => {
638
634
if self.text[content.clone()].trim().is_empty() {
@@ -687,32 +683,6 @@ impl Draft {
687
683
Some(self.repair(cursor))
688
684
}
689
685
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
716
686
/// Backspace at the start of a formatted line drops (or lifts) its format.
717
687
pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {
718
688
self.journal = Journal::default();
@@ -722,21 +692,24 @@ impl Draft {
722
692
let content = self.content_range(index);
723
693
match &kind {
724
694
LineKind::Text => None,
725
LineKind::Code(_) if cursor > line.start && cursor <= content.start => {
695
LineKind::Code(_) => {
726
696
let first_of_block = index == 0 || self.lines[index - 1] != kind;
727
if first_of_block {
728
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
729
}
730
self.splice(line.start - 1..content.start, "", &[]);
731
Some(self.repair(line.start - 1))
697
(cursor == line.start && first_of_block).then(|| {
698
self.lines[index] = LineKind::Text;
699
cursor
700
})
732
701
}
702
LineKind::Quote => (cursor == line.start).then(|| {
703
self.lines[index] = LineKind::Text;
704
cursor
705
}),
733
706
_ if cursor == line.start && index > 0 => {
734
707
self.splice(line.start - 1..content.start, "", &[]);
735
708
Some(self.repair(line.start - 1))
736
709
}
737
710
_ if cursor > line.start && cursor <= content.start => {
738
711
let lifted = match kind.depth() {
739
depth if kind.is_list() && depth > 0 => kind.with_depth(depth - 1),
712
depth if depth > 0 => kind.with_depth(depth - 1),
740
713
_ => LineKind::Text,
741
714
};
742
715
let cursor = self.set_line_kind(index, lifted, None, cursor);
@@ -808,8 +781,8 @@ impl Draft {
808
781
LineKind::Text
809
782
};
810
783
let number = match kind {
811
LineKind::Numbered(depth) => {
812
numbered_marker(&self.text[line.clone()], depth).map(|(_, number)| number)
784
LineKind::Numbered(_) => {
785
numbered_marker(&self.text[line.clone()]).map(|(_, number)| number)
813
786
}
814
787
_ => None,
815
788
};
@@ -1050,7 +1023,15 @@ impl Draft {
1050
1023
let breaks = replacement.matches('\n').count();
1051
1024
let kind = self.lines[first_line].clone();
1052
1025
let mut new_kinds = Vec::with_capacity(breaks + 1);
1053
if breaks > 0 && start == line_start && old_end == start {
1026
let pushes_line_down = breaks > 0
1027
&& start == line_start
1028
&& old_end == start
1029
&& !matches!(kind, LineKind::Code(_))
1030
&& self.text[start..]
1031
.chars()
1032
.next()
1033
.is_some_and(|next| next != '\n');
1034
if pushes_line_down {
1054
1035
new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));
1055
1036
new_kinds.push(kind);
1056
1037
} else {
@@ -1124,7 +1105,7 @@ impl Draft {
1124
1105
for previous in (0..index).rev() {
1125
1106
match &self.lines[previous] {
1126
1107
LineKind::Numbered(previous_depth) if *previous_depth == depth => {
1127
return numbered_marker(&self.text[ranges[previous].clone()], depth)
1108
return numbered_marker(&self.text[ranges[previous].clone()])
1128
1109
.map(|(_, number)| number);
1129
1110
}
1130
1111
kind if kind.is_list() && kind.depth() > depth => continue,
@@ -1142,7 +1123,7 @@ impl Draft {
1142
1123
None => own_number
1143
1124
.or_else(|| {
1144
1125
let line = self.line_ranges()[index].clone();
1145
numbered_marker(&self.text[line], *depth).map(|(_, number)| number)
1126
numbered_marker(&self.text[line]).map(|(_, number)| number)
1146
1127
})
1147
1128
.unwrap_or(1),
1148
1129
},
@@ -1178,37 +1159,11 @@ impl Draft {
1178
1159
}
1179
1160
}
1180
1161
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
1198
/// Lines whose marker was edited away become text; numbered items are renumbered; code
1199
/// lines get their padding back.
1162
/// List items whose marker was edited away become text; numbered items are renumbered.
1200
1163
fn repair(&mut self, mut cursor: usize) -> usize {
1201
1164
for index in 0..self.lines.len() {
1202
1165
let kind = self.lines[index].clone();
1203
if kind == LineKind::Text {
1204
continue;
1205
}
1206
if matches!(kind, LineKind::Code(_)) {
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);
1210
}
1211
cursor = self.drop_stray_padding(index, cursor);
1166
if !kind.is_list() {
1212
1167
continue;
1213
1168
}
1214
1169
let line = self.line_ranges()[index].clone();
@@ -1217,7 +1172,7 @@ impl Draft {
1217
1172
if current.starts_with(&expected) {
1218
1173
continue;
1219
1174
}
1220
match numbered_marker(current, kind.depth()) {
1175
match numbered_marker(current) {
1221
1176
Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {
1222
1177
cursor =
1223
1178
self.replace_marker(line.start..line.start + length, &expected, cursor);
@@ -1234,20 +1189,14 @@ fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {
1234
1189
}
1235
1190
1236
1191
fn bullet_marker(depth: u8) -> String {
1237
format!(
1238
"{}{} ",
1239
INDENT.repeat(depth as usize),
1240
BULLETS[depth as usize % BULLETS.len()]
1241
)
1192
format!("{} ", BULLETS[depth as usize % BULLETS.len()])
1242
1193
}
1243
1194
1244
1195
fn marker_text(kind: &LineKind, number: u32) -> String {
1245
1196
match kind {
1246
1197
LineKind::Bullet(depth) => bullet_marker(*depth),
1247
LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),
1248
LineKind::Quote => QUOTE_MARKER.to_owned(),
1249
LineKind::Code(_) => CODE_MARKER.to_owned(),
1250
LineKind::Text => String::new(),
1198
LineKind::Numbered(_) => format!("{number}. "),
1199
LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1251
1200
}
1252
1201
}
1253
1202
@@ -1261,22 +1210,18 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {
1261
1210
0
1262
1211
}
1263
1212
}
1264
LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),
1265
LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),
1266
LineKind::Code(_) if line.starts_with(CODE_MARKER) => CODE_MARKER.len(),
1213
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),
1267
1214
_ => 0,
1268
1215
}
1269
1216
}
1270
1217
1271
/// Byte length and number of a `1. ` marker at `depth`.
1272
fn numbered_marker(line: &str, depth: u8) -> Option<(usize, u32)> {
1273
let indent = INDENT.repeat(depth as usize);
1274
let rest = line.strip_prefix(indent.as_str())?;
1275
let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
1276
if digits == 0 || digits > 9 || !rest[digits..].starts_with(". ") {
1218
/// Byte length and number of a `1. ` marker.
1219
fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1220
let digits = line.bytes().take_while(u8::is_ascii_digit).count();
1221
if digits == 0 || digits > 9 || !line[digits..].starts_with(". ") {
1277
1222
return None;
1278
1223
}
1279
Some((indent.len() + digits + 2, rest[..digits].parse().ok()?))
1224
Some((digits + 2, line[..digits].parse().ok()?))
1280
1225
}
1281
1226
1282
1227
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
@@ -1324,9 +1269,8 @@ pub fn link_url(text: &str) -> Option<String> {
1324
1269
return Some(text.to_owned());
1325
1270
}
1326
1271
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());
1272
let host = scheme.contains('.') || scheme.eq_ignore_ascii_case("localhost");
1273
let host_and_port = host && rest.starts_with(|character: char| character.is_ascii_digit());
1330
1274
!host_and_port
1331
1275
&& scheme.starts_with(|character: char| character.is_ascii_alphabetic())
1332
1276
&& scheme
@@ -1553,7 +1497,7 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1553
1497
.find_map(|bullet| trimmed.strip_prefix(bullet))
1554
1498
{
1555
1499
(LineKind::Bullet(depth), None, rest)
1556
} else if let Some((length, number)) = numbered_marker(trimmed, 0) {
1500
} else if let Some((length, number)) = numbered_marker(trimmed) {
1557
1501
(LineKind::Numbered(depth), Some(number), &trimmed[length..])
1558
1502
} else if let Some(rest) = trimmed
1559
1503
.strip_prefix("> ")
@@ -1936,7 +1880,7 @@ mod tests {
1936
1880
assert_eq!(numbered.text(), "1. one");
1937
1881
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
1938
1882
let quote = typed_draft("> said");
1939
assert_eq!(quote.text(), format!("{QUOTE_MARKER}said"));
1883
assert_eq!(quote.text(), "said");
1940
1884
assert_eq!(quote.lines(), [LineKind::Quote]);
1941
1885
}
1942
1886
@@ -1969,7 +1913,7 @@ mod tests {
1969
1913
let mut draft = Draft::from_markdown("- a\n- b");
1970
1914
assert!(draft.indent(6..6, false));
1971
1915
assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);
1972
assert_eq!(draft.text(), format!("• a\n{INDENT}◦ b"));
1916
assert_eq!(draft.text(), "• a\n◦ b");
1973
1917
assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1974
1918
assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1975
1919
assert_eq!(draft.text(), "• a\nb");
@@ -1979,10 +1923,7 @@ mod tests {
1979
1923
#[test]
1980
1924
fn nested_numbering_counts_per_level() {
1981
1925
let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");
1982
assert_eq!(
1983
draft.text(),
1984
format!("1. a\n{INDENT}1. x\n{INDENT}2. y\n2. b")
1985
);
1926
assert_eq!(draft.text(), "1. a\n1. x\n2. y\n2. b");
1986
1927
}
1987
1928
1988
1929
#[test]
@@ -2020,15 +1961,12 @@ mod tests {
2020
1961
fn fence_and_enter_open_a_code_block_that_enter_continues() {
2021
1962
let mut draft = typed_draft("```rust");
2022
1963
let cursor = draft.break_line(draft.text().len(), false).unwrap();
2023
assert_eq!((draft.text(), cursor), (CODE_MARKER, CODE_MARKER.len()));
1964
assert_eq!((draft.text(), cursor), ("", 0));
2024
1965
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
2025
1966
typed(&mut draft, "fn x() {}");
2026
1967
let cursor = draft.break_line(draft.text().len(), false).unwrap();
2027
1968
assert_eq!(draft.lines().len(), 2);
2028
assert_eq!(
2029
draft.break_line(cursor, false),
2030
Some(cursor - CODE_MARKER.len())
2031
);
1969
assert_eq!(draft.break_line(cursor, false), Some(cursor));
2032
1970
assert_eq!(draft.lines()[1], LineKind::Text);
2033
1971
assert_eq!(
2034
1972
draft.to_html(),
@@ -2040,9 +1978,9 @@ mod tests {
2040
1978
fn markdown_inside_code_stays_literal() {
2041
1979
let mut draft = typed_draft("```");
2042
1980
let cursor = draft.break_line(3, false).unwrap();
2043
assert_eq!(cursor, CODE_MARKER.len());
1981
assert_eq!(cursor, 0);
2044
1982
typed(&mut draft, "a **b**");
2045
assert_eq!(draft.text(), format!("{CODE_MARKER}a **b**"));
1983
assert_eq!(draft.text(), "a **b**");
2046
1984
assert!(draft.marks().is_empty());
2047
1985
}
2048
1986
@@ -2191,19 +2129,13 @@ mod tests {
2191
2129
}
2192
2130
2193
2131
#[test]
2194
fn code_lines_carry_padding_that_survives_edits_and_stays_out_of_html() {
2195
let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");
2196
assert_eq!(
2197
draft.text(),
2198
format!("{CODE_MARKER}let a = 1;\n{CODE_MARKER}let b = 2;")
2199
);
2200
assert_eq!(draft.to_html(), "<pre>let a = 1;\nlet b = 2;</pre>");
2201
let second = draft.content_range(1).start;
2202
let cursor = draft.backspace_at_start(second).unwrap();
2203
assert_eq!(draft.text(), format!("{CODE_MARKER}let a = 1;let b = 2;"));
2204
assert_eq!(cursor, CODE_MARKER.len() + "let a = 1;".len());
2205
let cursor = draft.backspace_at_start(CODE_MARKER.len()).unwrap();
2206
assert_eq!((draft.lines()[0].clone(), cursor), (LineKind::Text, 0));
2132
fn code_lines_hold_only_their_content() {
2133
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");
2134
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");
2135
assert_eq!(draft.to_html(), "<pre>let a = 1;\n\u{2003}b</pre>");
2136
assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);
2137
assert_eq!(draft.backspace_at_start(0), Some(0));
2138
assert_eq!(draft.lines()[0], LineKind::Text);
2207
2139
}
2208
2140
2209
2141
#[test]
@@ -2228,32 +2160,20 @@ mod tests {
2228
2160
"<pre class=\"language-py\">def f():\n return 1</pre>"
2229
2161
);
2230
2162
let mut split = Draft::from_markdown("```\n a b\n```");
2231
let after_a = CODE_MARKER.len() + " a".len();
2163
let after_a = " a".len();
2232
2164
split.break_line(after_a, false).unwrap();
2233
2165
assert_eq!(split.to_html(), "<pre> a\n b</pre>");
2234
2166
}
2235
2167
2236
2168
#[test]
2237
fn delete_never_moves_padding_into_code() {
2238
let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");
2169
fn delete_at_a_line_end_joins_the_next_item_without_its_bullet() {
2170
let mut draft = Draft::from_markdown("- a\n- b");
2239
2171
let end_of_first = draft.line_ranges()[0].end;
2240
2172
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");
2173
assert_eq!(draft.text(), "• ab");
2174
assert_eq!(draft.delete_forward(0), Some(bullet_marker(0).len()));
2175
assert_eq!(draft.text(), "• b");
2176
assert_eq!(Draft::plain("a\nb").delete_forward(1), None);
2257
2177
}
2258
2178
2259
2179
#[test]
@@ -2267,6 +2187,7 @@ mod tests {
2267
2187
Some("https://example.com:8080/x".into())
2268
2188
);
2269
2189
assert_eq!(link_url("javascript:alert(1)"), None);
2190
assert_eq!(link_url("tel:0123456"), None);
2270
2191
}
2271
2192
2272
2193
#[test]
@@ -10,9 +10,6 @@ use crate::spans::Span;10
pub const MAX_DEPTH: u8 = 2;10
pub const MAX_DEPTH: u8 = 2;11
const BULLETS: [&str; 3] = ["•", "◦", "▪"];11
const BULLETS: [&str; 3] = ["•", "◦", "▪"];12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];13
const INDENT: &str = "\u{2003}\u{2003}";14
const QUOTE_MARKER: &str = "\u{2003}";15
const CODE_MARKER: &str = "\u{2003}";16
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];13
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];17
const FENCE: &str = "```";14
const FENCE: &str = "```";18
const MARKDOWN_INDENT: usize = 2;15
const MARKDOWN_INDENT: usize = 2;@@ -622,8 +619,7 @@ impl Draft {622
LineKind::Quote => {619
LineKind::Quote => {623
self.splice(cursor..cursor, "\n", &[]);620
self.splice(cursor..cursor, "\n", &[]);624
self.lines[index + 1] = LineKind::Quote;621
self.lines[index + 1] = LineKind::Quote;625
self.splice(cursor + 1..cursor + 1, QUOTE_MARKER, &[]);622
Some(cursor + 1)626
Some(cursor + 1 + QUOTE_MARKER.len())627
}623
}628
LineKind::Code(_) => {624
LineKind::Code(_) => {629
let last_of_block = self.lines.get(index + 1) != Some(&kind);625
let last_of_block = self.lines.get(index + 1) != Some(&kind);@@ -632,7 +628,7 @@ impl Draft {632
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));628
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));633
}629
}634
self.splice(cursor..cursor, "\n", &[]);630
self.splice(cursor..cursor, "\n", &[]);635
Some(self.repair(cursor + 1))631
Some(cursor + 1)636
}632
}637
list => {633
list => {638
if self.text[content.clone()].trim().is_empty() {634
if self.text[content.clone()].trim().is_empty() {@@ -687,32 +683,6 @@ impl Draft {687
Some(self.repair(cursor))683
Some(self.repair(cursor))688
}684
}689
685
690
/// The text of `range` without list, quote and code markers in front of whole lines691
/// 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
plain714
}715
716
/// Backspace at the start of a formatted line drops (or lifts) its format.686
/// Backspace at the start of a formatted line drops (or lifts) its format.717
pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {687
pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {718
self.journal = Journal::default();688
self.journal = Journal::default();@@ -722,21 +692,24 @@ impl Draft {722
let content = self.content_range(index);692
let content = self.content_range(index);723
match &kind {693
match &kind {724
LineKind::Text => None,694
LineKind::Text => None,725
LineKind::Code(_) if cursor > line.start && cursor <= content.start => {695
LineKind::Code(_) => {726
let first_of_block = index == 0 || self.lines[index - 1] != kind;696
let first_of_block = index == 0 || self.lines[index - 1] != kind;727
if first_of_block {697
(cursor == line.start && first_of_block).then(|| {728
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));698
self.lines[index] = LineKind::Text;729
}699
cursor730
self.splice(line.start - 1..content.start, "", &[]);700
})731
Some(self.repair(line.start - 1))732
}701
}702
LineKind::Quote => (cursor == line.start).then(|| {703
self.lines[index] = LineKind::Text;704
cursor705
}),733
_ if cursor == line.start && index > 0 => {706
_ if cursor == line.start && index > 0 => {734
self.splice(line.start - 1..content.start, "", &[]);707
self.splice(line.start - 1..content.start, "", &[]);735
Some(self.repair(line.start - 1))708
Some(self.repair(line.start - 1))736
}709
}737
_ if cursor > line.start && cursor <= content.start => {710
_ if cursor > line.start && cursor <= content.start => {738
let lifted = match kind.depth() {711
let lifted = match kind.depth() {739
depth if kind.is_list() && depth > 0 => kind.with_depth(depth - 1),712
depth if depth > 0 => kind.with_depth(depth - 1),740
_ => LineKind::Text,713
_ => LineKind::Text,741
};714
};742
let cursor = self.set_line_kind(index, lifted, None, cursor);715
let cursor = self.set_line_kind(index, lifted, None, cursor);@@ -808,8 +781,8 @@ impl Draft {808
LineKind::Text781
LineKind::Text809
};782
};810
let number = match kind {783
let number = match kind {811
LineKind::Numbered(depth) => {784
LineKind::Numbered(_) => {812
numbered_marker(&self.text[line.clone()], depth).map(|(_, number)| number)785
numbered_marker(&self.text[line.clone()]).map(|(_, number)| number)813
}786
}814
_ => None,787
_ => None,815
};788
};@@ -1050,7 +1023,15 @@ impl Draft {1050
let breaks = replacement.matches('\n').count();1023
let breaks = replacement.matches('\n').count();1051
let kind = self.lines[first_line].clone();1024
let kind = self.lines[first_line].clone();1052
let mut new_kinds = Vec::with_capacity(breaks + 1);1025
let mut new_kinds = Vec::with_capacity(breaks + 1);1053
if breaks > 0 && start == line_start && old_end == start {1026
let pushes_line_down = breaks > 01027
&& start == line_start1028
&& old_end == start1029
&& !matches!(kind, LineKind::Code(_))1030
&& self.text[start..]1031
.chars()1032
.next()1033
.is_some_and(|next| next != '\n');1034
if pushes_line_down {1054
new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));1035
new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));1055
new_kinds.push(kind);1036
new_kinds.push(kind);1056
} else {1037
} else {@@ -1124,7 +1105,7 @@ impl Draft {1124
for previous in (0..index).rev() {1105
for previous in (0..index).rev() {1125
match &self.lines[previous] {1106
match &self.lines[previous] {1126
LineKind::Numbered(previous_depth) if *previous_depth == depth => {1107
LineKind::Numbered(previous_depth) if *previous_depth == depth => {1127
return numbered_marker(&self.text[ranges[previous].clone()], depth)1108
return numbered_marker(&self.text[ranges[previous].clone()])1128
.map(|(_, number)| number);1109
.map(|(_, number)| number);1129
}1110
}1130
kind if kind.is_list() && kind.depth() > depth => continue,1111
kind if kind.is_list() && kind.depth() > depth => continue,@@ -1142,7 +1123,7 @@ impl Draft {1142
None => own_number1123
None => own_number1143
.or_else(|| {1124
.or_else(|| {1144
let line = self.line_ranges()[index].clone();1125
let line = self.line_ranges()[index].clone();1145
numbered_marker(&self.text[line], *depth).map(|(_, number)| number)1126
numbered_marker(&self.text[line]).map(|(_, number)| number)1146
})1127
})1147
.unwrap_or(1),1128
.unwrap_or(1),1148
},1129
},@@ -1178,37 +1159,11 @@ impl Draft {1178
}1159
}1179
}1160
}1180
1161
1181
/// Padding merged into a code line's content by a join or a cross-line delete.1162
/// List items whose marker was edited away become text; numbered items are renumbered.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
1198
/// Lines whose marker was edited away become text; numbered items are renumbered; code1199
/// lines get their padding back.1200
fn repair(&mut self, mut cursor: usize) -> usize {1163
fn repair(&mut self, mut cursor: usize) -> usize {1201
for index in 0..self.lines.len() {1164
for index in 0..self.lines.len() {1202
let kind = self.lines[index].clone();1165
let kind = self.lines[index].clone();1203
if kind == LineKind::Text {1166
if !kind.is_list() {1204
continue;1205
}1206
if matches!(kind, LineKind::Code(_)) {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);1210
}1211
cursor = self.drop_stray_padding(index, cursor);1212
continue;1167
continue;1213
}1168
}1214
let line = self.line_ranges()[index].clone();1169
let line = self.line_ranges()[index].clone();@@ -1217,7 +1172,7 @@ impl Draft {1217
if current.starts_with(&expected) {1172
if current.starts_with(&expected) {1218
continue;1173
continue;1219
}1174
}1220
match numbered_marker(current, kind.depth()) {1175
match numbered_marker(current) {1221
Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {1176
Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {1222
cursor =1177
cursor =1223
self.replace_marker(line.start..line.start + length, &expected, cursor);1178
self.replace_marker(line.start..line.start + length, &expected, cursor);@@ -1234,20 +1189,14 @@ fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {1234
}1189
}1235
1190
1236
fn bullet_marker(depth: u8) -> String {1191
fn bullet_marker(depth: u8) -> String {1237
format!(1192
format!("{} ", BULLETS[depth as usize % BULLETS.len()])1238
"{}{} ",1239
INDENT.repeat(depth as usize),1240
BULLETS[depth as usize % BULLETS.len()]1241
)1242
}1193
}1243
1194
1244
fn marker_text(kind: &LineKind, number: u32) -> String {1195
fn marker_text(kind: &LineKind, number: u32) -> String {1245
match kind {1196
match kind {1246
LineKind::Bullet(depth) => bullet_marker(*depth),1197
LineKind::Bullet(depth) => bullet_marker(*depth),1247
LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),1198
LineKind::Numbered(_) => format!("{number}. "),1248
LineKind::Quote => QUOTE_MARKER.to_owned(),1199
LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),1249
LineKind::Code(_) => CODE_MARKER.to_owned(),1250
LineKind::Text => String::new(),1251
}1200
}1252
}1201
}1253
1202
@@ -1261,22 +1210,18 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {1261
01210
01262
}1211
}1263
}1212
}1264
LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),1213
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),1265
LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),1266
LineKind::Code(_) if line.starts_with(CODE_MARKER) => CODE_MARKER.len(),1267
_ => 0,1214
_ => 0,1268
}1215
}1269
}1216
}1270
1217
1271
/// Byte length and number of a `1. ` marker at `depth`.1218
/// Byte length and number of a `1. ` marker.1272
fn numbered_marker(line: &str, depth: u8) -> Option<(usize, u32)> {1219
fn numbered_marker(line: &str) -> Option<(usize, u32)> {1273
let indent = INDENT.repeat(depth as usize);1220
let digits = line.bytes().take_while(u8::is_ascii_digit).count();1274
let rest = line.strip_prefix(indent.as_str())?;1221
if digits == 0 || digits > 9 || !line[digits..].starts_with(". ") {1275
let digits = rest.bytes().take_while(u8::is_ascii_digit).count();1276
if digits == 0 || digits > 9 || !rest[digits..].starts_with(". ") {1277
return None;1222
return None;1278
}1223
}1279
Some((indent.len() + digits + 2, rest[..digits].parse().ok()?))1224
Some((digits + 2, line[..digits].parse().ok()?))1280
}1225
}1281
1226
1282
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {1227
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {@@ -1324,9 +1269,8 @@ pub fn link_url(text: &str) -> Option<String> {1324
return Some(text.to_owned());1269
return Some(text.to_owned());1325
}1270
}1326
let scheme = text.split_once(':').filter(|(scheme, rest)| {1271
let scheme = text.split_once(':').filter(|(scheme, rest)| {1327
let host_and_port = scheme.contains('.')1272
let host = scheme.contains('.') || scheme.eq_ignore_ascii_case("localhost");1328
|| scheme.eq_ignore_ascii_case("localhost")1273
let host_and_port = host && rest.starts_with(|character: char| character.is_ascii_digit());1329
|| rest.starts_with(|character: char| character.is_ascii_digit());1330
!host_and_port1274
!host_and_port1331
&& scheme.starts_with(|character: char| character.is_ascii_alphabetic())1275
&& scheme.starts_with(|character: char| character.is_ascii_alphabetic())1332
&& scheme1276
&& scheme@@ -1553,7 +1497,7 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {1553
.find_map(|bullet| trimmed.strip_prefix(bullet))1497
.find_map(|bullet| trimmed.strip_prefix(bullet))1554
{1498
{1555
(LineKind::Bullet(depth), None, rest)1499
(LineKind::Bullet(depth), None, rest)1556
} else if let Some((length, number)) = numbered_marker(trimmed, 0) {1500
} else if let Some((length, number)) = numbered_marker(trimmed) {1557
(LineKind::Numbered(depth), Some(number), &trimmed[length..])1501
(LineKind::Numbered(depth), Some(number), &trimmed[length..])1558
} else if let Some(rest) = trimmed1502
} else if let Some(rest) = trimmed1559
.strip_prefix("> ")1503
.strip_prefix("> ")@@ -1936,7 +1880,7 @@ mod tests {1936
assert_eq!(numbered.text(), "1. one");1880
assert_eq!(numbered.text(), "1. one");1937
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);1881
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);1938
let quote = typed_draft("> said");1882
let quote = typed_draft("> said");1939
assert_eq!(quote.text(), format!("{QUOTE_MARKER}said"));1883
assert_eq!(quote.text(), "said");1940
assert_eq!(quote.lines(), [LineKind::Quote]);1884
assert_eq!(quote.lines(), [LineKind::Quote]);1941
}1885
}1942
1886
@@ -1969,7 +1913,7 @@ mod tests {1969
let mut draft = Draft::from_markdown("- a\n- b");1913
let mut draft = Draft::from_markdown("- a\n- b");1970
assert!(draft.indent(6..6, false));1914
assert!(draft.indent(6..6, false));1971
assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);1915
assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);1972
assert_eq!(draft.text(), format!("• a\n{INDENT}◦ b"));1916
assert_eq!(draft.text(), "• a\n◦ b");1973
assert!(draft.indent(draft.text().len()..draft.text().len(), true));1917
assert!(draft.indent(draft.text().len()..draft.text().len(), true));1974
assert!(draft.indent(draft.text().len()..draft.text().len(), true));1918
assert!(draft.indent(draft.text().len()..draft.text().len(), true));1975
assert_eq!(draft.text(), "• a\nb");1919
assert_eq!(draft.text(), "• a\nb");@@ -1979,10 +1923,7 @@ mod tests {1979
#[test]1923
#[test]1980
fn nested_numbering_counts_per_level() {1924
fn nested_numbering_counts_per_level() {1981
let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");1925
let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");1982
assert_eq!(1926
assert_eq!(draft.text(), "1. a\n1. x\n2. y\n2. b");1983
draft.text(),1984
format!("1. a\n{INDENT}1. x\n{INDENT}2. y\n2. b")1985
);1986
}1927
}1987
1928
1988
#[test]1929
#[test]@@ -2020,15 +1961,12 @@ mod tests {2020
fn fence_and_enter_open_a_code_block_that_enter_continues() {1961
fn fence_and_enter_open_a_code_block_that_enter_continues() {2021
let mut draft = typed_draft("```rust");1962
let mut draft = typed_draft("```rust");2022
let cursor = draft.break_line(draft.text().len(), false).unwrap();1963
let cursor = draft.break_line(draft.text().len(), false).unwrap();2023
assert_eq!((draft.text(), cursor), (CODE_MARKER, CODE_MARKER.len()));1964
assert_eq!((draft.text(), cursor), ("", 0));2024
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);1965
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);2025
typed(&mut draft, "fn x() {}");1966
typed(&mut draft, "fn x() {}");2026
let cursor = draft.break_line(draft.text().len(), false).unwrap();1967
let cursor = draft.break_line(draft.text().len(), false).unwrap();2027
assert_eq!(draft.lines().len(), 2);1968
assert_eq!(draft.lines().len(), 2);2028
assert_eq!(1969
assert_eq!(draft.break_line(cursor, false), Some(cursor));2029
draft.break_line(cursor, false),2030
Some(cursor - CODE_MARKER.len())2031
);2032
assert_eq!(draft.lines()[1], LineKind::Text);1970
assert_eq!(draft.lines()[1], LineKind::Text);2033
assert_eq!(1971
assert_eq!(2034
draft.to_html(),1972
draft.to_html(),@@ -2040,9 +1978,9 @@ mod tests {2040
fn markdown_inside_code_stays_literal() {1978
fn markdown_inside_code_stays_literal() {2041
let mut draft = typed_draft("```");1979
let mut draft = typed_draft("```");2042
let cursor = draft.break_line(3, false).unwrap();1980
let cursor = draft.break_line(3, false).unwrap();2043
assert_eq!(cursor, CODE_MARKER.len());1981
assert_eq!(cursor, 0);2044
typed(&mut draft, "a **b**");1982
typed(&mut draft, "a **b**");2045
assert_eq!(draft.text(), format!("{CODE_MARKER}a **b**"));1983
assert_eq!(draft.text(), "a **b**");2046
assert!(draft.marks().is_empty());1984
assert!(draft.marks().is_empty());2047
}1985
}2048
1986
@@ -2191,19 +2129,13 @@ mod tests {2191
}2129
}2192
2130
2193
#[test]2131
#[test]2194
fn code_lines_carry_padding_that_survives_edits_and_stays_out_of_html() {2132
fn code_lines_hold_only_their_content() {2195
let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");2133
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");2196
assert_eq!(2134
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");2197
draft.text(),2135
assert_eq!(draft.to_html(), "<pre>let a = 1;\n\u{2003}b</pre>");2198
format!("{CODE_MARKER}let a = 1;\n{CODE_MARKER}let b = 2;")2136
assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);2199
);2137
assert_eq!(draft.backspace_at_start(0), Some(0));2200
assert_eq!(draft.to_html(), "<pre>let a = 1;\nlet b = 2;</pre>");2138
assert_eq!(draft.lines()[0], LineKind::Text);2201
let second = draft.content_range(1).start;2202
let cursor = draft.backspace_at_start(second).unwrap();2203
assert_eq!(draft.text(), format!("{CODE_MARKER}let a = 1;let b = 2;"));2204
assert_eq!(cursor, CODE_MARKER.len() + "let a = 1;".len());2205
let cursor = draft.backspace_at_start(CODE_MARKER.len()).unwrap();2206
assert_eq!((draft.lines()[0].clone(), cursor), (LineKind::Text, 0));2207
}2139
}2208
2140
2209
#[test]2141
#[test]@@ -2228,32 +2160,20 @@ mod tests {2228
"<pre class=\"language-py\">def f():\n return 1</pre>"2160
"<pre class=\"language-py\">def f():\n return 1</pre>"2229
);2161
);2230
let mut split = Draft::from_markdown("```\n a b\n```");2162
let mut split = Draft::from_markdown("```\n a b\n```");2231
let after_a = CODE_MARKER.len() + " a".len();2163
let after_a = " a".len();2232
split.break_line(after_a, false).unwrap();2164
split.break_line(after_a, false).unwrap();2233
assert_eq!(split.to_html(), "<pre> a\n b</pre>");2165
assert_eq!(split.to_html(), "<pre> a\n b</pre>");2234
}2166
}2235
2167
2236
#[test]2168
#[test]2237
fn delete_never_moves_padding_into_code() {2169
fn delete_at_a_line_end_joins_the_next_item_without_its_bullet() {2238
let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");2170
let mut draft = Draft::from_markdown("- a\n- b");2239
let end_of_first = draft.line_ranges()[0].end;2171
let end_of_first = draft.line_ranges()[0].end;2240
assert_eq!(draft.delete_forward(end_of_first), Some(end_of_first));2172
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>");2173
assert_eq!(draft.text(), "• ab");2242
let cursor = draft.delete_forward(0).unwrap();2174
assert_eq!(draft.delete_forward(0), Some(bullet_marker(0).len()));2243
assert_eq!(cursor, CODE_MARKER.len());2175
assert_eq!(draft.text(), "• b");2244
assert_eq!(draft.to_html(), "<pre>et a = 1;let b = 2;</pre>");2176
assert_eq!(Draft::plain("a\nb").delete_forward(1), None);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
}2177
}2258
2178
2259
#[test]2179
#[test]@@ -2267,6 +2187,7 @@ mod tests {2267
Some("https://example.com:8080/x".into())2187
Some("https://example.com:8080/x".into())2268
);2188
);2269
assert_eq!(link_url("javascript:alert(1)"), None);2189
assert_eq!(link_url("javascript:alert(1)"), None);2190
assert_eq!(link_url("tel:0123456"), None);2270
}2191
}2271
2192
2272
#[test]2193
#[test]