Skip to main content

editor_core/
layout.rs

1//! Phase 3: Layout and Soft Wrapping (Headless Layout Engine)
2//!
3//! Calculates the visual representation of text given a container width.
4//! Computes character widths based on UAX #11 and implements headless reflow algorithm.
5
6use unicode_width::UnicodeWidthChar;
7
8/// Default tab width (in cells) used when a caller does not specify a tab width.
9pub const DEFAULT_TAB_WIDTH: usize = 4;
10
11/// Soft wrapping mode.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum WrapMode {
14    /// No soft wrapping (each logical line is a single visual line).
15    None,
16    /// Wrap at character boundaries (current behavior).
17    #[default]
18    Char,
19    /// Prefer wrapping at word boundaries (whitespace), falling back to character wrap.
20    Word,
21}
22
23/// Wrapped-line indentation policy.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum WrapIndent {
26    /// No indentation for wrapped continuations.
27    #[default]
28    None,
29    /// Indent wrapped continuations by the width (in cells) of the logical line's leading
30    /// whitespace prefix (spaces + tabs).
31    SameAsLineIndent,
32    /// Indent wrapped continuations by a fixed number of cells.
33    FixedCells(usize),
34}
35
36/// Wrap point
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct WrapPoint {
39    /// Character index where wrapping occurs (within the logical line)
40    pub char_index: usize,
41    /// Byte offset where wrapping occurs (within the logical line)
42    pub byte_offset: usize,
43}
44
45/// Visual line information
46#[derive(Debug, Clone)]
47pub struct VisualLineInfo {
48    /// Number of visual lines corresponding to this logical line
49    pub visual_line_count: usize,
50    /// List of wrap points
51    pub wrap_points: Vec<WrapPoint>,
52}
53
54impl VisualLineInfo {
55    /// Create an empty layout (a single visual line, no wrap points).
56    pub fn new() -> Self {
57        Self {
58            visual_line_count: 1,
59            wrap_points: Vec::new(),
60        }
61    }
62
63    /// Calculate visual line information from text and width constraint
64    pub fn from_text(text: &str, viewport_width: usize) -> Self {
65        let wrap_points = calculate_wrap_points(text, viewport_width);
66        let visual_line_count = wrap_points.len() + 1;
67
68        Self {
69            visual_line_count,
70            wrap_points,
71        }
72    }
73
74    /// Calculate visual line information from text and width constraint, with explicit `tab_width`.
75    pub fn from_text_with_tab_width(text: &str, viewport_width: usize, tab_width: usize) -> Self {
76        let wrap_points = calculate_wrap_points_with_tab_width(text, viewport_width, tab_width);
77        let visual_line_count = wrap_points.len() + 1;
78
79        Self {
80            visual_line_count,
81            wrap_points,
82        }
83    }
84
85    /// Calculate visual line information with explicit options.
86    pub fn from_text_with_options(
87        text: &str,
88        viewport_width: usize,
89        tab_width: usize,
90        wrap_mode: WrapMode,
91    ) -> Self {
92        Self::from_text_with_layout_options(
93            text,
94            viewport_width,
95            tab_width,
96            wrap_mode,
97            WrapIndent::None,
98        )
99    }
100
101    /// Calculate visual line information with explicit layout options.
102    pub fn from_text_with_layout_options(
103        text: &str,
104        viewport_width: usize,
105        tab_width: usize,
106        wrap_mode: WrapMode,
107        wrap_indent: WrapIndent,
108    ) -> Self {
109        let wrap_points = calculate_wrap_points_with_tab_width_mode_and_indent(
110            text,
111            viewport_width,
112            tab_width,
113            wrap_mode,
114            wrap_indent,
115        );
116        let visual_line_count = wrap_points.len() + 1;
117
118        Self {
119            visual_line_count,
120            wrap_points,
121        }
122    }
123}
124
125impl Default for VisualLineInfo {
126    fn default() -> Self {
127        Self::new()
128    }
129}
130
131/// Calculate visual width of a character (based on UAX #11)
132///
133/// Return value:
134/// - 1: Narrow character (ASCII, etc.)
135/// - 2: Wide character (CJK, fullwidth, etc.)
136/// - 0: Zero-width character (combining characters, etc.)
137pub fn char_width(ch: char) -> usize {
138    // Use unicode-width crate to implement UAX #11
139    UnicodeWidthChar::width(ch).unwrap_or(1)
140}
141
142/// Calculate visual width (in cells) for a character at a specific cell offset within the line.
143///
144/// Notes:
145/// - For most characters, width follows UAX #11 via [`char_width`].
146/// - For `'\t'`, width advances to the next tab stop based on `tab_width`.
147pub fn cell_width_at(ch: char, cell_offset_in_line: usize, tab_width: usize) -> usize {
148    if ch == '\t' {
149        let tab_width = tab_width.max(1);
150        let rem = cell_offset_in_line % tab_width;
151        tab_width - rem
152    } else {
153        char_width(ch)
154    }
155}
156
157/// Calculate total visual width of a string
158pub fn str_width(s: &str) -> usize {
159    s.chars().map(char_width).sum()
160}
161
162/// Calculate total visual width of a string, interpreting `'\t'` using `tab_width`.
163pub fn str_width_with_tab_width(s: &str, tab_width: usize) -> usize {
164    let mut x = 0usize;
165    for ch in s.chars() {
166        x = x.saturating_add(cell_width_at(ch, x, tab_width));
167    }
168    x
169}
170
171/// Calculate the visual cell offset from the start of the line to the given character column.
172///
173/// - `column` is counted in `char` (not bytes).
174/// - `'\t'` is expanded using `tab_width` and the current cell offset.
175pub fn visual_x_for_column(line: &str, column: usize, tab_width: usize) -> usize {
176    let mut x = 0usize;
177    for ch in line.chars().take(column) {
178        x = x.saturating_add(cell_width_at(ch, x, tab_width));
179    }
180    x
181}
182
183fn leading_whitespace_prefix_slice(line: &str) -> &str {
184    let bytes = line.as_bytes();
185    let mut end = 0usize;
186    while end < bytes.len() {
187        match bytes[end] {
188            b' ' | b'\t' => end += 1,
189            _ => break,
190        }
191    }
192    &line[..end]
193}
194
195pub(crate) fn wrap_indent_cells_for_line_text(
196    line_text: &str,
197    wrap_indent: WrapIndent,
198    viewport_width: usize,
199    tab_width: usize,
200) -> usize {
201    if viewport_width <= 1 {
202        return 0;
203    }
204
205    let raw = match wrap_indent {
206        WrapIndent::None => 0,
207        WrapIndent::FixedCells(n) => n,
208        WrapIndent::SameAsLineIndent => {
209            let prefix = leading_whitespace_prefix_slice(line_text);
210            str_width_with_tab_width(prefix, tab_width)
211        }
212    };
213
214    raw.min(viewport_width.saturating_sub(1))
215}
216
217/// Calculate wrap points for text
218///
219/// Given a width constraint, calculates where the text needs to wrap
220pub fn calculate_wrap_points(text: &str, viewport_width: usize) -> Vec<WrapPoint> {
221    calculate_wrap_points_with_tab_width(text, viewport_width, DEFAULT_TAB_WIDTH)
222}
223
224/// Calculate wrap points for text, interpreting `'\t'` using `tab_width`.
225pub fn calculate_wrap_points_with_tab_width(
226    text: &str,
227    viewport_width: usize,
228    tab_width: usize,
229) -> Vec<WrapPoint> {
230    calculate_wrap_points_with_tab_width_and_mode(text, viewport_width, tab_width, WrapMode::Char)
231}
232
233/// Calculate wrap points for text using a configurable [`WrapMode`].
234pub fn calculate_wrap_points_with_tab_width_and_mode(
235    text: &str,
236    viewport_width: usize,
237    tab_width: usize,
238    wrap_mode: WrapMode,
239) -> Vec<WrapPoint> {
240    calculate_wrap_points_with_tab_width_mode_and_indent(
241        text,
242        viewport_width,
243        tab_width,
244        wrap_mode,
245        WrapIndent::None,
246    )
247}
248
249/// Calculate wrap points for text using a configurable [`WrapMode`] and [`WrapIndent`].
250pub fn calculate_wrap_points_with_tab_width_mode_and_indent(
251    text: &str,
252    viewport_width: usize,
253    tab_width: usize,
254    wrap_mode: WrapMode,
255    wrap_indent: WrapIndent,
256) -> Vec<WrapPoint> {
257    if viewport_width == 0 {
258        return Vec::new();
259    }
260
261    match wrap_mode {
262        WrapMode::None => Vec::new(),
263        WrapMode::Char => {
264            let indent =
265                wrap_indent_cells_for_line_text(text, wrap_indent, viewport_width, tab_width);
266            calculate_wrap_points_char_with_tab_width(text, viewport_width, tab_width, indent)
267        }
268        WrapMode::Word => {
269            let indent =
270                wrap_indent_cells_for_line_text(text, wrap_indent, viewport_width, tab_width);
271            calculate_wrap_points_word_with_tab_width(text, viewport_width, tab_width, indent)
272        }
273    }
274}
275
276fn calculate_wrap_points_char_with_tab_width(
277    text: &str,
278    viewport_width: usize,
279    tab_width: usize,
280    wrap_indent_cells: usize,
281) -> Vec<WrapPoint> {
282    let mut wrap_points = Vec::new();
283    let mut x_in_segment = 0usize;
284    let mut x_in_line = 0usize;
285    // Whether the current visual segment already contains at least one character. A wrap is only
286    // valid once the current segment is non-empty; otherwise there is nowhere to move the character
287    // to (which would spin an oversized-first-char into an empty leading segment).
288    let mut segment_has_char = false;
289
290    for (char_index, (byte_offset, ch)) in text.char_indices().enumerate() {
291        let ch_width = cell_width_at(ch, x_in_line, tab_width);
292
293        // Wrap only when this character genuinely does not fit *and* the current segment already
294        // holds a character. Zero-width characters (ch_width == 0, e.g. combining marks / ZWJ)
295        // never exceed the width, so they always stay attached to the base character on the same
296        // visual line rather than being split onto the next one. A single character wider than the
297        // viewport is placed as-is on its own segment instead of being pushed to an empty line.
298        if segment_has_char && x_in_segment + ch_width > viewport_width {
299            wrap_points.push(WrapPoint {
300                char_index,
301                byte_offset,
302            });
303            x_in_segment = wrap_indent_cells;
304        }
305
306        x_in_segment = x_in_segment.saturating_add(ch_width);
307        x_in_line = x_in_line.saturating_add(ch_width);
308        // This character now occupies the (possibly newly started) segment.
309        segment_has_char = true;
310    }
311
312    wrap_points
313}
314
315fn calculate_wrap_points_word_with_tab_width(
316    text: &str,
317    viewport_width: usize,
318    tab_width: usize,
319    wrap_indent_cells: usize,
320) -> Vec<WrapPoint> {
321    let mut wrap_points = Vec::new();
322
323    let mut segment_start_char = 0usize;
324    let mut segment_start_x_in_line = 0usize;
325    let mut last_break: Option<(usize, usize, usize)> = None; // (char_index, byte_offset, x_in_line)
326
327    let mut x_in_line = 0usize;
328
329    for (char_index, (byte_offset, ch)) in text.char_indices().enumerate() {
330        let ch_width = cell_width_at(ch, x_in_line, tab_width);
331
332        loop {
333            let segment_indent = if segment_start_char == 0 {
334                0
335            } else {
336                wrap_indent_cells
337            };
338            let x_in_segment = x_in_line
339                .saturating_sub(segment_start_x_in_line)
340                .saturating_add(segment_indent);
341            if x_in_segment.saturating_add(ch_width) <= viewport_width {
342                break;
343            }
344
345            if let Some((break_char, break_byte, break_x)) = last_break
346                && break_char > segment_start_char
347            {
348                wrap_points.push(WrapPoint {
349                    char_index: break_char,
350                    byte_offset: break_byte,
351                });
352                segment_start_char = break_char;
353                segment_start_x_in_line = break_x;
354                last_break = None;
355                continue;
356            }
357
358            // Fallback: wrap at the current character.
359            wrap_points.push(WrapPoint {
360                char_index,
361                byte_offset,
362            });
363            segment_start_char = char_index;
364            segment_start_x_in_line = x_in_line;
365            last_break = None;
366            break;
367        }
368
369        x_in_line = x_in_line.saturating_add(ch_width);
370
371        if ch.is_whitespace() {
372            last_break = Some((char_index + 1, byte_offset + ch.len_utf8(), x_in_line));
373        }
374    }
375
376    wrap_points
377}
378
379/// Layout engine - manages visual representation of all lines
380pub struct LayoutEngine {
381    /// Viewport width (in character cells)
382    viewport_width: usize,
383    /// Tab width (in cells) for expanding `'\t'`
384    tab_width: usize,
385    /// Soft wrapping mode.
386    wrap_mode: WrapMode,
387    /// Wrapped-line indentation policy.
388    wrap_indent: WrapIndent,
389    /// Visual information for each logical line
390    line_layouts: Vec<VisualLineInfo>,
391}
392
393impl LayoutEngine {
394    /// Create a new layout engine
395    pub fn new(viewport_width: usize) -> Self {
396        Self {
397            viewport_width,
398            tab_width: DEFAULT_TAB_WIDTH,
399            wrap_mode: WrapMode::Char,
400            wrap_indent: WrapIndent::None,
401            line_layouts: Vec::new(),
402        }
403    }
404
405    /// Set viewport width.
406    ///
407    /// Callers must reflow existing lines after changing this option.
408    pub fn set_viewport_width(&mut self, width: usize) {
409        if self.viewport_width != width {
410            self.viewport_width = width;
411        }
412    }
413
414    /// Get viewport width
415    pub fn viewport_width(&self) -> usize {
416        self.viewport_width
417    }
418
419    /// Get wrap mode.
420    pub fn wrap_mode(&self) -> WrapMode {
421        self.wrap_mode
422    }
423
424    /// Set wrap mode.
425    ///
426    /// Callers must reflow existing lines after changing this option.
427    pub fn set_wrap_mode(&mut self, wrap_mode: WrapMode) {
428        if self.wrap_mode != wrap_mode {
429            self.wrap_mode = wrap_mode;
430        }
431    }
432
433    /// Get wrapped-line indentation policy.
434    pub fn wrap_indent(&self) -> WrapIndent {
435        self.wrap_indent
436    }
437
438    /// Set wrapped-line indentation policy.
439    ///
440    /// Callers must reflow existing lines after changing this option.
441    pub fn set_wrap_indent(&mut self, wrap_indent: WrapIndent) {
442        if self.wrap_indent != wrap_indent {
443            self.wrap_indent = wrap_indent;
444        }
445    }
446
447    /// Get tab width (in cells).
448    pub fn tab_width(&self) -> usize {
449        self.tab_width
450    }
451
452    /// Set tab width (in cells) used for expanding `'\t'`.
453    ///
454    /// Callers must reflow existing lines after changing this option.
455    pub fn set_tab_width(&mut self, tab_width: usize) {
456        let tab_width = tab_width.max(1);
457        if self.tab_width != tab_width {
458            self.tab_width = tab_width;
459        }
460    }
461
462    /// Build layout from list of text lines
463    pub fn from_lines(&mut self, lines: &[&str]) {
464        self.recalculate_all_from_lines(lines.iter().copied());
465    }
466
467    /// Recalculate layout for all lines using caller-provided text.
468    pub fn recalculate_all_from_lines<I, S>(&mut self, lines: I)
469    where
470        I: IntoIterator<Item = S>,
471        S: AsRef<str>,
472    {
473        self.line_layouts.clear();
474        for line in lines {
475            let line = line.as_ref();
476            self.line_layouts
477                .push(VisualLineInfo::from_text_with_layout_options(
478                    line,
479                    self.viewport_width,
480                    self.tab_width,
481                    self.wrap_mode,
482                    self.wrap_indent,
483                ));
484        }
485    }
486
487    /// Add a line
488    pub fn add_line(&mut self, text: &str) {
489        self.line_layouts
490            .push(VisualLineInfo::from_text_with_layout_options(
491                text,
492                self.viewport_width,
493                self.tab_width,
494                self.wrap_mode,
495                self.wrap_indent,
496            ));
497    }
498
499    /// Update a specific line
500    pub fn update_line(&mut self, line_index: usize, text: &str) {
501        if line_index < self.line_layouts.len() {
502            self.line_layouts[line_index] = VisualLineInfo::from_text_with_layout_options(
503                text,
504                self.viewport_width,
505                self.tab_width,
506                self.wrap_mode,
507                self.wrap_indent,
508            );
509        }
510    }
511
512    /// Insert a line
513    pub fn insert_line(&mut self, line_index: usize, text: &str) {
514        let pos = line_index.min(self.line_layouts.len());
515        self.line_layouts.insert(
516            pos,
517            VisualLineInfo::from_text_with_layout_options(
518                text,
519                self.viewport_width,
520                self.tab_width,
521                self.wrap_mode,
522                self.wrap_indent,
523            ),
524        );
525    }
526
527    /// Delete a line
528    pub fn delete_line(&mut self, line_index: usize) {
529        if line_index < self.line_layouts.len() {
530            self.line_layouts.remove(line_index);
531        }
532    }
533
534    /// Get visual information for a specific logical line
535    pub fn get_line_layout(&self, line_index: usize) -> Option<&VisualLineInfo> {
536        self.line_layouts.get(line_index)
537    }
538
539    /// Get total number of logical lines
540    pub fn logical_line_count(&self) -> usize {
541        self.line_layouts.len()
542    }
543
544    /// Get total number of visual lines
545    pub fn visual_line_count(&self) -> usize {
546        self.line_layouts.iter().map(|l| l.visual_line_count).sum()
547    }
548
549    /// Convert logical line number to visual line number
550    ///
551    /// Returns the line number of the first visual line of this logical line
552    pub fn logical_to_visual_line(&self, logical_line: usize) -> usize {
553        self.line_layouts
554            .iter()
555            .take(logical_line)
556            .map(|l| l.visual_line_count)
557            .sum()
558    }
559
560    /// Convert visual line number to logical line number and offset within line
561    ///
562    /// Returns (logical_line, visual_line_in_logical)
563    pub fn visual_to_logical_line(&self, visual_line: usize) -> (usize, usize) {
564        let mut cumulative_visual = 0;
565
566        for (logical_idx, layout) in self.line_layouts.iter().enumerate() {
567            if cumulative_visual + layout.visual_line_count > visual_line {
568                let visual_offset = visual_line - cumulative_visual;
569                return (logical_idx, visual_offset);
570            }
571            cumulative_visual += layout.visual_line_count;
572        }
573
574        // If out of range, return the last line
575        let last_line = self.line_layouts.len().saturating_sub(1);
576        let last_visual_offset = self
577            .line_layouts
578            .last()
579            .map(|l| l.visual_line_count.saturating_sub(1))
580            .unwrap_or(0);
581        (last_line, last_visual_offset)
582    }
583
584    /// Clear all lines
585    pub fn clear(&mut self) {
586        self.line_layouts.clear();
587    }
588
589    /// Convert logical coordinates (line, column) to visual coordinates (visual row number, x cell offset within row).
590    ///
591    /// - `logical_line`: Logical line number (0-based)
592    /// - `column`: Character column within the logical line (0-based, counted by `char`)
593    /// - `line_text`: Text for `logical_line`, supplied by the caller's canonical text store.
594    ///
595    /// Return value:
596    /// - `Some((visual_row, x))`: `visual_row` is the global visual row number, `x` is the cell offset within that visual row
597    /// - `None`: Line number out of range
598    pub fn logical_position_to_visual(
599        &self,
600        logical_line: usize,
601        column: usize,
602        line_text: &str,
603    ) -> Option<(usize, usize)> {
604        let layout = self.get_line_layout(logical_line)?;
605
606        let line_char_len = line_text.chars().count();
607        let column = column.min(line_char_len);
608
609        // Calculate which visual line the cursor belongs to (within this logical line) and the starting character index of that visual line.
610        let mut wrapped_offset = 0usize;
611        let mut segment_start_col = 0usize;
612
613        // The char_index in wrap_points indicates "where the next segment starts".
614        for wrap_point in &layout.wrap_points {
615            if column >= wrap_point.char_index {
616                wrapped_offset += 1;
617                segment_start_col = wrap_point.char_index;
618            } else {
619                break;
620            }
621        }
622
623        // Calculate visual width from segment start to column, with tab expansion.
624        let seg_start_x_in_line = visual_x_for_column(line_text, segment_start_col, self.tab_width);
625        let mut x_in_line = seg_start_x_in_line;
626        let mut x_in_segment = 0usize;
627        for ch in line_text
628            .chars()
629            .skip(segment_start_col)
630            .take(column.saturating_sub(segment_start_col))
631        {
632            let w = cell_width_at(ch, x_in_line, self.tab_width);
633            x_in_line = x_in_line.saturating_add(w);
634            x_in_segment = x_in_segment.saturating_add(w);
635        }
636
637        let indent = if wrapped_offset == 0 {
638            0
639        } else {
640            wrap_indent_cells_for_line_text(
641                line_text,
642                self.wrap_indent,
643                self.viewport_width,
644                self.tab_width,
645            )
646        };
647
648        let visual_row = self.logical_to_visual_line(logical_line) + wrapped_offset;
649        Some((visual_row, indent.saturating_add(x_in_segment)))
650    }
651
652    /// Convert logical coordinates (line, column) to visual coordinates, allowing column to exceed line end (virtual spaces).
653    ///
654    /// Difference from [`logical_position_to_visual`](Self::logical_position_to_visual):
655    /// - `column` is not clamped to `line_char_len`
656    /// - Excess portion is treated as virtual spaces of `' '` (width=1)
657    /// - `line_text` comes from the caller's canonical text store.
658    pub fn logical_position_to_visual_allow_virtual(
659        &self,
660        logical_line: usize,
661        column: usize,
662        line_text: &str,
663    ) -> Option<(usize, usize)> {
664        let layout = self.get_line_layout(logical_line)?;
665
666        let line_char_len = line_text.chars().count();
667        let clamped_column = column.min(line_char_len);
668
669        let mut wrapped_offset = 0usize;
670        let mut segment_start_col = 0usize;
671        for wrap_point in &layout.wrap_points {
672            if clamped_column >= wrap_point.char_index {
673                wrapped_offset += 1;
674                segment_start_col = wrap_point.char_index;
675            } else {
676                break;
677            }
678        }
679
680        let seg_start_x_in_line = visual_x_for_column(line_text, segment_start_col, self.tab_width);
681        let mut x_in_line = seg_start_x_in_line;
682        let mut x_in_segment = 0usize;
683        for ch in line_text
684            .chars()
685            .skip(segment_start_col)
686            .take(clamped_column.saturating_sub(segment_start_col))
687        {
688            let w = cell_width_at(ch, x_in_line, self.tab_width);
689            x_in_line = x_in_line.saturating_add(w);
690            x_in_segment = x_in_segment.saturating_add(w);
691        }
692
693        let indent = if wrapped_offset == 0 {
694            0
695        } else {
696            wrap_indent_cells_for_line_text(
697                line_text,
698                self.wrap_indent,
699                self.viewport_width,
700                self.tab_width,
701            )
702        };
703
704        let x_in_segment = x_in_segment + column.saturating_sub(line_char_len);
705        let visual_row = self.logical_to_visual_line(logical_line) + wrapped_offset;
706        Some((visual_row, indent.saturating_add(x_in_segment)))
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713
714    #[test]
715    fn test_char_width() {
716        // ASCII characters should have width 1
717        assert_eq!(char_width('a'), 1);
718        assert_eq!(char_width('A'), 1);
719        assert_eq!(char_width(' '), 1);
720
721        // CJK characters should have width 2
722        assert_eq!(char_width('你'), 2);
723        assert_eq!(char_width('好'), 2);
724        assert_eq!(char_width('世'), 2);
725        assert_eq!(char_width('界'), 2);
726
727        // Most emojis have width 2
728        assert_eq!(char_width('👋'), 2);
729        assert_eq!(char_width('🌍'), 2);
730        assert_eq!(char_width('🦀'), 2);
731    }
732
733    #[test]
734    fn test_str_width() {
735        assert_eq!(str_width("hello"), 5);
736        assert_eq!(str_width("你好"), 4); // 2 CJK characters = 4 cells
737        assert_eq!(str_width("hello你好"), 9); // 5 + 4
738        assert_eq!(str_width("👋🌍"), 4); // 2 emojis = 4 cells
739    }
740
741    #[test]
742    fn test_tab_width_expansion() {
743        // tab stops every 4 cells.
744        assert_eq!(cell_width_at('\t', 0, 4), 4);
745        assert_eq!(cell_width_at('\t', 1, 4), 3);
746        assert_eq!(cell_width_at('\t', 2, 4), 2);
747        assert_eq!(cell_width_at('\t', 3, 4), 1);
748        assert_eq!(cell_width_at('\t', 4, 4), 4);
749
750        assert_eq!(str_width_with_tab_width("\t", 4), 4);
751        assert_eq!(str_width_with_tab_width("a\t", 4), 4); // "a" (1) then tab to 4
752        assert_eq!(str_width_with_tab_width("ab\t", 4), 4); // 2 + 2
753        assert_eq!(str_width_with_tab_width("abc\t", 4), 4); // 3 + 1
754        assert_eq!(str_width_with_tab_width("abcd\t", 4), 8); // 4 + 4
755    }
756
757    #[test]
758    fn test_calculate_wrap_points_simple() {
759        // Viewport width of 10
760        let text = "hello world";
761        let wraps = calculate_wrap_points(text, 10);
762
763        // "hello world" = 11 characters, should wrap between "hello" and "world"
764        // But actually wraps after the 10th character
765        assert!(!wraps.is_empty());
766    }
767
768    #[test]
769    fn test_calculate_wrap_points_exact_fit() {
770        // Exactly 10 characters wide
771        let text = "1234567890";
772        let wraps = calculate_wrap_points(text, 10);
773
774        // Exactly fills, no wrapping needed
775        assert_eq!(wraps.len(), 0);
776    }
777
778    #[test]
779    fn test_calculate_wrap_points_one_over() {
780        // 11 characters, width of 10
781        let text = "12345678901";
782        let wraps = calculate_wrap_points(text, 10);
783
784        // Should wrap after the 10th character
785        assert_eq!(wraps.len(), 1);
786        assert_eq!(wraps[0].char_index, 10);
787    }
788
789    #[test]
790    fn test_calculate_wrap_points_cjk() {
791        // 5 CJK characters = 10 cells wide
792        let text = "你好世界测";
793        let wraps = calculate_wrap_points(text, 10);
794
795        // Exactly fills, no wrapping needed
796        assert_eq!(wraps.len(), 0);
797    }
798
799    #[test]
800    fn test_calculate_wrap_points_cjk_overflow() {
801        // 6 CJK characters = 12 cells, viewport width of 10
802        let text = "你好世界测试";
803        let wraps = calculate_wrap_points(text, 10);
804
805        // Should wrap after the 5th character (first 5 characters = 10 cells)
806        assert_eq!(wraps.len(), 1);
807        assert_eq!(wraps[0].char_index, 5);
808    }
809
810    #[test]
811    fn test_wrap_mode_none_disables_wrapping() {
812        let mut engine = LayoutEngine::new(5);
813        engine.set_wrap_mode(WrapMode::None);
814        engine.from_lines(&["abcdefghij"]);
815
816        assert_eq!(engine.visual_line_count(), 1);
817        let layout = engine.get_line_layout(0).expect("layout");
818        assert_eq!(layout.visual_line_count, 1);
819        assert!(layout.wrap_points.is_empty());
820    }
821
822    #[test]
823    fn test_word_wrap_prefers_whitespace_when_possible() {
824        // With width=7, char-wrap would wrap as "hello w" + "orld".
825        // Word-wrap should prefer wrapping at the whitespace boundary ("hello " + "world").
826        let text = "hello world";
827
828        let wraps = calculate_wrap_points_with_tab_width_and_mode(
829            text,
830            7,
831            DEFAULT_TAB_WIDTH,
832            WrapMode::Word,
833        );
834
835        assert_eq!(wraps.len(), 1);
836        assert_eq!(wraps[0].char_index, 6);
837    }
838
839    #[test]
840    fn test_wrap_indent_same_as_line_indent_reduces_continuation_width() {
841        let text = "    abcdefgh";
842        let wraps = calculate_wrap_points_with_tab_width_mode_and_indent(
843            text,
844            6,
845            DEFAULT_TAB_WIDTH,
846            WrapMode::Char,
847            WrapIndent::SameAsLineIndent,
848        );
849
850        let indices: Vec<usize> = wraps.iter().map(|wp| wp.char_index).collect();
851        assert_eq!(indices, vec![6, 8, 10]);
852    }
853
854    #[test]
855    fn test_wrap_double_width_char() {
856        // Viewport has 1 cell remaining, next is a double-width character
857        // "Hello" = 5 cells, "你" = 2 cells, viewport width = 6
858        let text = "Hello你";
859        let wraps = calculate_wrap_points(text, 6);
860
861        // "Hello" takes 5 cells, "你" needs 2 cells but only 1 remains
862        // So "你" should wrap intact to the next line
863        assert_eq!(wraps.len(), 1);
864        assert_eq!(wraps[0].char_index, 5); // Wrap before "你"
865    }
866
867    #[test]
868    fn test_zero_width_combining_mark_stays_with_base_char() {
869        // Regression (P3-18): a zero-width combining mark following the character that exactly
870        // fills the viewport must not be split onto its own visual line.
871        // "abcde" = 5 cells fills width 5; U+0301 (combining acute) has width 0 and must stay on
872        // the same visual line, so there is no wrap point.
873        let text = "abcde\u{0301}";
874        let wraps = calculate_wrap_points(text, 5);
875        assert_eq!(wraps.len(), 0, "combining mark must not force a wrap");
876
877        // A following real character does wrap normally.
878        let text2 = "abcde\u{0301}f";
879        let wraps2 = calculate_wrap_points(text2, 5);
880        assert_eq!(wraps2.len(), 1);
881        assert_eq!(
882            wraps2[0].char_index, 6,
883            "wrap before 'f', after the combining mark"
884        );
885    }
886
887    #[test]
888    fn test_oversized_first_char_does_not_create_empty_leading_segment() {
889        // Regression (P3-20): a character wider than the viewport must occupy the first segment
890        // rather than being wrapped to a new line (which would leave an empty leading segment and
891        // inflate the visual line count).
892        // "你" = 2 cells, viewport width = 1.
893        let single = calculate_wrap_points("你", 1);
894        assert_eq!(single.len(), 0, "a lone oversized char has no wrap point");
895        assert_eq!(VisualLineInfo::from_text("你", 1).visual_line_count, 1);
896
897        // Two oversized chars: the second wraps after the first (one wrap point), no empty
898        // leading segment.
899        let two = calculate_wrap_points("你好", 1);
900        assert_eq!(two.len(), 1);
901        assert_eq!(two[0].char_index, 1);
902    }
903
904    #[test]
905    fn test_exact_fit_does_not_emit_trailing_empty_wrap() {
906        // Regression (P2-17 family): a line that exactly fills the viewport with no following
907        // character must not emit a spurious wrap point / empty trailing visual line.
908        assert_eq!(calculate_wrap_points("12345", 5).len(), 0);
909        assert_eq!(VisualLineInfo::from_text("12345", 5).visual_line_count, 1);
910    }
911
912    #[test]
913    fn test_visual_line_info() {
914        let info = VisualLineInfo::from_text("1234567890abc", 10);
915        assert_eq!(info.visual_line_count, 2); // Needs 2 visual lines
916        assert_eq!(info.wrap_points.len(), 1);
917    }
918
919    #[test]
920    fn test_layout_engine_basic() {
921        let mut engine = LayoutEngine::new(10);
922        engine.add_line("hello");
923        engine.add_line("1234567890abc");
924
925        assert_eq!(engine.logical_line_count(), 2);
926        assert_eq!(engine.visual_line_count(), 3); // 1 + 2
927    }
928
929    #[test]
930    fn test_layout_engine_viewport_change() {
931        let mut engine = LayoutEngine::new(20);
932        engine.from_lines(&["hello world", "rust programming"]);
933
934        let initial_visual = engine.visual_line_count();
935        assert_eq!(initial_visual, 2); // Both lines don't need wrapping
936
937        // Reduce viewport width
938        engine.set_viewport_width(5);
939        // Note: Due to our implementation, need to reset lines
940        engine.from_lines(&["hello world", "rust programming"]);
941
942        let new_visual = engine.visual_line_count();
943        assert!(new_visual > initial_visual); // Should have more visual lines
944    }
945
946    #[test]
947    fn test_logical_to_visual() {
948        let mut engine = LayoutEngine::new(10);
949        engine.from_lines(&["12345", "1234567890abc", "hello"]);
950
951        // Line 0 ("12345") doesn't wrap, starts at visual line 0
952        assert_eq!(engine.logical_to_visual_line(0), 0);
953
954        // Line 1 ("1234567890abc") needs wrapping, starts at visual line 1
955        assert_eq!(engine.logical_to_visual_line(1), 1);
956
957        // Line 2 ("hello") starts at visual line 3 (0 + 1 + 2)
958        assert_eq!(engine.logical_to_visual_line(2), 3);
959    }
960
961    #[test]
962    fn test_visual_to_logical() {
963        let mut engine = LayoutEngine::new(10);
964        engine.from_lines(&["12345", "1234567890abc", "hello"]);
965
966        // Visual line 0 -> logical line 0
967        assert_eq!(engine.visual_to_logical_line(0), (0, 0));
968
969        // Visual line 1 -> logical line 1's 0th visual line
970        assert_eq!(engine.visual_to_logical_line(1), (1, 0));
971
972        // Visual line 2 -> logical line 1's 1st visual line
973        assert_eq!(engine.visual_to_logical_line(2), (1, 1));
974
975        // Visual line 3 -> logical line 2
976        assert_eq!(engine.visual_to_logical_line(3), (2, 0));
977    }
978}