atomcode-tuix 4.23.1

Open-source terminal AI coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// crates/atomcode-tuix/src/width.rs
use unicode_width::UnicodeWidthChar;

/// Terminal column width of a string, CJK-aware.
pub fn display_width(s: &str) -> usize {
    s.chars()
        .map(|c| UnicodeWidthChar::width(c).unwrap_or(0))
        .sum()
}

/// Split a line (possibly containing SGR escape sequences) into chunks
/// whose visible display width is at most `max_cols`. SGR bytes pass
/// through without consuming display columns. Handles CJK/emoji width.
///
/// This is the renderer-side replacement for terminal autowrap: we cannot
/// trust the terminal to wrap consistently at scroll-region boundaries,
/// so we wrap ourselves before emitting.
pub fn wrap_line_to_width(line: &str, max_cols: usize) -> Vec<String> {
    if max_cols == 0 || line.is_empty() {
        return vec![line.to_string()];
    }
    let mut chunks: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut cur_width = 0usize;
    let mut chars = line.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // SGR passthrough — doesn't count toward display width.
            current.push(c);
            while let Some(&p) = chars.peek() {
                chars.next();
                current.push(p);
                if p.is_ascii_alphabetic() || p == '~' {
                    break;
                }
            }
            continue;
        }
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if cur_width + w > max_cols && !current.is_empty() {
            chunks.push(std::mem::take(&mut current));
            cur_width = 0;
        }
        current.push(c);
        cur_width += w;
    }
    if !current.is_empty() {
        chunks.push(current);
    }
    if chunks.is_empty() {
        chunks.push(String::new());
    }
    chunks
}

/// Wrap `text` to `max_cols` columns AND locate the cursor's 2D position
/// within the wrapped layout. Honours explicit `\n` as a hard line break
/// (Shift+Enter in the input buffer). Returns `(lines, cursor_row, cursor_col)`
/// where `cursor_row` is 0-based within `lines` and `cursor_col` is the
/// display column within that row.
///
/// `cursor_byte` is a byte offset into `text`; `text.len()` (end-of-buffer)
/// is the expected maximum.
pub fn wrap_with_cursor(
    text: &str,
    max_cols: usize,
    cursor_byte: usize,
) -> (Vec<String>, usize, usize) {
    if max_cols == 0 {
        return (vec![String::new()], 0, 0);
    }
    let mut lines: Vec<String> = vec![String::new()];
    let mut col = 0usize;
    let mut byte = 0usize;
    let mut cursor_row = 0usize;
    let mut cursor_col = 0usize;
    let mut cursor_set = false;

    for c in text.chars() {
        // Wrap check BEFORE writing the char, so a cursor that lands
        // at byte==boundary appears on the new row at col 0 rather
        // than pinned to col `max_cols` on the old row (which would
        // overlap the right border).
        if c != '\n' {
            let w = UnicodeWidthChar::width(c).unwrap_or(0);
            if col + w > max_cols && !lines.last().unwrap().is_empty() {
                lines.push(String::new());
                col = 0;
            }
        }
        if !cursor_set && byte == cursor_byte {
            cursor_row = lines.len() - 1;
            cursor_col = col;
            cursor_set = true;
        }
        if c == '\n' {
            lines.push(String::new());
            col = 0;
        } else {
            let w = UnicodeWidthChar::width(c).unwrap_or(0);
            lines.last_mut().unwrap().push(c);
            col += w;
        }
        byte += c.len_utf8();
    }

    // Cursor at end-of-buffer falls through.
    if !cursor_set {
        cursor_row = lines.len() - 1;
        cursor_col = col;
    }
    (lines, cursor_row, cursor_col)
}

/// Slice `s` starting at display column `start_col`, taking up to `max_cols`
/// columns. Characters that straddle the start boundary are skipped. Used to
/// implement horizontal scroll in the input prompt — keeps the cursor visible
/// when the buffer exceeds the viewport width.
pub fn slice_cols(s: &str, start_col: usize, max_cols: usize) -> String {
    let mut col = 0usize;
    let mut acc = String::new();
    let mut acc_w = 0usize;
    for c in s.chars() {
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if col + w <= start_col {
            col += w;
        } else if col < start_col {
            col += w;
        } else {
            if acc_w + w > max_cols {
                break;
            }
            acc.push(c);
            acc_w += w;
            col += w;
        }
    }
    acc
}

/// Truncate `s` so its display width is at most `max_cols`.
/// Guaranteed to return a valid UTF-8 string that never splits a grapheme.
pub fn truncate_to_width(s: &str, max_cols: usize) -> String {
    if max_cols == 0 {
        return String::new();
    }
    let mut acc = String::with_capacity(s.len());
    let mut cols = 0usize;
    for c in s.chars() {
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if cols + w > max_cols {
            break;
        }
        acc.push(c);
        cols += w;
    }
    acc
}

