Debian Codegraph @

helix-core/src/position.rs

raw symbols SCIP
1 use std::{
2 borrow::Cow,
3 cmp::Ordering,
4 ops::{Add, AddAssign, Sub, SubAssign},
5 };
6
7 use helix_stdx::rope::RopeSliceExt;
8
9 use crate::{
10 chars::char_is_line_ending,
11 doc_formatter::{DocumentFormatter, TextFormat},
12 graphemes::{ensure_grapheme_boundary_prev, grapheme_width},
13 line_ending::line_end_char_index,
14 text_annotations::TextAnnotations,
15 RopeSlice,
16 };
17
18 /// Represents a single point in a text buffer. Zero indexed.
19 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
20 pub struct Position {
21 pub row: usize,
22 pub col: usize,
23 }
24
25 impl AddAssign for Position {
26 fn add_assign(&mut self, rhs: Self) {
27 self.row += rhs.row;
28 self.col += rhs.col;
29 }
30 }
31
32 impl SubAssign for Position {
33 fn sub_assign(&mut self, rhs: Self) {
34 self.row -= rhs.row;
35 self.col -= rhs.col;
36 }
37 }
38
39 impl Sub for Position {
40 type Output = Position;
41
42 fn sub(mut self, rhs: Self) -> Self::Output {
43 self -= rhs;
44 self
45 }
46 }
47
48 impl Add for Position {
49 type Output = Position;
50
51 fn add(mut self, rhs: Self) -> Self::Output {
52 self += rhs;
53 self
54 }
55 }
56
57 impl Position {
58 pub const fn new(row: usize, col: usize) -> Self {
59 Self { row, col }
60 }
61
62 pub const fn is_zero(self) -> bool {
63 self.row == 0 && self.col == 0
64 }
65
66 // TODO: generalize
67 pub fn traverse(self, text: &crate::Tendril) -> Self {
68 let Self { mut row, mut col } = self;
69 // TODO: there should be a better way here
70 let mut chars = text.chars().peekable();
71 while let Some(ch) = chars.next() {
72 if char_is_line_ending(ch) && !(ch == '\r' && chars.peek() == Some(&'\n')) {
73 row += 1;
74 col = 0;
75 } else {
76 col += 1;
77 }
78 }
79 Self { row, col }
80 }
81 }
82
83 impl From<(usize, usize)> for Position {
84 fn from(tuple: (usize, usize)) -> Self {
85 Self {
86 row: tuple.0,
87 col: tuple.1,
88 }
89 }
90 }
91
92 /// Convert a character index to (line, column) coordinates.
93 ///
94 /// column in `char` count which can be used for row:column display in
95 /// status line. See [`visual_coords_at_pos`] for a visual one.
96 pub fn coords_at_pos(text: RopeSlice, pos: usize) -> Position {
97 let line = text.char_to_line(pos);
98
99 let line_start = text.line_to_char(line);
100 let pos = ensure_grapheme_boundary_prev(text, pos);
101 let col = text.slice(line_start..pos).graphemes().count();
102
103 Position::new(line, col)
104 }
105
106 /// Convert a character index to (line, column) coordinates visually.
107 ///
108 /// Takes \t, double-width characters (CJK) into account as well as text
109 /// not in the document in the future.
110 /// See [`coords_at_pos`] for an "objective" one.
111 ///
112 /// This function should be used very rarely. Usually `visual_offset_from_anchor`
113 /// or `visual_offset_from_block` is preferable. However when you want to compute the
114 /// actual visual row/column in the text (not what is actually shown on screen)
115 /// then you should use this function. For example aligning text should ignore virtual
116 /// text and softwrap.
117 #[deprecated = "Doesn't account for softwrap or decorations, use visual_offset_from_anchor instead"]
118 pub fn visual_coords_at_pos(text: RopeSlice, pos: usize, tab_width: usize) -> Position {
119 let line = text.char_to_line(pos);
120
121 let line_start = text.line_to_char(line);
122 let pos = ensure_grapheme_boundary_prev(text, pos);
123
124 let mut col = 0;
125
126 for grapheme in text.slice(line_start..pos).graphemes() {
127 if grapheme == "\t" {
128 col += tab_width - (col % tab_width);
129 } else {
130 let grapheme = Cow::from(grapheme);
131 col += grapheme_width(&grapheme);
132 }
133 }
134
135 Position::new(line, col)
136 }
137
138 /// Returns the visual offset from the start of the first visual line
139 /// in the block that contains anchor.
140 /// Text is always wrapped at blocks, they usually correspond to
141 /// actual line breaks but for very long lines
142 /// softwrapping positions are estimated with an O(1) algorithm
143 /// to ensure consistent performance for large lines (currently unimplemented)
144 ///
145 /// Usually you want to use `visual_offset_from_anchor` instead but this function
146 /// can be useful (and faster) if
147 /// * You already know the visual position of the block
148 /// * You only care about the horizontal offset (column) and not the vertical offset (row)
149 pub fn visual_offset_from_block(
150 text: RopeSlice,
151 anchor: usize,
152 pos: usize,
153 text_fmt: &TextFormat,
154 annotations: &TextAnnotations,
155 ) -> (Position, usize) {
156 let mut last_pos = Position::default();
157 let mut formatter =
158 DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
159 let block_start = formatter.next_char_pos();
160
161 while let Some(grapheme) = formatter.next() {
162 last_pos = grapheme.visual_pos;
163 if formatter.next_char_pos() > pos {
164 return (grapheme.visual_pos, block_start);
165 }
166 }
167
168 (last_pos, block_start)
169 }
170
171 /// Returns the height of the given text when softwrapping
172 pub fn softwrapped_dimensions(text: RopeSlice, text_fmt: &TextFormat) -> (usize, u16) {
173 let last_pos =
174 visual_offset_from_block(text, 0, usize::MAX, text_fmt, &TextAnnotations::default()).0;
175 if last_pos.row == 0 {
176 (1, last_pos.col as u16)
177 } else {
178 (last_pos.row + 1, text_fmt.viewport_width)
179 }
180 }
181
182 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
183 pub enum VisualOffsetError {
184 PosBeforeAnchorRow,
185 PosAfterMaxRow,
186 }
187
188 /// Returns the visual offset from the start of the visual line
189 /// that contains anchor.
190 pub fn visual_offset_from_anchor(
191 text: RopeSlice,
192 anchor: usize,
193 pos: usize,
194 text_fmt: &TextFormat,
195 annotations: &TextAnnotations,
196 max_rows: usize,
197 ) -> Result<(Position, usize), VisualOffsetError> {
198 let mut formatter =
199 DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
200 let mut anchor_line = None;
201 let mut found_pos = None;
202 let mut last_pos = Position::default();
203
204 let block_start = formatter.next_char_pos();
205 if pos < block_start {
206 return Err(VisualOffsetError::PosBeforeAnchorRow);
207 }
208
209 while let Some(grapheme) = formatter.next() {
210 last_pos = grapheme.visual_pos;
211
212 if formatter.next_char_pos() > pos {
213 if let Some(anchor_line) = anchor_line {
214 last_pos.row -= anchor_line;
215 return Ok((last_pos, block_start));
216 } else {
217 found_pos = Some(last_pos);
218 }
219 }
220 if formatter.next_char_pos() > anchor && anchor_line.is_none() {
221 if let Some(mut found_pos) = found_pos {
222 return if found_pos.row == last_pos.row {
223 found_pos.row = 0;
224 Ok((found_pos, block_start))
225 } else {
226 Err(VisualOffsetError::PosBeforeAnchorRow)
227 };
228 } else {
229 anchor_line = Some(last_pos.row);
230 }
231 }
232
233 if let Some(anchor_line) = anchor_line {
234 if grapheme.visual_pos.row >= anchor_line + max_rows {
235 return Err(VisualOffsetError::PosAfterMaxRow);
236 }
237 }
238 }
239
240 let anchor_line = anchor_line.unwrap_or(last_pos.row);
241 last_pos.row -= anchor_line;
242
243 Ok((last_pos, block_start))
244 }
245
246 /// Convert (line, column) coordinates to a character index.
247 ///
248 /// If the `line` coordinate is beyond the end of the file, the EOF
249 /// position will be returned.
250 ///
251 /// If the `column` coordinate is past the end of the given line, the
252 /// line-end position will be returned. What constitutes the "line-end
253 /// position" depends on the parameter `limit_before_line_ending`. If it's
254 /// `true`, the line-end position will be just *before* the line ending
255 /// character. If `false` it will be just *after* the line ending
256 /// character--on the border between the current line and the next.
257 ///
258 /// Usually you only want `limit_before_line_ending` to be `true` if you're working
259 /// with left-side block-cursor positions, as this prevents the the block cursor
260 /// from jumping to the next line. Otherwise you typically want it to be `false`,
261 /// such as when dealing with raw anchor/head positions.
262 pub fn pos_at_coords(text: RopeSlice, coords: Position, limit_before_line_ending: bool) -> usize {
263 let Position { mut row, col } = coords;
264 if limit_before_line_ending {
265 let lines = text.len_lines() - 1;
266
267 row = row.min(if crate::line_ending::get_line_ending(&text).is_some() {
268 // if the last line is empty, don't jump to it
269 lines - 1
270 } else {
271 lines
272 });
273 };
274 let line_start = text.line_to_char(row);
275 let line_end = if limit_before_line_ending {
276 line_end_char_index(&text, row)
277 } else {
278 text.line_to_char((row + 1).min(text.len_lines()))
279 };
280
281 let mut col_char_offset = 0;
282 for (i, g) in text.slice(line_start..line_end).graphemes().enumerate() {
283 if i == col {
284 break;
285 }
286 col_char_offset += g.chars().count();
287 }
288
289 line_start + col_char_offset
290 }
291
292 /// Convert visual (line, column) coordinates to a character index.
293 ///
294 /// If the `line` coordinate is beyond the end of the file, the EOF
295 /// position will be returned.
296 ///
297 /// If the `column` coordinate is past the end of the given line, the
298 /// line-end position (in this case, just before the line ending
299 /// character) will be returned.
300 /// This function should be used very rarely. Usually `char_idx_at_visual_offset` is preferable.
301 /// However when you want to compute a char position from the visual row/column in the text
302 /// (not what is actually shown on screen) then you should use this function.
303 /// For example aligning text should ignore virtual text and softwrap.
304 #[deprecated = "Doesn't account for softwrap or decorations, use char_idx_at_visual_offset instead"]
305 pub fn pos_at_visual_coords(text: RopeSlice, coords: Position, tab_width: usize) -> usize {
306 let Position { mut row, col } = coords;
307 row = row.min(text.len_lines() - 1);
308 let line_start = text.line_to_char(row);
309 let line_end = line_end_char_index(&text, row);
310
311 let mut col_char_offset = 0;
312 let mut cols_remaining = col;
313 for grapheme in text.slice(line_start..line_end).graphemes() {
314 let grapheme_width = if grapheme == "\t" {
315 tab_width - ((col - cols_remaining) % tab_width)
316 } else {
317 let grapheme = Cow::from(grapheme);
318 grapheme_width(&grapheme)
319 };
320
321 // If pos is in the middle of a wider grapheme (tab for example)
322 // return the starting offset.
323 if grapheme_width > cols_remaining {
324 break;
325 }
326
327 cols_remaining -= grapheme_width;
328 col_char_offset += grapheme.chars().count();
329 }
330
331 line_start + col_char_offset
332 }
333
334 /// Returns the char index on the visual line `row_offset` below the visual line of
335 /// the provided char index `anchor` that is closest to the supplied visual `column`.
336 ///
337 /// If the targeted visual line is entirely covered by virtual text the last
338 /// char position before the virtual text and a virtual offset is returned instead.
339 ///
340 /// If no (text) grapheme starts at exactly at the specified column the
341 /// start of the grapheme to the left is returned. If there is no grapheme
342 /// to the left (for example if the line starts with virtual text) then the positioning
343 /// of the next grapheme to the right is returned.
344 ///
345 /// If the `line` coordinate is beyond the end of the file, the EOF
346 /// position will be returned.
347 ///
348 /// If the `column` coordinate is past the end of the given line, the
349 /// line-end position (in this case, just before the line ending
350 /// character) will be returned.
351 ///
352 /// # Returns
353 ///
354 /// `(real_char_idx, virtual_lines)`
355 ///
356 /// The nearest character idx "closest" (see above) to the specified visual offset
357 /// on the visual line is returned if the visual line contains any text:
358 /// If the visual line at the specified offset is a virtual line generated by a `LineAnnotation`
359 /// the previous char_index is returned, together with the remaining vertical offset (`virtual_lines`)
360 pub fn char_idx_at_visual_offset(
361 text: RopeSlice,
362 mut anchor: usize,
363 mut row_offset: isize,
364 column: usize,
365 text_fmt: &TextFormat,
366 annotations: &TextAnnotations,
367 ) -> (usize, usize) {
368 let mut pos = anchor;
369 // convert row relative to visual line containing anchor to row relative to a block containing anchor (anchor may change)
370 loop {
371 let (visual_pos_in_block, block_char_offset) =
372 visual_offset_from_block(text, anchor, pos, text_fmt, annotations);
373 row_offset += visual_pos_in_block.row as isize;
374 anchor = block_char_offset;
375 if row_offset >= 0 {
376 break;
377 }
378
379 if block_char_offset == 0 {
380 row_offset = 0;
381 break;
382 }
383 // the row_offset is negative so we need to look at the previous block
384 // set the anchor to the last char before the current block so that we can compute
385 // the distance of this block from the start of the previous block
386 pos = anchor;
387 anchor -= 1;
388 }
389
390 char_idx_at_visual_block_offset(
391 text,
392 anchor,
393 row_offset as usize,
394 column,
395 text_fmt,
396 annotations,
397 )
398 }
399
400 /// This function behaves the same as `char_idx_at_visual_offset`, except that
401 /// the vertical offset `row` is always computed relative to the block that contains `anchor`
402 /// instead of the visual line that contains `anchor`.
403 /// Usually `char_idx_at_visual_offset` is more useful but this function can be
404 /// used in some situations as an optimization when `visual_offset_from_block` was used
405 ///
406 /// # Returns
407 ///
408 /// `(real_char_idx, virtual_lines)`
409 ///
410 /// See `char_idx_at_visual_offset` for details
411 pub fn char_idx_at_visual_block_offset(
412 text: RopeSlice,
413 anchor: usize,
414 row: usize,
415 column: usize,
416 text_fmt: &TextFormat,
417 annotations: &TextAnnotations,
418 ) -> (usize, usize) {
419 let mut formatter =
420 DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
421 let mut last_char_idx = formatter.next_char_pos();
422 let mut found_non_virtual_on_row = false;
423 let mut last_row = 0;
424 for grapheme in &mut formatter {
425 match grapheme.visual_pos.row.cmp(&row) {
426 Ordering::Equal => {
427 if grapheme.visual_pos.col + grapheme.width() > column {
428 if !grapheme.is_virtual() {
429 return (grapheme.char_idx, 0);
430 } else if found_non_virtual_on_row {
431 return (last_char_idx, 0);
432 }
433 } else if !grapheme.is_virtual() {
434 found_non_virtual_on_row = true;
435 last_char_idx = grapheme.char_idx;
436 }
437 }
438 Ordering::Greater if found_non_virtual_on_row => return (last_char_idx, 0),
439 Ordering::Greater => return (last_char_idx, row - last_row),
440 Ordering::Less => {
441 if !grapheme.is_virtual() {
442 last_row = grapheme.visual_pos.row;
443 last_char_idx = grapheme.char_idx;
444 }
445 }
446 }
447 }
448
449 (formatter.next_char_pos(), 0)
450 }
451
452 #[cfg(test)]
453 mod test {
454 use super::*;
455 use crate::text_annotations::InlineAnnotation;
456 use crate::Rope;
457
458 #[test]
459 fn test_ordering() {
460 // (0, 5) is less than (1, 0)
461 assert!(Position::new(0, 5) < Position::new(1, 0));
462 }
463
464 #[test]
465 fn test_coords_at_pos() {
466 let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
467 let slice = text.slice(..);
468 assert_eq!(coords_at_pos(slice, 0), (0, 0).into());
469 assert_eq!(coords_at_pos(slice, 5), (0, 5).into()); // position on \n
470 assert_eq!(coords_at_pos(slice, 6), (1, 0).into()); // position on w
471 assert_eq!(coords_at_pos(slice, 7), (1, 1).into()); // position on o
472 assert_eq!(coords_at_pos(slice, 10), (1, 4).into()); // position on d
473
474 // Test with wide characters.
475 let text = Rope::from("今日はいい\n");
476 let slice = text.slice(..);
477 assert_eq!(coords_at_pos(slice, 0), (0, 0).into());
478 assert_eq!(coords_at_pos(slice, 1), (0, 1).into());
479 assert_eq!(coords_at_pos(slice, 2), (0, 2).into());
480 assert_eq!(coords_at_pos(slice, 3), (0, 3).into());
481 assert_eq!(coords_at_pos(slice, 4), (0, 4).into());
482 assert_eq!(coords_at_pos(slice, 5), (0, 5).into());
483 assert_eq!(coords_at_pos(slice, 6), (1, 0).into());
484
485 // Test with grapheme clusters.
486 let text = Rope::from("a̐éö̲\r\n");
487 let slice = text.slice(..);
488 assert_eq!(coords_at_pos(slice, 0), (0, 0).into());
489 assert_eq!(coords_at_pos(slice, 2), (0, 1).into());
490 assert_eq!(coords_at_pos(slice, 4), (0, 2).into());
491 assert_eq!(coords_at_pos(slice, 7), (0, 3).into());
492 assert_eq!(coords_at_pos(slice, 9), (1, 0).into());
493
494 // Test with wide-character grapheme clusters.
495 let text = Rope::from("किमपि\n");
496 let slice = text.slice(..);
497 assert_eq!(coords_at_pos(slice, 0), (0, 0).into());
498 assert_eq!(coords_at_pos(slice, 2), (0, 1).into());
499 assert_eq!(coords_at_pos(slice, 3), (0, 2).into());
500 assert_eq!(coords_at_pos(slice, 5), (0, 3).into());
501 assert_eq!(coords_at_pos(slice, 6), (1, 0).into());
502
503 // Test with tabs.
504 let text = Rope::from("\tHello\n");
505 let slice = text.slice(..);
506 assert_eq!(coords_at_pos(slice, 0), (0, 0).into());
507 assert_eq!(coords_at_pos(slice, 1), (0, 1).into());
508 assert_eq!(coords_at_pos(slice, 2), (0, 2).into());
509 }
510
511 #[test]
512 #[allow(deprecated)]
513 fn test_visual_coords_at_pos() {
514 let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
515 let slice = text.slice(..);
516 assert_eq!(visual_coords_at_pos(slice, 0, 8), (0, 0).into());
517 assert_eq!(visual_coords_at_pos(slice, 5, 8), (0, 5).into()); // position on \n
518 assert_eq!(visual_coords_at_pos(slice, 6, 8), (1, 0).into()); // position on w
519 assert_eq!(visual_coords_at_pos(slice, 7, 8), (1, 1).into()); // position on o
520 assert_eq!(visual_coords_at_pos(slice, 10, 8), (1, 4).into()); // position on d
521
522 // Test with wide characters.
523 let text = Rope::from("今日はいい\n");
524 let slice = text.slice(..);
525 assert_eq!(visual_coords_at_pos(slice, 0, 8), (0, 0).into());
526 assert_eq!(visual_coords_at_pos(slice, 1, 8), (0, 2).into());
527 assert_eq!(visual_coords_at_pos(slice, 2, 8), (0, 4).into());
528 assert_eq!(visual_coords_at_pos(slice, 3, 8), (0, 6).into());
529 assert_eq!(visual_coords_at_pos(slice, 4, 8), (0, 8).into());
530 assert_eq!(visual_coords_at_pos(slice, 5, 8), (0, 10).into());
531 assert_eq!(visual_coords_at_pos(slice, 6, 8), (1, 0).into());
532
533 // Test with grapheme clusters.
534 let text = Rope::from("a̐éö̲\r\n");
535 let slice = text.slice(..);
536 assert_eq!(visual_coords_at_pos(slice, 0, 8), (0, 0).into());
537 assert_eq!(visual_coords_at_pos(slice, 2, 8), (0, 1).into());
538 assert_eq!(visual_coords_at_pos(slice, 4, 8), (0, 2).into());
539 assert_eq!(visual_coords_at_pos(slice, 7, 8), (0, 3).into());
540 assert_eq!(visual_coords_at_pos(slice, 9, 8), (1, 0).into());
541
542 // Test with wide-character grapheme clusters.
543 // TODO: account for cluster.
544 let text = Rope::from("किमपि\n");
545 let slice = text.slice(..);
546 assert_eq!(visual_coords_at_pos(slice, 0, 8), (0, 0).into());
547 assert_eq!(visual_coords_at_pos(slice, 2, 8), (0, 2).into());
548 assert_eq!(visual_coords_at_pos(slice, 3, 8), (0, 3).into());
549 assert_eq!(visual_coords_at_pos(slice, 5, 8), (0, 5).into());
550 assert_eq!(visual_coords_at_pos(slice, 6, 8), (1, 0).into());
551
552 // Test with tabs.
553 let text = Rope::from("\tHello\n");
554 let slice = text.slice(..);
555 assert_eq!(visual_coords_at_pos(slice, 0, 8), (0, 0).into());
556 assert_eq!(visual_coords_at_pos(slice, 1, 8), (0, 8).into());
557 assert_eq!(visual_coords_at_pos(slice, 2, 8), (0, 9).into());
558 }
559
560 #[test]
561 fn test_visual_off_from_block() {
562 let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
563 let slice = text.slice(..);
564 let annot = TextAnnotations::default();
565 let text_fmt = TextFormat::default();
566 assert_eq!(
567 visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
568 (0, 0).into()
569 );
570 assert_eq!(
571 visual_offset_from_block(slice, 0, 5, &text_fmt, &annot).0,
572 (0, 5).into()
573 ); // position on \n
574 assert_eq!(
575 visual_offset_from_block(slice, 0, 6, &text_fmt, &annot).0,
576 (1, 0).into()
577 ); // position on w
578 assert_eq!(
579 visual_offset_from_block(slice, 0, 7, &text_fmt, &annot).0,
580 (1, 1).into()
581 ); // position on o
582 assert_eq!(
583 visual_offset_from_block(slice, 0, 10, &text_fmt, &annot).0,
584 (1, 4).into()
585 ); // position on d
586
587 // Test with wide characters.
588 let text = Rope::from("今日はいい\n");
589 let slice = text.slice(..);
590 assert_eq!(
591 visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
592 (0, 0).into()
593 );
594 assert_eq!(
595 visual_offset_from_block(slice, 0, 1, &text_fmt, &annot).0,
596 (0, 2).into()
597 );
598 assert_eq!(
599 visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
600 (0, 4).into()
601 );
602 assert_eq!(
603 visual_offset_from_block(slice, 0, 3, &text_fmt, &annot).0,
604 (0, 6).into()
605 );
606 assert_eq!(
607 visual_offset_from_block(slice, 0, 4, &text_fmt, &annot).0,
608 (0, 8).into()
609 );
610 assert_eq!(
611 visual_offset_from_block(slice, 0, 5, &text_fmt, &annot).0,
612 (0, 10).into()
613 );
614 assert_eq!(
615 visual_offset_from_block(slice, 0, 6, &text_fmt, &annot).0,
616 (1, 0).into()
617 );
618
619 // Test with grapheme clusters.
620 let text = Rope::from("a̐éö̲\r\n");
621 let slice = text.slice(..);
622 assert_eq!(
623 visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
624 (0, 0).into()
625 );
626 assert_eq!(
627 visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
628 (0, 1).into()
629 );
630 assert_eq!(
631 visual_offset_from_block(slice, 0, 4, &text_fmt, &annot).0,
632 (0, 2).into()
633 );
634 assert_eq!(
635 visual_offset_from_block(slice, 0, 7, &text_fmt, &annot).0,
636 (0, 3).into()
637 );
638 assert_eq!(
639 visual_offset_from_block(slice, 0, 9, &text_fmt, &annot).0,
640 (1, 0).into()
641 );
642
643 // Test with wide-character grapheme clusters.
644 // TODO: account for cluster.
645 let text = Rope::from("किमपि\n");
646 let slice = text.slice(..);
647 assert_eq!(
648 visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
649 (0, 0).into()
650 );
651 assert_eq!(
652 visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
653 (0, 2).into()
654 );
655 assert_eq!(
656 visual_offset_from_block(slice, 0, 3, &text_fmt, &annot).0,
657 (0, 3).into()
658 );
659 assert_eq!(
660 visual_offset_from_block(slice, 0, 5, &text_fmt, &annot).0,
661 (0, 5).into()
662 );
663 assert_eq!(
664 visual_offset_from_block(slice, 0, 6, &text_fmt, &annot).0,
665 (1, 0).into()
666 );
667
668 // Test with tabs.
669 let text = Rope::from("\tHello\n");
670 let slice = text.slice(..);
671 assert_eq!(
672 visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
673 (0, 0).into()
674 );
675 assert_eq!(
676 visual_offset_from_block(slice, 0, 1, &text_fmt, &annot).0,
677 (0, 4).into()
678 );
679 assert_eq!(
680 visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
681 (0, 5).into()
682 );
683 }
684 #[test]
685 fn test_pos_at_coords() {
686 let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
687 let slice = text.slice(..);
688 assert_eq!(pos_at_coords(slice, (0, 0).into(), false), 0);
689 assert_eq!(pos_at_coords(slice, (0, 5).into(), false), 5); // position on \n
690 assert_eq!(pos_at_coords(slice, (0, 6).into(), false), 6); // position after \n
691 assert_eq!(pos_at_coords(slice, (0, 6).into(), true), 5); // position after \n
692 assert_eq!(pos_at_coords(slice, (1, 0).into(), false), 6); // position on w
693 assert_eq!(pos_at_coords(slice, (1, 1).into(), false), 7); // position on o
694 assert_eq!(pos_at_coords(slice, (1, 4).into(), false), 10); // position on d
695
696 // Test with wide characters.
697 // TODO: account for character width.
698 let text = Rope::from("今日はいい\n");
699 let slice = text.slice(..);
700 assert_eq!(pos_at_coords(slice, (0, 0).into(), false), 0);
701 assert_eq!(pos_at_coords(slice, (0, 1).into(), false), 1);
702 assert_eq!(pos_at_coords(slice, (0, 2).into(), false), 2);
703 assert_eq!(pos_at_coords(slice, (0, 3).into(), false), 3);
704 assert_eq!(pos_at_coords(slice, (0, 4).into(), false), 4);
705 assert_eq!(pos_at_coords(slice, (0, 5).into(), false), 5);
706 assert_eq!(pos_at_coords(slice, (0, 6).into(), false), 6);
707 assert_eq!(pos_at_coords(slice, (0, 6).into(), true), 5);
708 assert_eq!(pos_at_coords(slice, (1, 0).into(), false), 6);
709
710 // Test with grapheme clusters.
711 let text = Rope::from("a̐éö̲\r\n");
712 let slice = text.slice(..);
713 assert_eq!(pos_at_coords(slice, (0, 0).into(), false), 0);
714 assert_eq!(pos_at_coords(slice, (0, 1).into(), false), 2);
715 assert_eq!(pos_at_coords(slice, (0, 2).into(), false), 4);
716 assert_eq!(pos_at_coords(slice, (0, 3).into(), false), 7); // \r\n is one char here
717 assert_eq!(pos_at_coords(slice, (0, 4).into(), false), 9);
718 assert_eq!(pos_at_coords(slice, (0, 4).into(), true), 7);
719 assert_eq!(pos_at_coords(slice, (1, 0).into(), false), 9);
720
721 // Test with wide-character grapheme clusters.
722 // TODO: account for character width.
723 let text = Rope::from("किमपि");
724 // 2 - 1 - 2 codepoints
725 // TODO: delete handling as per https://news.ycombinator.com/item?id=20058454
726 let slice = text.slice(..);
727 assert_eq!(pos_at_coords(slice, (0, 0).into(), false), 0);
728 assert_eq!(pos_at_coords(slice, (0, 1).into(), false), 2);
729 assert_eq!(pos_at_coords(slice, (0, 2).into(), false), 3);
730 assert_eq!(pos_at_coords(slice, (0, 3).into(), false), 5);
731 assert_eq!(pos_at_coords(slice, (0, 3).into(), true), 5);
732
733 // Test with tabs.
734 // Todo: account for tab stops.
735 let text = Rope::from("\tHello\n");
736 let slice = text.slice(..);
737 assert_eq!(pos_at_coords(slice, (0, 0).into(), false), 0);
738 assert_eq!(pos_at_coords(slice, (0, 1).into(), false), 1);
739 assert_eq!(pos_at_coords(slice, (0, 2).into(), false), 2);
740
741 // Test out of bounds.
742 let text = Rope::new();
743 let slice = text.slice(..);
744 assert_eq!(pos_at_coords(slice, (10, 0).into(), true), 0);
745 assert_eq!(pos_at_coords(slice, (0, 10).into(), true), 0);
746 assert_eq!(pos_at_coords(slice, (10, 10).into(), true), 0);
747 }
748
749 #[test]
750 #[allow(deprecated)]
751 fn test_pos_at_visual_coords() {
752 let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
753 let slice = text.slice(..);
754 assert_eq!(pos_at_visual_coords(slice, (0, 0).into(), 4), 0);
755 assert_eq!(pos_at_visual_coords(slice, (0, 5).into(), 4), 5); // position on \n
756 assert_eq!(pos_at_visual_coords(slice, (0, 6).into(), 4), 5); // position after \n
757 assert_eq!(pos_at_visual_coords(slice, (1, 0).into(), 4), 6); // position on w
758 assert_eq!(pos_at_visual_coords(slice, (1, 1).into(), 4), 7); // position on o
759 assert_eq!(pos_at_visual_coords(slice, (1, 4).into(), 4), 10); // position on d
760
761 // Test with wide characters.
762 let text = Rope::from("今日はいい\n");
763 let slice = text.slice(..);
764 assert_eq!(pos_at_visual_coords(slice, (0, 0).into(), 4), 0);
765 assert_eq!(pos_at_visual_coords(slice, (0, 1).into(), 4), 0);
766 assert_eq!(pos_at_visual_coords(slice, (0, 2).into(), 4), 1);
767 assert_eq!(pos_at_visual_coords(slice, (0, 3).into(), 4), 1);
768 assert_eq!(pos_at_visual_coords(slice, (0, 4).into(), 4), 2);
769 assert_eq!(pos_at_visual_coords(slice, (0, 5).into(), 4), 2);
770 assert_eq!(pos_at_visual_coords(slice, (0, 6).into(), 4), 3);
771 assert_eq!(pos_at_visual_coords(slice, (0, 7).into(), 4), 3);
772 assert_eq!(pos_at_visual_coords(slice, (0, 8).into(), 4), 4);
773 assert_eq!(pos_at_visual_coords(slice, (0, 9).into(), 4), 4);
774 // assert_eq!(pos_at_visual_coords(slice, (0, 10).into(), 4, false), 5);
775 // assert_eq!(pos_at_visual_coords(slice, (0, 10).into(), 4, true), 5);
776 assert_eq!(pos_at_visual_coords(slice, (1, 0).into(), 4), 6);
777
778 // Test with grapheme clusters.
779 let text = Rope::from("a̐éö̲\r\n");
780 let slice = text.slice(..);
781 assert_eq!(pos_at_visual_coords(slice, (0, 0).into(), 4), 0);
782 assert_eq!(pos_at_visual_coords(slice, (0, 1).into(), 4), 2);
783 assert_eq!(pos_at_visual_coords(slice, (0, 2).into(), 4), 4);
784 assert_eq!(pos_at_visual_coords(slice, (0, 3).into(), 4), 7); // \r\n is one char here
785 assert_eq!(pos_at_visual_coords(slice, (0, 4).into(), 4), 7);
786 assert_eq!(pos_at_visual_coords(slice, (1, 0).into(), 4), 9);
787
788 // Test with wide-character grapheme clusters.
789 let text = Rope::from("किमपि");
790 // 2 - 1 - 2 codepoints
791 // TODO: delete handling as per https://news.ycombinator.com/item?id=20058454
792 let slice = text.slice(..);
793 assert_eq!(pos_at_visual_coords(slice, (0, 0).into(), 4), 0);
794 assert_eq!(pos_at_visual_coords(slice, (0, 1).into(), 4), 0);
795 assert_eq!(pos_at_visual_coords(slice, (0, 2).into(), 4), 2);
796 assert_eq!(pos_at_visual_coords(slice, (0, 3).into(), 4), 3);
797
798 // Test with tabs.
799 let text = Rope::from("\tHello\n");
800 let slice = text.slice(..);
801 assert_eq!(pos_at_visual_coords(slice, (0, 0).into(), 4), 0);
802 assert_eq!(pos_at_visual_coords(slice, (0, 1).into(), 4), 0);
803 assert_eq!(pos_at_visual_coords(slice, (0, 2).into(), 4), 0);
804 assert_eq!(pos_at_visual_coords(slice, (0, 3).into(), 4), 0);
805 assert_eq!(pos_at_visual_coords(slice, (0, 4).into(), 4), 1);
806 assert_eq!(pos_at_visual_coords(slice, (0, 5).into(), 4), 2);
807
808 // Test out of bounds.
809 let text = Rope::new();
810 let slice = text.slice(..);
811 assert_eq!(pos_at_visual_coords(slice, (10, 0).into(), 4), 0);
812 assert_eq!(pos_at_visual_coords(slice, (0, 10).into(), 4), 0);
813 assert_eq!(pos_at_visual_coords(slice, (10, 10).into(), 4), 0);
814 }
815
816 #[test]
817 fn test_char_idx_at_visual_row_offset_inline_annotation() {
818 let text = Rope::from("foo\nbar");
819 let slice = text.slice(..);
820 let mut text_fmt = TextFormat::default();
821 let annotations = [InlineAnnotation {
822 text: "x".repeat(100).into(),
823 char_idx: 3,
824 }];
825 text_fmt.soft_wrap = true;
826
827 assert_eq!(
828 char_idx_at_visual_offset(
829 slice,
830 0,
831 1,
832 0,
833 &text_fmt,
834 TextAnnotations::default().add_inline_annotations(&annotations, None)
835 ),
836 (2, 1)
837 );
838 }
839
840 #[test]
841 fn test_char_idx_at_visual_row_offset() {
842 let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ\nfoo");
843 let slice = text.slice(..);
844 let mut text_fmt = TextFormat::default();
845 for i in 0isize..3isize {
846 for j in -2isize..=2isize {
847 if !(0..3).contains(&(i + j)) {
848 continue;
849 }
850 println!("{i} {j}");
851 assert_eq!(
852 char_idx_at_visual_offset(
853 slice,
854 slice.line_to_char(i as usize),
855 j,
856 3,
857 &text_fmt,
858 &TextAnnotations::default(),
859 )
860 .0,
861 slice.line_to_char((i + j) as usize) + 3
862 );
863 }
864 }
865
866 text_fmt.soft_wrap = true;
867 let mut softwrapped_text = "foo ".repeat(10);
868 softwrapped_text.push('\n');
869 let last_char = softwrapped_text.len() - 1;
870
871 let text = Rope::from(softwrapped_text.repeat(3));
872 let slice = text.slice(..);
873 assert_eq!(
874 char_idx_at_visual_offset(
875 slice,
876 last_char,
877 0,
878 0,
879 &text_fmt,
880 &TextAnnotations::default(),
881 )
882 .0,
883 32
884 );
885 assert_eq!(
886 char_idx_at_visual_offset(
887 slice,
888 last_char,
889 -1,
890 0,
891 &text_fmt,
892 &TextAnnotations::default(),
893 )
894 .0,
895 16
896 );
897 assert_eq!(
898 char_idx_at_visual_offset(
899 slice,
900 last_char,
901 -2,
902 0,
903 &text_fmt,
904 &TextAnnotations::default(),
905 )
906 .0,
907 0
908 );
909 assert_eq!(
910 char_idx_at_visual_offset(
911 slice,
912 softwrapped_text.len() + last_char,
913 -2,
914 0,
915 &text_fmt,
916 &TextAnnotations::default(),
917 )
918 .0,
919 softwrapped_text.len()
920 );
921
922 assert_eq!(
923 char_idx_at_visual_offset(
924 slice,
925 softwrapped_text.len() + last_char,
926 -5,
927 0,
928 &text_fmt,
929 &TextAnnotations::default(),
930 )
931 .0,
932 0
933 );
934 }
935 }