1use collections::BTreeMap;
2use gpui::HighlightStyle;
3use language::Chunk;
4use multi_buffer::{MultiBufferChunks, MultiBufferSnapshot, ToOffset as _};
5use std::{
6 cmp,
7 iter::{self, Peekable},
8 ops::Range,
9 vec,
10};
11
12use crate::display_map::{HighlightKey, TextHighlights};
13
14pub struct CustomHighlightsChunks<'a> {
15 buffer_chunks: MultiBufferChunks<'a>,
16 buffer_chunk: Option<Chunk<'a>>,
17 offset: usize,
18 multibuffer_snapshot: &'a MultiBufferSnapshot,
19
20 highlight_endpoints: Peekable<vec::IntoIter<HighlightEndpoint>>,
21 active_highlights: BTreeMap<HighlightKey, HighlightStyle>,
22 text_highlights: Option<&'a TextHighlights>,
23}
24
25#[derive(Debug, Copy, Clone, Eq, PartialEq)]
26struct HighlightEndpoint {
27 offset: usize,
28 tag: HighlightKey,
29 style: Option<HighlightStyle>,
30}
31
32impl<'a> CustomHighlightsChunks<'a> {
33 pub fn new(
34 range: Range<usize>,
35 language_aware: bool,
36 text_highlights: Option<&'a TextHighlights>,
37 multibuffer_snapshot: &'a MultiBufferSnapshot,
38 ) -> Self {
39 Self {
40 buffer_chunks: multibuffer_snapshot.chunks(range.clone(), language_aware),
41 buffer_chunk: None,
42 offset: range.start,
43 text_highlights,
44 highlight_endpoints: create_highlight_endpoints(
45 &range,
46 text_highlights,
47 multibuffer_snapshot,
48 ),
49 active_highlights: Default::default(),
50 multibuffer_snapshot,
51 }
52 }
53
54 pub fn seek(&mut self, new_range: Range<usize>) {
55 self.highlight_endpoints =
56 create_highlight_endpoints(&new_range, self.text_highlights, self.multibuffer_snapshot);
57 self.offset = new_range.start;
58 self.buffer_chunks.seek(new_range);
59 self.buffer_chunk.take();
60 self.active_highlights.clear()
61 }
62}
63
64fn create_highlight_endpoints(
65 range: &Range<usize>,
66 text_highlights: Option<&TextHighlights>,
67 buffer: &MultiBufferSnapshot,
68) -> iter::Peekable<vec::IntoIter<HighlightEndpoint>> {
69 let mut highlight_endpoints = Vec::new();
70 if let Some(text_highlights) = text_highlights {
71 let start = buffer.anchor_after(range.start);
72 let end = buffer.anchor_after(range.end);
73 for (&tag, text_highlights) in text_highlights.iter() {
74 let style = text_highlights.0;
75 let ranges = &text_highlights.1;
76
77 let start_ix = match ranges.binary_search_by(|probe| {
78 let cmp = probe.end.cmp(&start, buffer);
79 if cmp.is_gt() {
80 cmp::Ordering::Greater
81 } else {
82 cmp::Ordering::Less
83 }
84 }) {
85 Ok(i) | Err(i) => i,
86 };
87
88 for range in &ranges[start_ix..] {
89 if range.start.cmp(&end, buffer).is_ge() {
90 break;
91 }
92
93 let start = range.start.to_offset(buffer);
94 let end = range.end.to_offset(buffer);
95 if start == end {
96 continue;
97 }
98 highlight_endpoints.push(HighlightEndpoint {
99 offset: start,
100 tag,
101 style: Some(style),
102 });
103 highlight_endpoints.push(HighlightEndpoint {
104 offset: end,
105 tag,
106 style: None,
107 });
108 }
109 }
110 highlight_endpoints.sort();
111 }
112 highlight_endpoints.into_iter().peekable()
113}
114
115impl<'a> Iterator for CustomHighlightsChunks<'a> {
116 type Item = Chunk<'a>;
117
118 fn next(&mut self) -> Option<Self::Item> {
119 let mut next_highlight_endpoint = usize::MAX;
120 while let Some(endpoint) = self.highlight_endpoints.peek().copied() {
121 if endpoint.offset <= self.offset {
122 if let Some(style) = endpoint.style {
123 self.active_highlights.insert(endpoint.tag, style);
124 } else {
125 self.active_highlights.remove(&endpoint.tag);
126 }
127 self.highlight_endpoints.next();
128 } else {
129 next_highlight_endpoint = endpoint.offset;
130 break;
131 }
132 }
133
134 let chunk = match &mut self.buffer_chunk {
135 Some(it) => it,
136 slot => slot.insert(self.buffer_chunks.next()?),
137 };
138 while chunk.text.is_empty() {
139 *chunk = self.buffer_chunks.next()?;
140 }
141
142 let split_idx = chunk.text.len().min(next_highlight_endpoint - self.offset);
143 let (prefix, suffix) = chunk.text.split_at(split_idx);
144 self.offset += prefix.len();
145
146 let mask = 1u128.unbounded_shl(split_idx as u32).wrapping_sub(1);
147 let chars = chunk.chars & mask;
148 let tabs = chunk.tabs & mask;
149 let mut prefix = Chunk {
150 text: prefix,
151 chars,
152 tabs,
153 ..chunk.clone()
154 };
155
156 chunk.chars = chunk.chars.unbounded_shr(split_idx as u32);
157 chunk.tabs = chunk.tabs.unbounded_shr(split_idx as u32);
158 chunk.text = suffix;
159 if !self.active_highlights.is_empty() {
160 prefix.highlight_style = self
161 .active_highlights
162 .values()
163 .copied()
164 .reduce(|acc, active_highlight| acc.highlight(active_highlight));
165 }
166 Some(prefix)
167 }
168}
169
170impl PartialOrd for HighlightEndpoint {
171 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
172 Some(self.cmp(other))
173 }
174}
175
176impl Ord for HighlightEndpoint {
177 fn cmp(&self, other: &Self) -> cmp::Ordering {
178 self.offset
179 .cmp(&other.offset)
180 .then_with(|| self.style.is_some().cmp(&other.style.is_some()))
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use std::{any::TypeId, sync::Arc};
187
188 use super::*;
189 use crate::MultiBuffer;
190 use gpui::App;
191 use rand::prelude::*;
192 use util::RandomCharIter;
193
194 #[gpui::test(iterations = 100)]
195 fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
196 // Generate random buffer using existing test infrastructure
197 let len = rng.random_range(10..10000);
198 let buffer = if rng.random() {
199 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
200 MultiBuffer::build_simple(&text, cx)
201 } else {
202 MultiBuffer::build_random(&mut rng, cx)
203 };
204
205 let buffer_snapshot = buffer.read(cx).snapshot(cx);
206
207 // Create random highlights
208 let mut highlights = sum_tree::TreeMap::default();
209 let highlight_count = rng.random_range(1..10);
210
211 for _i in 0..highlight_count {
212 let style = HighlightStyle {
213 color: Some(gpui::Hsla {
214 h: rng.random::<f32>(),
215 s: rng.random::<f32>(),
216 l: rng.random::<f32>(),
217 a: 1.0,
218 }),
219 ..Default::default()
220 };
221
222 let mut ranges = Vec::new();
223 let range_count = rng.random_range(1..10);
224 let text = buffer_snapshot.text();
225 for _ in 0..range_count {
226 if buffer_snapshot.len() == 0 {
227 continue;
228 }
229
230 let mut start = rng.random_range(0..=buffer_snapshot.len().saturating_sub(10));
231
232 while !text.is_char_boundary(start) {
233 start = start.saturating_sub(1);
234 }
235
236 let end_end = buffer_snapshot.len().min(start + 100);
237 let mut end = rng.random_range(start..=end_end);
238 while !text.is_char_boundary(end) {
239 end = end.saturating_sub(1);
240 }
241
242 if start < end {
243 start = end;
244 }
245 let start_anchor = buffer_snapshot.anchor_before(start);
246 let end_anchor = buffer_snapshot.anchor_after(end);
247 ranges.push(start_anchor..end_anchor);
248 }
249
250 let type_id = TypeId::of::<()>(); // Simple type ID for testing
251 highlights.insert(HighlightKey::Type(type_id), Arc::new((style, ranges)));
252 }
253
254 // Get all chunks and verify their bitmaps
255 let chunks =
256 CustomHighlightsChunks::new(0..buffer_snapshot.len(), false, None, &buffer_snapshot);
257
258 for chunk in chunks {
259 let chunk_text = chunk.text;
260 let chars_bitmap = chunk.chars;
261 let tabs_bitmap = chunk.tabs;
262
263 // Check empty chunks have empty bitmaps
264 if chunk_text.is_empty() {
265 assert_eq!(
266 chars_bitmap, 0,
267 "Empty chunk should have empty chars bitmap"
268 );
269 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
270 continue;
271 }
272
273 // Verify that chunk text doesn't exceed 128 bytes
274 assert!(
275 chunk_text.len() <= 128,
276 "Chunk text length {} exceeds 128 bytes",
277 chunk_text.len()
278 );
279
280 // Verify chars bitmap
281 let char_indices = chunk_text
282 .char_indices()
283 .map(|(i, _)| i)
284 .collect::<Vec<_>>();
285
286 for byte_idx in 0..chunk_text.len() {
287 let should_have_bit = char_indices.contains(&byte_idx);
288 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
289
290 if has_bit != should_have_bit {
291 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
292 eprintln!("Char indices: {:?}", char_indices);
293 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
294 assert_eq!(
295 has_bit, should_have_bit,
296 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
297 byte_idx, chunk_text, should_have_bit, has_bit
298 );
299 }
300 }
301
302 // Verify tabs bitmap
303 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
304 let is_tab = byte == b'\t';
305 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
306
307 if has_bit != is_tab {
308 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
309 eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
310 assert_eq!(
311 has_bit, is_tab,
312 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
313 byte_idx, chunk_text, byte as char, is_tab, has_bit
314 );
315 }
316 }
317 }
318 }
319}