Debian Codegraph @

helix-view/src/view.rs

raw symbols SCIP
1 use crate::{
2 align_view,
3 annotations::diagnostics::InlineDiagnostics,
4 document::{DocumentColorSwatches, DocumentInlayHints},
5 editor::{GutterConfig, GutterType},
6 graphics::Rect,
7 handlers::diagnostics::DiagnosticsHandler,
8 Align, Document, DocumentId, Theme, ViewId,
9 };
10
11 use helix_core::{
12 char_idx_at_visual_offset,
13 doc_formatter::TextFormat,
14 text_annotations::TextAnnotations,
15 visual_offset_from_anchor, visual_offset_from_block, Position, RopeSlice, Selection,
16 Transaction,
17 VisualOffsetError::{PosAfterMaxRow, PosBeforeAnchorRow},
18 };
19
20 use std::{
21 collections::{HashMap, VecDeque},
22 fmt,
23 };
24
25 const JUMP_LIST_CAPACITY: usize = 30;
26
27 type Jump = (DocumentId, Selection);
28
29 #[derive(Debug, Clone)]
30 pub struct JumpList {
31 jumps: VecDeque<Jump>,
32 current: usize,
33 }
34
35 impl JumpList {
36 pub fn new(initial: Jump) -> Self {
37 let mut jumps = VecDeque::with_capacity(JUMP_LIST_CAPACITY);
38 jumps.push_back(initial);
39 Self { jumps, current: 0 }
40 }
41
42 fn push_impl(&mut self, jump: Jump) -> usize {
43 let mut num_removed_from_front = 0;
44 self.jumps.truncate(self.current);
45 // don't push duplicates
46 if self.jumps.back() != Some(&jump) {
47 // If the jumplist is full, drop the oldest item.
48 while self.jumps.len() >= JUMP_LIST_CAPACITY {
49 self.jumps.pop_front();
50 num_removed_from_front += 1;
51 }
52
53 self.jumps.push_back(jump);
54 self.current = self.jumps.len();
55 }
56 num_removed_from_front
57 }
58
59 pub(crate) fn push(&mut self, jump: Jump) {
60 self.push_impl(jump);
61 }
62
63 pub(crate) fn forward(&mut self, count: usize) -> Option<&Jump> {
64 if self.current + count < self.jumps.len() {
65 self.current += count;
66 self.jumps.get(self.current)
67 } else {
68 None
69 }
70 }
71
72 // Taking view and doc to prevent unnecessary cloning when jump is not required.
73 pub(crate) fn backward(
74 &mut self,
75 view_id: ViewId,
76 doc: &mut Document,
77 count: usize,
78 ) -> Option<&Jump> {
79 if let Some(mut current) = self.current.checked_sub(count) {
80 if self.current == self.jumps.len() {
81 let jump = (doc.id(), doc.selection(view_id).clone());
82 let num_removed = self.push_impl(jump);
83 current = current.saturating_sub(num_removed);
84 }
85 self.current = current;
86
87 // Avoid jumping to the current location.
88 let (doc_id, selection) = self.jumps.get(self.current)?;
89 if doc.id() == *doc_id && doc.selection(view_id) == selection {
90 self.current = self.current.checked_sub(1)?;
91 }
92 self.jumps.get(self.current)
93 } else {
94 None
95 }
96 }
97
98 pub fn remove(&mut self, doc_id: &DocumentId) {
99 // Count the entries before the navigation cursor so that, after the
100 // matching entries are dropped, `current` keeps pointing at the same
101 // logical jump. Without this adjustment the cursor drifts onto an
102 // unrelated entry, or is left past the end of the list (when it sat at
103 // the tip), which breaks subsequent `forward`/`backward` navigation.
104 let removed_before_current = self
105 .jumps
106 .iter()
107 .take(self.current)
108 .filter(|(other_id, _)| other_id == doc_id)
109 .count();
110 self.jumps.retain(|(other_id, _)| other_id != doc_id);
111 self.current = self
112 .current
113 .saturating_sub(removed_before_current)
114 .min(self.jumps.len());
115 }
116
117 pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Jump> {
118 self.jumps.iter()
119 }
120
121 /// Applies a [`Transaction`] of changes to the jumplist.
122 /// This is necessary to ensure that changes to documents do not leave jump-list
123 /// selections pointing to parts of the text which no longer exist.
124 fn apply(&mut self, transaction: &Transaction, doc: &Document) {
125 let text = doc.text().slice(..);
126
127 for (doc_id, selection) in &mut self.jumps {
128 if doc.id() == *doc_id {
129 *selection = selection
130 .clone()
131 .map(transaction.changes())
132 .ensure_invariants(text);
133 }
134 }
135 }
136 }
137
138 #[derive(Clone, Debug, PartialEq, Eq, Copy, Default)]
139 pub struct ViewPosition {
140 pub anchor: usize,
141 pub horizontal_offset: usize,
142 pub vertical_offset: usize,
143 }
144
145 #[derive(Clone)]
146 pub struct View {
147 pub id: ViewId,
148 pub area: Rect,
149 pub doc: DocumentId,
150 pub jumps: JumpList,
151 // documents accessed from this view from the oldest one to last viewed one
152 pub docs_access_history: Vec<DocumentId>,
153 /// the last modified files before the current one
154 /// ordered from most frequent to least frequent
155 // uses two docs because we want to be able to swap between the
156 // two last modified docs which we need to manually keep track of
157 pub last_modified_docs: [Option<DocumentId>; 2],
158 /// used to store previous selections of tree-sitter objects
159 pub object_selections: Vec<Selection>,
160 /// all gutter-related configuration settings, used primarily for gutter rendering
161 pub gutters: GutterConfig,
162 /// A mapping between documents and the last history revision the view was updated at.
163 /// Changes between documents and views are synced lazily when switching windows. This
164 /// mapping keeps track of the last applied history revision so that only new changes
165 /// are applied.
166 doc_revisions: HashMap<DocumentId, usize>,
167 // HACKS: there should really only be a global diagnostics handler (the
168 // non-focused views should just not have different handling for the cursor
169 // line). For that we would need accces to editor everywhere (we want to use
170 // the positioning code) so this can only happen by refactoring View and
171 // Document into entity component like structure. That is a huge refactor
172 // left to future work. For now we treat all views as focused and give them
173 // each their own handler.
174 pub diagnostics_handler: DiagnosticsHandler,
175 }
176
177 impl fmt::Debug for View {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.debug_struct("View")
180 .field("id", &self.id)
181 .field("area", &self.area)
182 .field("doc", &self.doc)
183 .finish()
184 }
185 }
186
187 impl View {
188 pub fn new(doc: DocumentId, gutters: GutterConfig) -> Self {
189 Self {
190 id: ViewId::default(),
191 doc,
192 area: Rect::default(), // will get calculated upon inserting into tree
193 jumps: JumpList::new((doc, Selection::point(0))), // TODO: use actual sel
194 docs_access_history: Vec::new(),
195 last_modified_docs: [None, None],
196 object_selections: Vec::new(),
197 gutters,
198 doc_revisions: HashMap::new(),
199 diagnostics_handler: DiagnosticsHandler::new(),
200 }
201 }
202
203 pub fn add_to_history(&mut self, id: DocumentId) {
204 if let Some(pos) = self.docs_access_history.iter().position(|&doc| doc == id) {
205 self.docs_access_history.remove(pos);
206 }
207 self.docs_access_history.push(id);
208 }
209
210 pub fn inner_area(&self, doc: &Document) -> Rect {
211 self.area.clip_left(self.gutter_offset(doc)).clip_bottom(1) // -1 for statusline
212 }
213
214 pub fn inner_height(&self) -> usize {
215 self.area.clip_bottom(1).height.into() // -1 for statusline
216 }
217
218 pub fn inner_width(&self, doc: &Document) -> u16 {
219 self.area.clip_left(self.gutter_offset(doc)).width
220 }
221
222 pub fn gutters(&self) -> &[GutterType] {
223 &self.gutters.layout
224 }
225
226 pub fn gutter_offset(&self, doc: &Document) -> u16 {
227 let total_width = self
228 .gutters
229 .layout
230 .iter()
231 .map(|gutter| gutter.width(self, doc) as u16)
232 .sum();
233 if total_width < self.area.width {
234 total_width
235 } else {
236 0
237 }
238 }
239
240 //
241 pub fn offset_coords_to_in_view(
242 &self,
243 doc: &Document,
244 scrolloff: usize,
245 ) -> Option<ViewPosition> {
246 self.offset_coords_to_in_view_center::<false>(doc, scrolloff)
247 }
248
249 pub fn offset_coords_to_in_view_center<const CENTERING: bool>(
250 &self,
251 doc: &Document,
252 scrolloff: usize,
253 ) -> Option<ViewPosition> {
254 let view_offset = doc.get_view_offset(self.id)?;
255 let doc_text = doc.text().slice(..);
256 let viewport = self.inner_area(doc);
257 let vertical_viewport_end = view_offset.vertical_offset + viewport.height as usize;
258 let text_fmt = doc.text_format(viewport.width, None);
259 let annotations = self.text_annotations(doc, None);
260
261 let (scrolloff_top, scrolloff_bottom) = if CENTERING {
262 (0, 0)
263 } else {
264 (
265 // - 1 from the top so we have at least one gap in the middle.
266 scrolloff.min(viewport.height.saturating_sub(1) as usize / 2),
267 scrolloff.min(viewport.height as usize / 2),
268 )
269 };
270 let (scrolloff_left, scrolloff_right) = if CENTERING {
271 (0, 0)
272 } else {
273 (
274 // - 1 from the left so we have at least one gap in the middle.
275 scrolloff.min(viewport.width.saturating_sub(1) as usize / 2),
276 scrolloff.min(viewport.width as usize / 2),
277 )
278 };
279
280 let cursor = doc.selection(self.id).primary().cursor(doc_text);
281 let mut offset = view_offset;
282 let off = visual_offset_from_anchor(
283 doc_text,
284 offset.anchor,
285 cursor,
286 &text_fmt,
287 &annotations,
288 vertical_viewport_end,
289 );
290
291 let (new_anchor, at_top) = match off {
292 Ok((visual_pos, _)) if visual_pos.row < scrolloff_top + offset.vertical_offset => {
293 if CENTERING {
294 // cursor out of view
295 return None;
296 }
297 (true, true)
298 }
299 Ok((visual_pos, _)) if visual_pos.row + scrolloff_bottom >= vertical_viewport_end => {
300 (true, false)
301 }
302 Ok((_, _)) => (false, false),
303 Err(_) if CENTERING => return None,
304 Err(PosBeforeAnchorRow) => (true, true),
305 Err(PosAfterMaxRow) => (true, false),
306 };
307
308 if new_anchor {
309 let v_off = if at_top {
310 scrolloff_top as isize
311 } else {
312 viewport.height as isize - scrolloff_bottom as isize - 1
313 };
314 (offset.anchor, offset.vertical_offset) =
315 char_idx_at_visual_offset(doc_text, cursor, -v_off, 0, &text_fmt, &annotations);
316 }
317
318 if text_fmt.soft_wrap {
319 offset.horizontal_offset = 0;
320 } else {
321 // determine the current visual column of the text
322 let col = off
323 .unwrap_or_else(|_| {
324 visual_offset_from_block(
325 doc_text,
326 offset.anchor,
327 cursor,
328 &text_fmt,
329 &annotations,
330 )
331 })
332 .0
333 .col;
334
335 let last_col = offset.horizontal_offset + viewport.width.saturating_sub(1) as usize;
336 if col > last_col.saturating_sub(scrolloff_right) {
337 // scroll right
338 offset.horizontal_offset += col - (last_col.saturating_sub(scrolloff_right))
339 } else if col < offset.horizontal_offset + scrolloff_left {
340 // scroll left
341 offset.horizontal_offset = col.saturating_sub(scrolloff_left)
342 };
343 }
344
345 // if we are not centering return None if view position is unchanged
346 if !CENTERING && offset == view_offset {
347 return None;
348 }
349
350 Some(offset)
351 }
352
353 pub fn ensure_cursor_in_view(&self, doc: &mut Document, scrolloff: usize) {
354 if let Some(offset) = self.offset_coords_to_in_view_center::<false>(doc, scrolloff) {
355 doc.set_view_offset(self.id, offset);
356 }
357 }
358
359 pub fn ensure_cursor_in_view_center(&self, doc: &mut Document, scrolloff: usize) {
360 if let Some(offset) = self.offset_coords_to_in_view_center::<true>(doc, scrolloff) {
361 doc.set_view_offset(self.id, offset);
362 } else {
363 align_view(doc, self, Align::Center);
364 }
365 }
366
367 pub fn is_cursor_in_view(&mut self, doc: &Document, scrolloff: usize) -> bool {
368 self.offset_coords_to_in_view(doc, scrolloff).is_none()
369 }
370
371 /// Estimates the last visible document line on screen.
372 /// This estimate is an upper bound obtained by calculating the first
373 /// visible line and adding the viewport height.
374 /// The actual last visible line may be smaller if softwrapping occurs
375 /// or virtual text lines are visible
376 #[inline]
377 pub fn estimate_last_doc_line(&self, doc: &Document) -> usize {
378 let doc_text = doc.text().slice(..);
379 let line = doc_text.char_to_line(doc.view_offset(self.id).anchor.min(doc_text.len_chars()));
380 // Saturating subs to make it inclusive zero indexing.
381 (line + self.inner_height())
382 .min(doc_text.len_lines())
383 .saturating_sub(1)
384 }
385
386 /// Calculates the last non-empty visual line on screen
387 #[inline]
388 pub fn last_visual_line(&self, doc: &Document) -> usize {
389 let doc_text = doc.text().slice(..);
390 let viewport = self.inner_area(doc);
391 let text_fmt = doc.text_format(viewport.width, None);
392 let annotations = self.text_annotations(doc, None);
393 let view_offset = doc.view_offset(self.id);
394
395 // last visual line in view is trivial to compute
396 let visual_height = doc.view_offset(self.id).vertical_offset + viewport.height as usize;
397
398 // fast path when the EOF is not visible on the screen,
399 if self.estimate_last_doc_line(doc) < doc_text.len_lines() - 1 {
400 return visual_height.saturating_sub(1);
401 }
402
403 // translate to document line
404 let pos = visual_offset_from_anchor(
405 doc_text,
406 view_offset.anchor,
407 usize::MAX,
408 &text_fmt,
409 &annotations,
410 visual_height,
411 );
412
413 match pos {
414 Ok((Position { row, .. }, _)) => row.saturating_sub(view_offset.vertical_offset),
415 Err(PosAfterMaxRow) => visual_height.saturating_sub(1),
416 Err(PosBeforeAnchorRow) => 0,
417 }
418 }
419
420 /// Translates a document position to an absolute position in the terminal.
421 /// Returns a (line, col) position if the position is visible on screen.
422 // TODO: Could return width as well for the character width at cursor.
423 pub fn screen_coords_at_pos(
424 &self,
425 doc: &Document,
426 text: RopeSlice,
427 pos: usize,
428 ) -> Option<Position> {
429 let view_offset = doc.view_offset(self.id);
430
431 let viewport = self.inner_area(doc);
432 let text_fmt = doc.text_format(viewport.width, None);
433 let annotations = self.text_annotations(doc, None);
434
435 let mut pos = visual_offset_from_anchor(
436 text,
437 view_offset.anchor,
438 pos,
439 &text_fmt,
440 &annotations,
441 viewport.height as usize,
442 )
443 .ok()?
444 .0;
445 if pos.row < view_offset.vertical_offset {
446 return None;
447 }
448 pos.row -= view_offset.vertical_offset;
449 if pos.row >= viewport.height as usize {
450 return None;
451 }
452 pos.col = pos.col.saturating_sub(view_offset.horizontal_offset);
453
454 Some(pos)
455 }
456
457 /// Get the text annotations to display in the current view for the given document and theme.
458 pub fn text_annotations<'a>(
459 &self,
460 doc: &'a Document,
461 theme: Option<&Theme>,
462 ) -> TextAnnotations<'a> {
463 let mut text_annotations = TextAnnotations::default();
464
465 if let Some(labels) = doc.jump_labels.get(&self.id) {
466 let style = theme.and_then(|t| t.find_highlight("ui.virtual.jump-label"));
467 text_annotations.add_overlay(labels, style);
468 }
469
470 if let Some(DocumentInlayHints {
471 id: _,
472 type_inlay_hints,
473 parameter_inlay_hints,
474 other_inlay_hints,
475 padding_before_inlay_hints,
476 padding_after_inlay_hints,
477 }) = doc.inlay_hints.get(&self.id)
478 {
479 let type_style = theme.and_then(|t| t.find_highlight("ui.virtual.inlay-hint.type"));
480 let parameter_style =
481 theme.and_then(|t| t.find_highlight("ui.virtual.inlay-hint.parameter"));
482 let other_style = theme.and_then(|t| t.find_highlight("ui.virtual.inlay-hint"));
483
484 // Overlapping annotations are ignored apart from the first so the order here is not random:
485 // types -> parameters -> others should hopefully be the "correct" order for most use cases,
486 // with the padding coming before and after as expected.
487 text_annotations
488 .add_inline_annotations(padding_before_inlay_hints, None)
489 .add_inline_annotations(type_inlay_hints, type_style)
490 .add_inline_annotations(parameter_inlay_hints, parameter_style)
491 .add_inline_annotations(other_inlay_hints, other_style)
492 .add_inline_annotations(padding_after_inlay_hints, None);
493 };
494 let config = doc.config.load();
495
496 if config.lsp.display_color_swatches {
497 if let Some(DocumentColorSwatches {
498 color_swatches,
499 colors,
500 color_swatches_padding,
501 }) = &doc.color_swatches
502 {
503 for (color_swatch, color) in color_swatches.iter().zip(colors) {
504 text_annotations
505 .add_inline_annotations(std::slice::from_ref(color_swatch), Some(*color));
506 }
507
508 text_annotations.add_inline_annotations(color_swatches_padding, None);
509 }
510 }
511
512 let width = self.inner_width(doc);
513 let enable_cursor_line = self
514 .diagnostics_handler
515 .show_cursorline_diagnostics(doc, self.id);
516 let config = config.inline_diagnostics.prepare(width, enable_cursor_line);
517 if !config.disabled() {
518 let cursor = doc
519 .selection(self.id)
520 .primary()
521 .cursor(doc.text().slice(..));
522 text_annotations.add_line_annotation(InlineDiagnostics::new(
523 doc,
524 cursor,
525 width,
526 doc.view_offset(self.id).horizontal_offset,
527 config,
528 ));
529 }
530
531 text_annotations
532 }
533
534 pub fn text_pos_at_screen_coords(
535 &self,
536 doc: &Document,
537 row: u16,
538 column: u16,
539 fmt: TextFormat,
540 annotations: &TextAnnotations,
541 ignore_virtual_text: bool,
542 ) -> Option<usize> {
543 let inner = self.inner_area(doc);
544 // 1 for status
545 if row < inner.top() || row >= inner.bottom() {
546 return None;
547 }
548
549 if column < inner.left() || column > inner.right() {
550 return None;
551 }
552
553 self.text_pos_at_visual_coords(
554 doc,
555 row - inner.y,
556 column - inner.x,
557 fmt,
558 annotations,
559 ignore_virtual_text,
560 )
561 }
562
563 pub fn text_pos_at_visual_coords(
564 &self,
565 doc: &Document,
566 row: u16,
567 column: u16,
568 text_fmt: TextFormat,
569 annotations: &TextAnnotations,
570 ignore_virtual_text: bool,
571 ) -> Option<usize> {
572 let text = doc.text().slice(..);
573 let view_offset = doc.view_offset(self.id);
574
575 let text_row = row as usize + view_offset.vertical_offset;
576 let text_col = column as usize + view_offset.horizontal_offset;
577
578 let (char_idx, virt_lines) = char_idx_at_visual_offset(
579 text,
580 view_offset.anchor,
581 text_row as isize,
582 text_col,
583 &text_fmt,
584 annotations,
585 );
586
587 // if the cursor is on a line with only virtual text return None
588 if virt_lines != 0 && ignore_virtual_text {
589 return None;
590 }
591 Some(char_idx)
592 }
593
594 /// Translates a screen position to position in the text document.
595 /// Returns a usize typed position in bounds of the text if found in this view, None if out of view.
596 pub fn pos_at_screen_coords(
597 &self,
598 doc: &Document,
599 row: u16,
600 column: u16,
601 ignore_virtual_text: bool,
602 ) -> Option<usize> {
603 self.text_pos_at_screen_coords(
604 doc,
605 row,
606 column,
607 doc.text_format(self.inner_width(doc), None),
608 &self.text_annotations(doc, None),
609 ignore_virtual_text,
610 )
611 }
612
613 pub fn pos_at_visual_coords(
614 &self,
615 doc: &Document,
616 row: u16,
617 column: u16,
618 ignore_virtual_text: bool,
619 ) -> Option<usize> {
620 self.text_pos_at_visual_coords(
621 doc,
622 row,
623 column,
624 doc.text_format(self.inner_width(doc), None),
625 &self.text_annotations(doc, None),
626 ignore_virtual_text,
627 )
628 }
629
630 /// Translates screen coordinates into coordinates on the gutter of the view.
631 /// Returns a tuple of usize typed line and column numbers starting with 0.
632 /// Returns None if coordinates are not on the gutter.
633 pub fn gutter_coords_at_screen_coords(&self, row: u16, column: u16) -> Option<Position> {
634 // 1 for status
635 if row < self.area.top() || row >= self.area.bottom() {
636 return None;
637 }
638
639 if column < self.area.left() || column > self.area.right() {
640 return None;
641 }
642
643 Some(Position::new(
644 (row - self.area.top()) as usize,
645 (column - self.area.left()) as usize,
646 ))
647 }
648
649 pub fn remove_document(&mut self, doc_id: &DocumentId) {
650 self.jumps.remove(doc_id);
651 self.docs_access_history.retain(|doc| doc != doc_id);
652 }
653
654 // pub fn traverse<F>(&self, text: RopeSlice, start: usize, end: usize, fun: F)
655 // where
656 // F: Fn(usize, usize),
657 // {
658 // let start = self.screen_coords_at_pos(text, start);
659 // let end = self.screen_coords_at_pos(text, end);
660
661 // match (start, end) {
662 // // fully on screen
663 // (Some(start), Some(end)) => {
664 // // we want to calculate ends of lines for each char..
665 // }
666 // // from start to end of screen
667 // (Some(start), None) => {}
668 // // from start of screen to end
669 // (None, Some(end)) => {}
670 // // not on screen
671 // (None, None) => return,
672 // }
673 // }
674
675 /// Applies a [`Transaction`] to the view.
676 pub fn apply(&mut self, transaction: &Transaction, doc: &mut Document) {
677 self.jumps.apply(transaction, doc);
678 self.doc_revisions
679 .insert(doc.id(), doc.get_current_revision());
680 }
681
682 pub fn sync_changes(&mut self, doc: &mut Document) {
683 if let Some(transaction) = self.changes_to_sync(doc) {
684 self.apply(&transaction, doc);
685 }
686 }
687
688 pub(crate) fn changes_to_sync(&mut self, doc: &mut Document) -> Option<Transaction> {
689 let latest_revision = doc.get_current_revision();
690 let current_revision = *self
691 .doc_revisions
692 .entry(doc.id())
693 .or_insert(latest_revision);
694
695 if current_revision == latest_revision {
696 return None;
697 }
698
699 doc.history.get_mut().changes_since(current_revision)
700 }
701
702 pub fn push_jump(&mut self, doc: &mut Document, jump: (DocumentId, Selection)) {
703 // The pushed selection is valid at the document's *current* revision, so the
704 // view must be synced to that revision first. Otherwise the new entry would
705 // be left ahead of `doc_revisions[doc]`, and the next `sync_changes` would
706 // map it through a changeset whose pre-image predates it, panicking in
707 // `ChangeSet::update_positions` when the document has since grown.
708 self.sync_changes(doc);
709 self.jumps.push(jump);
710 }
711 }
712
713 #[cfg(test)]
714 mod tests {
715 use std::sync::Arc;
716
717 use super::*;
718 use arc_swap::ArcSwap;
719 use helix_core::{syntax, Rope};
720
721 // 1 diagnostic + 1 spacer + 3 linenr (< 1000 lines) + 1 spacer + 1 diff
722 const DEFAULT_GUTTER_OFFSET: u16 = 7;
723
724 // 1 diagnostics + 1 spacer + 1 gutter
725 const DEFAULT_GUTTER_OFFSET_ONLY_DIAGNOSTICS: u16 = 3;
726
727 use crate::document::Document;
728 use crate::editor::{Config, GutterConfig, GutterLineNumbersConfig, GutterType};
729
730 #[test]
731 fn test_text_pos_at_screen_coords() {
732 let mut view = View::new(DocumentId::default(), GutterConfig::default());
733 view.area = Rect::new(40, 40, 40, 40);
734 let rope = Rope::from_str("abc\n\tdef");
735 let mut doc = Document::from(
736 rope,
737 None,
738 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
739 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
740 );
741 doc.ensure_view_init(view.id);
742
743 assert_eq!(
744 view.text_pos_at_screen_coords(
745 &doc,
746 40,
747 2,
748 TextFormat::default(),
749 &TextAnnotations::default(),
750 true
751 ),
752 None
753 );
754
755 assert_eq!(
756 view.text_pos_at_screen_coords(
757 &doc,
758 40,
759 41,
760 TextFormat::default(),
761 &TextAnnotations::default(),
762 true
763 ),
764 None
765 );
766
767 assert_eq!(
768 view.text_pos_at_screen_coords(
769 &doc,
770 0,
771 2,
772 TextFormat::default(),
773 &TextAnnotations::default(),
774 true
775 ),
776 None
777 );
778
779 assert_eq!(
780 view.text_pos_at_screen_coords(
781 &doc,
782 0,
783 49,
784 TextFormat::default(),
785 &TextAnnotations::default(),
786 true
787 ),
788 None
789 );
790
791 assert_eq!(
792 view.text_pos_at_screen_coords(
793 &doc,
794 0,
795 41,
796 TextFormat::default(),
797 &TextAnnotations::default(),
798 true
799 ),
800 None
801 );
802
803 assert_eq!(
804 view.text_pos_at_screen_coords(
805 &doc,
806 40,
807 81,
808 TextFormat::default(),
809 &TextAnnotations::default(),
810 true
811 ),
812 None
813 );
814
815 assert_eq!(
816 view.text_pos_at_screen_coords(
817 &doc,
818 78,
819 41,
820 TextFormat::default(),
821 &TextAnnotations::default(),
822 true
823 ),
824 None
825 );
826
827 assert_eq!(
828 view.text_pos_at_screen_coords(
829 &doc,
830 40,
831 40 + DEFAULT_GUTTER_OFFSET + 3,
832 TextFormat::default(),
833 &TextAnnotations::default(),
834 true
835 ),
836 Some(3)
837 );
838
839 assert_eq!(
840 view.text_pos_at_screen_coords(
841 &doc,
842 40,
843 80,
844 TextFormat::default(),
845 &TextAnnotations::default(),
846 true
847 ),
848 Some(3)
849 );
850
851 assert_eq!(
852 view.text_pos_at_screen_coords(
853 &doc,
854 41,
855 40 + DEFAULT_GUTTER_OFFSET + 1,
856 TextFormat::default(),
857 &TextAnnotations::default(),
858 true
859 ),
860 Some(4)
861 );
862
863 assert_eq!(
864 view.text_pos_at_screen_coords(
865 &doc,
866 41,
867 40 + DEFAULT_GUTTER_OFFSET + 4,
868 TextFormat::default(),
869 &TextAnnotations::default(),
870 true
871 ),
872 Some(5)
873 );
874
875 assert_eq!(
876 view.text_pos_at_screen_coords(
877 &doc,
878 41,
879 40 + DEFAULT_GUTTER_OFFSET + 7,
880 TextFormat::default(),
881 &TextAnnotations::default(),
882 true
883 ),
884 Some(8)
885 );
886
887 assert_eq!(
888 view.text_pos_at_screen_coords(
889 &doc,
890 41,
891 80,
892 TextFormat::default(),
893 &TextAnnotations::default(),
894 true
895 ),
896 Some(8)
897 );
898 }
899
900 #[test]
901 fn test_text_pos_at_screen_coords_without_line_numbers_gutter() {
902 let mut view = View::new(
903 DocumentId::default(),
904 GutterConfig {
905 layout: vec![GutterType::Diagnostics],
906 line_numbers: GutterLineNumbersConfig::default(),
907 },
908 );
909 view.area = Rect::new(40, 40, 40, 40);
910 let rope = Rope::from_str("abc\n\tdef");
911 let mut doc = Document::from(
912 rope,
913 None,
914 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
915 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
916 );
917 doc.ensure_view_init(view.id);
918 assert_eq!(
919 view.text_pos_at_screen_coords(
920 &doc,
921 41,
922 40 + DEFAULT_GUTTER_OFFSET_ONLY_DIAGNOSTICS + 1,
923 TextFormat::default(),
924 &TextAnnotations::default(),
925 true
926 ),
927 Some(4)
928 );
929 }
930
931 #[test]
932 fn test_text_pos_at_screen_coords_without_any_gutters() {
933 let mut view = View::new(
934 DocumentId::default(),
935 GutterConfig {
936 layout: vec![],
937 line_numbers: GutterLineNumbersConfig::default(),
938 },
939 );
940 view.area = Rect::new(40, 40, 40, 40);
941 let rope = Rope::from_str("abc\n\tdef");
942 let mut doc = Document::from(
943 rope,
944 None,
945 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
946 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
947 );
948 doc.ensure_view_init(view.id);
949 assert_eq!(
950 view.text_pos_at_screen_coords(
951 &doc,
952 41,
953 40 + 1,
954 TextFormat::default(),
955 &TextAnnotations::default(),
956 true
957 ),
958 Some(4)
959 );
960 }
961
962 #[test]
963 fn test_text_pos_at_screen_coords_cjk() {
964 let mut view = View::new(DocumentId::default(), GutterConfig::default());
965 view.area = Rect::new(40, 40, 40, 40);
966 let rope = Rope::from_str("Hi! こんにちは皆さん");
967 let mut doc = Document::from(
968 rope,
969 None,
970 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
971 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
972 );
973 doc.ensure_view_init(view.id);
974
975 assert_eq!(
976 view.text_pos_at_screen_coords(
977 &doc,
978 40,
979 40 + DEFAULT_GUTTER_OFFSET,
980 TextFormat::default(),
981 &TextAnnotations::default(),
982 true
983 ),
984 Some(0)
985 );
986
987 assert_eq!(
988 view.text_pos_at_screen_coords(
989 &doc,
990 40,
991 40 + DEFAULT_GUTTER_OFFSET + 4,
992 TextFormat::default(),
993 &TextAnnotations::default(),
994 true
995 ),
996 Some(4)
997 );
998 assert_eq!(
999 view.text_pos_at_screen_coords(
1000 &doc,
1001 40,
1002 40 + DEFAULT_GUTTER_OFFSET + 5,
1003 TextFormat::default(),
1004 &TextAnnotations::default(),
1005 true
1006 ),
1007 Some(4)
1008 );
1009
1010 assert_eq!(
1011 view.text_pos_at_screen_coords(
1012 &doc,
1013 40,
1014 40 + DEFAULT_GUTTER_OFFSET + 6,
1015 TextFormat::default(),
1016 &TextAnnotations::default(),
1017 true
1018 ),
1019 Some(5)
1020 );
1021
1022 assert_eq!(
1023 view.text_pos_at_screen_coords(
1024 &doc,
1025 40,
1026 40 + DEFAULT_GUTTER_OFFSET + 7,
1027 TextFormat::default(),
1028 &TextAnnotations::default(),
1029 true
1030 ),
1031 Some(5)
1032 );
1033
1034 assert_eq!(
1035 view.text_pos_at_screen_coords(
1036 &doc,
1037 40,
1038 40 + DEFAULT_GUTTER_OFFSET + 8,
1039 TextFormat::default(),
1040 &TextAnnotations::default(),
1041 true
1042 ),
1043 Some(6)
1044 );
1045 }
1046
1047 #[test]
1048 fn test_text_pos_at_screen_coords_graphemes() {
1049 let mut view = View::new(DocumentId::default(), GutterConfig::default());
1050 view.area = Rect::new(40, 40, 40, 40);
1051 let rope = Rope::from_str("Hèl̀l̀ò world!");
1052 let mut doc = Document::from(
1053 rope,
1054 None,
1055 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
1056 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
1057 );
1058 doc.ensure_view_init(view.id);
1059
1060 assert_eq!(
1061 view.text_pos_at_screen_coords(
1062 &doc,
1063 40,
1064 40 + DEFAULT_GUTTER_OFFSET,
1065 TextFormat::default(),
1066 &TextAnnotations::default(),
1067 true
1068 ),
1069 Some(0)
1070 );
1071
1072 assert_eq!(
1073 view.text_pos_at_screen_coords(
1074 &doc,
1075 40,
1076 40 + DEFAULT_GUTTER_OFFSET + 1,
1077 TextFormat::default(),
1078 &TextAnnotations::default(),
1079 true
1080 ),
1081 Some(1)
1082 );
1083
1084 assert_eq!(
1085 view.text_pos_at_screen_coords(
1086 &doc,
1087 40,
1088 40 + DEFAULT_GUTTER_OFFSET + 2,
1089 TextFormat::default(),
1090 &TextAnnotations::default(),
1091 true
1092 ),
1093 Some(3)
1094 );
1095
1096 assert_eq!(
1097 view.text_pos_at_screen_coords(
1098 &doc,
1099 40,
1100 40 + DEFAULT_GUTTER_OFFSET + 3,
1101 TextFormat::default(),
1102 &TextAnnotations::default(),
1103 true
1104 ),
1105 Some(5)
1106 );
1107
1108 assert_eq!(
1109 view.text_pos_at_screen_coords(
1110 &doc,
1111 40,
1112 40 + DEFAULT_GUTTER_OFFSET + 4,
1113 TextFormat::default(),
1114 &TextAnnotations::default(),
1115 true
1116 ),
1117 Some(7)
1118 );
1119 }
1120
1121 /// `JumpList::remove` dropped every entry belonging to a document (e.g. when
1122 /// a buffer is closed) but left `current` untouched. Because `current` is an
1123 /// index into the entry list, removing entries that sit *before* it leaves
1124 /// it pointing at a different entry, or past the end of a now-shorter list.
1125 /// The next `forward`/`backward` then navigates from the wrong place (or
1126 /// no-ops). `remove` must shift `current` left by the number of removed
1127 /// entries that preceded it, and clamp it to the new length.
1128 #[test]
1129 fn jumplist_remove_adjusts_current() {
1130 let doc_a = DocumentId::new(1);
1131 let doc_b = DocumentId::new(2);
1132
1133 let entries =
1134 |jumps: &JumpList| -> Vec<DocumentId> { jumps.iter().map(|(id, _)| *id).collect() };
1135
1136 // Build [A, B, A, B, A] directly. `push`/`push_impl` truncate to
1137 // `current` and advance it, so we set the fields explicitly to control
1138 // exactly where the navigation cursor sits.
1139 let make = |current: usize| -> JumpList {
1140 let mut jumps = JumpList::new((doc_a, Selection::point(0)));
1141 jumps.jumps = [
1142 (doc_a, Selection::point(0)),
1143 (doc_b, Selection::point(1)),
1144 (doc_a, Selection::point(2)),
1145 (doc_b, Selection::point(3)),
1146 (doc_a, Selection::point(4)),
1147 ]
1148 .into_iter()
1149 .collect();
1150 jumps.current = current;
1151 jumps
1152 };
1153
1154 // `current` in the middle: two A entries (indices 0, 2) precede index 3.
1155 let mut jumps = make(3);
1156 jumps.remove(&doc_a);
1157 assert_eq!(entries(&jumps), vec![doc_b, doc_b]);
1158 // The B entry that was at index 3 is now at index 1; `current` follows it.
1159 assert_eq!(jumps.current, 1);
1160 assert_eq!(
1161 jumps.iter().nth(jumps.current),
1162 Some(&(doc_b, Selection::point(3)))
1163 );
1164
1165 // `current` at the tip (== len): must stay a valid tip (== new len),
1166 // not dangle past the end.
1167 let mut jumps = make(5);
1168 jumps.remove(&doc_a);
1169 assert_eq!(jumps.current, jumps.jumps.len());
1170 assert_eq!(jumps.current, 2);
1171
1172 // Removing the *only* remaining document empties the list; `current`
1173 // must clamp to 0 rather than point past the end.
1174 let mut jumps = make(3);
1175 jumps.remove(&doc_a);
1176 jumps.remove(&doc_b);
1177 assert_eq!(jumps.jumps.len(), 0);
1178 assert_eq!(jumps.current, 0);
1179
1180 // `current` at the front with leading removed entries: clamps to 0.
1181 let mut jumps = make(0);
1182 jumps.remove(&doc_a);
1183 assert_eq!(jumps.current, 0);
1184 assert_eq!(entries(&jumps), vec![doc_b, doc_b]);
1185 }
1186
1187 /// `JumpList::push` records a jump using the document's *current* selection
1188 /// (i.e. positions valid at the document's current history revision), but it
1189 /// never advances the view's `doc_revisions` entry for that document. As a
1190 /// result, the next `View::sync_changes` computes `changes_since(old_revision)`
1191 /// and maps *every* jump - including the freshly pushed one - through a
1192 /// changeset whose pre-image is the *older*, shorter document. A jump that
1193 /// points past the end of that older document then runs off the end of the
1194 /// changeset and panics in `ChangeSet::update_positions`
1195 /// ("Positions ... are out of range for changeset len ...").
1196 ///
1197 /// To trigger the stale `doc_revisions` window without reaching into private
1198 /// fields we use two views over the same document: committing an edit through
1199 /// `view2` advances the shared document's history and updates *view2*'s
1200 /// `doc_revisions`, while `view1`'s `doc_revisions` is left pointing at the
1201 /// pre-edit revision. Pushing a jump into `view1` afterwards reproduces the
1202 /// exact situation `push` fails to guard against.
1203 #[test]
1204 fn jumplist_push_keeps_doc_revisions_in_sync() {
1205 let config = Arc::new(ArcSwap::new(Arc::new(Config::default())));
1206 let loader = Arc::new(ArcSwap::from_pointee(syntax::Loader::default()));
1207
1208 // Revision 0: a short document.
1209 let mut doc = Document::from(Rope::from_str("ab"), None, config, loader);
1210
1211 let mut view1 = View::new(doc.id(), GutterConfig::default());
1212 let mut view2 = View::new(doc.id(), GutterConfig::default());
1213 doc.ensure_view_init(view1.id);
1214 doc.ensure_view_init(view2.id);
1215
1216 // Sync view1 at revision 0 so its `doc_revisions` records the short doc.
1217 view1.sync_changes(&mut doc);
1218 assert_eq!(doc.get_current_revision(), 0);
1219
1220 // Commit an insertion *through view2*, growing the document and advancing
1221 // its history to revision 1. Only view2's `doc_revisions` is updated here;
1222 // view1 still believes the document is at revision 0.
1223 let insert = Transaction::change(
1224 doc.text(),
1225 std::iter::once((2, 2, Some("XXXXXXXXXX".into()))),
1226 );
1227 assert!(doc.apply(&insert, view2.id));
1228 doc.append_changes_to_history(&mut view2);
1229 assert_eq!(doc.get_current_revision(), 1);
1230 let len = doc.text().len_chars();
1231 assert_eq!(len, 12);
1232
1233 // Push a jump into view1 at the end of the *current* (revision 1) document.
1234 // This selection is perfectly valid for the document as it stands now.
1235 //
1236 // `View::push_jump` syncs view1 to the document's current revision before
1237 // appending, so the new entry and `doc_revisions` agree. The raw
1238 // `view1.jumps.push(...)` would instead leave the entry ahead of
1239 // `doc_revisions` (still revision 0), and the `sync_changes` below would
1240 // map position 12 through the revision 0 -> 1 changeset (pre-image only
1241 // 2 chars) and panic in `ChangeSet::update_positions`.
1242 let jump = (doc.id(), Selection::point(len));
1243 view1.push_jump(&mut doc, jump);
1244
1245 // With the fix in place this is a no-op for the freshly pushed entry and
1246 // the jump remains a valid, in-bounds selection.
1247 view1.sync_changes(&mut doc);
1248
1249 let (_, selection) = view1.jumps.iter().next_back().unwrap();
1250 assert!(
1251 selection.primary().head <= doc.text().len_chars(),
1252 "jumplist selection must stay within document bounds after sync",
1253 );
1254 }
1255 }