movement.rs

  1use super::{Bias, DisplayPoint, DisplaySnapshot, SelectionGoal, ToDisplayPoint};
  2use crate::{char_kind, CharKind, ToPoint};
  3use anyhow::Result;
  4use std::ops::Range;
  5
  6pub fn left(map: &DisplaySnapshot, mut point: DisplayPoint) -> Result<DisplayPoint> {
  7    if point.column() > 0 {
  8        *point.column_mut() -= 1;
  9    } else if point.row() > 0 {
 10        *point.row_mut() -= 1;
 11        *point.column_mut() = map.line_len(point.row());
 12    }
 13    Ok(map.clip_point(point, Bias::Left))
 14}
 15
 16pub fn right(map: &DisplaySnapshot, mut point: DisplayPoint) -> Result<DisplayPoint> {
 17    let max_column = map.line_len(point.row());
 18    if point.column() < max_column {
 19        *point.column_mut() += 1;
 20    } else if point.row() < map.max_point().row() {
 21        *point.row_mut() += 1;
 22        *point.column_mut() = 0;
 23    }
 24    Ok(map.clip_point(point, Bias::Right))
 25}
 26
 27pub fn up(
 28    map: &DisplaySnapshot,
 29    start: DisplayPoint,
 30    goal: SelectionGoal,
 31) -> Result<(DisplayPoint, SelectionGoal)> {
 32    let mut goal_column = if let SelectionGoal::Column(column) = goal {
 33        column
 34    } else {
 35        map.column_to_chars(start.row(), start.column())
 36    };
 37
 38    let prev_row = start.row().saturating_sub(1);
 39    let mut point = map.clip_point(
 40        DisplayPoint::new(prev_row, map.line_len(prev_row)),
 41        Bias::Left,
 42    );
 43    if point.row() < start.row() {
 44        *point.column_mut() = map.column_from_chars(point.row(), goal_column);
 45    } else {
 46        point = DisplayPoint::new(0, 0);
 47        goal_column = 0;
 48    }
 49
 50    let clip_bias = if point.column() == map.line_len(point.row()) {
 51        Bias::Left
 52    } else {
 53        Bias::Right
 54    };
 55
 56    Ok((
 57        map.clip_point(point, clip_bias),
 58        SelectionGoal::Column(goal_column),
 59    ))
 60}
 61
 62pub fn down(
 63    map: &DisplaySnapshot,
 64    start: DisplayPoint,
 65    goal: SelectionGoal,
 66) -> Result<(DisplayPoint, SelectionGoal)> {
 67    let mut goal_column = if let SelectionGoal::Column(column) = goal {
 68        column
 69    } else {
 70        map.column_to_chars(start.row(), start.column())
 71    };
 72
 73    let next_row = start.row() + 1;
 74    let mut point = map.clip_point(DisplayPoint::new(next_row, 0), Bias::Right);
 75    if point.row() > start.row() {
 76        *point.column_mut() = map.column_from_chars(point.row(), goal_column);
 77    } else {
 78        point = map.max_point();
 79        goal_column = map.column_to_chars(point.row(), point.column())
 80    }
 81
 82    let clip_bias = if point.column() == map.line_len(point.row()) {
 83        Bias::Left
 84    } else {
 85        Bias::Right
 86    };
 87
 88    Ok((
 89        map.clip_point(point, clip_bias),
 90        SelectionGoal::Column(goal_column),
 91    ))
 92}
 93
 94pub fn line_beginning(
 95    map: &DisplaySnapshot,
 96    point: DisplayPoint,
 97    toggle_indent: bool,
 98) -> DisplayPoint {
 99    let (indent, is_blank) = map.line_indent(point.row());
100    if toggle_indent && !is_blank && point.column() != indent {
101        DisplayPoint::new(point.row(), indent)
102    } else {
103        DisplayPoint::new(point.row(), 0)
104    }
105}
106
107pub fn line_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
108    let line_end = DisplayPoint::new(point.row(), map.line_len(point.row()));
109    map.clip_point(line_end, Bias::Left)
110}
111
112pub fn prev_word_boundary(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
113    let mut line_start = 0;
114    if point.row() > 0 {
115        if let Some(indent) = map.soft_wrap_indent(point.row() - 1) {
116            line_start = indent;
117        }
118    }
119
120    if point.column() == line_start {
121        if point.row() == 0 {
122            return DisplayPoint::new(0, 0);
123        } else {
124            let row = point.row() - 1;
125            point = map.clip_point(DisplayPoint::new(row, map.line_len(row)), Bias::Left);
126        }
127    }
128
129    let mut boundary = DisplayPoint::new(point.row(), 0);
130    let mut column = 0;
131    let mut prev_char_kind = CharKind::Newline;
132    for c in map.chars_at(DisplayPoint::new(point.row(), 0)) {
133        if column >= point.column() {
134            break;
135        }
136
137        let char_kind = char_kind(c);
138        if char_kind != prev_char_kind
139            && char_kind != CharKind::Whitespace
140            && char_kind != CharKind::Newline
141        {
142            *boundary.column_mut() = column;
143        }
144
145        prev_char_kind = char_kind;
146        column += c.len_utf8() as u32;
147    }
148    boundary
149}
150
151pub fn next_word_boundary(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
152    let mut prev_char_kind = None;
153    for c in map.chars_at(point) {
154        let char_kind = char_kind(c);
155        if let Some(prev_char_kind) = prev_char_kind {
156            if c == '\n' {
157                break;
158            }
159            if prev_char_kind != char_kind
160                && prev_char_kind != CharKind::Whitespace
161                && prev_char_kind != CharKind::Newline
162            {
163                break;
164            }
165        }
166
167        if c == '\n' {
168            *point.row_mut() += 1;
169            *point.column_mut() = 0;
170        } else {
171            *point.column_mut() += c.len_utf8() as u32;
172        }
173        prev_char_kind = Some(char_kind);
174    }
175    map.clip_point(point, Bias::Right)
176}
177
178pub fn is_inside_word(map: &DisplaySnapshot, point: DisplayPoint) -> bool {
179    let ix = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
180    let text = &map.buffer_snapshot;
181    let next_char_kind = text.chars_at(ix).next().map(char_kind);
182    let prev_char_kind = text.reversed_chars_at(ix).next().map(char_kind);
183    prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
184}
185
186pub fn surrounding_word(map: &DisplaySnapshot, position: DisplayPoint) -> Range<DisplayPoint> {
187    let position = map
188        .clip_point(position, Bias::Left)
189        .to_offset(map, Bias::Left);
190    let (range, _) = map.buffer_snapshot.surrounding_word(position);
191    let start = range
192        .start
193        .to_point(&map.buffer_snapshot)
194        .to_display_point(map);
195    let end = range
196        .end
197        .to_point(&map.buffer_snapshot)
198        .to_display_point(map);
199    start..end
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use crate::{
206        display_map::{BlockDisposition, BlockProperties},
207        Buffer, DisplayMap, ExcerptProperties, MultiBuffer,
208    };
209    use gpui::{elements::Empty, Element};
210    use language::Point;
211    use std::sync::Arc;
212
213    #[gpui::test]
214    fn test_move_up_and_down_with_excerpts(cx: &mut gpui::MutableAppContext) {
215        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
216        let font_id = cx
217            .font_cache()
218            .select_font(family_id, &Default::default())
219            .unwrap();
220
221        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefg\nhijkl\nmn", cx));
222        let mut excerpt1_header_position = None;
223        let mut excerpt2_header_position = None;
224        let multibuffer = cx.add_model(|cx| {
225            let mut multibuffer = MultiBuffer::new(0);
226            let excerpt1_id = multibuffer.push_excerpt(
227                ExcerptProperties {
228                    buffer: &buffer,
229                    range: Point::new(0, 0)..Point::new(1, 4),
230                },
231                cx,
232            );
233            let excerpt2_id = multibuffer.push_excerpt(
234                ExcerptProperties {
235                    buffer: &buffer,
236                    range: Point::new(2, 0)..Point::new(3, 2),
237                },
238                cx,
239            );
240
241            excerpt1_header_position = Some(
242                multibuffer
243                    .read(cx)
244                    .anchor_in_excerpt(excerpt1_id, language::Anchor::min()),
245            );
246            excerpt2_header_position = Some(
247                multibuffer
248                    .read(cx)
249                    .anchor_in_excerpt(excerpt2_id, language::Anchor::min()),
250            );
251            multibuffer
252        });
253
254        let display_map =
255            cx.add_model(|cx| DisplayMap::new(multibuffer, 2, font_id, 14.0, None, cx));
256        display_map.update(cx, |display_map, cx| {
257            display_map.insert_blocks(
258                [
259                    BlockProperties {
260                        position: excerpt1_header_position.unwrap(),
261                        height: 2,
262                        render: Arc::new(|_| Empty::new().boxed()),
263                        disposition: BlockDisposition::Above,
264                    },
265                    BlockProperties {
266                        position: excerpt2_header_position.unwrap(),
267                        height: 3,
268                        render: Arc::new(|_| Empty::new().boxed()),
269                        disposition: BlockDisposition::Above,
270                    },
271                ],
272                cx,
273            )
274        });
275
276        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
277        assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\n\nhijkl\nmn");
278
279        // Can't move up into the first excerpt's header
280        assert_eq!(
281            up(&snapshot, DisplayPoint::new(2, 2), SelectionGoal::Column(2)).unwrap(),
282            (DisplayPoint::new(2, 0), SelectionGoal::Column(0)),
283        );
284        assert_eq!(
285            up(&snapshot, DisplayPoint::new(2, 0), SelectionGoal::None).unwrap(),
286            (DisplayPoint::new(2, 0), SelectionGoal::Column(0)),
287        );
288
289        // Move up and down within first excerpt
290        assert_eq!(
291            up(&snapshot, DisplayPoint::new(3, 4), SelectionGoal::Column(4)).unwrap(),
292            (DisplayPoint::new(2, 3), SelectionGoal::Column(4)),
293        );
294        assert_eq!(
295            down(&snapshot, DisplayPoint::new(2, 3), SelectionGoal::Column(4)).unwrap(),
296            (DisplayPoint::new(3, 4), SelectionGoal::Column(4)),
297        );
298
299        // Move up and down across second excerpt's header
300        assert_eq!(
301            up(&snapshot, DisplayPoint::new(7, 5), SelectionGoal::Column(5)).unwrap(),
302            (DisplayPoint::new(3, 4), SelectionGoal::Column(5)),
303        );
304        assert_eq!(
305            down(&snapshot, DisplayPoint::new(3, 4), SelectionGoal::Column(5)).unwrap(),
306            (DisplayPoint::new(7, 5), SelectionGoal::Column(5)),
307        );
308
309        // Can't move down off the end
310        assert_eq!(
311            down(&snapshot, DisplayPoint::new(8, 0), SelectionGoal::Column(0)).unwrap(),
312            (DisplayPoint::new(8, 2), SelectionGoal::Column(2)),
313        );
314        assert_eq!(
315            down(&snapshot, DisplayPoint::new(8, 2), SelectionGoal::Column(2)).unwrap(),
316            (DisplayPoint::new(8, 2), SelectionGoal::Column(2)),
317        );
318    }
319
320    #[gpui::test]
321    fn test_prev_next_word_boundary_multibyte(cx: &mut gpui::MutableAppContext) {
322        let tab_size = 4;
323        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
324        let font_id = cx
325            .font_cache()
326            .select_font(family_id, &Default::default())
327            .unwrap();
328        let font_size = 14.0;
329
330        let buffer = MultiBuffer::build_simple("a bcΔ defγ hi—jk", cx);
331        let display_map =
332            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
333        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
334        assert_eq!(
335            prev_word_boundary(&snapshot, DisplayPoint::new(0, 12)),
336            DisplayPoint::new(0, 7)
337        );
338        assert_eq!(
339            prev_word_boundary(&snapshot, DisplayPoint::new(0, 7)),
340            DisplayPoint::new(0, 2)
341        );
342        assert_eq!(
343            prev_word_boundary(&snapshot, DisplayPoint::new(0, 6)),
344            DisplayPoint::new(0, 2)
345        );
346        assert_eq!(
347            prev_word_boundary(&snapshot, DisplayPoint::new(0, 2)),
348            DisplayPoint::new(0, 0)
349        );
350        assert_eq!(
351            prev_word_boundary(&snapshot, DisplayPoint::new(0, 1)),
352            DisplayPoint::new(0, 0)
353        );
354
355        assert_eq!(
356            next_word_boundary(&snapshot, DisplayPoint::new(0, 0)),
357            DisplayPoint::new(0, 1)
358        );
359        assert_eq!(
360            next_word_boundary(&snapshot, DisplayPoint::new(0, 1)),
361            DisplayPoint::new(0, 6)
362        );
363        assert_eq!(
364            next_word_boundary(&snapshot, DisplayPoint::new(0, 2)),
365            DisplayPoint::new(0, 6)
366        );
367        assert_eq!(
368            next_word_boundary(&snapshot, DisplayPoint::new(0, 6)),
369            DisplayPoint::new(0, 12)
370        );
371        assert_eq!(
372            next_word_boundary(&snapshot, DisplayPoint::new(0, 7)),
373            DisplayPoint::new(0, 12)
374        );
375    }
376
377    #[gpui::test]
378    fn test_surrounding_word(cx: &mut gpui::MutableAppContext) {
379        let tab_size = 4;
380        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
381        let font_id = cx
382            .font_cache()
383            .select_font(family_id, &Default::default())
384            .unwrap();
385        let font_size = 14.0;
386        let buffer = MultiBuffer::build_simple("lorem ipsum   dolor\n    sit", cx);
387        let display_map =
388            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
389        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
390
391        assert_eq!(
392            surrounding_word(&snapshot, DisplayPoint::new(0, 0)),
393            DisplayPoint::new(0, 0)..DisplayPoint::new(0, 5),
394        );
395        assert_eq!(
396            surrounding_word(&snapshot, DisplayPoint::new(0, 2)),
397            DisplayPoint::new(0, 0)..DisplayPoint::new(0, 5),
398        );
399        assert_eq!(
400            surrounding_word(&snapshot, DisplayPoint::new(0, 5)),
401            DisplayPoint::new(0, 0)..DisplayPoint::new(0, 5),
402        );
403        assert_eq!(
404            surrounding_word(&snapshot, DisplayPoint::new(0, 6)),
405            DisplayPoint::new(0, 6)..DisplayPoint::new(0, 11),
406        );
407        assert_eq!(
408            surrounding_word(&snapshot, DisplayPoint::new(0, 7)),
409            DisplayPoint::new(0, 6)..DisplayPoint::new(0, 11),
410        );
411        assert_eq!(
412            surrounding_word(&snapshot, DisplayPoint::new(0, 11)),
413            DisplayPoint::new(0, 6)..DisplayPoint::new(0, 11),
414        );
415        assert_eq!(
416            surrounding_word(&snapshot, DisplayPoint::new(0, 13)),
417            DisplayPoint::new(0, 11)..DisplayPoint::new(0, 14),
418        );
419        assert_eq!(
420            surrounding_word(&snapshot, DisplayPoint::new(0, 14)),
421            DisplayPoint::new(0, 14)..DisplayPoint::new(0, 19),
422        );
423        assert_eq!(
424            surrounding_word(&snapshot, DisplayPoint::new(0, 17)),
425            DisplayPoint::new(0, 14)..DisplayPoint::new(0, 19),
426        );
427        assert_eq!(
428            surrounding_word(&snapshot, DisplayPoint::new(0, 19)),
429            DisplayPoint::new(0, 14)..DisplayPoint::new(0, 19),
430        );
431        assert_eq!(
432            surrounding_word(&snapshot, DisplayPoint::new(1, 0)),
433            DisplayPoint::new(1, 0)..DisplayPoint::new(1, 4),
434        );
435        assert_eq!(
436            surrounding_word(&snapshot, DisplayPoint::new(1, 1)),
437            DisplayPoint::new(1, 0)..DisplayPoint::new(1, 4),
438        );
439        assert_eq!(
440            surrounding_word(&snapshot, DisplayPoint::new(1, 6)),
441            DisplayPoint::new(1, 4)..DisplayPoint::new(1, 7),
442        );
443        assert_eq!(
444            surrounding_word(&snapshot, DisplayPoint::new(1, 7)),
445            DisplayPoint::new(1, 4)..DisplayPoint::new(1, 7),
446        );
447    }
448}