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