feat(composer): link URLs while typing and pasting
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -499,9 +499,21 @@ impl Composer {
499
499
if typed.is_some() && self.convert_markdown(cursor, window, cx) {
500
500
return;
501
501
}
502
if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
503
return;
504
}
502
505
self.convert_emoji(typed, cursor, window, cx);
503
506
}
504
507
508
fn convert_link(&mut self, cursor: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
509
let before = self.draft.clone();
510
if !self.draft.autolink_typed(cursor) {
511
return false;
512
}
513
self.finish_conversion(before, cursor, window, cx);
514
true
515
}
516
505
517
fn convert_markdown(
506
518
&mut self,
507
519
cursor: usize,
@@ -579,7 +591,11 @@ impl Composer {
579
591
};
580
592
let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);
581
593
let cursor = self.draft.insert_lines(start..cursor, &lines);
594
let changed_text = self.draft.text().get(start..cursor) != Some(pasted.as_str());
582
595
self.commit(Some(cursor), window, cx);
596
if !changed_text {
597
return true;
598
}
583
599
self.paste_hint = Some(cx.spawn(async move |this, cx| {
584
600
cx.background_executor().timer(PASTE_HINT_DURATION).await;
585
601
this.update(cx, |this, cx| {
@@ -952,6 +968,7 @@ impl Composer {
952
968
}
953
969
match self.draft.break_line(selection.start, shift) {
954
970
Some(cursor) => {
971
self.draft.link_word_ending_at(selection.start);
955
972
self.commit(Some(cursor), window, cx);
956
973
true
957
974
}
@@ -2459,6 +2476,118 @@ mod tests {
2459
2476
);
2460
2477
}
2461
2478
2479
#[gpui_kit::test]
2480
fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {
2481
use teams_core::{Mark, MarkKind};
2482
2483
let mut typist = typist(cx);
2484
typist.type_text("see https://a.b ");
2485
assert_eq!(typist.value(), "see https://a.b ");
2486
assert_eq!(
2487
typist.draft().marks(),
2488
[Mark {
2489
range: 4..15,
2490
kind: MarkKind::Link("https://a.b".into())
2491
}]
2492
);
2493
typist.press("backspace");
2494
assert_eq!(typist.value(), "see https://a.b ");
2495
assert!(typist.draft().marks().is_empty());
2496
}
2497
2498
#[gpui_kit::test]
2499
fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {
2500
let mut typist = typist(cx);
2501
typist.type_text("https://a.b ");
2502
assert_eq!(typist.draft().marks().len(), 1);
2503
typist.press("ctrl-z");
2504
assert!(typist.draft().marks().is_empty());
2505
}
2506
2507
#[gpui_kit::test]
2508
fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
2509
use teams_core::{Mark, MarkKind};
2510
2511
let mut typist = typist(cx);
2512
typist
2513
.cx
2514
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(
2515
"x https://a.b y".to_owned(),
2516
));
2517
typist.press("ctrl-v");
2518
assert_eq!(typist.value(), "x https://a.b y");
2519
assert_eq!(
2520
typist.draft().marks(),
2521
[Mark {
2522
range: 2..13,
2523
kind: MarkKind::Link("https://a.b".into())
2524
}]
2525
);
2526
typist.press("ctrl-z");
2527
assert_eq!(typist.value(), "x https://a.b y");
2528
assert!(typist.draft().marks().is_empty());
2529
}
2530
2531
#[gpui_kit::test]
2532
fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {
2533
use teams_core::{Mark, MarkKind};
2534
2535
let mut typist = typist(cx);
2536
typist.type_text("https://a.b x");
2537
typist.press("home");
2538
typist.press("shift-right ".repeat(11).trim_end());
2539
typist.press("ctrl-k");
2540
typist.type_text("other.de");
2541
typist.press("enter");
2542
assert_eq!(
2543
typist.draft().marks(),
2544
[Mark {
2545
range: 0..11,
2546
kind: MarkKind::Link("https://other.de".into())
2547
}]
2548
);
2549
typist.press("ctrl-k backspace enter");
2550
assert!(typist.draft().marks().is_empty());
2551
assert_eq!(typist.value(), "https://a.b x");
2552
}
2553
2554
#[gpui_kit::test]
2555
fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {
2556
use teams_core::{Mark, MarkKind};
2557
2558
let mut typist = typist(cx);
2559
typist.type_text("- https://a.b");
2560
typist.press("enter");
2561
assert_eq!(typist.value(), "• https://a.b\n• ");
2562
assert_eq!(
2563
typist.draft().marks(),
2564
[Mark {
2565
range: 4..15,
2566
kind: MarkKind::Link("https://a.b".into())
2567
}]
2568
);
2569
}
2570
2571
#[gpui_kit::test]
2572
fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {
2573
let mut typist = typist(cx);
2574
typist
2575
.cx
2576
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(
2577
"x https://a.b y".to_owned(),
2578
));
2579
typist.press("ctrl-v");
2580
assert_eq!(typist.draft().marks().len(), 1);
2581
let composer = typist.composer.clone();
2582
assert!(
2583
typist
2584
.cx
2585
.update(|cx| composer.read(cx).paste_hint.is_none())
2586
);
2587
typist.press("ctrl-z");
2588
assert!(typist.draft().marks().is_empty());
2589
}
2590
2462
2591
#[gpui_kit::test]
2463
2592
fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
2464
2593
let mut typist = typist(cx);
@@ -499,9 +499,21 @@ impl Composer {499
if typed.is_some() && self.convert_markdown(cursor, window, cx) {499
if typed.is_some() && self.convert_markdown(cursor, window, cx) {500
return;500
return;501
}501
}502
if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {503
return;504
}502
self.convert_emoji(typed, cursor, window, cx);505
self.convert_emoji(typed, cursor, window, cx);503
}506
}504
507
508
fn convert_link(&mut self, cursor: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {509
let before = self.draft.clone();510
if !self.draft.autolink_typed(cursor) {511
return false;512
}513
self.finish_conversion(before, cursor, window, cx);514
true515
}516
505
fn convert_markdown(517
fn convert_markdown(506
&mut self,518
&mut self,507
cursor: usize,519
cursor: usize,@@ -579,7 +591,11 @@ impl Composer {579
};591
};580
let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);592
let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);581
let cursor = self.draft.insert_lines(start..cursor, &lines);593
let cursor = self.draft.insert_lines(start..cursor, &lines);594
let changed_text = self.draft.text().get(start..cursor) != Some(pasted.as_str());582
self.commit(Some(cursor), window, cx);595
self.commit(Some(cursor), window, cx);596
if !changed_text {597
return true;598
}583
self.paste_hint = Some(cx.spawn(async move |this, cx| {599
self.paste_hint = Some(cx.spawn(async move |this, cx| {584
cx.background_executor().timer(PASTE_HINT_DURATION).await;600
cx.background_executor().timer(PASTE_HINT_DURATION).await;585
this.update(cx, |this, cx| {601
this.update(cx, |this, cx| {@@ -952,6 +968,7 @@ impl Composer {952
}968
}953
match self.draft.break_line(selection.start, shift) {969
match self.draft.break_line(selection.start, shift) {954
Some(cursor) => {970
Some(cursor) => {971
self.draft.link_word_ending_at(selection.start);955
self.commit(Some(cursor), window, cx);972
self.commit(Some(cursor), window, cx);956
true973
true957
}974
}@@ -2459,6 +2476,118 @@ mod tests {2459
);2476
);2460
}2477
}2461
2478
2479
#[gpui_kit::test]2480
fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {2481
use teams_core::{Mark, MarkKind};2482
2483
let mut typist = typist(cx);2484
typist.type_text("see https://a.b ");2485
assert_eq!(typist.value(), "see https://a.b ");2486
assert_eq!(2487
typist.draft().marks(),2488
[Mark {2489
range: 4..15,2490
kind: MarkKind::Link("https://a.b".into())2491
}]2492
);2493
typist.press("backspace");2494
assert_eq!(typist.value(), "see https://a.b ");2495
assert!(typist.draft().marks().is_empty());2496
}2497
2498
#[gpui_kit::test]2499
fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {2500
let mut typist = typist(cx);2501
typist.type_text("https://a.b ");2502
assert_eq!(typist.draft().marks().len(), 1);2503
typist.press("ctrl-z");2504
assert!(typist.draft().marks().is_empty());2505
}2506
2507
#[gpui_kit::test]2508
fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {2509
use teams_core::{Mark, MarkKind};2510
2511
let mut typist = typist(cx);2512
typist2513
.cx2514
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(2515
"x https://a.b y".to_owned(),2516
));2517
typist.press("ctrl-v");2518
assert_eq!(typist.value(), "x https://a.b y");2519
assert_eq!(2520
typist.draft().marks(),2521
[Mark {2522
range: 2..13,2523
kind: MarkKind::Link("https://a.b".into())2524
}]2525
);2526
typist.press("ctrl-z");2527
assert_eq!(typist.value(), "x https://a.b y");2528
assert!(typist.draft().marks().is_empty());2529
}2530
2531
#[gpui_kit::test]2532
fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {2533
use teams_core::{Mark, MarkKind};2534
2535
let mut typist = typist(cx);2536
typist.type_text("https://a.b x");2537
typist.press("home");2538
typist.press("shift-right ".repeat(11).trim_end());2539
typist.press("ctrl-k");2540
typist.type_text("other.de");2541
typist.press("enter");2542
assert_eq!(2543
typist.draft().marks(),2544
[Mark {2545
range: 0..11,2546
kind: MarkKind::Link("https://other.de".into())2547
}]2548
);2549
typist.press("ctrl-k backspace enter");2550
assert!(typist.draft().marks().is_empty());2551
assert_eq!(typist.value(), "https://a.b x");2552
}2553
2554
#[gpui_kit::test]2555
fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {2556
use teams_core::{Mark, MarkKind};2557
2558
let mut typist = typist(cx);2559
typist.type_text("- https://a.b");2560
typist.press("enter");2561
assert_eq!(typist.value(), "• https://a.b\n• ");2562
assert_eq!(2563
typist.draft().marks(),2564
[Mark {2565
range: 4..15,2566
kind: MarkKind::Link("https://a.b".into())2567
}]2568
);2569
}2570
2571
#[gpui_kit::test]2572
fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {2573
let mut typist = typist(cx);2574
typist2575
.cx2576
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(2577
"x https://a.b y".to_owned(),2578
));2579
typist.press("ctrl-v");2580
assert_eq!(typist.draft().marks().len(), 1);2581
let composer = typist.composer.clone();2582
assert!(2583
typist2584
.cx2585
.update(|cx| composer.read(cx).paste_hint.is_none())2586
);2587
typist.press("ctrl-z");2588
assert!(typist.draft().marks().is_empty());2589
}2590
2462
#[gpui_kit::test]2591
#[gpui_kit::test]2463
fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {2592
fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {2464
let mut typist = typist(cx);2593
let mut typist = typist(cx);@@ -11,6 +11,8 @@ pub const MAX_DEPTH: u8 = 2;
11
11
const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12
12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13
13
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
14
const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"];
15
const AUTOLINK_TRAILING: &str = ".,;:!?'\"";
14
16
const FENCE: &str = "```";
15
17
const MARKDOWN_INDENT: usize = 2;
16
18
@@ -533,7 +535,9 @@ impl Draft {
533
535
kinds = typing.apply(kinds);
534
536
}
535
537
let marker = self.marker_range(self.line_at(start));
538
let auto_urls = self.auto_link_urls(&(start..old_end));
536
539
self.splice(start..old_end, &replacement, &kinds);
540
self.retarget_links(&auto_urls, &(start..start + replacement.len()));
537
541
self.journal = Journal::default();
538
542
let mut cursor = cursor.min(self.text.len());
539
543
let typed_into_marker = old_end == start
@@ -601,6 +605,51 @@ impl Draft {
601
605
))
602
606
}
603
607
608
/// A URL typed just before the space or newline at `cursor - 1` becomes a link.
609
pub fn autolink_typed(&mut self, cursor: usize) -> bool {
610
self.journal = Journal::default();
611
let Some(end) = cursor.checked_sub(1) else {
612
return false;
613
};
614
if !matches!(self.text.get(end..cursor), Some(" " | "\n")) {
615
return false;
616
}
617
self.link_word_ending_at(end)
618
}
619
620
/// Links the URL in the word that ends at `end`. Leaves the journal alone.
621
pub fn link_word_ending_at(&mut self, end: usize) -> bool {
622
let index = self.line_at(end);
623
if matches!(self.lines[index], LineKind::Code(_)) {
624
return false;
625
}
626
let content_start = self.content_range(index).start;
627
let Some(before) = self.text.get(content_start..end) else {
628
return false;
629
};
630
let word_start = before.rfind(char::is_whitespace).map_or(0, |at| {
631
at + before[at..].chars().next().map_or(1, char::len_utf8)
632
});
633
let word = &before[word_start..];
634
let Some(found) = word.char_indices().find_map(|(offset, _)| {
635
let previous = word[..offset].chars().next_back();
636
let length = bare_url_at(&word[offset..], previous)?;
637
Some(offset..offset + length)
638
}) else {
639
return false;
640
};
641
let range =
642
content_start + word_start + found.start..content_start + word_start + found.end;
643
let taken = self.marks.iter().any(|mark| {
644
matches!(mark.kind, MarkKind::Code | MarkKind::Link(_)) && overlaps(&mark.range, &range)
645
});
646
let Some(url) = link_url(&self.text[range.clone()]).filter(|_| !taken) else {
647
return false;
648
};
649
self.add_mark(range, MarkKind::Link(url));
650
true
651
}
652
604
653
/// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence.
605
654
/// `None` leaves the key to the caller: send, or a plain newline.
606
655
pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option<usize> {
@@ -942,6 +991,46 @@ impl Draft {
942
991
kinds
943
992
}
944
993
994
fn auto_link_urls(&self, range: &Range<usize>) -> Vec<String> {
995
self.marks
996
.iter()
997
.filter_map(|mark| match &mark.kind {
998
MarkKind::Link(url)
999
if mark.range.start <= range.end
1000
&& range.start <= mark.range.end
1001
&& autolink_prefix(&self.text[mark.range.clone()]).is_some()
1002
&& link_url(&self.text[mark.range.clone()]).as_ref() == Some(url) =>
1003
{
1004
Some(url.clone())
1005
}
1006
_ => None,
1007
})
1008
.collect()
1009
}
1010
1011
fn retarget_links(&mut self, auto_urls: &[String], edited: &Range<usize>) {
1012
if auto_urls.is_empty() {
1013
return;
1014
}
1015
let mut kept = Vec::with_capacity(self.marks.len());
1016
for mark in std::mem::take(&mut self.marks) {
1017
let touched = mark.range.start <= edited.end && edited.start <= mark.range.end;
1018
match &mark.kind {
1019
MarkKind::Link(url) if touched && auto_urls.contains(url) => {
1020
if let Some(new_url) = link_url(&self.text[mark.range.clone()]) {
1021
kept.push(Mark {
1022
range: mark.range,
1023
kind: MarkKind::Link(new_url),
1024
});
1025
}
1026
}
1027
_ => kept.push(mark),
1028
}
1029
}
1030
self.marks = kept;
1031
self.normalize_marks();
1032
}
1033
945
1034
fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {
946
1035
(self.line_at(range.start)..=self.line_at(range.end))
947
1036
.map(|index| {
@@ -1283,6 +1372,39 @@ pub fn link_url(text: &str) -> Option<String> {
1283
1372
scheme.is_none().then(|| format!("https://{text}"))
1284
1373
}
1285
1374
1375
fn autolink_prefix(text: &str) -> Option<&'static str> {
1376
AUTOLINK_PREFIXES.into_iter().find(|prefix| {
1377
text.get(..prefix.len())
1378
.is_some_and(|head| head.eq_ignore_ascii_case(prefix))
1379
})
1380
}
1381
1382
/// Length of the URL at the start of `rest`, when `previous` does not continue a word.
1383
fn bare_url_at(rest: &str, previous: Option<char>) -> Option<usize> {
1384
if previous.is_some_and(char::is_alphanumeric) {
1385
return None;
1386
}
1387
bare_url_len(rest)
1388
}
1389
1390
/// Length of the URL a word starts with, without trailing punctuation.
1391
fn bare_url_len(rest: &str) -> Option<usize> {
1392
let word = &rest[..rest.find(char::is_whitespace).unwrap_or(rest.len())];
1393
let prefix = autolink_prefix(word)?;
1394
let mut end = word.len();
1395
while let Some(last) = word[..end].chars().next_back() {
1396
let trailing = match last {
1397
')' => word[..end].matches(')').count() > word[..end].matches('(').count(),
1398
other => AUTOLINK_TRAILING.contains(other),
1399
};
1400
if !trailing {
1401
break;
1402
}
1403
end -= last.len_utf8();
1404
}
1405
(end > prefix.len()).then_some(end)
1406
}
1407
1286
1408
/// The markers of a format closed by the last typed character, relative to `before`.
1287
1409
fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
1288
1410
let end = before.len();
@@ -1528,20 +1650,34 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1528
1650
fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1529
1651
let mut text = String::with_capacity(source.len());
1530
1652
let mut marks = Vec::new();
1531
parse_into(source, &mut text, &mut marks);
1653
parse_into(source, &mut text, &mut marks, true);
1532
1654
(text, marks)
1533
1655
}
1534
1656
1535
fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>) {
1657
fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>, autolink: bool) {
1536
1658
let mut rest = source;
1537
1659
let mut previous: Option<char> = None;
1538
1660
while let Some(character) = rest.chars().next() {
1661
if autolink
1662
&& let Some(length) = bare_url_at(rest, previous)
1663
&& let Some(url) = link_url(&rest[..length])
1664
{
1665
let start = text.len();
1666
text.push_str(&rest[..length]);
1667
marks.push(Mark {
1668
range: start..text.len(),
1669
kind: MarkKind::Link(url),
1670
});
1671
previous = rest[..length].chars().next_back();
1672
rest = &rest[length..];
1673
continue;
1674
}
1539
1675
if let Some((inner, consumed, kind)) = inline_at(rest, previous) {
1540
1676
let start = text.len();
1541
if kind == MarkKind::Code {
1542
text.push_str(inner);
1543
} else {
1544
parse_into(inner, text, marks);
1677
match kind {
1678
MarkKind::Code => text.push_str(inner),
1679
MarkKind::Link(_) => parse_into(inner, text, marks, false),
1680
_ => parse_into(inner, text, marks, autolink),
1545
1681
}
1546
1682
marks.push(Mark {
1547
1683
range: start..text.len(),
@@ -1804,6 +1940,182 @@ mod tests {
1804
1940
);
1805
1941
}
1806
1942
1943
fn typed_autolinked(draft: &mut Draft, text: &str) {
1944
for character in text.chars() {
1945
let mut next = draft.text().to_owned();
1946
next.push(character);
1947
let cursor = next.len();
1948
draft.apply_edit(&next, cursor, None);
1949
draft.autolink_typed(cursor);
1950
draft.take_edits();
1951
}
1952
}
1953
1954
fn autolinked(text: &str) -> Draft {
1955
let mut draft = Draft::default();
1956
typed_autolinked(&mut draft, text);
1957
draft
1958
}
1959
1960
fn edited(draft: &mut Draft, range: Range<usize>, replacement: &str) {
1961
let mut next = draft.text().to_owned();
1962
next.replace_range(range.clone(), replacement);
1963
draft.apply_edit(&next, range.start + replacement.len(), None);
1964
}
1965
1966
#[test]
1967
fn typed_url_followed_by_a_space_becomes_a_link() {
1968
let draft = autolinked("https://example.com ");
1969
assert_eq!(
1970
draft.marks(),
1971
[mark(0..19, MarkKind::Link("https://example.com".into()))]
1972
);
1973
}
1974
1975
#[test]
1976
fn typed_url_followed_by_a_newline_becomes_a_link() {
1977
let draft = autolinked("a mailto:x@y.de\n");
1978
assert_eq!(
1979
draft.marks(),
1980
[mark(2..15, MarkKind::Link("mailto:x@y.de".into()))]
1981
);
1982
}
1983
1984
#[test]
1985
fn autolink_leaves_trailing_punctuation_out_and_adds_the_scheme() {
1986
let draft = autolinked("see www.x.de. ");
1987
assert_eq!(
1988
draft.marks(),
1989
[mark(4..12, MarkKind::Link("https://www.x.de".into()))]
1990
);
1991
let wiki = autolinked("https://a.b/x_(y) ");
1992
assert_eq!(
1993
wiki.marks(),
1994
[mark(0..17, MarkKind::Link("https://a.b/x_(y)".into()))]
1995
);
1996
let bracketed = autolinked("https://a.b) ");
1997
assert_eq!(
1998
bracketed.marks(),
1999
[mark(0..11, MarkKind::Link("https://a.b".into()))]
2000
);
2001
}
2002
2003
#[test]
2004
fn autolink_starts_after_any_non_alphanumeric_character() {
2005
let bracketed = autolinked("(https://a.b) ");
2006
assert_eq!(
2007
bracketed.marks(),
2008
[mark(1..12, MarkKind::Link("https://a.b".into()))]
2009
);
2010
let quoted = autolinked("\"www.x.de\" ");
2011
assert_eq!(
2012
quoted.marks(),
2013
[mark(1..9, MarkKind::Link("https://www.x.de".into()))]
2014
);
2015
let colon = autolinked("see:https://a.b ");
2016
assert_eq!(
2017
colon.marks(),
2018
[mark(4..15, MarkKind::Link("https://a.b".into()))]
2019
);
2020
assert!(autolinked("xhttps://a.b ").marks().is_empty());
2021
}
2022
2023
#[test]
2024
fn a_link_labelled_with_a_bare_domain_keeps_its_url_when_relabelled() {
2025
let mut draft = Draft::plain("example.com");
2026
draft.set_link(0..11, "example.com");
2027
edited(&mut draft, 0..11, "our site");
2028
assert_eq!(
2029
draft.marks(),
2030
[mark(0..8, MarkKind::Link("https://example.com".into()))]
2031
);
2032
}
2033
2034
#[test]
2035
fn autolink_skips_plain_words_code_and_existing_links() {
2036
assert!(autolinked("example.com ").marks().is_empty());
2037
assert!(autolinked("http:// ").marks().is_empty());
2038
let mut block = Draft::from_markdown("```\nhttps://a.b");
2039
typed_autolinked(&mut block, " ");
2040
assert!(block.marks().is_empty());
2041
let mut code = Draft::plain("https://a.b");
2042
code.toggle(0..11, MarkKind::Code);
2043
typed_autolinked(&mut code, " ");
2044
assert_eq!(code.marks(), [mark(0..11, MarkKind::Code)]);
2045
let mut linked = Draft::plain("https://a.b");
2046
linked.set_link(0..11, "https://other.de");
2047
typed_autolinked(&mut linked, " ");
2048
assert_eq!(
2049
linked.marks(),
2050
[mark(0..11, MarkKind::Link("https://other.de".into()))]
2051
);
2052
}
2053
2054
#[test]
2055
fn markdown_import_links_bare_urls_outside_code_and_labels() {
2056
let draft = Draft::from_markdown("go to https://a.b now");
2057
assert_eq!(
2058
draft.marks(),
2059
[mark(6..17, MarkKind::Link("https://a.b".into()))]
2060
);
2061
assert_eq!(
2062
Draft::from_markdown("run `https://a.b` now").marks(),
2063
[mark(4..15, MarkKind::Code)]
2064
);
2065
let labelled = Draft::from_markdown("[https://a.b](https://c.d)");
2066
assert_eq!(
2067
labelled.marks(),
2068
[mark(0..11, MarkKind::Link("https://c.d".into()))]
2069
);
2070
assert!(has_markdown("x https://a.b y"));
2071
}
2072
2073
#[test]
2074
fn editing_an_auto_link_moves_its_url() {
2075
let mut draft = autolinked("https://a.bc ");
2076
edited(&mut draft, 11..12, "d");
2077
assert_eq!(
2078
draft.marks(),
2079
[mark(0..12, MarkKind::Link("https://a.bd".into()))]
2080
);
2081
edited(&mut draft, 11..11, "e");
2082
assert_eq!(
2083
draft.marks(),
2084
[mark(0..13, MarkKind::Link("https://a.bed".into()))]
2085
);
2086
}
2087
2088
#[test]
2089
fn editing_a_labelled_link_keeps_its_url() {
2090
let mut draft = typed_draft("[docs](https://example.com)");
2091
edited(&mut draft, 2..2, "x");
2092
assert_eq!(
2093
draft.marks(),
2094
[mark(0..5, MarkKind::Link("https://example.com".into()))]
2095
);
2096
}
2097
2098
#[test]
2099
fn breaking_an_auto_link_into_non_url_text_removes_it() {
2100
let mut draft = autolinked("https://a.bc ");
2101
edited(&mut draft, 9..9, " ");
2102
assert!(draft.marks().is_empty());
2103
}
2104
2105
#[test]
2106
fn an_auto_link_can_be_relabelled_or_unlinked() {
2107
let mut draft = autolinked("https://a.bc ");
2108
assert_eq!(draft.link_in(0..4), Some("https://a.bc".into()));
2109
draft.set_link(0..12, "https://other.de");
2110
assert_eq!(
2111
draft.marks(),
2112
[mark(0..12, MarkKind::Link("https://other.de".into()))]
2113
);
2114
edited(&mut draft, 12..12, "x");
2115
draft.set_link(0..12, "");
2116
assert!(draft.marks().is_empty());
2117
}
2118
1807
2119
#[test]
1808
2120
fn snake_case_and_spaced_stars_stay_text() {
1809
2121
assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");
@@ -11,6 +11,8 @@ 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 LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];13
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];14
const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"];15
const AUTOLINK_TRAILING: &str = ".,;:!?'\"";14
const FENCE: &str = "```";16
const FENCE: &str = "```";15
const MARKDOWN_INDENT: usize = 2;17
const MARKDOWN_INDENT: usize = 2;16
18
@@ -533,7 +535,9 @@ impl Draft {533
kinds = typing.apply(kinds);535
kinds = typing.apply(kinds);534
}536
}535
let marker = self.marker_range(self.line_at(start));537
let marker = self.marker_range(self.line_at(start));538
let auto_urls = self.auto_link_urls(&(start..old_end));536
self.splice(start..old_end, &replacement, &kinds);539
self.splice(start..old_end, &replacement, &kinds);540
self.retarget_links(&auto_urls, &(start..start + replacement.len()));537
self.journal = Journal::default();541
self.journal = Journal::default();538
let mut cursor = cursor.min(self.text.len());542
let mut cursor = cursor.min(self.text.len());539
let typed_into_marker = old_end == start543
let typed_into_marker = old_end == start@@ -601,6 +605,51 @@ impl Draft {601
))605
))602
}606
}603
607
608
/// A URL typed just before the space or newline at `cursor - 1` becomes a link.609
pub fn autolink_typed(&mut self, cursor: usize) -> bool {610
self.journal = Journal::default();611
let Some(end) = cursor.checked_sub(1) else {612
return false;613
};614
if !matches!(self.text.get(end..cursor), Some(" " | "\n")) {615
return false;616
}617
self.link_word_ending_at(end)618
}619
620
/// Links the URL in the word that ends at `end`. Leaves the journal alone.621
pub fn link_word_ending_at(&mut self, end: usize) -> bool {622
let index = self.line_at(end);623
if matches!(self.lines[index], LineKind::Code(_)) {624
return false;625
}626
let content_start = self.content_range(index).start;627
let Some(before) = self.text.get(content_start..end) else {628
return false;629
};630
let word_start = before.rfind(char::is_whitespace).map_or(0, |at| {631
at + before[at..].chars().next().map_or(1, char::len_utf8)632
});633
let word = &before[word_start..];634
let Some(found) = word.char_indices().find_map(|(offset, _)| {635
let previous = word[..offset].chars().next_back();636
let length = bare_url_at(&word[offset..], previous)?;637
Some(offset..offset + length)638
}) else {639
return false;640
};641
let range =642
content_start + word_start + found.start..content_start + word_start + found.end;643
let taken = self.marks.iter().any(|mark| {644
matches!(mark.kind, MarkKind::Code | MarkKind::Link(_)) && overlaps(&mark.range, &range)645
});646
let Some(url) = link_url(&self.text[range.clone()]).filter(|_| !taken) else {647
return false;648
};649
self.add_mark(range, MarkKind::Link(url));650
true651
}652
604
/// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence.653
/// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence.605
/// `None` leaves the key to the caller: send, or a plain newline.654
/// `None` leaves the key to the caller: send, or a plain newline.606
pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option<usize> {655
pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option<usize> {@@ -942,6 +991,46 @@ impl Draft {942
kinds991
kinds943
}992
}944
993
994
fn auto_link_urls(&self, range: &Range<usize>) -> Vec<String> {995
self.marks996
.iter()997
.filter_map(|mark| match &mark.kind {998
MarkKind::Link(url)999
if mark.range.start <= range.end1000
&& range.start <= mark.range.end1001
&& autolink_prefix(&self.text[mark.range.clone()]).is_some()1002
&& link_url(&self.text[mark.range.clone()]).as_ref() == Some(url) =>1003
{1004
Some(url.clone())1005
}1006
_ => None,1007
})1008
.collect()1009
}1010
1011
fn retarget_links(&mut self, auto_urls: &[String], edited: &Range<usize>) {1012
if auto_urls.is_empty() {1013
return;1014
}1015
let mut kept = Vec::with_capacity(self.marks.len());1016
for mark in std::mem::take(&mut self.marks) {1017
let touched = mark.range.start <= edited.end && edited.start <= mark.range.end;1018
match &mark.kind {1019
MarkKind::Link(url) if touched && auto_urls.contains(url) => {1020
if let Some(new_url) = link_url(&self.text[mark.range.clone()]) {1021
kept.push(Mark {1022
range: mark.range,1023
kind: MarkKind::Link(new_url),1024
});1025
}1026
}1027
_ => kept.push(mark),1028
}1029
}1030
self.marks = kept;1031
self.normalize_marks();1032
}1033
945
fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {1034
fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {946
(self.line_at(range.start)..=self.line_at(range.end))1035
(self.line_at(range.start)..=self.line_at(range.end))947
.map(|index| {1036
.map(|index| {@@ -1283,6 +1372,39 @@ pub fn link_url(text: &str) -> Option<String> {1283
scheme.is_none().then(|| format!("https://{text}"))1372
scheme.is_none().then(|| format!("https://{text}"))1284
}1373
}1285
1374
1375
fn autolink_prefix(text: &str) -> Option<&'static str> {1376
AUTOLINK_PREFIXES.into_iter().find(|prefix| {1377
text.get(..prefix.len())1378
.is_some_and(|head| head.eq_ignore_ascii_case(prefix))1379
})1380
}1381
1382
/// Length of the URL at the start of `rest`, when `previous` does not continue a word.1383
fn bare_url_at(rest: &str, previous: Option<char>) -> Option<usize> {1384
if previous.is_some_and(char::is_alphanumeric) {1385
return None;1386
}1387
bare_url_len(rest)1388
}1389
1390
/// Length of the URL a word starts with, without trailing punctuation.1391
fn bare_url_len(rest: &str) -> Option<usize> {1392
let word = &rest[..rest.find(char::is_whitespace).unwrap_or(rest.len())];1393
let prefix = autolink_prefix(word)?;1394
let mut end = word.len();1395
while let Some(last) = word[..end].chars().next_back() {1396
let trailing = match last {1397
')' => word[..end].matches(')').count() > word[..end].matches('(').count(),1398
other => AUTOLINK_TRAILING.contains(other),1399
};1400
if !trailing {1401
break;1402
}1403
end -= last.len_utf8();1404
}1405
(end > prefix.len()).then_some(end)1406
}1407
1286
/// The markers of a format closed by the last typed character, relative to `before`.1408
/// The markers of a format closed by the last typed character, relative to `before`.1287
fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {1409
fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {1288
let end = before.len();1410
let end = before.len();@@ -1528,20 +1650,34 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {1528
fn parse_inline(source: &str) -> (String, Vec<Mark>) {1650
fn parse_inline(source: &str) -> (String, Vec<Mark>) {1529
let mut text = String::with_capacity(source.len());1651
let mut text = String::with_capacity(source.len());1530
let mut marks = Vec::new();1652
let mut marks = Vec::new();1531
parse_into(source, &mut text, &mut marks);1653
parse_into(source, &mut text, &mut marks, true);1532
(text, marks)1654
(text, marks)1533
}1655
}1534
1656
1535
fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>) {1657
fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>, autolink: bool) {1536
let mut rest = source;1658
let mut rest = source;1537
let mut previous: Option<char> = None;1659
let mut previous: Option<char> = None;1538
while let Some(character) = rest.chars().next() {1660
while let Some(character) = rest.chars().next() {1661
if autolink1662
&& let Some(length) = bare_url_at(rest, previous)1663
&& let Some(url) = link_url(&rest[..length])1664
{1665
let start = text.len();1666
text.push_str(&rest[..length]);1667
marks.push(Mark {1668
range: start..text.len(),1669
kind: MarkKind::Link(url),1670
});1671
previous = rest[..length].chars().next_back();1672
rest = &rest[length..];1673
continue;1674
}1539
if let Some((inner, consumed, kind)) = inline_at(rest, previous) {1675
if let Some((inner, consumed, kind)) = inline_at(rest, previous) {1540
let start = text.len();1676
let start = text.len();1541
if kind == MarkKind::Code {1677
match kind {1542
text.push_str(inner);1678
MarkKind::Code => text.push_str(inner),1543
} else {1679
MarkKind::Link(_) => parse_into(inner, text, marks, false),1544
parse_into(inner, text, marks);1680
_ => parse_into(inner, text, marks, autolink),1545
}1681
}1546
marks.push(Mark {1682
marks.push(Mark {1547
range: start..text.len(),1683
range: start..text.len(),@@ -1804,6 +1940,182 @@ mod tests {1804
);1940
);1805
}1941
}1806
1942
1943
fn typed_autolinked(draft: &mut Draft, text: &str) {1944
for character in text.chars() {1945
let mut next = draft.text().to_owned();1946
next.push(character);1947
let cursor = next.len();1948
draft.apply_edit(&next, cursor, None);1949
draft.autolink_typed(cursor);1950
draft.take_edits();1951
}1952
}1953
1954
fn autolinked(text: &str) -> Draft {1955
let mut draft = Draft::default();1956
typed_autolinked(&mut draft, text);1957
draft1958
}1959
1960
fn edited(draft: &mut Draft, range: Range<usize>, replacement: &str) {1961
let mut next = draft.text().to_owned();1962
next.replace_range(range.clone(), replacement);1963
draft.apply_edit(&next, range.start + replacement.len(), None);1964
}1965
1966
#[test]1967
fn typed_url_followed_by_a_space_becomes_a_link() {1968
let draft = autolinked("https://example.com ");1969
assert_eq!(1970
draft.marks(),1971
[mark(0..19, MarkKind::Link("https://example.com".into()))]1972
);1973
}1974
1975
#[test]1976
fn typed_url_followed_by_a_newline_becomes_a_link() {1977
let draft = autolinked("a mailto:x@y.de\n");1978
assert_eq!(1979
draft.marks(),1980
[mark(2..15, MarkKind::Link("mailto:x@y.de".into()))]1981
);1982
}1983
1984
#[test]1985
fn autolink_leaves_trailing_punctuation_out_and_adds_the_scheme() {1986
let draft = autolinked("see www.x.de. ");1987
assert_eq!(1988
draft.marks(),1989
[mark(4..12, MarkKind::Link("https://www.x.de".into()))]1990
);1991
let wiki = autolinked("https://a.b/x_(y) ");1992
assert_eq!(1993
wiki.marks(),1994
[mark(0..17, MarkKind::Link("https://a.b/x_(y)".into()))]1995
);1996
let bracketed = autolinked("https://a.b) ");1997
assert_eq!(1998
bracketed.marks(),1999
[mark(0..11, MarkKind::Link("https://a.b".into()))]2000
);2001
}2002
2003
#[test]2004
fn autolink_starts_after_any_non_alphanumeric_character() {2005
let bracketed = autolinked("(https://a.b) ");2006
assert_eq!(2007
bracketed.marks(),2008
[mark(1..12, MarkKind::Link("https://a.b".into()))]2009
);2010
let quoted = autolinked("\"www.x.de\" ");2011
assert_eq!(2012
quoted.marks(),2013
[mark(1..9, MarkKind::Link("https://www.x.de".into()))]2014
);2015
let colon = autolinked("see:https://a.b ");2016
assert_eq!(2017
colon.marks(),2018
[mark(4..15, MarkKind::Link("https://a.b".into()))]2019
);2020
assert!(autolinked("xhttps://a.b ").marks().is_empty());2021
}2022
2023
#[test]2024
fn a_link_labelled_with_a_bare_domain_keeps_its_url_when_relabelled() {2025
let mut draft = Draft::plain("example.com");2026
draft.set_link(0..11, "example.com");2027
edited(&mut draft, 0..11, "our site");2028
assert_eq!(2029
draft.marks(),2030
[mark(0..8, MarkKind::Link("https://example.com".into()))]2031
);2032
}2033
2034
#[test]2035
fn autolink_skips_plain_words_code_and_existing_links() {2036
assert!(autolinked("example.com ").marks().is_empty());2037
assert!(autolinked("http:// ").marks().is_empty());2038
let mut block = Draft::from_markdown("```\nhttps://a.b");2039
typed_autolinked(&mut block, " ");2040
assert!(block.marks().is_empty());2041
let mut code = Draft::plain("https://a.b");2042
code.toggle(0..11, MarkKind::Code);2043
typed_autolinked(&mut code, " ");2044
assert_eq!(code.marks(), [mark(0..11, MarkKind::Code)]);2045
let mut linked = Draft::plain("https://a.b");2046
linked.set_link(0..11, "https://other.de");2047
typed_autolinked(&mut linked, " ");2048
assert_eq!(2049
linked.marks(),2050
[mark(0..11, MarkKind::Link("https://other.de".into()))]2051
);2052
}2053
2054
#[test]2055
fn markdown_import_links_bare_urls_outside_code_and_labels() {2056
let draft = Draft::from_markdown("go to https://a.b now");2057
assert_eq!(2058
draft.marks(),2059
[mark(6..17, MarkKind::Link("https://a.b".into()))]2060
);2061
assert_eq!(2062
Draft::from_markdown("run `https://a.b` now").marks(),2063
[mark(4..15, MarkKind::Code)]2064
);2065
let labelled = Draft::from_markdown("[https://a.b](https://c.d)");2066
assert_eq!(2067
labelled.marks(),2068
[mark(0..11, MarkKind::Link("https://c.d".into()))]2069
);2070
assert!(has_markdown("x https://a.b y"));2071
}2072
2073
#[test]2074
fn editing_an_auto_link_moves_its_url() {2075
let mut draft = autolinked("https://a.bc ");2076
edited(&mut draft, 11..12, "d");2077
assert_eq!(2078
draft.marks(),2079
[mark(0..12, MarkKind::Link("https://a.bd".into()))]2080
);2081
edited(&mut draft, 11..11, "e");2082
assert_eq!(2083
draft.marks(),2084
[mark(0..13, MarkKind::Link("https://a.bed".into()))]2085
);2086
}2087
2088
#[test]2089
fn editing_a_labelled_link_keeps_its_url() {2090
let mut draft = typed_draft("[docs](https://example.com)");2091
edited(&mut draft, 2..2, "x");2092
assert_eq!(2093
draft.marks(),2094
[mark(0..5, MarkKind::Link("https://example.com".into()))]2095
);2096
}2097
2098
#[test]2099
fn breaking_an_auto_link_into_non_url_text_removes_it() {2100
let mut draft = autolinked("https://a.bc ");2101
edited(&mut draft, 9..9, " ");2102
assert!(draft.marks().is_empty());2103
}2104
2105
#[test]2106
fn an_auto_link_can_be_relabelled_or_unlinked() {2107
let mut draft = autolinked("https://a.bc ");2108
assert_eq!(draft.link_in(0..4), Some("https://a.bc".into()));2109
draft.set_link(0..12, "https://other.de");2110
assert_eq!(2111
draft.marks(),2112
[mark(0..12, MarkKind::Link("https://other.de".into()))]2113
);2114
edited(&mut draft, 12..12, "x");2115
draft.set_link(0..12, "");2116
assert!(draft.marks().is_empty());2117
}2118
1807
#[test]2119
#[test]1808
fn snake_case_and_spaced_stars_stay_text() {2120
fn snake_case_and_spaced_stars_stay_text() {1809
assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");2121
assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");