1use std::ops::Range;
2
3use collections::HashMap;
4use itertools::Itertools;
5use text::{AnchorRangeExt, BufferId, ToPoint};
6use ui::ViewContext;
7use util::ResultExt;
8
9use crate::Editor;
10
11#[derive(Clone, Default)]
12pub(super) struct LinkedEditingRanges(
13 /// Ranges are non-overlapping and sorted by .0 (thus, [x + 1].start > [x].end must hold)
14 pub HashMap<BufferId, Vec<(Range<text::Anchor>, Vec<Range<text::Anchor>>)>>,
15);
16
17impl LinkedEditingRanges {
18 pub(super) fn get(
19 &self,
20 id: BufferId,
21 anchor: Range<text::Anchor>,
22 snapshot: &text::BufferSnapshot,
23 ) -> Option<&(Range<text::Anchor>, Vec<Range<text::Anchor>>)> {
24 let ranges_for_buffer = self.0.get(&id)?;
25 let lower_bound = ranges_for_buffer
26 .partition_point(|(range, _)| range.start.cmp(&anchor.start, snapshot).is_le());
27 if lower_bound == 0 {
28 // None of the linked ranges contains `anchor`.
29 return None;
30 }
31 ranges_for_buffer
32 .get(lower_bound - 1)
33 .filter(|(range, _)| range.end.cmp(&anchor.end, snapshot).is_ge())
34 }
35 pub(super) fn is_empty(&self) -> bool {
36 self.0.is_empty()
37 }
38}
39pub(super) fn refresh_linked_ranges(this: &mut Editor, cx: &mut ViewContext<Editor>) -> Option<()> {
40 if this.pending_rename.is_some() {
41 return None;
42 }
43 let project = this.project.clone()?;
44 let selections = this.selections.all::<usize>(cx);
45 let buffer = this.buffer.read(cx);
46 let mut applicable_selections = vec![];
47 let snapshot = buffer.snapshot(cx);
48 for selection in selections {
49 let cursor_position = selection.head();
50 let start_position = snapshot.anchor_before(cursor_position);
51 let end_position = snapshot.anchor_after(selection.tail());
52 if start_position.buffer_id != end_position.buffer_id || end_position.buffer_id.is_none() {
53 // Throw away selections spanning multiple buffers.
54 continue;
55 }
56 if let Some(buffer) = end_position.buffer_id.and_then(|id| buffer.buffer(id)) {
57 applicable_selections.push((
58 buffer,
59 start_position.text_anchor,
60 end_position.text_anchor,
61 ));
62 }
63 }
64 if applicable_selections.is_empty() {
65 return None;
66 }
67 this.linked_editing_range_task = Some(cx.spawn(|this, mut cx| async move {
68 let highlights = project
69 .update(&mut cx, |project, cx| {
70 let mut linked_edits_tasks = vec![];
71
72 for (buffer, start, end) in &applicable_selections {
73 let snapshot = buffer.read(cx).snapshot();
74 let buffer_id = buffer.read(cx).remote_id();
75
76 let linked_edits_task = project.linked_edit(buffer, *start, cx);
77 let highlights = move || async move {
78 let edits = linked_edits_task.await.log_err()?;
79 // Find the range containing our current selection.
80 // We might not find one, because the selection contains both the start and end of the contained range
81 // (think of selecting <`html>foo`</html> - even though there's a matching closing tag, the selection goes beyond the range of the opening tag)
82 // or the language server may not have returned any ranges.
83
84 let start_point = start.to_point(&snapshot);
85 let end_point = end.to_point(&snapshot);
86 let _current_selection_contains_range = edits.iter().find(|range| {
87 range.start.to_point(&snapshot) <= start_point
88 && range.end.to_point(&snapshot) >= end_point
89 });
90 _current_selection_contains_range?;
91 // Now link every range as each-others sibling.
92 let mut siblings: HashMap<Range<text::Anchor>, Vec<_>> = Default::default();
93 let mut insert_sorted_anchor =
94 |key: &Range<text::Anchor>, value: &Range<text::Anchor>| {
95 siblings.entry(key.clone()).or_default().push(value.clone());
96 };
97 for items in edits.into_iter().combinations(2) {
98 let Ok([first, second]): Result<[_; 2], _> = items.try_into() else {
99 unreachable!()
100 };
101
102 insert_sorted_anchor(&first, &second);
103 insert_sorted_anchor(&second, &first);
104 }
105 let mut siblings: Vec<(_, _)> = siblings.into_iter().collect();
106 siblings.sort_by(|lhs, rhs| lhs.0.cmp(&rhs.0, &snapshot));
107 Some((buffer_id, siblings))
108 };
109 linked_edits_tasks.push(highlights());
110 }
111 linked_edits_tasks
112 })
113 .log_err()?;
114
115 let highlights = futures::future::join_all(highlights).await;
116
117 this.update(&mut cx, |this, cx| {
118 this.linked_edit_ranges.0.clear();
119 if this.pending_rename.is_some() {
120 return;
121 }
122 for (buffer_id, ranges) in highlights.into_iter().flatten() {
123 this.linked_edit_ranges
124 .0
125 .entry(buffer_id)
126 .or_default()
127 .extend(ranges);
128 }
129 for (buffer_id, values) in this.linked_edit_ranges.0.iter_mut() {
130 let Some(snapshot) = this
131 .buffer
132 .read(cx)
133 .buffer(*buffer_id)
134 .map(|buffer| buffer.read(cx).snapshot())
135 else {
136 continue;
137 };
138 values.sort_by(|lhs, rhs| lhs.0.cmp(&rhs.0, &snapshot));
139 }
140
141 cx.notify();
142 })
143 .log_err();
144
145 Some(())
146 }));
147 None
148}