fix(composer): review findings on the rich composer
- insert_lines returns the offset after the pasted text mid-line - No Markdown or copied-format conversion when pasting into code - A selection ending at the start of the next line leaves that line out of list toggles, list state and indent - Links take only http, https and mailto; typed, pasted, received and link-editor links share one normalization - Ctrl+B, toolbar and link changes are their own undo and redo steps - Smiley and :code: conversion and the emoji popup stay off in code - Undo with nothing to undo no longer leaves the replay flag set - Code blocks cover empty lines; code lines carry 10 px padding - Block and Bar range decorations keep empty ranges, lines counted with ends included Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -22,7 +22,7 @@ use gpui_kit::*;
22
22
use teams_core::{
23
23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24
24
MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, has_markdown,
25
map_offset, reverse_edits,
25
link_url, map_offset, reverse_edits,
26
26
};
27
27
28
28
use super::attachment_tray::{
@@ -214,6 +214,8 @@ pub struct Composer {
214
214
decorations: DraftDecorations,
215
215
pending_style: Option<TypingStyle>,
216
216
snapshots: VecDeque<Draft>,
217
format_undo: Vec<(Draft, Draft)>,
218
format_redo: Vec<(Draft, Draft)>,
217
219
replaying_history: bool,
218
220
pasted_markdown: Option<String>,
219
221
paste_hint: Option<Task<()>>,
@@ -295,15 +297,6 @@ fn looks_like_url(text: &str) -> bool {
295
297
&& !text.contains(char::is_whitespace)
296
298
}
297
299
298
fn normalized_url(text: &str) -> String {
299
let text = text.trim();
300
if text.is_empty() || text.contains("://") || text.starts_with("mailto:") {
301
text.to_owned()
302
} else {
303
format!("https://{text}")
304
}
305
}
306
307
300
fn candidate_key(candidate: &MentionCandidate) -> &str {
308
301
match candidate {
309
302
MentionCandidate::Person(person) => &person.user_id,
@@ -349,6 +342,8 @@ impl Composer {
349
342
decorations,
350
343
pending_style: None,
351
344
snapshots: VecDeque::new(),
345
format_undo: Vec::new(),
346
format_redo: Vec::new(),
352
347
replaying_history: false,
353
348
pasted_markdown: None,
354
349
paste_hint: None,
@@ -477,6 +472,9 @@ impl Composer {
477
472
window: &mut Window,
478
473
cx: &mut Context<Self>,
479
474
) {
475
if self.draft.in_code(cursor) {
476
return;
477
}
480
478
let value = self.draft.text();
481
479
let found = match typed {
482
480
Some(':') => emoji::closing_code(value, cursor)
@@ -629,6 +627,8 @@ impl Composer {
629
627
self.link_editor = None;
630
628
self.toolbar_dismissed = None;
631
629
self.snapshots.clear();
630
self.format_undo.clear();
631
self.format_redo.clear();
632
632
self.remember_snapshot();
633
633
self.refresh_style(cx);
634
634
}
@@ -668,6 +668,59 @@ impl Composer {
668
668
true
669
669
}
670
670
671
/// A format-only change is an undo step of its own; the input's history has no record of it.
672
fn record_format(&mut self, before: Draft, cx: &mut Context<Self>) {
673
if before != self.draft {
674
self.format_undo.push((before, self.draft.clone()));
675
if self.format_undo.len() > SNAPSHOT_LIMIT {
676
self.format_undo.remove(0);
677
}
678
self.format_redo.clear();
679
}
680
self.remember_snapshot();
681
self.refresh_style(cx);
682
}
683
684
fn step_format(&mut self, undo: bool, cx: &mut Context<Self>) -> bool {
685
let (from, to) = if undo {
686
(&mut self.format_undo, &mut self.format_redo)
687
} else {
688
(&mut self.format_redo, &mut self.format_undo)
689
};
690
let matches = from
691
.last()
692
.is_some_and(|(before, after)| *(if undo { after } else { before }) == self.draft);
693
if !matches {
694
return false;
695
}
696
let Some(step) = from.pop() else {
697
return false;
698
};
699
self.draft = if undo { step.0.clone() } else { step.1.clone() };
700
to.push(step);
701
self.pending_style = None;
702
self.remember_snapshot();
703
self.refresh_style(cx);
704
cx.notify();
705
true
706
}
707
708
/// Undo and Redo set `replaying_history` for the Change they cause; a second deferral runs
709
/// after that Change, so the flag never outlives an undo with nothing to undo.
710
fn begin_history_replay(&mut self, cx: &mut Context<Self>) {
711
self.replaying_history = true;
712
self.conversion = None;
713
self.paste_hint = None;
714
let composer = cx.entity().downgrade();
715
cx.defer(move |cx| {
716
cx.defer(move |cx| {
717
composer
718
.update(cx, |this, _| this.replaying_history = false)
719
.ok();
720
});
721
});
722
}
723
671
724
fn selection(&self, cx: &App) -> Range<usize> {
672
725
self.input.read(cx).selected_range()
673
726
}
@@ -687,10 +740,10 @@ impl Composer {
687
740
pending.toggle(kind, &self.draft.style_at(cursor));
688
741
self.pending_style = (!pending.is_empty()).then_some(pending);
689
742
} else {
743
let before = self.draft.clone();
690
744
self.draft.toggle(selection, kind);
691
745
self.draft.take_edits();
692
self.remember_snapshot();
693
self.refresh_style(cx);
746
self.record_format(before, cx);
694
747
}
695
748
cx.notify();
696
749
}
@@ -771,7 +824,15 @@ impl Composer {
771
824
let Some(editor) = self.link_editor.take() else {
772
825
return;
773
826
};
774
let url = normalized_url(&editor.field.read(cx).value());
827
let typed = editor.field.read(cx).value().trim().to_owned();
828
let url = if typed.is_empty() {
829
String::new()
830
} else if let Some(url) = link_url(&typed) {
831
url
832
} else {
833
self.link_editor = Some(editor);
834
return;
835
};
775
836
self.focus(window, cx);
776
837
if editor.range.is_empty() {
777
838
if !url.is_empty() {
@@ -779,10 +840,10 @@ impl Composer {
779
840
self.commit(Some(end), window, cx);
780
841
}
781
842
} else {
843
let before = self.draft.clone();
782
844
self.draft.set_link(editor.range.clone(), &url);
783
845
self.draft.take_edits();
784
self.remember_snapshot();
785
self.refresh_style(cx);
846
self.record_format(before, cx);
786
847
self.input.update(cx, |state, cx| {
787
848
state.set_selected_range(editor.range.clone(), cx)
788
849
});
@@ -888,7 +949,8 @@ impl Composer {
888
949
889
950
fn update_emoji(&mut self, cx: &mut Context<Self>) {
890
951
let state = self.input.read(cx);
891
let found = emoji::active_query(&state.value(), state.cursor());
952
let found = emoji::active_query(&state.value(), state.cursor())
953
.filter(|_| !self.draft.in_code(state.cursor()));
892
954
if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {
893
955
self.emoji_dismissed_at = None;
894
956
}
@@ -1093,6 +1155,7 @@ impl Composer {
1093
1155
let attachments_apply = self.editing.is_none();
1094
1156
if self.undone_value.as_deref() != Some(state.value().as_ref())
1095
1157
&& let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
1158
&& !draft.in_code(range.end - 1)
1096
1159
{
1097
1160
draft.replace(range, glyph);
1098
1161
draft.take_edits();
@@ -1226,6 +1289,9 @@ impl Composer {
1226
1289
let Some(text) = item.text() else {
1227
1290
return false;
1228
1291
};
1292
if self.draft.in_code(self.selection(cx).start) {
1293
return false;
1294
}
1229
1295
if let Some(lines) = self.copied_lines(item, &text) {
1230
1296
let cursor = self.draft.insert_lines(self.selection(cx), &lines);
1231
1297
self.commit(Some(cursor), window, cx);
@@ -1879,17 +1945,20 @@ impl Render for Composer {
1879
1945
}
1880
1946
}))
1881
1947
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
1882
.capture_action(cx.listener(|this, _: &Undo, _, _| {
1883
if this.link_editor.is_none() {
1884
this.replaying_history = true;
1885
this.conversion = None;
1886
this.paste_hint = None;
1948
.capture_action(cx.listener(|this, _: &Undo, _, cx| {
1949
if this.link_editor.is_some() {
1950
} else if this.step_format(true, cx) {
1951
cx.stop_propagation();
1952
} else {
1953
this.begin_history_replay(cx);
1887
1954
}
1888
1955
}))
1889
.capture_action(cx.listener(|this, _: &Redo, _, _| {
1890
if this.link_editor.is_none() {
1891
this.replaying_history = true;
1892
this.conversion = None;
1956
.capture_action(cx.listener(|this, _: &Redo, _, cx| {
1957
if this.link_editor.is_some() {
1958
} else if this.step_format(false, cx) {
1959
cx.stop_propagation();
1960
} else {
1961
this.begin_history_replay(cx);
1893
1962
}
1894
1963
}))
1895
1964
.capture_action(cx.listener(|this, _: &Copy, _, cx| {
@@ -2409,6 +2478,56 @@ mod tests {
2409
2478
);
2410
2479
}
2411
2480
2481
#[gpui_kit::test]
2482
fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {
2483
use teams_core::{FormatState, MarkKind};
2484
2485
let mut typist = typist(cx);
2486
typist.type_text("hello");
2487
typist.press("shift-left shift-left ctrl-b");
2488
typist.press("ctrl-z");
2489
assert_eq!(typist.value(), "hello");
2490
assert!(typist.draft().marks().is_empty());
2491
typist.press("ctrl-y");
2492
assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2493
typist.press("end");
2494
typist.type_text(" x");
2495
typist.press("ctrl-z");
2496
assert_eq!(typist.value(), "hello");
2497
assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2498
typist.press("ctrl-z");
2499
assert!(typist.draft().marks().is_empty());
2500
}
2501
2502
#[gpui_kit::test]
2503
fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
2504
let mut typist = typist(cx);
2505
typist.press("ctrl-z");
2506
typist.type_text("**a**");
2507
assert_eq!(typist.value(), "a");
2508
}
2509
2510
#[gpui_kit::test]
2511
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
2512
let mut typist = typist(cx);
2513
typist.type_text("```");
2514
typist.press("enter");
2515
typist.type_text(":) ");
2516
typist
2517
.cx
2518
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
2519
typist.press("ctrl-v");
2520
assert_eq!(typist.value(), " :) **x**");
2521
let composer = typist.composer.clone();
2522
assert!(
2523
typist
2524
.cx
2525
.update(|cx| composer.read(cx).paste_hint.is_none())
2526
);
2527
let outgoing = typist.outgoing();
2528
assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
2529
}
2530
2412
2531
#[gpui_kit::test]
2413
2532
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
2414
2533
let mut typist = typist(cx);
@@ -22,7 +22,7 @@ use gpui_kit::*;22
use teams_core::{22
use teams_core::{23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,24
MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, has_markdown,24
MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, has_markdown,25
map_offset, reverse_edits,25
link_url, map_offset, reverse_edits,26
};26
};27
27
28
use super::attachment_tray::{28
use super::attachment_tray::{@@ -214,6 +214,8 @@ pub struct Composer {214
decorations: DraftDecorations,214
decorations: DraftDecorations,215
pending_style: Option<TypingStyle>,215
pending_style: Option<TypingStyle>,216
snapshots: VecDeque<Draft>,216
snapshots: VecDeque<Draft>,217
format_undo: Vec<(Draft, Draft)>,218
format_redo: Vec<(Draft, Draft)>,217
replaying_history: bool,219
replaying_history: bool,218
pasted_markdown: Option<String>,220
pasted_markdown: Option<String>,219
paste_hint: Option<Task<()>>,221
paste_hint: Option<Task<()>>,@@ -295,15 +297,6 @@ fn looks_like_url(text: &str) -> bool {295
&& !text.contains(char::is_whitespace)297
&& !text.contains(char::is_whitespace)296
}298
}297
299
298
fn normalized_url(text: &str) -> String {299
let text = text.trim();300
if text.is_empty() || text.contains("://") || text.starts_with("mailto:") {301
text.to_owned()302
} else {303
format!("https://{text}")304
}305
}306
307
fn candidate_key(candidate: &MentionCandidate) -> &str {300
fn candidate_key(candidate: &MentionCandidate) -> &str {308
match candidate {301
match candidate {309
MentionCandidate::Person(person) => &person.user_id,302
MentionCandidate::Person(person) => &person.user_id,@@ -349,6 +342,8 @@ impl Composer {349
decorations,342
decorations,350
pending_style: None,343
pending_style: None,351
snapshots: VecDeque::new(),344
snapshots: VecDeque::new(),345
format_undo: Vec::new(),346
format_redo: Vec::new(),352
replaying_history: false,347
replaying_history: false,353
pasted_markdown: None,348
pasted_markdown: None,354
paste_hint: None,349
paste_hint: None,@@ -477,6 +472,9 @@ impl Composer {477
window: &mut Window,472
window: &mut Window,478
cx: &mut Context<Self>,473
cx: &mut Context<Self>,479
) {474
) {475
if self.draft.in_code(cursor) {476
return;477
}480
let value = self.draft.text();478
let value = self.draft.text();481
let found = match typed {479
let found = match typed {482
Some(':') => emoji::closing_code(value, cursor)480
Some(':') => emoji::closing_code(value, cursor)@@ -629,6 +627,8 @@ impl Composer {629
self.link_editor = None;627
self.link_editor = None;630
self.toolbar_dismissed = None;628
self.toolbar_dismissed = None;631
self.snapshots.clear();629
self.snapshots.clear();630
self.format_undo.clear();631
self.format_redo.clear();632
self.remember_snapshot();632
self.remember_snapshot();633
self.refresh_style(cx);633
self.refresh_style(cx);634
}634
}@@ -668,6 +668,59 @@ impl Composer {668
true668
true669
}669
}670
670
671
/// A format-only change is an undo step of its own; the input's history has no record of it.672
fn record_format(&mut self, before: Draft, cx: &mut Context<Self>) {673
if before != self.draft {674
self.format_undo.push((before, self.draft.clone()));675
if self.format_undo.len() > SNAPSHOT_LIMIT {676
self.format_undo.remove(0);677
}678
self.format_redo.clear();679
}680
self.remember_snapshot();681
self.refresh_style(cx);682
}683
684
fn step_format(&mut self, undo: bool, cx: &mut Context<Self>) -> bool {685
let (from, to) = if undo {686
(&mut self.format_undo, &mut self.format_redo)687
} else {688
(&mut self.format_redo, &mut self.format_undo)689
};690
let matches = from691
.last()692
.is_some_and(|(before, after)| *(if undo { after } else { before }) == self.draft);693
if !matches {694
return false;695
}696
let Some(step) = from.pop() else {697
return false;698
};699
self.draft = if undo { step.0.clone() } else { step.1.clone() };700
to.push(step);701
self.pending_style = None;702
self.remember_snapshot();703
self.refresh_style(cx);704
cx.notify();705
true706
}707
708
/// Undo and Redo set `replaying_history` for the Change they cause; a second deferral runs709
/// after that Change, so the flag never outlives an undo with nothing to undo.710
fn begin_history_replay(&mut self, cx: &mut Context<Self>) {711
self.replaying_history = true;712
self.conversion = None;713
self.paste_hint = None;714
let composer = cx.entity().downgrade();715
cx.defer(move |cx| {716
cx.defer(move |cx| {717
composer718
.update(cx, |this, _| this.replaying_history = false)719
.ok();720
});721
});722
}723
671
fn selection(&self, cx: &App) -> Range<usize> {724
fn selection(&self, cx: &App) -> Range<usize> {672
self.input.read(cx).selected_range()725
self.input.read(cx).selected_range()673
}726
}@@ -687,10 +740,10 @@ impl Composer {687
pending.toggle(kind, &self.draft.style_at(cursor));740
pending.toggle(kind, &self.draft.style_at(cursor));688
self.pending_style = (!pending.is_empty()).then_some(pending);741
self.pending_style = (!pending.is_empty()).then_some(pending);689
} else {742
} else {743
let before = self.draft.clone();690
self.draft.toggle(selection, kind);744
self.draft.toggle(selection, kind);691
self.draft.take_edits();745
self.draft.take_edits();692
self.remember_snapshot();746
self.record_format(before, cx);693
self.refresh_style(cx);694
}747
}695
cx.notify();748
cx.notify();696
}749
}@@ -771,7 +824,15 @@ impl Composer {771
let Some(editor) = self.link_editor.take() else {824
let Some(editor) = self.link_editor.take() else {772
return;825
return;773
};826
};774
let url = normalized_url(&editor.field.read(cx).value());827
let typed = editor.field.read(cx).value().trim().to_owned();828
let url = if typed.is_empty() {829
String::new()830
} else if let Some(url) = link_url(&typed) {831
url832
} else {833
self.link_editor = Some(editor);834
return;835
};775
self.focus(window, cx);836
self.focus(window, cx);776
if editor.range.is_empty() {837
if editor.range.is_empty() {777
if !url.is_empty() {838
if !url.is_empty() {@@ -779,10 +840,10 @@ impl Composer {779
self.commit(Some(end), window, cx);840
self.commit(Some(end), window, cx);780
}841
}781
} else {842
} else {843
let before = self.draft.clone();782
self.draft.set_link(editor.range.clone(), &url);844
self.draft.set_link(editor.range.clone(), &url);783
self.draft.take_edits();845
self.draft.take_edits();784
self.remember_snapshot();846
self.record_format(before, cx);785
self.refresh_style(cx);786
self.input.update(cx, |state, cx| {847
self.input.update(cx, |state, cx| {787
state.set_selected_range(editor.range.clone(), cx)848
state.set_selected_range(editor.range.clone(), cx)788
});849
});@@ -888,7 +949,8 @@ impl Composer {888
949
889
fn update_emoji(&mut self, cx: &mut Context<Self>) {950
fn update_emoji(&mut self, cx: &mut Context<Self>) {890
let state = self.input.read(cx);951
let state = self.input.read(cx);891
let found = emoji::active_query(&state.value(), state.cursor());952
let found = emoji::active_query(&state.value(), state.cursor())953
.filter(|_| !self.draft.in_code(state.cursor()));892
if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {954
if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {893
self.emoji_dismissed_at = None;955
self.emoji_dismissed_at = None;894
}956
}@@ -1093,6 +1155,7 @@ impl Composer {1093
let attachments_apply = self.editing.is_none();1155
let attachments_apply = self.editing.is_none();1094
if self.undone_value.as_deref() != Some(state.value().as_ref())1156
if self.undone_value.as_deref() != Some(state.value().as_ref())1095
&& let Some((range, glyph)) = emoji::trailing_smiley(draft.text())1157
&& let Some((range, glyph)) = emoji::trailing_smiley(draft.text())1158
&& !draft.in_code(range.end - 1)1096
{1159
{1097
draft.replace(range, glyph);1160
draft.replace(range, glyph);1098
draft.take_edits();1161
draft.take_edits();@@ -1226,6 +1289,9 @@ impl Composer {1226
let Some(text) = item.text() else {1289
let Some(text) = item.text() else {1227
return false;1290
return false;1228
};1291
};1292
if self.draft.in_code(self.selection(cx).start) {1293
return false;1294
}1229
if let Some(lines) = self.copied_lines(item, &text) {1295
if let Some(lines) = self.copied_lines(item, &text) {1230
let cursor = self.draft.insert_lines(self.selection(cx), &lines);1296
let cursor = self.draft.insert_lines(self.selection(cx), &lines);1231
self.commit(Some(cursor), window, cx);1297
self.commit(Some(cursor), window, cx);@@ -1879,17 +1945,20 @@ impl Render for Composer {1879
}1945
}1880
}))1946
}))1881
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))1947
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))1882
.capture_action(cx.listener(|this, _: &Undo, _, _| {1948
.capture_action(cx.listener(|this, _: &Undo, _, cx| {1883
if this.link_editor.is_none() {1949
if this.link_editor.is_some() {1884
this.replaying_history = true;1950
} else if this.step_format(true, cx) {1885
this.conversion = None;1951
cx.stop_propagation();1886
this.paste_hint = None;1952
} else {1953
this.begin_history_replay(cx);1887
}1954
}1888
}))1955
}))1889
.capture_action(cx.listener(|this, _: &Redo, _, _| {1956
.capture_action(cx.listener(|this, _: &Redo, _, cx| {1890
if this.link_editor.is_none() {1957
if this.link_editor.is_some() {1891
this.replaying_history = true;1958
} else if this.step_format(false, cx) {1892
this.conversion = None;1959
cx.stop_propagation();1960
} else {1961
this.begin_history_replay(cx);1893
}1962
}1894
}))1963
}))1895
.capture_action(cx.listener(|this, _: &Copy, _, cx| {1964
.capture_action(cx.listener(|this, _: &Copy, _, cx| {@@ -2409,6 +2478,56 @@ mod tests {2409
);2478
);2410
}2479
}2411
2480
2481
#[gpui_kit::test]2482
fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {2483
use teams_core::{FormatState, MarkKind};2484
2485
let mut typist = typist(cx);2486
typist.type_text("hello");2487
typist.press("shift-left shift-left ctrl-b");2488
typist.press("ctrl-z");2489
assert_eq!(typist.value(), "hello");2490
assert!(typist.draft().marks().is_empty());2491
typist.press("ctrl-y");2492
assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);2493
typist.press("end");2494
typist.type_text(" x");2495
typist.press("ctrl-z");2496
assert_eq!(typist.value(), "hello");2497
assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);2498
typist.press("ctrl-z");2499
assert!(typist.draft().marks().is_empty());2500
}2501
2502
#[gpui_kit::test]2503
fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {2504
let mut typist = typist(cx);2505
typist.press("ctrl-z");2506
typist.type_text("**a**");2507
assert_eq!(typist.value(), "a");2508
}2509
2510
#[gpui_kit::test]2511
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {2512
let mut typist = typist(cx);2513
typist.type_text("```");2514
typist.press("enter");2515
typist.type_text(":) ");2516
typist2517
.cx2518
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));2519
typist.press("ctrl-v");2520
assert_eq!(typist.value(), " :) **x**");2521
let composer = typist.composer.clone();2522
assert!(2523
typist2524
.cx2525
.update(|cx| composer.read(cx).paste_hint.is_none())2526
);2527
let outgoing = typist.outgoing();2528
assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");2529
}2530
2412
#[gpui_kit::test]2531
#[gpui_kit::test]2413
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {2532
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {2414
let mut typist = typist(cx);2533
let mut typist = typist(cx);@@ -54,20 +54,11 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
54
54
style
55
55
}
56
56
57
/// A range the block or bar decoration paints over every line of `lines`; `None` when the
58
/// block is one empty line it cannot address yet.
59
fn block_range(draft: &Draft, lines: Range<usize>) -> Option<Range<usize>> {
57
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover
58
/// every line starting inside it, ends included, so empty lines count too.
59
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
60
60
let line_ranges = draft.line_ranges();
61
let start = line_ranges[lines.start].start;
62
let end = line_ranges[lines.end - 1].end;
63
if end > start {
64
return Some(start..end);
65
}
66
if end < draft.text().len() {
67
return Some(start..start + 1);
68
}
69
let previous_has_text = lines.start > 0 && !line_ranges[lines.start - 1].is_empty();
70
previous_has_text.then(|| start - 1..start)
61
line_ranges[lines.start].start..line_ranges[lines.end - 1].end
71
62
}
72
63
73
64
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
@@ -122,18 +113,18 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
122
113
}
123
114
}
124
115
let block = match kind {
125
LineKind::Code(_) => block_range(draft, index..run_end).map(|range| {
126
RangeDecoration::new(range)
116
LineKind::Code(_) => Some(
117
RangeDecoration::new(block_range(draft, index..run_end))
127
118
.with_style(RangeDecorationStyle::Block)
128
119
.with_color(theme::code_surface())
129
.with_radius(px(CODE_BLOCK_RADIUS))
130
}),
131
LineKind::Quote => block_range(draft, index..run_end).map(|range| {
132
RangeDecoration::new(range)
120
.with_radius(px(CODE_BLOCK_RADIUS)),
121
),
122
LineKind::Quote => Some(
123
RangeDecoration::new(block_range(draft, index..run_end))
133
124
.with_style(RangeDecorationStyle::Bar)
134
125
.with_color(theme::border_strong())
135
.with_radius(px(QUOTE_BAR_WIDTH))
136
}),
126
.with_radius(px(QUOTE_BAR_WIDTH)),
127
),
137
128
_ => None,
138
129
};
139
130
ranges.extend(block);
@@ -153,11 +144,23 @@ mod tests {
153
144
154
145
use super::{block_range, draft_style};
155
146
147
fn line(kind: LineKind, content: &str) -> DraftLine {
148
DraftLine {
149
kind,
150
number: None,
151
content: content.into(),
152
marks: Vec::new(),
153
}
154
}
155
156
156
#[test]
157
157
fn list_markers_hang_and_code_gets_a_pill() {
158
158
let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");
159
159
let style = draft_style(&draft, "Mono".into());
160
assert_eq!(style.markers, [draft.marker_range(0)]);
160
assert_eq!(
161
style.markers,
162
[draft.marker_range(0), draft.marker_range(1)]
163
);
161
164
assert_eq!(
162
165
style
163
166
.ranges
@@ -169,21 +172,23 @@ mod tests {
169
172
}
170
173
171
174
#[test]
172
fn an_empty_code_line_at_the_end_still_gets_its_block() {
175
fn a_code_block_covers_its_empty_last_line_before_text() {
173
176
let draft = Draft::from_lines(&[
174
DraftLine {
175
kind: LineKind::Text,
176
number: None,
177
content: "intro".into(),
178
marks: Vec::new(),
179
},
180
DraftLine {
181
kind: LineKind::Code(None),
182
number: None,
183
content: String::new(),
184
marks: Vec::new(),
185
},
177
line(LineKind::Code(None), "x"),
178
line(LineKind::Code(None), ""),
179
line(LineKind::Text, "after"),
186
180
]);
187
assert_eq!(block_range(&draft, 1..2), Some(5..6));
181
let block = block_range(&draft, 0..2);
182
let empty_line_start = draft.line_ranges()[1].start;
183
assert!(block.contains(&empty_line_start) || block.end == empty_line_start);
184
assert!(block.end < draft.line_ranges()[2].start);
185
}
186
187
#[test]
188
fn a_lone_code_line_still_gets_a_block() {
189
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);
190
let style = draft_style(&draft, "Mono".into());
191
assert_eq!(style.ranges.len(), 1);
192
assert_eq!(style.ranges[0].style(), RangeDecorationStyle::Block);
188
193
}
189
194
}
@@ -54,20 +54,11 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {54
style54
style55
}55
}56
56
57
/// A range the block or bar decoration paints over every line of `lines`; `None` when the57
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover58
/// block is one empty line it cannot address yet.58
/// every line starting inside it, ends included, so empty lines count too.59
fn block_range(draft: &Draft, lines: Range<usize>) -> Option<Range<usize>> {59
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {60
let line_ranges = draft.line_ranges();60
let line_ranges = draft.line_ranges();61
let start = line_ranges[lines.start].start;61
line_ranges[lines.start].start..line_ranges[lines.end - 1].end62
let end = line_ranges[lines.end - 1].end;63
if end > start {64
return Some(start..end);65
}66
if end < draft.text().len() {67
return Some(start..start + 1);68
}69
let previous_has_text = lines.start > 0 && !line_ranges[lines.start - 1].is_empty();70
previous_has_text.then(|| start - 1..start)71
}62
}72
63
73
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {64
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {@@ -122,18 +113,18 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {122
}113
}123
}114
}124
let block = match kind {115
let block = match kind {125
LineKind::Code(_) => block_range(draft, index..run_end).map(|range| {116
LineKind::Code(_) => Some(126
RangeDecoration::new(range)117
RangeDecoration::new(block_range(draft, index..run_end))127
.with_style(RangeDecorationStyle::Block)118
.with_style(RangeDecorationStyle::Block)128
.with_color(theme::code_surface())119
.with_color(theme::code_surface())129
.with_radius(px(CODE_BLOCK_RADIUS))120
.with_radius(px(CODE_BLOCK_RADIUS)),130
}),121
),131
LineKind::Quote => block_range(draft, index..run_end).map(|range| {122
LineKind::Quote => Some(132
RangeDecoration::new(range)123
RangeDecoration::new(block_range(draft, index..run_end))133
.with_style(RangeDecorationStyle::Bar)124
.with_style(RangeDecorationStyle::Bar)134
.with_color(theme::border_strong())125
.with_color(theme::border_strong())135
.with_radius(px(QUOTE_BAR_WIDTH))126
.with_radius(px(QUOTE_BAR_WIDTH)),136
}),127
),137
_ => None,128
_ => None,138
};129
};139
ranges.extend(block);130
ranges.extend(block);@@ -153,11 +144,23 @@ mod tests {153
144
154
use super::{block_range, draft_style};145
use super::{block_range, draft_style};155
146
147
fn line(kind: LineKind, content: &str) -> DraftLine {148
DraftLine {149
kind,150
number: None,151
content: content.into(),152
marks: Vec::new(),153
}154
}155
156
#[test]156
#[test]157
fn list_markers_hang_and_code_gets_a_pill() {157
fn list_markers_hang_and_code_gets_a_pill() {158
let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");158
let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");159
let style = draft_style(&draft, "Mono".into());159
let style = draft_style(&draft, "Mono".into());160
assert_eq!(style.markers, [draft.marker_range(0)]);160
assert_eq!(161
style.markers,162
[draft.marker_range(0), draft.marker_range(1)]163
);161
assert_eq!(164
assert_eq!(162
style165
style163
.ranges166
.ranges@@ -169,21 +172,23 @@ mod tests {169
}172
}170
173
171
#[test]174
#[test]172
fn an_empty_code_line_at_the_end_still_gets_its_block() {175
fn a_code_block_covers_its_empty_last_line_before_text() {173
let draft = Draft::from_lines(&[176
let draft = Draft::from_lines(&[174
DraftLine {177
line(LineKind::Code(None), "x"),175
kind: LineKind::Text,178
line(LineKind::Code(None), ""),176
number: None,179
line(LineKind::Text, "after"),177
content: "intro".into(),178
marks: Vec::new(),179
},180
DraftLine {181
kind: LineKind::Code(None),182
number: None,183
content: String::new(),184
marks: Vec::new(),185
},186
]);180
]);187
assert_eq!(block_range(&draft, 1..2), Some(5..6));181
let block = block_range(&draft, 0..2);182
let empty_line_start = draft.line_ranges()[1].start;183
assert!(block.contains(&empty_line_start) || block.end == empty_line_start);184
assert!(block.end < draft.line_ranges()[2].start);185
}186
187
#[test]188
fn a_lone_code_line_still_gets_a_block() {189
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);190
let style = draft_style(&draft, "Mono".into());191
assert_eq!(style.ranges.len(), 1);192
assert_eq!(style.ranges[0].style(), RangeDecorationStyle::Block);188
}193
}189
}194
}@@ -12,6 +12,8 @@ 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 = " ";
16
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
15
17
const FENCE: &str = "```";
16
18
const MARKDOWN_INDENT: usize = 2;
17
19
@@ -388,6 +390,14 @@ impl Draft {
388
390
self.marker_range(index).end..line.end
389
391
}
390
392
393
/// Inside a code block line, or strictly inside inline code.
394
pub fn in_code(&self, offset: usize) -> bool {
395
matches!(self.lines[self.line_at(offset)], LineKind::Code(_))
396
|| self.marks.iter().any(|mark| {
397
mark.kind == MarkKind::Code && mark.range.start < offset && offset < mark.range.end
398
})
399
}
400
391
401
/// Formats that text typed at `offset` takes on.
392
402
pub fn style_at(&self, offset: usize) -> Vec<MarkKind> {
393
403
self.style_for_insertion(offset, offset)
@@ -429,8 +439,18 @@ impl Draft {
429
439
}
430
440
}
431
441
442
/// A line the selection only touches at its start does not count.
443
fn selected_lines(&self, range: &Range<usize>) -> std::ops::RangeInclusive<usize> {
444
let first = self.line_at(range.start);
445
let mut last = self.line_at(range.end);
446
if last > first && self.line_ranges()[last].start == range.end {
447
last -= 1;
448
}
449
first..=last
450
}
451
432
452
pub fn line_state(&self, range: Range<usize>, kind: &LineKind) -> FormatState {
433
let lines = self.line_at(range.start)..=self.line_at(range.end);
453
let lines = self.selected_lines(&range);
434
454
let count = lines.clone().count();
435
455
let matching = lines
436
456
.filter(|index| self.lines[*index].same_format(kind))
@@ -466,9 +486,13 @@ impl Draft {
466
486
}
467
487
}
468
488
469
/// An empty `url` removes the link.
489
/// An empty `url` removes the link; one `link_url` refuses changes nothing.
470
490
pub fn set_link(&mut self, range: Range<usize>, url: &str) {
471
491
self.journal = Journal::default();
492
let url = url.trim();
493
if !url.is_empty() && link_url(url).is_none() {
494
return;
495
}
472
496
let link = MarkKind::Link(url.to_owned());
473
497
self.remove_marks(range.clone(), &link);
474
498
if !url.is_empty() {
@@ -478,7 +502,7 @@ impl Draft {
478
502
}
479
503
}
480
504
481
/// Returns the offset after the inserted link text.
505
/// Returns the offset after the inserted link text; plain text when `link_url` refuses `url`.
482
506
pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize {
483
507
self.journal = Journal::default();
484
508
self.splice(offset..offset, text, &[]);
@@ -592,8 +616,7 @@ impl Draft {
592
616
LineKind::Text => {
593
617
let language = fence_language(&self.text[content.clone()])?;
594
618
self.splice(content.clone(), "", &[]);
595
self.lines[index] = LineKind::Code(language);
596
Some(content.start)
619
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
597
620
}
598
621
LineKind::Quote if !shift => None,
599
622
LineKind::Quote => {
@@ -606,11 +629,10 @@ impl Draft {
606
629
let last_of_block = self.lines.get(index + 1) != Some(&kind);
607
630
let block_continues_above = index > 0 && self.lines[index - 1] == kind;
608
631
if content.is_empty() && last_of_block && block_continues_above && !shift {
609
self.lines[index] = LineKind::Text;
610
return Some(cursor);
632
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
611
633
}
612
634
self.splice(cursor..cursor, "\n", &[]);
613
Some(cursor + 1)
635
Some(self.repair(cursor + 1))
614
636
}
615
637
list => {
616
638
if self.text[content.clone()].trim().is_empty() {
@@ -639,12 +661,13 @@ impl Draft {
639
661
let content = self.content_range(index);
640
662
match &kind {
641
663
LineKind::Text => None,
642
LineKind::Code(_) => {
664
LineKind::Code(_) if cursor > line.start && cursor <= content.start => {
643
665
let first_of_block = index == 0 || self.lines[index - 1] != kind;
644
(cursor == content.start && first_of_block).then(|| {
645
self.lines[index] = LineKind::Text;
646
cursor
647
})
666
if first_of_block {
667
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
668
}
669
self.splice(line.start - 1..content.start, "", &[]);
670
Some(self.repair(line.start - 1))
648
671
}
649
672
_ if cursor == line.start && index > 0 => {
650
673
self.splice(line.start - 1..content.start, "", &[]);
@@ -665,7 +688,7 @@ impl Draft {
665
688
/// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item.
666
689
pub fn indent(&mut self, range: Range<usize>, outdent: bool) -> bool {
667
690
self.journal = Journal::default();
668
let lines = self.line_at(range.start)..=self.line_at(range.end);
691
let lines = self.selected_lines(&range);
669
692
if !lines.clone().all(|index| self.lines[index].is_list()) {
670
693
return false;
671
694
}
@@ -686,7 +709,7 @@ impl Draft {
686
709
/// All selected lines `kind` already: back to text. Otherwise all become `kind`.
687
710
pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {
688
711
self.journal = Journal::default();
689
let lines = self.line_at(range.start)..=self.line_at(range.end);
712
let lines = self.selected_lines(&range);
690
713
let all = lines
691
714
.clone()
692
715
.all(|index| self.lines[index].same_format(&kind));
@@ -777,6 +800,7 @@ impl Draft {
777
800
}
778
801
offset += line.content.len() + 1;
779
802
}
803
let length_before_markers = self.text.len();
780
804
for (position, line) in lines.iter().enumerate() {
781
805
let first_and_kept = position == 0 && !line_was_empty;
782
806
if first_and_kept || line.kind == self.lines[index + position] {
@@ -784,9 +808,8 @@ impl Draft {
784
808
}
785
809
self.set_line_kind(index + position, line.kind.clone(), line.number, 0);
786
810
}
787
let last = index + lines.len().saturating_sub(1);
788
811
let end =
789
self.content_range(last).start + lines.last().map_or(0, |line| line.content.len());
812
(range.start + joined.len() + self.text.len()).saturating_sub(length_before_markers);
790
813
self.repair(end)
791
814
}
792
815
@@ -892,7 +915,15 @@ impl Draft {
892
915
.collect()
893
916
}
894
917
918
/// Links with a scheme other than http, https or mailto stay plain text.
895
919
fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {
920
let kind = match kind {
921
MarkKind::Link(url) => match link_url(&url) {
922
Some(url) => MarkKind::Link(url),
923
None => return,
924
},
925
other => other,
926
};
896
927
if !range.is_empty() {
897
928
self.marks.push(Mark { range, kind });
898
929
self.normalize_marks();
@@ -1086,11 +1117,19 @@ impl Draft {
1086
1117
}
1087
1118
}
1088
1119
1089
/// Lines whose marker was edited away become text; numbered items are renumbered.
1120
/// Lines whose marker was edited away become text; numbered items are renumbered; code
1121
/// lines get their padding back.
1090
1122
fn repair(&mut self, mut cursor: usize) -> usize {
1091
1123
for index in 0..self.lines.len() {
1092
1124
let kind = self.lines[index].clone();
1093
if matches!(kind, LineKind::Text | LineKind::Code(_)) {
1125
if kind == LineKind::Text {
1126
continue;
1127
}
1128
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);
1132
}
1094
1133
continue;
1095
1134
}
1096
1135
let line = self.line_ranges()[index].clone();
@@ -1128,7 +1167,8 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1128
1167
LineKind::Bullet(depth) => bullet_marker(*depth),
1129
1168
LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),
1130
1169
LineKind::Quote => QUOTE_MARKER.to_owned(),
1131
LineKind::Text | LineKind::Code(_) => String::new(),
1170
LineKind::Code(_) => CODE_MARKER.to_owned(),
1171
LineKind::Text => String::new(),
1132
1172
}
1133
1173
}
1134
1174
@@ -1144,6 +1184,7 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {
1144
1184
}
1145
1185
LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),
1146
1186
LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),
1187
LineKind::Code(_) if line.starts_with(CODE_MARKER) => CODE_MARKER.len(),
1147
1188
_ => 0,
1148
1189
}
1149
1190
}
@@ -1193,6 +1234,28 @@ fn word_before(text: &str) -> bool {
1193
1234
.is_some_and(|character| character.is_alphanumeric())
1194
1235
}
1195
1236
1237
/// `https://` added when there is no scheme. `None` for any scheme but http, https and mailto.
1238
pub fn link_url(text: &str) -> Option<String> {
1239
let text = text.trim();
1240
if text.is_empty() || text.contains(char::is_whitespace) {
1241
return None;
1242
}
1243
let lower = text.to_ascii_lowercase();
1244
if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
1245
return Some(text.to_owned());
1246
}
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
});
1256
scheme.is_none().then(|| format!("https://{text}"))
1257
}
1258
1196
1259
/// The markers of a format closed by the last typed character, relative to `before`.
1197
1260
fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
1198
1261
let end = before.len();
@@ -1203,7 +1266,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1203
1266
return Some((
1204
1267
whole.start()..whole.start() + 1,
1205
1268
label.end()..end,
1206
MarkKind::Link(captures[2].to_owned()),
1269
MarkKind::Link(link_url(&captures[2])?),
1207
1270
));
1208
1271
}
1209
1272
for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
@@ -1476,7 +1539,7 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1476
1539
return Some((
1477
1540
label.as_str(),
1478
1541
captures.get(0)?.end(),
1479
MarkKind::Link(captures[2].to_owned()),
1542
MarkKind::Link(link_url(&captures[2])?),
1480
1543
));
1481
1544
}
1482
1545
for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
@@ -1727,7 +1790,10 @@ mod tests {
1727
1790
assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);
1728
1791
let mut linked = typed_draft("[a](u)");
1729
1792
typed(&mut linked, "b");
1730
assert_eq!(linked.marks(), [mark(0..1, MarkKind::Link("u".into()))]);
1793
assert_eq!(
1794
linked.marks(),
1795
[mark(0..1, MarkKind::Link("https://u".into()))]
1796
);
1731
1797
}
1732
1798
1733
1799
#[test]
@@ -1874,12 +1940,15 @@ mod tests {
1874
1940
fn fence_and_enter_open_a_code_block_that_enter_continues() {
1875
1941
let mut draft = typed_draft("```rust");
1876
1942
let cursor = draft.break_line(draft.text().len(), false).unwrap();
1877
assert_eq!((draft.text(), cursor), ("", 0));
1943
assert_eq!((draft.text(), cursor), (CODE_MARKER, CODE_MARKER.len()));
1878
1944
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
1879
1945
typed(&mut draft, "fn x() {}");
1880
1946
let cursor = draft.break_line(draft.text().len(), false).unwrap();
1881
1947
assert_eq!(draft.lines().len(), 2);
1882
assert_eq!(draft.break_line(cursor, false), Some(cursor));
1948
assert_eq!(
1949
draft.break_line(cursor, false),
1950
Some(cursor - CODE_MARKER.len())
1951
);
1883
1952
assert_eq!(draft.lines()[1], LineKind::Text);
1884
1953
assert_eq!(
1885
1954
draft.to_html(),
@@ -1891,9 +1960,9 @@ mod tests {
1891
1960
fn markdown_inside_code_stays_literal() {
1892
1961
let mut draft = typed_draft("```");
1893
1962
let cursor = draft.break_line(3, false).unwrap();
1894
assert_eq!(cursor, 0);
1963
assert_eq!(cursor, CODE_MARKER.len());
1895
1964
typed(&mut draft, "a **b**");
1896
assert_eq!(draft.text(), "a **b**");
1965
assert_eq!(draft.text(), format!("{CODE_MARKER}a **b**"));
1897
1966
assert!(draft.marks().is_empty());
1898
1967
}
1899
1968
@@ -1989,6 +2058,83 @@ mod tests {
1989
2058
assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);
1990
2059
}
1991
2060
2061
#[test]
2062
fn a_paste_inside_a_line_puts_the_cursor_after_the_pasted_text() {
2063
let lines = Draft::from_markdown("**big**").slice(0..usize::MAX);
2064
let mut plain = Draft::plain("hello world");
2065
assert_eq!(plain.insert_lines(6..6, &lines), 9);
2066
assert_eq!(plain.text(), "hello bigworld");
2067
let mut item = Draft::from_markdown("- item one");
2068
let before_one = bullet_marker(0).len() + "item ".len();
2069
assert_eq!(
2070
item.insert_lines(before_one..before_one, &lines),
2071
before_one + 3
2072
);
2073
}
2074
2075
#[test]
2076
fn a_selection_ending_at_the_next_line_start_leaves_that_line_alone() {
2077
let mut draft = Draft::plain("first\nsecond");
2078
assert_eq!(
2079
draft.line_state(0..6, &LineKind::Bullet(0)),
2080
FormatState::Off
2081
);
2082
draft.toggle_lines(0..6, LineKind::Bullet(0));
2083
assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Text]);
2084
let end_of_first = draft.line_ranges()[1].start;
2085
assert_eq!(
2086
draft.line_state(0..end_of_first, &LineKind::Bullet(0)),
2087
FormatState::On
2088
);
2089
assert!(draft.indent(0..end_of_first, false));
2090
assert_eq!(draft.lines()[1], LineKind::Text);
2091
}
2092
2093
#[test]
2094
fn links_only_take_http_https_and_mailto() {
2095
assert_eq!(link_url("example.com"), Some("https://example.com".into()));
2096
assert_eq!(link_url("mailto:a@b.test"), Some("mailto:a@b.test".into()));
2097
assert_eq!(link_url("javascript:alert(1)"), None);
2098
assert_eq!(link_url("data:text/html,x"), None);
2099
let typed = typed_draft("[x](javascript:alert)");
2100
assert!(typed.marks().is_empty());
2101
let pasted = Draft::from_markdown("[x](javascript:alert) [y](example.com)");
2102
assert_eq!(
2103
pasted.marks(),
2104
[mark(22..23, MarkKind::Link("https://example.com".into()))]
2105
);
2106
let mut set = Draft::plain("go");
2107
set.set_link(0..2, "javascript:alert(1)");
2108
assert!(set.marks().is_empty());
2109
let spans = Draft::from_spans(&html_to_spans("<a href=\"javascript:x\">bad</a>"));
2110
assert!(spans.marks().is_empty());
2111
}
2112
2113
#[test]
2114
fn code_lines_carry_padding_that_survives_edits_and_stays_out_of_html() {
2115
let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");
2116
assert_eq!(
2117
draft.text(),
2118
format!("{CODE_MARKER}let a = 1;\n{CODE_MARKER}let b = 2;")
2119
);
2120
assert_eq!(draft.to_html(), "<pre>let a = 1;\nlet b = 2;</pre>");
2121
let second = draft.content_range(1).start;
2122
let cursor = draft.backspace_at_start(second).unwrap();
2123
assert_eq!(draft.text(), format!("{CODE_MARKER}let a = 1;let b = 2;"));
2124
assert_eq!(cursor, CODE_MARKER.len() + "let a = 1;".len());
2125
let cursor = draft.backspace_at_start(CODE_MARKER.len()).unwrap();
2126
assert_eq!((draft.lines()[0].clone(), cursor), (LineKind::Text, 0));
2127
}
2128
2129
#[test]
2130
fn in_code_covers_code_lines_and_the_inside_of_inline_code() {
2131
let draft = Draft::from_markdown("a `cd` e\n```\nx\n```");
2132
assert!(!draft.in_code(2));
2133
assert!(draft.in_code(3));
2134
assert!(!draft.in_code(4));
2135
assert!(draft.in_code(draft.text().len()));
2136
}
2137
1992
2138
#[test]
1993
2139
fn journal_merges_edits_into_ranges_of_the_old_text() {
1994
2140
let mut draft = Draft::plain("a **b** c");
@@ -12,6 +12,8 @@ const BULLETS: [&str; 3] = ["•", "◦", "▪"];12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];13
const INDENT: &str = "\u{2003}\u{2003}";13
const INDENT: &str = "\u{2003}\u{2003}";14
const QUOTE_MARKER: &str = "\u{2003}";14
const QUOTE_MARKER: &str = "\u{2003}";15
const CODE_MARKER: &str = " ";16
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];15
const FENCE: &str = "```";17
const FENCE: &str = "```";16
const MARKDOWN_INDENT: usize = 2;18
const MARKDOWN_INDENT: usize = 2;17
19
@@ -388,6 +390,14 @@ impl Draft {388
self.marker_range(index).end..line.end390
self.marker_range(index).end..line.end389
}391
}390
392
393
/// Inside a code block line, or strictly inside inline code.394
pub fn in_code(&self, offset: usize) -> bool {395
matches!(self.lines[self.line_at(offset)], LineKind::Code(_))396
|| self.marks.iter().any(|mark| {397
mark.kind == MarkKind::Code && mark.range.start < offset && offset < mark.range.end398
})399
}400
391
/// Formats that text typed at `offset` takes on.401
/// Formats that text typed at `offset` takes on.392
pub fn style_at(&self, offset: usize) -> Vec<MarkKind> {402
pub fn style_at(&self, offset: usize) -> Vec<MarkKind> {393
self.style_for_insertion(offset, offset)403
self.style_for_insertion(offset, offset)@@ -429,8 +439,18 @@ impl Draft {429
}439
}430
}440
}431
441
442
/// A line the selection only touches at its start does not count.443
fn selected_lines(&self, range: &Range<usize>) -> std::ops::RangeInclusive<usize> {444
let first = self.line_at(range.start);445
let mut last = self.line_at(range.end);446
if last > first && self.line_ranges()[last].start == range.end {447
last -= 1;448
}449
first..=last450
}451
432
pub fn line_state(&self, range: Range<usize>, kind: &LineKind) -> FormatState {452
pub fn line_state(&self, range: Range<usize>, kind: &LineKind) -> FormatState {433
let lines = self.line_at(range.start)..=self.line_at(range.end);453
let lines = self.selected_lines(&range);434
let count = lines.clone().count();454
let count = lines.clone().count();435
let matching = lines455
let matching = lines436
.filter(|index| self.lines[*index].same_format(kind))456
.filter(|index| self.lines[*index].same_format(kind))@@ -466,9 +486,13 @@ impl Draft {466
}486
}467
}487
}468
488
469
/// An empty `url` removes the link.489
/// An empty `url` removes the link; one `link_url` refuses changes nothing.470
pub fn set_link(&mut self, range: Range<usize>, url: &str) {490
pub fn set_link(&mut self, range: Range<usize>, url: &str) {471
self.journal = Journal::default();491
self.journal = Journal::default();492
let url = url.trim();493
if !url.is_empty() && link_url(url).is_none() {494
return;495
}472
let link = MarkKind::Link(url.to_owned());496
let link = MarkKind::Link(url.to_owned());473
self.remove_marks(range.clone(), &link);497
self.remove_marks(range.clone(), &link);474
if !url.is_empty() {498
if !url.is_empty() {@@ -478,7 +502,7 @@ impl Draft {478
}502
}479
}503
}480
504
481
/// Returns the offset after the inserted link text.505
/// Returns the offset after the inserted link text; plain text when `link_url` refuses `url`.482
pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize {506
pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize {483
self.journal = Journal::default();507
self.journal = Journal::default();484
self.splice(offset..offset, text, &[]);508
self.splice(offset..offset, text, &[]);@@ -592,8 +616,7 @@ impl Draft {592
LineKind::Text => {616
LineKind::Text => {593
let language = fence_language(&self.text[content.clone()])?;617
let language = fence_language(&self.text[content.clone()])?;594
self.splice(content.clone(), "", &[]);618
self.splice(content.clone(), "", &[]);595
self.lines[index] = LineKind::Code(language);619
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))596
Some(content.start)597
}620
}598
LineKind::Quote if !shift => None,621
LineKind::Quote if !shift => None,599
LineKind::Quote => {622
LineKind::Quote => {@@ -606,11 +629,10 @@ impl Draft {606
let last_of_block = self.lines.get(index + 1) != Some(&kind);629
let last_of_block = self.lines.get(index + 1) != Some(&kind);607
let block_continues_above = index > 0 && self.lines[index - 1] == kind;630
let block_continues_above = index > 0 && self.lines[index - 1] == kind;608
if content.is_empty() && last_of_block && block_continues_above && !shift {631
if content.is_empty() && last_of_block && block_continues_above && !shift {609
self.lines[index] = LineKind::Text;632
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));610
return Some(cursor);611
}633
}612
self.splice(cursor..cursor, "\n", &[]);634
self.splice(cursor..cursor, "\n", &[]);613
Some(cursor + 1)635
Some(self.repair(cursor + 1))614
}636
}615
list => {637
list => {616
if self.text[content.clone()].trim().is_empty() {638
if self.text[content.clone()].trim().is_empty() {@@ -639,12 +661,13 @@ impl Draft {639
let content = self.content_range(index);661
let content = self.content_range(index);640
match &kind {662
match &kind {641
LineKind::Text => None,663
LineKind::Text => None,642
LineKind::Code(_) => {664
LineKind::Code(_) if cursor > line.start && cursor <= content.start => {643
let first_of_block = index == 0 || self.lines[index - 1] != kind;665
let first_of_block = index == 0 || self.lines[index - 1] != kind;644
(cursor == content.start && first_of_block).then(|| {666
if first_of_block {645
self.lines[index] = LineKind::Text;667
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));646
cursor668
}647
})669
self.splice(line.start - 1..content.start, "", &[]);670
Some(self.repair(line.start - 1))648
}671
}649
_ if cursor == line.start && index > 0 => {672
_ if cursor == line.start && index > 0 => {650
self.splice(line.start - 1..content.start, "", &[]);673
self.splice(line.start - 1..content.start, "", &[]);@@ -665,7 +688,7 @@ impl Draft {665
/// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item.688
/// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item.666
pub fn indent(&mut self, range: Range<usize>, outdent: bool) -> bool {689
pub fn indent(&mut self, range: Range<usize>, outdent: bool) -> bool {667
self.journal = Journal::default();690
self.journal = Journal::default();668
let lines = self.line_at(range.start)..=self.line_at(range.end);691
let lines = self.selected_lines(&range);669
if !lines.clone().all(|index| self.lines[index].is_list()) {692
if !lines.clone().all(|index| self.lines[index].is_list()) {670
return false;693
return false;671
}694
}@@ -686,7 +709,7 @@ impl Draft {686
/// All selected lines `kind` already: back to text. Otherwise all become `kind`.709
/// All selected lines `kind` already: back to text. Otherwise all become `kind`.687
pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {710
pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {688
self.journal = Journal::default();711
self.journal = Journal::default();689
let lines = self.line_at(range.start)..=self.line_at(range.end);712
let lines = self.selected_lines(&range);690
let all = lines713
let all = lines691
.clone()714
.clone()692
.all(|index| self.lines[index].same_format(&kind));715
.all(|index| self.lines[index].same_format(&kind));@@ -777,6 +800,7 @@ impl Draft {777
}800
}778
offset += line.content.len() + 1;801
offset += line.content.len() + 1;779
}802
}803
let length_before_markers = self.text.len();780
for (position, line) in lines.iter().enumerate() {804
for (position, line) in lines.iter().enumerate() {781
let first_and_kept = position == 0 && !line_was_empty;805
let first_and_kept = position == 0 && !line_was_empty;782
if first_and_kept || line.kind == self.lines[index + position] {806
if first_and_kept || line.kind == self.lines[index + position] {@@ -784,9 +808,8 @@ impl Draft {784
}808
}785
self.set_line_kind(index + position, line.kind.clone(), line.number, 0);809
self.set_line_kind(index + position, line.kind.clone(), line.number, 0);786
}810
}787
let last = index + lines.len().saturating_sub(1);788
let end =811
let end =789
self.content_range(last).start + lines.last().map_or(0, |line| line.content.len());812
(range.start + joined.len() + self.text.len()).saturating_sub(length_before_markers);790
self.repair(end)813
self.repair(end)791
}814
}792
815
@@ -892,7 +915,15 @@ impl Draft {892
.collect()915
.collect()893
}916
}894
917
918
/// Links with a scheme other than http, https or mailto stay plain text.895
fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {919
fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {920
let kind = match kind {921
MarkKind::Link(url) => match link_url(&url) {922
Some(url) => MarkKind::Link(url),923
None => return,924
},925
other => other,926
};896
if !range.is_empty() {927
if !range.is_empty() {897
self.marks.push(Mark { range, kind });928
self.marks.push(Mark { range, kind });898
self.normalize_marks();929
self.normalize_marks();@@ -1086,11 +1117,19 @@ impl Draft {1086
}1117
}1087
}1118
}1088
1119
1089
/// Lines whose marker was edited away become text; numbered items are renumbered.1120
/// Lines whose marker was edited away become text; numbered items are renumbered; code1121
/// lines get their padding back.1090
fn repair(&mut self, mut cursor: usize) -> usize {1122
fn repair(&mut self, mut cursor: usize) -> usize {1091
for index in 0..self.lines.len() {1123
for index in 0..self.lines.len() {1092
let kind = self.lines[index].clone();1124
let kind = self.lines[index].clone();1093
if matches!(kind, LineKind::Text | LineKind::Code(_)) {1125
if kind == LineKind::Text {1126
continue;1127
}1128
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);1132
}1094
continue;1133
continue;1095
}1134
}1096
let line = self.line_ranges()[index].clone();1135
let line = self.line_ranges()[index].clone();@@ -1128,7 +1167,8 @@ fn marker_text(kind: &LineKind, number: u32) -> String {1128
LineKind::Bullet(depth) => bullet_marker(*depth),1167
LineKind::Bullet(depth) => bullet_marker(*depth),1129
LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),1168
LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),1130
LineKind::Quote => QUOTE_MARKER.to_owned(),1169
LineKind::Quote => QUOTE_MARKER.to_owned(),1131
LineKind::Text | LineKind::Code(_) => String::new(),1170
LineKind::Code(_) => CODE_MARKER.to_owned(),1171
LineKind::Text => String::new(),1132
}1172
}1133
}1173
}1134
1174
@@ -1144,6 +1184,7 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {1144
}1184
}1145
LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),1185
LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),1146
LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),1186
LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),1187
LineKind::Code(_) if line.starts_with(CODE_MARKER) => CODE_MARKER.len(),1147
_ => 0,1188
_ => 0,1148
}1189
}1149
}1190
}@@ -1193,6 +1234,28 @@ fn word_before(text: &str) -> bool {1193
.is_some_and(|character| character.is_alphanumeric())1234
.is_some_and(|character| character.is_alphanumeric())1194
}1235
}1195
1236
1237
/// `https://` added when there is no scheme. `None` for any scheme but http, https and mailto.1238
pub fn link_url(text: &str) -> Option<String> {1239
let text = text.trim();1240
if text.is_empty() || text.contains(char::is_whitespace) {1241
return None;1242
}1243
let lower = text.to_ascii_lowercase();1244
if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {1245
return Some(text.to_owned());1246
}1247
let scheme = text1248
.split_once(':')1249
.map(|(scheme, _)| scheme)1250
.filter(|scheme| {1251
scheme.starts_with(|character: char| character.is_ascii_alphabetic())1252
&& scheme1253
.chars()1254
.all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character))1255
});1256
scheme.is_none().then(|| format!("https://{text}"))1257
}1258
1196
/// The markers of a format closed by the last typed character, relative to `before`.1259
/// The markers of a format closed by the last typed character, relative to `before`.1197
fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {1260
fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {1198
let end = before.len();1261
let end = before.len();@@ -1203,7 +1266,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>1203
return Some((1266
return Some((1204
whole.start()..whole.start() + 1,1267
whole.start()..whole.start() + 1,1205
label.end()..end,1268
label.end()..end,1206
MarkKind::Link(captures[2].to_owned()),1269
MarkKind::Link(link_url(&captures[2])?),1207
));1270
));1208
}1271
}1209
for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {1272
for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {@@ -1476,7 +1539,7 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin1476
return Some((1539
return Some((1477
label.as_str(),1540
label.as_str(),1478
captures.get(0)?.end(),1541
captures.get(0)?.end(),1479
MarkKind::Link(captures[2].to_owned()),1542
MarkKind::Link(link_url(&captures[2])?),1480
));1543
));1481
}1544
}1482
for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {1545
for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {@@ -1727,7 +1790,10 @@ mod tests {1727
assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);1790
assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);1728
let mut linked = typed_draft("[a](u)");1791
let mut linked = typed_draft("[a](u)");1729
typed(&mut linked, "b");1792
typed(&mut linked, "b");1730
assert_eq!(linked.marks(), [mark(0..1, MarkKind::Link("u".into()))]);1793
assert_eq!(1794
linked.marks(),1795
[mark(0..1, MarkKind::Link("https://u".into()))]1796
);1731
}1797
}1732
1798
1733
#[test]1799
#[test]@@ -1874,12 +1940,15 @@ mod tests {1874
fn fence_and_enter_open_a_code_block_that_enter_continues() {1940
fn fence_and_enter_open_a_code_block_that_enter_continues() {1875
let mut draft = typed_draft("```rust");1941
let mut draft = typed_draft("```rust");1876
let cursor = draft.break_line(draft.text().len(), false).unwrap();1942
let cursor = draft.break_line(draft.text().len(), false).unwrap();1877
assert_eq!((draft.text(), cursor), ("", 0));1943
assert_eq!((draft.text(), cursor), (CODE_MARKER, CODE_MARKER.len()));1878
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);1944
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);1879
typed(&mut draft, "fn x() {}");1945
typed(&mut draft, "fn x() {}");1880
let cursor = draft.break_line(draft.text().len(), false).unwrap();1946
let cursor = draft.break_line(draft.text().len(), false).unwrap();1881
assert_eq!(draft.lines().len(), 2);1947
assert_eq!(draft.lines().len(), 2);1882
assert_eq!(draft.break_line(cursor, false), Some(cursor));1948
assert_eq!(1949
draft.break_line(cursor, false),1950
Some(cursor - CODE_MARKER.len())1951
);1883
assert_eq!(draft.lines()[1], LineKind::Text);1952
assert_eq!(draft.lines()[1], LineKind::Text);1884
assert_eq!(1953
assert_eq!(1885
draft.to_html(),1954
draft.to_html(),@@ -1891,9 +1960,9 @@ mod tests {1891
fn markdown_inside_code_stays_literal() {1960
fn markdown_inside_code_stays_literal() {1892
let mut draft = typed_draft("```");1961
let mut draft = typed_draft("```");1893
let cursor = draft.break_line(3, false).unwrap();1962
let cursor = draft.break_line(3, false).unwrap();1894
assert_eq!(cursor, 0);1963
assert_eq!(cursor, CODE_MARKER.len());1895
typed(&mut draft, "a **b**");1964
typed(&mut draft, "a **b**");1896
assert_eq!(draft.text(), "a **b**");1965
assert_eq!(draft.text(), format!("{CODE_MARKER}a **b**"));1897
assert!(draft.marks().is_empty());1966
assert!(draft.marks().is_empty());1898
}1967
}1899
1968
@@ -1989,6 +2058,83 @@ mod tests {1989
assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);2058
assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);1990
}2059
}1991
2060
2061
#[test]2062
fn a_paste_inside_a_line_puts_the_cursor_after_the_pasted_text() {2063
let lines = Draft::from_markdown("**big**").slice(0..usize::MAX);2064
let mut plain = Draft::plain("hello world");2065
assert_eq!(plain.insert_lines(6..6, &lines), 9);2066
assert_eq!(plain.text(), "hello bigworld");2067
let mut item = Draft::from_markdown("- item one");2068
let before_one = bullet_marker(0).len() + "item ".len();2069
assert_eq!(2070
item.insert_lines(before_one..before_one, &lines),2071
before_one + 32072
);2073
}2074
2075
#[test]2076
fn a_selection_ending_at_the_next_line_start_leaves_that_line_alone() {2077
let mut draft = Draft::plain("first\nsecond");2078
assert_eq!(2079
draft.line_state(0..6, &LineKind::Bullet(0)),2080
FormatState::Off2081
);2082
draft.toggle_lines(0..6, LineKind::Bullet(0));2083
assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Text]);2084
let end_of_first = draft.line_ranges()[1].start;2085
assert_eq!(2086
draft.line_state(0..end_of_first, &LineKind::Bullet(0)),2087
FormatState::On2088
);2089
assert!(draft.indent(0..end_of_first, false));2090
assert_eq!(draft.lines()[1], LineKind::Text);2091
}2092
2093
#[test]2094
fn links_only_take_http_https_and_mailto() {2095
assert_eq!(link_url("example.com"), Some("https://example.com".into()));2096
assert_eq!(link_url("mailto:a@b.test"), Some("mailto:a@b.test".into()));2097
assert_eq!(link_url("javascript:alert(1)"), None);2098
assert_eq!(link_url("data:text/html,x"), None);2099
let typed = typed_draft("[x](javascript:alert)");2100
assert!(typed.marks().is_empty());2101
let pasted = Draft::from_markdown("[x](javascript:alert) [y](example.com)");2102
assert_eq!(2103
pasted.marks(),2104
[mark(22..23, MarkKind::Link("https://example.com".into()))]2105
);2106
let mut set = Draft::plain("go");2107
set.set_link(0..2, "javascript:alert(1)");2108
assert!(set.marks().is_empty());2109
let spans = Draft::from_spans(&html_to_spans("<a href=\"javascript:x\">bad</a>"));2110
assert!(spans.marks().is_empty());2111
}2112
2113
#[test]2114
fn code_lines_carry_padding_that_survives_edits_and_stays_out_of_html() {2115
let mut draft = Draft::from_markdown("```\nlet a = 1;\nlet b = 2;\n```");2116
assert_eq!(2117
draft.text(),2118
format!("{CODE_MARKER}let a = 1;\n{CODE_MARKER}let b = 2;")2119
);2120
assert_eq!(draft.to_html(), "<pre>let a = 1;\nlet b = 2;</pre>");2121
let second = draft.content_range(1).start;2122
let cursor = draft.backspace_at_start(second).unwrap();2123
assert_eq!(draft.text(), format!("{CODE_MARKER}let a = 1;let b = 2;"));2124
assert_eq!(cursor, CODE_MARKER.len() + "let a = 1;".len());2125
let cursor = draft.backspace_at_start(CODE_MARKER.len()).unwrap();2126
assert_eq!((draft.lines()[0].clone(), cursor), (LineKind::Text, 0));2127
}2128
2129
#[test]2130
fn in_code_covers_code_lines_and_the_inside_of_inline_code() {2131
let draft = Draft::from_markdown("a `cd` e\n```\nx\n```");2132
assert!(!draft.in_code(2));2133
assert!(draft.in_code(3));2134
assert!(!draft.in_code(4));2135
assert!(draft.in_code(draft.text().len()));2136
}2137
1992
#[test]2138
#[test]1993
fn journal_merges_edits_into_ranges_of_the_old_text() {2139
fn journal_merges_edits_into_ranges_of_the_old_text() {1994
let mut draft = Draft::plain("a **b** c");2140
let mut draft = Draft::plain("a **b** c");@@ -27,7 +27,7 @@ pub use avatars::Avatar;
27
27
pub use card::card_content_text;
28
28
pub use draft::{
29
29
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
30
has_markdown, map_offset, reverse_edits,
30
has_markdown, link_url, map_offset, reverse_edits,
31
31
};
32
32
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
33
33
pub use error::{Error, Result};
@@ -27,7 +27,7 @@ pub use avatars::Avatar;27
pub use card::card_content_text;27
pub use card::card_content_text;28
pub use draft::{28
pub use draft::{29
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,29
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,30
has_markdown, map_offset, reverse_edits,30
has_markdown, link_url, map_offset, reverse_edits,31
};31
};32
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};32
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};33
pub use error::{Error, Result};33
pub use error::{Error, Result};@@ -18,7 +18,7 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
18
18
| `src/input/editor/decorations.rs` | `TextDecorationCollection<M = EditorMode>`, `RangeDecorationCollection<M = EditorMode>`, `create_*_collection` on `impl<M: DecoratedMode>`; `DecorationCollections` / `TrackedDecoration` `pub` + `#[doc(hidden)]` | same API on textarea and editor; default type param keeps editor code unchanged |
19
19
| `src/input/editor/mod.rs`, `src/input/mod.rs` | doc no longer says decorations are editor-only; export `DecoratedMode`, `TextareaExtras` | docs, API |
20
20
| `src/input/editor/display_map/text_wrapper.rs` | lines with inline tokens wrap through `measured_wrap_boundaries` too (`atomic` token ranges, token width + shaped text segments) instead of gpui's `LineWrapper` | mention lines honour font overrides and hanging indent |
21
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()` | rounded inline code pills, full-width code block fill, quote bar |
21
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()`; Block and Bar keep empty ranges (`TrackedDecoration::keeps_empty`) and the index finds them | rounded inline code pills, full-width code block fill, quote bar; a block over one empty line |
22
22
| `src/input/base/element.rs` | `layout_range_decoration_quads()` paints pills, blocks and bars as quads below the fills | rounded corners and borders, which paths cannot draw |
23
23
| `src/input/base/state.rs` | `apply_edits(&[(Range, String)])` on all states | several edits in one undo step without touching inline tokens between them |
24
24
@@ -18,7 +18,7 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in18
| `src/input/editor/decorations.rs` | `TextDecorationCollection<M = EditorMode>`, `RangeDecorationCollection<M = EditorMode>`, `create_*_collection` on `impl<M: DecoratedMode>`; `DecorationCollections` / `TrackedDecoration` `pub` + `#[doc(hidden)]` | same API on textarea and editor; default type param keeps editor code unchanged |18
| `src/input/editor/decorations.rs` | `TextDecorationCollection<M = EditorMode>`, `RangeDecorationCollection<M = EditorMode>`, `create_*_collection` on `impl<M: DecoratedMode>`; `DecorationCollections` / `TrackedDecoration` `pub` + `#[doc(hidden)]` | same API on textarea and editor; default type param keeps editor code unchanged |19
| `src/input/editor/mod.rs`, `src/input/mod.rs` | doc no longer says decorations are editor-only; export `DecoratedMode`, `TextareaExtras` | docs, API |19
| `src/input/editor/mod.rs`, `src/input/mod.rs` | doc no longer says decorations are editor-only; export `DecoratedMode`, `TextareaExtras` | docs, API |20
| `src/input/editor/display_map/text_wrapper.rs` | lines with inline tokens wrap through `measured_wrap_boundaries` too (`atomic` token ranges, token width + shaped text segments) instead of gpui's `LineWrapper` | mention lines honour font overrides and hanging indent |20
| `src/input/editor/display_map/text_wrapper.rs` | lines with inline tokens wrap through `measured_wrap_boundaries` too (`atomic` token ranges, token width + shaped text segments) instead of gpui's `LineWrapper` | mention lines honour font overrides and hanging indent |21
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()` | rounded inline code pills, full-width code block fill, quote bar |21
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()`; Block and Bar keep empty ranges (`TrackedDecoration::keeps_empty`) and the index finds them | rounded inline code pills, full-width code block fill, quote bar; a block over one empty line |22
| `src/input/base/element.rs` | `layout_range_decoration_quads()` paints pills, blocks and bars as quads below the fills | rounded corners and borders, which paths cannot draw |22
| `src/input/base/element.rs` | `layout_range_decoration_quads()` paints pills, blocks and bars as quads below the fills | rounded corners and borders, which paths cannot draw |23
| `src/input/base/state.rs` | `apply_edits(&[(Range, String)])` on all states | several edits in one undo step without touching inline tokens between them |23
| `src/input/base/state.rs` | `apply_edits(&[(Range, String)])` on all states | several edits in one undo step without touching inline tokens between them |24
24
@@ -886,14 +886,13 @@ impl<M: InputModeKind> TextElement<M> {
886
886
) -> Vec<PaintQuad> {
887
887
let state = self.state.read(cx);
888
888
let origin = bounds.origin + point(last_layout.line_number_width, px(0.));
889
let text_end = state.text.len();
890
889
let mut visible_spans: Vec<Range<usize>> = Vec::new();
891
890
for (&offset, line) in last_layout
892
891
.visible_line_byte_offsets
893
892
.iter()
894
893
.zip(last_layout.lines.iter())
895
894
{
896
let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end);
895
let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end + 1);
897
896
if let Some(previous) = visible_spans.last_mut().filter(|span| span.end == offset) {
898
897
previous.end = end;
899
898
} else if offset < end {
@@ -932,8 +931,7 @@ impl<M: InputModeKind> TextElement<M> {
932
931
{
933
932
let height =
934
933
last_layout.line_height * line.wrapped_lines.len().max(1) as f32;
935
let covered = range.contains(&line_start)
936
|| (line_start == range.end && range.end == text_end);
934
let covered = (range.start..=range.end).contains(&line_start);
937
935
if covered {
938
936
top.get_or_insert(y);
939
937
bottom = y + height;
@@ -3858,7 +3856,7 @@ mod tests {
3858
3856
.with_style(RangeDecorationStyle::Pill)
3859
3857
.with_radius(px(4.)),
3860
3858
RangeDecoration::new(3..8).with_style(RangeDecorationStyle::Block),
3861
RangeDecoration::new(8..9)
3859
RangeDecoration::new(9..9)
3862
3860
.with_style(RangeDecorationStyle::Bar)
3863
3861
.with_radius(px(3.)),
3864
3862
],
@@ -886,14 +886,13 @@ impl<M: InputModeKind> TextElement<M> {886
) -> Vec<PaintQuad> {886
) -> Vec<PaintQuad> {887
let state = self.state.read(cx);887
let state = self.state.read(cx);888
let origin = bounds.origin + point(last_layout.line_number_width, px(0.));888
let origin = bounds.origin + point(last_layout.line_number_width, px(0.));889
let text_end = state.text.len();890
let mut visible_spans: Vec<Range<usize>> = Vec::new();889
let mut visible_spans: Vec<Range<usize>> = Vec::new();891
for (&offset, line) in last_layout890
for (&offset, line) in last_layout892
.visible_line_byte_offsets891
.visible_line_byte_offsets893
.iter()892
.iter()894
.zip(last_layout.lines.iter())893
.zip(last_layout.lines.iter())895
{894
{896
let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end);895
let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end + 1);897
if let Some(previous) = visible_spans.last_mut().filter(|span| span.end == offset) {896
if let Some(previous) = visible_spans.last_mut().filter(|span| span.end == offset) {898
previous.end = end;897
previous.end = end;899
} else if offset < end {898
} else if offset < end {@@ -932,8 +931,7 @@ impl<M: InputModeKind> TextElement<M> {932
{931
{933
let height =932
let height =934
last_layout.line_height * line.wrapped_lines.len().max(1) as f32;933
last_layout.line_height * line.wrapped_lines.len().max(1) as f32;935
let covered = range.contains(&line_start)934
let covered = (range.start..=range.end).contains(&line_start);936
|| (line_start == range.end && range.end == text_end);937
if covered {935
if covered {938
top.get_or_insert(y);936
top.get_or_insert(y);939
bottom = y + height;937
bottom = y + height;@@ -3858,7 +3856,7 @@ mod tests {3858
.with_style(RangeDecorationStyle::Pill)3856
.with_style(RangeDecorationStyle::Pill)3859
.with_radius(px(4.)),3857
.with_radius(px(4.)),3860
RangeDecoration::new(3..8).with_style(RangeDecorationStyle::Block),3858
RangeDecoration::new(3..8).with_style(RangeDecorationStyle::Block),3861
RangeDecoration::new(8..9)3859
RangeDecoration::new(9..9)3862
.with_style(RangeDecorationStyle::Bar)3860
.with_style(RangeDecorationStyle::Bar)3863
.with_radius(px(3.)),3861
.with_radius(px(3.)),3864
],3862
],@@ -22,7 +22,7 @@ pub enum RangeDecorationStyle {
22
22
/// A rounded box per visual row around the glyphs, e.g. an inline code pill.
23
23
Pill,
24
24
/// One rounded box across the full text width of every line whose start lies in
25
/// `range.start..=range.end`, e.g. a code block background.
25
/// `range.start..=range.end`, e.g. a code block background. The range may be empty.
26
26
Block,
27
27
/// A bar at the left edge of the lines a [`Self::Block`] would cover, e.g. a quote.
28
28
Bar,
@@ -312,6 +312,10 @@ impl<M: DecoratedMode> RangeDecorationCollection<M> {
312
312
pub trait TrackedDecoration {
313
313
fn range(&self) -> &Range<usize>;
314
314
fn range_mut(&mut self) -> &mut Range<usize>;
315
/// An empty range still means something, e.g. a block over one empty line.
316
fn keeps_empty(&self) -> bool {
317
false
318
}
315
319
}
316
320
317
321
impl TrackedDecoration for TextDecoration {
@@ -330,6 +334,12 @@ impl TrackedDecoration for RangeDecoration {
330
334
fn range_mut(&mut self) -> &mut Range<usize> {
331
335
&mut self.range
332
336
}
337
fn keeps_empty(&self) -> bool {
338
matches!(
339
self.style,
340
RangeDecorationStyle::Block | RangeDecorationStyle::Bar
341
)
342
}
333
343
}
334
344
335
345
/// A balanced interval index over stable insertion-order entries. Each midpoint
@@ -378,14 +388,16 @@ impl DecorationIndex {
378
388
return 0;
379
389
}
380
390
let mid = span.start + span.len() / 2;
381
if self.max_ends[mid] <= range.start {
391
if self.max_ends[mid] < range.start {
382
392
return 1;
383
393
}
384
394
let mut visited = 1 + self.query(decorations, span.start..mid, range, matches);
385
395
let ix = self.indices[mid];
386
396
let candidate = decorations[ix].range();
387
397
if candidate.start < range.end {
388
if candidate.end > range.start {
398
if candidate.end > range.start
399
|| (candidate.is_empty() && candidate.start == range.start)
400
{
389
401
matches.push(ix);
390
402
}
391
403
visited += self.query(decorations, mid + 1..span.end, range, matches);
@@ -467,7 +479,7 @@ impl<T: TrackedDecoration> DecorationCollections<T> {
467
479
entry.decorations.retain_mut(|decoration| {
468
480
*decoration.range_mut() =
469
481
adjust_range_for_edit(decoration.range(), edited_range, inserted_len);
470
let keep = !decoration.range().is_empty();
482
let keep = !decoration.range().is_empty() || decoration.keeps_empty();
471
483
remap.push(if keep { retained } else { usize::MAX });
472
484
retained += usize::from(keep);
473
485
keep
@@ -670,12 +682,13 @@ fn normalize<T: TrackedDecoration>(text: &Rope, decorations: Vec<T>) -> Vec<T> {
670
682
.filter_map(|mut decoration| {
671
683
// Reject reversed ranges before clipping, which could otherwise turn a
672
684
// reversed pair within a multibyte character into a nonempty range.
673
if decoration.range().is_empty() {
685
let reversed = decoration.range().start > decoration.range().end;
686
if reversed || (decoration.range().is_empty() && !decoration.keeps_empty()) {
674
687
return None;
675
688
}
676
689
let range = text.clip_offset(decoration.range().start, Bias::Left)
677
690
..text.clip_offset(decoration.range().end, Bias::Right);
678
if range.is_empty() {
691
if range.is_empty() && !decoration.keeps_empty() {
679
692
return None;
680
693
}
681
694
*decoration.range_mut() = range;
@@ -22,7 +22,7 @@ pub enum RangeDecorationStyle {22
/// A rounded box per visual row around the glyphs, e.g. an inline code pill.22
/// A rounded box per visual row around the glyphs, e.g. an inline code pill.23
Pill,23
Pill,24
/// One rounded box across the full text width of every line whose start lies in24
/// One rounded box across the full text width of every line whose start lies in25
/// `range.start..=range.end`, e.g. a code block background.25
/// `range.start..=range.end`, e.g. a code block background. The range may be empty.26
Block,26
Block,27
/// A bar at the left edge of the lines a [`Self::Block`] would cover, e.g. a quote.27
/// A bar at the left edge of the lines a [`Self::Block`] would cover, e.g. a quote.28
Bar,28
Bar,@@ -312,6 +312,10 @@ impl<M: DecoratedMode> RangeDecorationCollection<M> {312
pub trait TrackedDecoration {312
pub trait TrackedDecoration {313
fn range(&self) -> &Range<usize>;313
fn range(&self) -> &Range<usize>;314
fn range_mut(&mut self) -> &mut Range<usize>;314
fn range_mut(&mut self) -> &mut Range<usize>;315
/// An empty range still means something, e.g. a block over one empty line.316
fn keeps_empty(&self) -> bool {317
false318
}315
}319
}316
320
317
impl TrackedDecoration for TextDecoration {321
impl TrackedDecoration for TextDecoration {@@ -330,6 +334,12 @@ impl TrackedDecoration for RangeDecoration {330
fn range_mut(&mut self) -> &mut Range<usize> {334
fn range_mut(&mut self) -> &mut Range<usize> {331
&mut self.range335
&mut self.range332
}336
}337
fn keeps_empty(&self) -> bool {338
matches!(339
self.style,340
RangeDecorationStyle::Block | RangeDecorationStyle::Bar341
)342
}333
}343
}334
344
335
/// A balanced interval index over stable insertion-order entries. Each midpoint345
/// A balanced interval index over stable insertion-order entries. Each midpoint@@ -378,14 +388,16 @@ impl DecorationIndex {378
return 0;388
return 0;379
}389
}380
let mid = span.start + span.len() / 2;390
let mid = span.start + span.len() / 2;381
if self.max_ends[mid] <= range.start {391
if self.max_ends[mid] < range.start {382
return 1;392
return 1;383
}393
}384
let mut visited = 1 + self.query(decorations, span.start..mid, range, matches);394
let mut visited = 1 + self.query(decorations, span.start..mid, range, matches);385
let ix = self.indices[mid];395
let ix = self.indices[mid];386
let candidate = decorations[ix].range();396
let candidate = decorations[ix].range();387
if candidate.start < range.end {397
if candidate.start < range.end {388
if candidate.end > range.start {398
if candidate.end > range.start399
|| (candidate.is_empty() && candidate.start == range.start)400
{389
matches.push(ix);401
matches.push(ix);390
}402
}391
visited += self.query(decorations, mid + 1..span.end, range, matches);403
visited += self.query(decorations, mid + 1..span.end, range, matches);@@ -467,7 +479,7 @@ impl<T: TrackedDecoration> DecorationCollections<T> {467
entry.decorations.retain_mut(|decoration| {479
entry.decorations.retain_mut(|decoration| {468
*decoration.range_mut() =480
*decoration.range_mut() =469
adjust_range_for_edit(decoration.range(), edited_range, inserted_len);481
adjust_range_for_edit(decoration.range(), edited_range, inserted_len);470
let keep = !decoration.range().is_empty();482
let keep = !decoration.range().is_empty() || decoration.keeps_empty();471
remap.push(if keep { retained } else { usize::MAX });483
remap.push(if keep { retained } else { usize::MAX });472
retained += usize::from(keep);484
retained += usize::from(keep);473
keep485
keep@@ -670,12 +682,13 @@ fn normalize<T: TrackedDecoration>(text: &Rope, decorations: Vec<T>) -> Vec<T> {670
.filter_map(|mut decoration| {682
.filter_map(|mut decoration| {671
// Reject reversed ranges before clipping, which could otherwise turn a683
// Reject reversed ranges before clipping, which could otherwise turn a672
// reversed pair within a multibyte character into a nonempty range.684
// reversed pair within a multibyte character into a nonempty range.673
if decoration.range().is_empty() {685
let reversed = decoration.range().start > decoration.range().end;686
if reversed || (decoration.range().is_empty() && !decoration.keeps_empty()) {674
return None;687
return None;675
}688
}676
let range = text.clip_offset(decoration.range().start, Bias::Left)689
let range = text.clip_offset(decoration.range().start, Bias::Left)677
..text.clip_offset(decoration.range().end, Bias::Right);690
..text.clip_offset(decoration.range().end, Bias::Right);678
if range.is_empty() {691
if range.is_empty() && !decoration.keeps_empty() {679
return None;692
return None;680
}693
}681
*decoration.range_mut() = range;694
*decoration.range_mut() = range;