/// Truncate `s` to `max_cols` display columns, appending `…` when
/// truncation happened so the reader sees a visible "there was more"
/// marker instead of a silent cut mid-word. Reserves 1 column for the
/// ellipsis, so the actual content slice is `max_cols - 1` cols wide.
/// Strings that already fit are returned unchanged.
pub fn truncate_with_ellipsis(s: &str, max_cols: usize) -> String {
    if max_cols == 0 {
        return String::new();
    }
    if display_width(s) <= max_cols {
        return s.to_string();
    }
    let budget = max_cols.saturating_sub(1).max(1);
    let mut acc = truncate_to_width(s, budget);
    acc.push('');
    acc
}

/// Truncate a file-system path to `max_cols` display columns, using a
/// path-aware strategy that preserves the **last segment** (the project or
/// folder name — the most useful bit) and replaces leading segments with
/// `.../`.  Both `/` and `\` are treated as separators.
///
/// Examples (max_cols = 20):
///
///   ~/Documents/WPSDrive/NotLoginPage
///     → .../NotLoginPage          (keeps the last segment)
///
///   ~/a/b/c                       (max_cols = 6)
///     → .../c                     (keeps `.../` + last segment)
///
///   ~/foo                         (max_cols = 5)
///     → ~/foo                     (fits, no truncation)
///
/// If the last segment alone exceeds `max_cols`, the function falls back
/// to a plain `truncate_with_ellipsis` so the output always fits.
pub fn truncate_path(path: &str, max_cols: usize) -> String {
    if max_cols == 0 {
        return String::new();
    }
    if display_width(path) <= max_cols {
        return path.to_string();
    }

    // Find the last separator and take everything after it.
    let last_sep = path.rfind(|c: char| c == '/' || c == '\\');
    let last_segment = match last_sep {
        Some(i) => &path[i + 1..],
        None => path, // no separator — the whole string is the "segment"
    };

    // Build the candidate: ".../" + last_segment
    let ellipsis_prefix = ".../";
    let candidate = format!("{}{}", ellipsis_prefix, last_segment);

    if display_width(&candidate) <= max_cols {
        return candidate;
    }

    // Last segment is too long even with ".../" prefix — truncate it.
    // Reserve width for ".../" (4 cols).
    let prefix_w = display_width(ellipsis_prefix);
    let budget = max_cols.saturating_sub(prefix_w).max(1);
    let truncated_last = truncate_to_width(last_segment, budget);
    format!("{}{}", ellipsis_prefix, truncated_last)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ascii_width_equals_len() {
        assert_eq!(display_width("hello"), 5);
    }

    #[test]
    fn cjk_char_is_width_two() {
        assert_eq!(display_width("你好"), 4);
        assert_eq!(display_width("a你b"), 4); // 1 + 2 + 1
    }

    #[test]
    fn emoji_width_is_two() {
        assert_eq!(display_width("👍"), 2);
    }

    #[test]
    fn truncate_to_width_respects_boundary() {
        // 15-char ASCII input, limit width 5 → first 5 chars
        assert_eq!(truncate_to_width("hello world", 5), "hello");
    }

    #[test]
    fn truncate_to_width_cjk_never_splits_char() {
        // "你好world" = 2+2+1+1+1+1+1 = 9 cols; limit 3 → "你" (width 2), not "你\xXX"
        let out = truncate_to_width("你好world", 3);
        assert_eq!(out, "");
        assert_eq!(display_width(&out), 2);
    }

    #[test]
    fn truncate_to_width_zero_width_safe() {
        assert_eq!(truncate_to_width("abc", 0), "");
    }

    #[test]
    fn truncate_to_width_exact_fit() {
        assert_eq!(truncate_to_width("你好", 4), "你好");
    }

    #[test]
    fn truncate_to_width_preserves_under_limit() {
        assert_eq!(truncate_to_width("hi", 10), "hi");
    }

    #[test]
    fn slice_cols_window_midway() {
        // "abcdefghij" start 3, width 4 → "defg"
        assert_eq!(slice_cols("abcdefghij", 3, 4), "defg");
    }

    #[test]
    fn slice_cols_cjk_straddle_skipped() {
        // "你好world" = 2+2+1+1+1+1+1. start_col=1 straddles "你" → skip it.
        // Then start at col 2 with 4 cols → "好wo".
        assert_eq!(slice_cols("你好world", 1, 4), "好wo");
    }

    #[test]
    fn slice_cols_past_end_empty() {
        assert_eq!(slice_cols("abc", 10, 5), "");
    }

    #[test]
    fn slice_cols_start_zero_matches_truncate() {
        assert_eq!(slice_cols("hello world", 0, 5), "hello");
    }

    #[test]
    fn wrap_with_cursor_short_text_single_row() {
        let (lines, r, c) = wrap_with_cursor("hi", 10, 2);
        assert_eq!(lines, vec!["hi".to_string()]);
        assert_eq!((r, c), (0, 2));
    }

    #[test]
    fn wrap_with_cursor_overflow_moves_to_next_row() {
        let (lines, r, c) = wrap_with_cursor("abcdef", 3, 3);
        assert_eq!(lines, vec!["abc".to_string(), "def".to_string()]);
        // cursor at byte 3 (between abc and def) → start of row 1
        assert_eq!((r, c), (1, 0));
    }

    #[test]
    fn wrap_with_cursor_honours_explicit_newline() {
        let (lines, r, c) = wrap_with_cursor("ab\ncd", 10, 4);
        assert_eq!(lines, vec!["ab".to_string(), "cd".to_string()]);
        assert_eq!((r, c), (1, 1));
    }

    #[test]
    fn wrap_with_cursor_end_of_buffer() {
        let (lines, r, c) = wrap_with_cursor("hello", 10, 5);
        assert_eq!(lines, vec!["hello".to_string()]);
        assert_eq!((r, c), (0, 5));
    }

    #[test]
    fn wrap_with_cursor_cjk_widths() {
        // "你好" = 4 cols. max=3 → wraps after "你" (width 2 fits, next
        // char 好 (w=2) would overflow 2+2=4>3, so wrap).
        let (lines, _, _) = wrap_with_cursor("你好", 3, 0);
        assert_eq!(lines, vec!["".to_string(), "".to_string()]);
    }

    // --- truncate_path tests ---

    #[test]
    fn truncate_path_short_path_unchanged() {
        // Path fits within max_cols → returned as-is.
        assert_eq!(truncate_path("~/foo", 20), "~/foo");
    }

    #[test]
    fn truncate_path_keeps_last_segment() {
        // Long path: keep last segment with ".../" prefix.
        assert_eq!(
            truncate_path("~/Documents/WPSDrive/NotLoginPage", 20),
            ".../NotLoginPage"
        );
    }

    #[test]
    fn truncate_path_exact_fit() {
        // ".../NotLoginPage" = 16 cols. At max_cols = 16 it should fit.
        assert_eq!(
            truncate_path("~/Documents/WPSDrive/NotLoginPage", 16),
            ".../NotLoginPage"
        );
    }

    #[test]
    fn truncate_path_very_tight_budget() {
        // Even a single-char last segment + ".../" = 5 cols should fit.
        assert_eq!(truncate_path("~/a/b/c", 6), ".../c");
    }

    #[test]
    fn truncate_path_last_segment_too_long() {
        // Last segment itself exceeds budget after ".../" prefix.
        // ".../" = 4 cols, budget for last segment = 10 - 4 = 6 cols.
        // "NotLoginPage" = 12 cols → truncated to 6 cols.
        assert_eq!(
            truncate_path("~/Documents/WPSDrive/NotLoginPage", 10),
            ".../NotLog"
        );
    }

    #[test]
    fn truncate_path_no_separator() {
        // No path separators → treat entire string as the "last segment".
        // "verylongname" = 12 cols, max 8 → ".../" + 4 cols of name.
        assert_eq!(truncate_path("verylongname", 8), ".../very");
    }

    #[test]
    fn truncate_path_windows_backslash() {
        // Windows paths with backslash separators.
        assert_eq!(
            truncate_path(r"~\Documents\WPSDrive\NotLoginPage", 20),
            ".../NotLoginPage"
        );
    }

    #[test]
    fn truncate_path_zero_cols() {
        assert_eq!(truncate_path("~/foo", 0), "");
    }

    #[test]
    fn truncate_path_cjk_segment() {
        // CJK project name: "项目" = 4 cols, ".../项目" = 8 cols.
        assert_eq!(
            truncate_path("~/Documents/工作/项目", 20),
            ".../项目"
        );
    }

    #[test]
    fn truncate_path_cjk_tight_budget() {
        // "项目" = 4 cols, ".../" = 4 cols, total = 8.
        assert_eq!(truncate_path("~/a/b/项目", 8), ".../项目");
    }
    #[test]
    fn wrap_line_to_width_truecolor_sgr_passthrough_zero_width() {
        // Truecolor open `\x1b[38;2;198;120;221m` is 18 bytes of escape sequence.
        // If the SGR-passthrough loop ever stops handling it correctly, those
        // bytes leak into column accounting and downstream wrapping shatters.
        // Pin the invariant: the visible content `let x = 1;` is 10 cols, so
        // it must fit in a 10-col budget with no wrap.
        let tinted = "\x1b[38;2;198;120;221mlet\x1b[23;39m x = 1;";
        let chunks = wrap_line_to_width(tinted, 10);
        assert_eq!(chunks.len(), 1, "must not wrap when visible width fits, got: {:?}", chunks);
        // The tinted line is returned verbatim — escapes still present.
        assert!(chunks[0].contains("\x1b[38;2;198;120;221m"));
    }

    #[test]
    fn wrap_line_to_width_truecolor_with_italic_passthrough() {
        // `\x1b[3;38;2;124;132;153m` is the COMMENT SGR — 3 (italic) plus
        // truecolor fg. Same passthrough guarantee.
        let tinted = "\x1b[3;38;2;124;132;153m// comment\x1b[23;39m";
        let chunks = wrap_line_to_width(tinted, 10);
        assert_eq!(chunks.len(), 1);
    }
}