uncurses/ansi/wrap.rs
1//! Width-aware wrapping for ANSI-decorated strings.
2//!
3//! ## Category
4//!
5//! Hard wrap, word wrap, and combined wrap utilities insert newlines based on
6//! terminal display columns while preserving ANSI escape sequences verbatim.
7//!
8//! ## Width conventions
9//!
10//! Visible text width comes from [`crate::ansi::text::tokenize`] and [`WidthMode`].
11//! Escape tokens are zero-width and stay attached to the current word, separator,
12//! or line segment so styling and hyperlinks survive wrapping.
13//!
14//! ## Mode interaction
15//!
16//! Wrapping does not interpret terminal modes. It treats mode-setting and
17//! mode-dependent sequences as bytes to preserve, not as state transitions.
18//!
19//! Sequence boundaries and widths come from [`crate::ansi::text`];
20//! which byte ends a control string, and when a byte in `0x80..=0x9F`
21//! is a C1 control rather than part of a character, are documented there.
22
23use super::text::{TokenKind, WidthMode, string_width, tokenize};
24
25#[inline]
26fn bs(b: &[u8]) -> &str {
27 // The tokenizer never splits a character: text tokens are whole grapheme
28 // clusters, and every sequence scanner steps a whole UTF-8 character at a
29 // time. Nothing enforced that, and when a scanner did split one - 0x9C is
30 // 8-bit ST and also a continuation byte, so an OSC title containing a
31 // check mark ended mid-character - the ill-formed bytes arrived here and
32 // this was undefined behaviour. Checked where checking is free.
33 debug_assert!(
34 std::str::from_utf8(b).is_ok(),
35 "token split a UTF-8 character: {b:?}"
36 );
37 // SAFETY: `b` is a token slice of `&str` input, taken on character
38 // boundaries, as asserted above.
39 unsafe { std::str::from_utf8_unchecked(b) }
40}
41
42/// Default break characters for [`wordwrap`] and [`wrap`]: hyphen, comma, period, semicolon, colon, and space (`"-,.;: "`).
43pub const DEFAULT_BREAKPOINTS: &str = "-,.;: ";
44
45/// Hard-wrap `s` so no visible line exceeds `limit` columns.
46///
47/// Breaks occur at exact width boundaries, including inside words. ANSI escapes are copied verbatim and contribute zero width. If `preserve_space` is `false`, a space that lands at a break boundary is dropped.
48pub fn hardwrap(s: &str, limit: usize, preserve_space: bool) -> String {
49 hardwrap_mode(s, limit, preserve_space, WidthMode::default(), false)
50}
51
52/// Width-mode variant of [`hardwrap`].
53///
54/// `mode` and `eaw_wide` control grapheme width calculation. `limit == 0` returns the input unchanged.
55pub fn hardwrap_mode(
56 s: &str,
57 limit: usize,
58 preserve_space: bool,
59 mode: WidthMode,
60 eaw_wide: bool,
61) -> String {
62 if limit == 0 {
63 return s.to_string();
64 }
65 let mut out = String::with_capacity(s.len());
66 let mut col = 0usize;
67 for tok in tokenize(s.as_bytes(), mode, eaw_wide) {
68 match tok.kind {
69 TokenKind::Escape => out.push_str(bs(tok.bytes)),
70 TokenKind::Control if tok.control == b'\n' => {
71 out.push('\n');
72 col = 0;
73 }
74 TokenKind::Control => out.push_str(bs(tok.bytes)),
75 TokenKind::Text => {
76 let text = tok.bytes;
77 let w = usize::from(tok.width);
78 if w == 0 {
79 out.push_str(bs(text));
80 continue;
81 }
82 if col + w > limit {
83 out.push('\n');
84 col = 0;
85 if !preserve_space && text == b" " {
86 continue;
87 }
88 }
89 out.push_str(bs(text));
90 col += w;
91 }
92 }
93 }
94 out
95}
96
97/// Word-wrap `s` at `breakpoints` so visible lines fit within `limit` where possible.
98///
99/// Long words are not split; use [`wrap`] when oversized words should be hard-wrapped. ANSI escapes are preserved and do not contribute width.
100pub fn wordwrap(s: &str, limit: usize, breakpoints: &str) -> String {
101 wordwrap_mode(s, limit, breakpoints, WidthMode::default(), false)
102}
103
104/// Width-mode variant of [`wordwrap`].
105///
106/// `breakpoints` is a set of characters where a line may break. `mode` and `eaw_wide` control grapheme width calculation; `limit == 0` returns the input unchanged.
107pub fn wordwrap_mode(
108 s: &str,
109 limit: usize,
110 breakpoints: &str,
111 mode: WidthMode,
112 eaw_wide: bool,
113) -> String {
114 wordwrap_inner(s, limit, breakpoints, mode, eaw_wide).0
115}
116
117/// [`wordwrap_mode`], and whether any line it produced is still wider than
118/// `limit`.
119///
120/// Word wrapping measures every line it emits in order to decide where to
121/// break, so the answer costs nothing here and a second width pass over the
122/// whole output anywhere else. It is what lets [`wrap_mode`] stop after one
123/// pass on text whose words all fit, which is nearly all text.
124fn wordwrap_inner(
125 s: &str,
126 limit: usize,
127 breakpoints: &str,
128 mode: WidthMode,
129 eaw_wide: bool,
130) -> (String, bool) {
131 if limit == 0 {
132 // No wrapping happened, so nothing was made to fit and nothing needs
133 // to be: `hardwrap_mode` returns its input unchanged at this limit
134 // too.
135 return (s.to_string(), false);
136 }
137 // A breakpoint test that is an array index, not a scan. `is_break` runs
138 // once per grapheme, and a linear search of the breakpoint list per
139 // character is the kind of constant that only shows up on a megabyte.
140 let mut ascii_bp = [false; 128];
141 let mut wide_bp: Vec<char> = Vec::new();
142 for c in breakpoints.chars() {
143 match u32::from(c) {
144 n if n < 128 => ascii_bp[n as usize] = true,
145 _ => wide_bp.push(c),
146 }
147 }
148 // The ASCII half was an index and the non-ASCII half was still a scan,
149 // which put the same constant back for anyone whose breakpoints are not
150 // ASCII: wrapping n characters on n breakpoints measured an exponent of
151 // 1.895. Sorting once buys a binary search and needs no new type.
152 wide_bp.sort_unstable();
153 let is_bp = |c: char| match u32::from(c) {
154 n if n < 128 => ascii_bp[n as usize],
155 _ => wide_bp.binary_search(&c).is_ok(),
156 };
157
158 // We build the output as: completed lines + current line state.
159 // `line` is the bytes already committed to the current line.
160 // `word` is the current pending word.
161 // `space` is whitespace separator buffered between `line` and `word`.
162 let mut out = String::with_capacity(s.len());
163 let mut line = String::new();
164 let mut line_w = 0usize;
165 let mut word = String::new();
166 let mut word_w = 0usize;
167 let mut space = String::new();
168 let mut space_w = 0usize;
169 let mut over = false;
170
171 let mut flush_word_to_line = |line: &mut String,
172 line_w: &mut usize,
173 word: &mut String,
174 word_w: &mut usize,
175 space: &mut String,
176 space_w: &mut usize| {
177 if !word.is_empty() {
178 // If line+space+word exceeds limit and line is non-empty, wrap.
179 // Handled by caller before calling.
180 line.push_str(space);
181 line.push_str(word);
182 *line_w += *space_w + *word_w;
183 // The only place `line_w` grows, and it is cleared the moment the
184 // line is emitted, so its value here is the width that line will
185 // be emitted at - checking it once here covers all five emit
186 // sites. A line ends up over the limit when a single word is
187 // wider than the limit, which is what hard wrapping is for.
188 over |= *line_w > limit;
189 space.clear();
190 *space_w = 0;
191 word.clear();
192 *word_w = 0;
193 }
194 };
195
196 for tok in tokenize(s.as_bytes(), mode, eaw_wide) {
197 match tok.kind {
198 TokenKind::Escape => {
199 // Attach escapes to whatever segment is currently being built.
200 if !word.is_empty() {
201 word.push_str(bs(tok.bytes));
202 } else if !space.is_empty() {
203 space.push_str(bs(tok.bytes));
204 } else {
205 line.push_str(bs(tok.bytes));
206 }
207 }
208 TokenKind::Control if tok.control == b'\n' => {
209 // Flush current word and emit the line.
210 flush_word_to_line(
211 &mut line,
212 &mut line_w,
213 &mut word,
214 &mut word_w,
215 &mut space,
216 &mut space_w,
217 );
218 out.push_str(&line);
219 out.push('\n');
220 line.clear();
221 line_w = 0;
222 space.clear();
223 space_w = 0;
224 }
225 TokenKind::Control => {
226 // Treat as part of the current word.
227 word.push_str(bs(tok.bytes));
228 }
229 TokenKind::Text => {
230 let text = tok.bytes;
231 let w = usize::from(tok.width);
232 let is_break = bs(text).chars().all(&is_bp);
233 let is_space = text == b" " || text == b"\t";
234
235 if is_space {
236 // Spaces become separator.
237 // First flush pending word to line.
238 if !word.is_empty() {
239 // If word doesn't fit on current line, wrap first.
240 if line_w > 0 && line_w + space_w + word_w > limit {
241 out.push_str(&line);
242 out.push('\n');
243 line.clear();
244 line_w = 0;
245 space.clear();
246 space_w = 0;
247 }
248 flush_word_to_line(
249 &mut line,
250 &mut line_w,
251 &mut word,
252 &mut word_w,
253 &mut space,
254 &mut space_w,
255 );
256 }
257 space.push_str(bs(text));
258 space_w += w;
259 } else if is_break {
260 // Non-space breakpoint (e.g. '-', ','). Stay attached to word but
261 // mark that we can break after.
262 word.push_str(bs(text));
263 word_w += w;
264 // Flush after the breakpoint character.
265 if line_w > 0 && line_w + space_w + word_w > limit {
266 out.push_str(&line);
267 out.push('\n');
268 line.clear();
269 line_w = 0;
270 space.clear();
271 space_w = 0;
272 }
273 flush_word_to_line(
274 &mut line,
275 &mut line_w,
276 &mut word,
277 &mut word_w,
278 &mut space,
279 &mut space_w,
280 );
281 } else {
282 word.push_str(bs(text));
283 word_w += w;
284 }
285 }
286 }
287 }
288
289 // Final flush.
290 if !word.is_empty() {
291 if line_w > 0 && line_w + space_w + word_w > limit {
292 out.push_str(&line);
293 out.push('\n');
294 line.clear();
295 line_w = 0;
296 space.clear();
297 space_w = 0;
298 }
299 flush_word_to_line(
300 &mut line,
301 &mut line_w,
302 &mut word,
303 &mut word_w,
304 &mut space,
305 &mut space_w,
306 );
307 } else if !space.is_empty() {
308 // Trailing space attaches to line, and can be what carries it over -
309 // the one line that ends up too wide without an oversized word in it.
310 line.push_str(&space);
311 over |= line_w + space_w > limit;
312 }
313 out.push_str(&line);
314 (out, over)
315}
316
317/// Soft-wrap `s` at word breakpoints, then hard-wrap any remaining overlong line.
318///
319/// This combines [`wordwrap`] with [`hardwrap`] so every visible line fits within `limit` when `limit > 0`.
320pub fn wrap(s: &str, limit: usize, breakpoints: &str) -> String {
321 wrap_mode(s, limit, breakpoints, WidthMode::default(), false)
322}
323
324/// Width-mode variant of [`wrap`].
325///
326/// `mode` and `eaw_wide` control grapheme width calculation. `limit == 0` returns the input unchanged.
327pub fn wrap_mode(
328 s: &str,
329 limit: usize,
330 breakpoints: &str,
331 mode: WidthMode,
332 eaw_wide: bool,
333) -> String {
334 if limit == 0 {
335 return s.to_string();
336 }
337 // First wordwrap, then hardwrap - but only the lines that need it, and
338 // only if any line does.
339 //
340 // Hard-wrapping exists for the one case word-wrapping cannot solve: a
341 // single word longer than the limit. Every other line is already inside
342 // it, and running the hard wrap over those lines is a second full pass
343 // that copies them to themselves. That pass is not cheap - measured, the
344 // wrap was exactly the sum of its two halves, so it cost as much as the
345 // wrapping did.
346 //
347 // Nor is asking whether a line is too wide, if it is asked by measuring
348 // the line again: the word wrap has already measured every line it
349 // emitted, so it is the only pass that needs to measure at all. It
350 // returns what it found. On text whose words all fit, which is nearly all
351 // text, the second pass now disappears entirely - along with the width
352 // pass that used to decide whether to run it.
353 let (wrapped, over) = wordwrap_inner(s, limit, breakpoints, mode, eaw_wide);
354 if !over {
355 // No cross-check of `over` against a fresh measurement of the output
356 // here. Measuring line by line restarts the parser at every newline,
357 // so a control string spanning one - an unterminated APC, say - reads
358 // as visible text on the lines after it, which is why the two
359 // disagree on output that is correct. The word wrap carries that
360 // state across newlines and is the one that can see it.
361 return wrapped;
362 }
363 // Some line is over. Measure to find which - the output is allocated
364 // lazily, at the first line that is.
365 let mut out: Option<String> = None;
366 let mut consumed = 0usize;
367 for line in wrapped.split('\n') {
368 let wide = string_width(line.as_bytes(), mode, eaw_wide) > limit;
369 match (&mut out, wide) {
370 // Still byte-for-byte `wrapped`; nothing to copy yet.
371 (None, false) => {}
372 (None, true) => {
373 let mut o = String::with_capacity(wrapped.len());
374 o.push_str(&wrapped[..consumed]);
375 o.push_str(&hardwrap_mode(line, limit, false, mode, eaw_wide));
376 out = Some(o);
377 }
378 (Some(o), _) => {
379 o.push('\n');
380 if wide {
381 o.push_str(&hardwrap_mode(line, limit, false, mode, eaw_wide));
382 } else {
383 // Copied rather than re-emitted. A line that fits comes
384 // back from the hard wrap byte-identical, so this is
385 // simply not doing the work - it is not guarding against
386 // a difference. `hardwrap_mode` does re-encode a lone C1
387 // control byte as the two-byte UTF-8 for that code point,
388 // but that cannot arise from `&str` input: at a character
389 // boundary in valid UTF-8 a byte in `0x80..=0x9F` is never
390 // a lead byte, so the tokenizer never emits one as a
391 // `Control`.
392 o.push_str(line);
393 }
394 }
395 }
396 consumed += line.len() + 1;
397 }
398 out.unwrap_or(wrapped)
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 #[test]
406 fn hardwrap_basic() {
407 assert_eq!(hardwrap("hello world", 5, true), "hello\n worl\nd");
408 }
409
410 #[test]
411 fn hardwrap_no_preserve_space() {
412 assert_eq!(hardwrap("hello world", 5, false), "hello\nworld");
413 }
414
415 #[test]
416 fn hardwrap_preserves_ansi() {
417 let s = "\x1b[31mhello world\x1b[m";
418 let got = hardwrap(s, 5, false);
419 assert_eq!(got, "\x1b[31mhello\nworld\x1b[m");
420 }
421
422 #[test]
423 fn hardwrap_explicit_newline() {
424 assert_eq!(hardwrap("ab\ncd", 5, true), "ab\ncd");
425 }
426
427 #[test]
428 fn wordwrap_basic() {
429 assert_eq!(wordwrap("hello world", 5, " "), "hello\nworld");
430 }
431
432 #[test]
433 fn wordwrap_long_word_not_broken() {
434 // "abcdefghij" is 10 wide, limit 5 — wordwrap leaves it intact.
435 assert_eq!(wordwrap("abcdefghij", 5, " "), "abcdefghij");
436 }
437
438 #[test]
439 fn wordwrap_explicit_newline() {
440 assert_eq!(wordwrap("a b\nc d", 10, " "), "a b\nc d");
441 }
442
443 #[test]
444 fn wordwrap_with_hyphen_break() {
445 let got = wordwrap("foo-bar-baz", 4, DEFAULT_BREAKPOINTS);
446 assert_eq!(got, "foo-\nbar-\nbaz");
447 }
448
449 /// Non-ASCII breakpoints are looked up in a sorted list, so they only
450 /// work if that list is actually sorted.
451 #[test]
452 fn wordwrap_breaks_on_non_ascii_breakpoints() {
453 // Deliberately unsorted, and with a decoy that is not in the input.
454 assert_eq!(
455 wordwrap("ab\u{3002}cd", 3, "\u{ff1b}\u{3002}\u{300c}"),
456 "ab\u{3002}\ncd"
457 );
458 assert_eq!(
459 wordwrap("ab\u{ff1b}cd", 3, "\u{ff1b}\u{3002}"),
460 "ab\u{ff1b}\ncd"
461 );
462 // A character absent from the set must not break.
463 assert_eq!(wordwrap("ab\u{3001}cd", 3, "\u{3002}"), "ab\u{3001}cd");
464 }
465
466 #[test]
467 fn wrap_breaks_long_words() {
468 assert_eq!(wrap("abcdefghij", 5, " "), "abcde\nfghij");
469 }
470
471 #[test]
472 fn wrap_mixed() {
473 assert_eq!(
474 wrap("hello superlongword end", 5, " "),
475 "hello\nsuper\nlongw\nord\nend"
476 );
477 }
478
479 /// `wrap` hard wraps only when word wrapping tells it a line is still too
480 /// wide, and word wrapping counts a line's width as it builds it. A
481 /// trailing space is the one thing that lands on a line after that count
482 /// is otherwise final: "hello" fits in five columns and "hello " does not,
483 /// with no oversized word anywhere to notice.
484 #[test]
485 fn wrap_hard_wraps_a_line_carried_over_by_a_trailing_space() {
486 assert_eq!(wrap("hello ", 5, " "), "hello\n");
487 assert_eq!(wrap("ab cd ", 5, " "), "ab cd\n");
488 // Still within the limit with the space on it, so left alone.
489 assert_eq!(wrap("hi ", 5, " "), "hi ");
490 }
491
492 #[test]
493 fn wordwrap_zero_limit_returns_input() {
494 assert_eq!(wordwrap("anything", 0, " "), "anything");
495 }
496
497 /// An unterminated control string swallows everything after it, newlines
498 /// included, so the text on the following lines is never visible and the
499 /// input needs no wrapping at all. Measuring the output one line at a time
500 /// cannot see that - the parser restarts at each newline and reads the
501 /// payload as ordinary text - which is why `wrap` trusts the width the
502 /// word wrap carried across the newline instead of measuring again.
503 #[test]
504 fn wrap_leaves_a_control_string_spanning_a_newline_alone() {
505 let s = "\x1b_\nworld\u{4e00}\u{1f1fa}\x07\u{1f1fa}";
506 assert_eq!(string_width(s.as_bytes(), WidthMode::default(), false), 0);
507 assert_eq!(wrap(s, 8, " \t-"), s);
508 }
509}