Preserve consecutive spaces when wrapping text for preview and print.
Word-wrap no longer collapses runs of spaces, so manual column padding in templates survives. Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -18,11 +18,12 @@ A document is a sequence of **blocks**. Blank lines become paper feeds (`@feed 1
18
18
19
19
### Paragraphs
20
20
21
Plain text (and `${parameters}`). One or more consecutive non-empty lines form a paragraph. There is **no** inline bold/italic/code markup.
21
Plain text (and `${parameters}`). One or more consecutive non-empty lines form a paragraph. There is **no** inline bold/italic/code markup. Consecutive spaces are preserved (not collapsed) so authors can pad columns manually.
22
22
23
23
```markdown
24
24
Thank you for your purchase!
25
25
Visit us again soon.
26
Item 12.00
26
27
```
27
28
28
29
### Headings
@@ -18,11 +18,12 @@ A document is a sequence of **blocks**. Blank lines become paper feeds (`@feed 118
18
19
### Paragraphs19
### Paragraphs20
20
21
Plain text (and `${parameters}`). One or more consecutive non-empty lines form a paragraph. There is **no** inline bold/italic/code markup.21
Plain text (and `${parameters}`). One or more consecutive non-empty lines form a paragraph. There is **no** inline bold/italic/code markup. Consecutive spaces are preserved (not collapsed) so authors can pad columns manually.22
22
23
```markdown23
```markdown24
Thank you for your purchase!24
Thank you for your purchase!25
Visit us again soon.25
Visit us again soon.26
Item 12.0026
```27
```27
28
28
### Headings29
### Headings@@ -47,7 +47,7 @@ A template is plain text: paragraphs, headings, lists, checkboxes, `${text}` / `
47
47
48
48
### Paragraphs
49
49
50
Consecutive non-empty lines form one paragraph.
50
Consecutive non-empty lines form one paragraph. Multiple spaces in a row are kept (useful for manual column layout); they are not collapsed to one.
51
51
52
52
### Headings
53
53
@@ -47,7 +47,7 @@ A template is plain text: paragraphs, headings, lists, checkboxes, `${text}` / `47
47
48
### Paragraphs48
### Paragraphs49
49
50
Consecutive non-empty lines form one paragraph.50
Consecutive non-empty lines form one paragraph. Multiple spaces in a row are kept (useful for manual column layout); they are not collapsed to one.51
51
52
### Headings52
### Headings53
53
@@ -52,7 +52,7 @@ pub fn wrap_hanging(
52
52
) -> Vec<String> {
53
53
let first_budget = max_cols.saturating_sub(first_prefix.chars().count());
54
54
let next_budget = max_cols.saturating_sub(next_prefix.chars().count());
55
let content_lines = wrap_content_var_budget(text, first_budget, next_budget);
55
let content_lines = wrap_tokens_var_budget(&tokenize(text), first_budget, next_budget);
56
56
57
57
content_lines
58
58
.into_iter()
@@ -67,147 +67,218 @@ pub fn wrap_hanging(
67
67
.collect()
68
68
}
69
69
70
fn wrap_content_var_budget(text: &str, first_budget: usize, next_budget: usize) -> Vec<String> {
71
if first_budget == 0 && next_budget == 0 {
70
/// Word-wrap `text` to at most `max_cols` characters per line.
71
/// Explicit newlines in `text` start a new wrapped paragraph.
72
/// Consecutive spaces are preserved (not collapsed).
73
pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
74
if max_cols == 0 {
72
75
return vec![text.to_string()];
73
76
}
74
77
75
let words: Vec<&str> = text.split_whitespace().collect();
76
if words.is_empty() {
77
return vec![String::new()];
78
}
79
80
78
let mut lines = Vec::new();
81
let mut current = String::new();
82
let mut budget = first_budget.max(1);
83
let mut word_idx = 0usize;
79
for paragraph in text.split('\n') {
80
lines.extend(wrap_line(paragraph, max_cols));
81
}
82
if lines.is_empty() {
83
lines.push(String::new());
84
}
85
lines
86
}
84
87
85
while word_idx < words.len() {
86
let word = words[word_idx];
87
let word_len = word.chars().count();
88
fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
89
if line.is_empty() {
90
return vec![String::new()];
91
}
92
wrap_tokens_var_budget(&tokenize(line), max_cols, max_cols)
93
}
88
94
89
if current.is_empty() {
90
if word_len <= budget {
91
current.push_str(word);
92
word_idx += 1;
93
} else {
94
// Hard-break overlong tokens (URLs, etc.). Must advance word_idx
95
// or this loop never terminates.
96
let mut remaining = word;
97
while !remaining.is_empty() {
98
let chunk = take_char_prefix(remaining, budget);
99
let consumed = chunk.chars().count();
100
if chunk.is_empty() {
101
break;
102
}
103
lines.push(chunk);
104
remaining = &remaining[remaining
105
.char_indices()
106
.nth(consumed)
107
.map(|(idx, _)| idx)
108
.unwrap_or(remaining.len())..];
109
budget = next_budget.max(1);
110
}
111
word_idx += 1;
112
}
95
/// Split into alternating word / whitespace runs so multi-space gaps stay intact.
96
fn tokenize(text: &str) -> Vec<Token<'_>> {
97
let mut tokens = Vec::new();
98
let mut rest = text;
99
while !rest.is_empty() {
100
let first = rest.chars().next().unwrap();
101
if is_wrap_space(first) {
102
let end = rest
103
.char_indices()
104
.find(|(_, c)| !is_wrap_space(*c))
105
.map(|(i, _)| i)
106
.unwrap_or(rest.len());
107
tokens.push(Token::Spaces(&rest[..end]));
108
rest = &rest[end..];
113
109
} else {
114
let current_len = current.chars().count();
115
if current_len + 1 + word_len <= budget {
116
current.push(' ');
117
current.push_str(word);
118
word_idx += 1;
119
} else {
120
lines.push(std::mem::take(&mut current));
121
budget = next_budget.max(1);
122
}
110
let end = rest
111
.char_indices()
112
.find(|(_, c)| is_wrap_space(*c))
113
.map(|(i, _)| i)
114
.unwrap_or(rest.len());
115
tokens.push(Token::Word(&rest[..end]));
116
rest = &rest[end..];
123
117
}
124
118
}
119
tokens
120
}
125
121
126
if !current.is_empty() {
127
lines.push(current);
128
}
129
if lines.is_empty() {
130
lines.push(String::new());
131
}
132
lines
122
fn is_wrap_space(c: char) -> bool {
123
c == ' ' || c == '\t'
133
124
}
134
125
135
fn take_char_prefix(text: &str, max_chars: usize) -> String {
136
text.chars().take(max_chars).collect()
126
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127
enum Token<'a> {
128
Word(&'a str),
129
Spaces(&'a str),
137
130
}
138
131
139
/// Word-wrap `text` to at most `max_cols` characters per line.
140
/// Explicit newlines in `text` start a new wrapped paragraph.
141
pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
142
if max_cols == 0 {
143
return vec![text.to_string()];
132
impl<'a> Token<'a> {
133
fn as_str(self) -> &'a str {
134
match self {
135
Token::Word(s) | Token::Spaces(s) => s,
136
}
144
137
}
145
138
146
let mut lines = Vec::new();
147
for paragraph in text.split('\n') {
148
lines.extend(wrap_line(paragraph, max_cols));
139
fn len_chars(self) -> usize {
140
self.as_str().chars().count()
149
141
}
150
if lines.is_empty() {
151
lines.push(String::new());
142
143
fn is_spaces(self) -> bool {
144
matches!(self, Token::Spaces(_))
152
145
}
153
lines
154
146
}
155
147
156
fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
157
if line.is_empty() {
148
fn wrap_tokens_var_budget(
149
tokens: &[Token<'_>],
150
first_budget: usize,
151
next_budget: usize,
152
) -> Vec<String> {
153
if tokens.is_empty() {
158
154
return vec![String::new()];
159
155
}
156
if first_budget == 0 && next_budget == 0 {
157
return vec![tokens.iter().map(|t| t.as_str()).collect()];
158
}
160
159
161
160
let mut lines = Vec::new();
162
161
let mut current = String::new();
162
let mut budget = first_budget.max(1);
163
let mut idx = 0usize;
164
// After wrapping mid-line, skip the whitespace that sat between words.
165
let mut skip_leading_spaces = false;
166
167
while idx < tokens.len() {
168
let tok = tokens[idx];
169
170
if tok.is_spaces() {
171
if current.is_empty() {
172
if skip_leading_spaces {
173
idx += 1;
174
continue;
175
}
176
// Leading spaces of the original line (or a space-only line).
177
let spaces = tok.as_str();
178
let space_len = tok.len_chars();
179
if space_len <= budget {
180
current.push_str(spaces);
181
idx += 1;
182
} else {
183
let mut remaining = spaces;
184
while !remaining.is_empty() {
185
let chunk = take_char_prefix(remaining, budget);
186
let consumed = chunk.chars().count();
187
if chunk.is_empty() {
188
break;
189
}
190
lines.push(chunk);
191
remaining = char_slice_from(remaining, consumed);
192
budget = next_budget.max(1);
193
}
194
idx += 1;
195
skip_leading_spaces = false;
196
}
197
continue;
198
}
163
199
164
for word in line.split_whitespace() {
165
let word_len = word.chars().count();
166
if current.is_empty() {
167
if word_len <= max_cols {
168
current.push_str(word);
200
let cur_len = current.chars().count();
201
let space_len = tok.len_chars();
202
if cur_len + space_len <= budget {
203
current.push_str(tok.as_str());
204
idx += 1;
169
205
} else {
170
lines.extend(split_long_word(word, max_cols));
206
// Spaces don't fit: end the line (trim trailing pad) and skip
207
// this space run on the continuation.
208
flush_line(&mut lines, &mut current);
209
budget = next_budget.max(1);
210
skip_leading_spaces = true;
171
211
}
172
} else {
173
let current_len = current.chars().count();
174
if current_len + 1 + word_len <= max_cols {
175
current.push(' ');
212
continue;
213
}
214
215
// Word token
216
let word = tok.as_str();
217
let word_len = tok.len_chars();
218
219
if current.is_empty() {
220
if word_len <= budget {
176
221
current.push_str(word);
222
idx += 1;
223
skip_leading_spaces = false;
177
224
} else {
178
lines.push(std::mem::take(&mut current));
179
if word_len <= max_cols {
180
current.push_str(word);
181
} else {
182
lines.extend(split_long_word(word, max_cols));
225
let mut remaining = word;
226
while !remaining.is_empty() {
227
let chunk = take_char_prefix(remaining, budget);
228
let consumed = chunk.chars().count();
229
if chunk.is_empty() {
230
break;
231
}
232
lines.push(chunk);
233
remaining = char_slice_from(remaining, consumed);
234
budget = next_budget.max(1);
183
235
}
236
idx += 1;
237
skip_leading_spaces = true;
184
238
}
239
continue;
240
}
241
242
let cur_len = current.chars().count();
243
if cur_len + word_len <= budget {
244
current.push_str(word);
245
idx += 1;
246
skip_leading_spaces = false;
247
} else {
248
flush_line(&mut lines, &mut current);
249
budget = next_budget.max(1);
250
skip_leading_spaces = true;
251
// Retry the same word on the new line.
185
252
}
186
253
}
187
254
188
255
if !current.is_empty() {
189
256
lines.push(current);
190
257
}
191
192
258
if lines.is_empty() {
193
259
lines.push(String::new());
194
260
}
195
261
lines
196
262
}
197
263
198
fn split_long_word(word: &str, max_cols: usize) -> Vec<String> {
199
let mut chunks = Vec::new();
200
let mut chunk = String::new();
201
for ch in word.chars() {
202
if chunk.chars().count() >= max_cols {
203
chunks.push(std::mem::take(&mut chunk));
204
}
205
chunk.push(ch);
264
fn flush_line(lines: &mut Vec<String>, current: &mut String) {
265
// Drop trailing spaces that only existed as padding before a wrapped word.
266
let trimmed = current.trim_end_matches(is_wrap_space).to_string();
267
if !trimmed.is_empty() {
268
lines.push(trimmed);
206
269
}
207
if !chunk.is_empty() {
208
chunks.push(chunk);
270
current.clear();
271
}
272
273
fn take_char_prefix(text: &str, max_chars: usize) -> String {
274
text.chars().take(max_chars).collect()
275
}
276
277
fn char_slice_from(text: &str, skip_chars: usize) -> &str {
278
match text.char_indices().nth(skip_chars) {
279
Some((idx, _)) => &text[idx..],
280
None => "",
209
281
}
210
chunks
211
282
}
212
283
213
284
#[cfg(test)]
@@ -257,7 +328,10 @@ mod tests {
257
328
fn hanging_wrap_hard_breaks_url_without_hanging() {
258
329
let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
259
330
let lines = wrap_bullet_item(url, 32);
260
assert!(lines.len() >= 2, "expected hard-break into multiple lines: {lines:?}");
331
assert!(
332
lines.len() >= 2,
333
"expected hard-break into multiple lines: {lines:?}"
334
);
261
335
assert!(lines[0].starts_with("* https://"));
262
336
let joined: String = lines
263
337
.iter()
@@ -277,4 +351,35 @@ mod tests {
277
351
assert!(lines.len() >= 2);
278
352
assert_eq!(lines.concat(), url);
279
353
}
354
355
#[test]
356
fn preserves_multiple_spaces_within_line() {
357
let lines = wrap_text("Item 12.00", 32);
358
assert_eq!(lines, vec!["Item 12.00"]);
359
}
360
361
#[test]
362
fn preserves_multiple_spaces_when_wrapping() {
363
// "aa" + 4 spaces + "bb" = 8; budget 6 wraps before bb, spaces not leading next line.
364
let lines = wrap_text("aa bb", 6);
365
assert_eq!(lines, vec!["aa", "bb"]);
366
}
367
368
#[test]
369
fn preserves_leading_spaces() {
370
let lines = wrap_text(" hello", 32);
371
assert_eq!(lines, vec![" hello"]);
372
}
373
374
#[test]
375
fn space_only_line_is_preserved() {
376
let lines = wrap_text(" ", 32);
377
assert_eq!(lines, vec![" "]);
378
}
379
380
#[test]
381
fn bullet_preserves_multiple_spaces() {
382
let lines = wrap_bullet_item("A B", 32);
383
assert_eq!(lines, vec!["* A B"]);
384
}
280
385
}
@@ -52,7 +52,7 @@ pub fn wrap_hanging(52
) -> Vec<String> {
52
) -> Vec<String> {
53
let first_budget = max_cols.saturating_sub(first_prefix.chars().count());
53
let first_budget = max_cols.saturating_sub(first_prefix.chars().count());
54
let next_budget = max_cols.saturating_sub(next_prefix.chars().count());
54
let next_budget = max_cols.saturating_sub(next_prefix.chars().count());
55
let content_lines = wrap_content_var_budget(text, first_budget, next_budget);
55
let content_lines = wrap_tokens_var_budget(&tokenize(text), first_budget, next_budget);
56
56
57
content_lines
57
content_lines
58
.into_iter()
58
.into_iter()
@@ -67,147 +67,218 @@ pub fn wrap_hanging(67
.collect()
67
.collect()
68
}
68
}
69
69
70
fn wrap_content_var_budget(text: &str, first_budget: usize, next_budget: usize) -> Vec<String> {
70
/// Word-wrap `text` to at most `max_cols` characters per line.
71
if first_budget == 0 && next_budget == 0 {
71
/// Explicit newlines in `text` start a new wrapped paragraph.
72
/// Consecutive spaces are preserved (not collapsed).
73
pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
74
if max_cols == 0 {
72
return vec![text.to_string()];
75
return vec![text.to_string()];
73
}
76
}
74
77
75
let words: Vec<&str> = text.split_whitespace().collect();
76
if words.is_empty() {
77
return vec![String::new()];
78
}
79
80
let mut lines = Vec::new();
78
let mut lines = Vec::new();
81
let mut current = String::new();
79
for paragraph in text.split('\n') {
82
let mut budget = first_budget.max(1);
80
lines.extend(wrap_line(paragraph, max_cols));
83
let mut word_idx = 0usize;
81
}
82
if lines.is_empty() {
83
lines.push(String::new());
84
}
85
lines
86
}
84
87
85
while word_idx < words.len() {
88
fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
86
let word = words[word_idx];
89
if line.is_empty() {
87
let word_len = word.chars().count();
90
return vec![String::new()];
91
}
92
wrap_tokens_var_budget(&tokenize(line), max_cols, max_cols)
93
}
88
94
89
if current.is_empty() {
95
/// Split into alternating word / whitespace runs so multi-space gaps stay intact.
90
if word_len <= budget {
96
fn tokenize(text: &str) -> Vec<Token<'_>> {
91
current.push_str(word);
97
let mut tokens = Vec::new();
92
word_idx += 1;
98
let mut rest = text;
93
} else {
99
while !rest.is_empty() {
94
// Hard-break overlong tokens (URLs, etc.). Must advance word_idx
100
let first = rest.chars().next().unwrap();
95
// or this loop never terminates.
101
if is_wrap_space(first) {
96
let mut remaining = word;
102
let end = rest
97
while !remaining.is_empty() {
103
.char_indices()
98
let chunk = take_char_prefix(remaining, budget);
104
.find(|(_, c)| !is_wrap_space(*c))
99
let consumed = chunk.chars().count();
105
.map(|(i, _)| i)
100
if chunk.is_empty() {
106
.unwrap_or(rest.len());
101
break;
107
tokens.push(Token::Spaces(&rest[..end]));
102
}
108
rest = &rest[end..];
103
lines.push(chunk);
104
remaining = &remaining[remaining
105
.char_indices()
106
.nth(consumed)
107
.map(|(idx, _)| idx)
108
.unwrap_or(remaining.len())..];
109
budget = next_budget.max(1);
110
}
111
word_idx += 1;
112
}
113
} else {
109
} else {
114
let current_len = current.chars().count();
110
let end = rest
115
if current_len + 1 + word_len <= budget {
111
.char_indices()
116
current.push(' ');
112
.find(|(_, c)| is_wrap_space(*c))
117
current.push_str(word);
113
.map(|(i, _)| i)
118
word_idx += 1;
114
.unwrap_or(rest.len());
119
} else {
115
tokens.push(Token::Word(&rest[..end]));
120
lines.push(std::mem::take(&mut current));
116
rest = &rest[end..];
121
budget = next_budget.max(1);
122
}
123
}
117
}
124
}
118
}
119
tokens
120
}
125
121
126
if !current.is_empty() {
122
fn is_wrap_space(c: char) -> bool {
127
lines.push(current);
123
c == ' ' || c == '\t'
128
}
129
if lines.is_empty() {
130
lines.push(String::new());
131
}
132
lines
133
}
124
}
134
125
135
fn take_char_prefix(text: &str, max_chars: usize) -> String {
126
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136
text.chars().take(max_chars).collect()
127
enum Token<'a> {
128
Word(&'a str),
129
Spaces(&'a str),
137
}
130
}
138
131
139
/// Word-wrap `text` to at most `max_cols` characters per line.
132
impl<'a> Token<'a> {
140
/// Explicit newlines in `text` start a new wrapped paragraph.
133
fn as_str(self) -> &'a str {
141
pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
134
match self {
142
if max_cols == 0 {
135
Token::Word(s) | Token::Spaces(s) => s,
143
return vec![text.to_string()];
136
}
144
}
137
}
145
138
146
let mut lines = Vec::new();
139
fn len_chars(self) -> usize {
147
for paragraph in text.split('\n') {
140
self.as_str().chars().count()
148
lines.extend(wrap_line(paragraph, max_cols));
149
}
141
}
150
if lines.is_empty() {
142
151
lines.push(String::new());
143
fn is_spaces(self) -> bool {
144
matches!(self, Token::Spaces(_))
152
}
145
}
153
lines
154
}
146
}
155
147
156
fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
148
fn wrap_tokens_var_budget(
157
if line.is_empty() {
149
tokens: &[Token<'_>],
150
first_budget: usize,
151
next_budget: usize,
152
) -> Vec<String> {
153
if tokens.is_empty() {
158
return vec![String::new()];
154
return vec![String::new()];
159
}
155
}
156
if first_budget == 0 && next_budget == 0 {
157
return vec![tokens.iter().map(|t| t.as_str()).collect()];
158
}
160
159
161
let mut lines = Vec::new();
160
let mut lines = Vec::new();
162
let mut current = String::new();
161
let mut current = String::new();
162
let mut budget = first_budget.max(1);
163
let mut idx = 0usize;
164
// After wrapping mid-line, skip the whitespace that sat between words.
165
let mut skip_leading_spaces = false;
166
167
while idx < tokens.len() {
168
let tok = tokens[idx];
169
170
if tok.is_spaces() {
171
if current.is_empty() {
172
if skip_leading_spaces {
173
idx += 1;
174
continue;
175
}
176
// Leading spaces of the original line (or a space-only line).
177
let spaces = tok.as_str();
178
let space_len = tok.len_chars();
179
if space_len <= budget {
180
current.push_str(spaces);
181
idx += 1;
182
} else {
183
let mut remaining = spaces;
184
while !remaining.is_empty() {
185
let chunk = take_char_prefix(remaining, budget);
186
let consumed = chunk.chars().count();
187
if chunk.is_empty() {
188
break;
189
}
190
lines.push(chunk);
191
remaining = char_slice_from(remaining, consumed);
192
budget = next_budget.max(1);
193
}
194
idx += 1;
195
skip_leading_spaces = false;
196
}
197
continue;
198
}
163
199
164
for word in line.split_whitespace() {
200
let cur_len = current.chars().count();
165
let word_len = word.chars().count();
201
let space_len = tok.len_chars();
166
if current.is_empty() {
202
if cur_len + space_len <= budget {
167
if word_len <= max_cols {
203
current.push_str(tok.as_str());
168
current.push_str(word);
204
idx += 1;
169
} else {
205
} else {
170
lines.extend(split_long_word(word, max_cols));
206
// Spaces don't fit: end the line (trim trailing pad) and skip
207
// this space run on the continuation.
208
flush_line(&mut lines, &mut current);
209
budget = next_budget.max(1);
210
skip_leading_spaces = true;
171
}
211
}
172
} else {
212
continue;
173
let current_len = current.chars().count();
213
}
174
if current_len + 1 + word_len <= max_cols {
214
175
current.push(' ');
215
// Word token
216
let word = tok.as_str();
217
let word_len = tok.len_chars();
218
219
if current.is_empty() {
220
if word_len <= budget {
176
current.push_str(word);
221
current.push_str(word);
222
idx += 1;
223
skip_leading_spaces = false;
177
} else {
224
} else {
178
lines.push(std::mem::take(&mut current));
225
let mut remaining = word;
179
if word_len <= max_cols {
226
while !remaining.is_empty() {
180
current.push_str(word);
227
let chunk = take_char_prefix(remaining, budget);
181
} else {
228
let consumed = chunk.chars().count();
182
lines.extend(split_long_word(word, max_cols));
229
if chunk.is_empty() {
230
break;
231
}
232
lines.push(chunk);
233
remaining = char_slice_from(remaining, consumed);
234
budget = next_budget.max(1);
183
}
235
}
236
idx += 1;
237
skip_leading_spaces = true;
184
}
238
}
239
continue;
240
}
241
242
let cur_len = current.chars().count();
243
if cur_len + word_len <= budget {
244
current.push_str(word);
245
idx += 1;
246
skip_leading_spaces = false;
247
} else {
248
flush_line(&mut lines, &mut current);
249
budget = next_budget.max(1);
250
skip_leading_spaces = true;
251
// Retry the same word on the new line.
185
}
252
}
186
}
253
}
187
254
188
if !current.is_empty() {
255
if !current.is_empty() {
189
lines.push(current);
256
lines.push(current);
190
}
257
}
191
192
if lines.is_empty() {
258
if lines.is_empty() {
193
lines.push(String::new());
259
lines.push(String::new());
194
}
260
}
195
lines
261
lines
196
}
262
}
197
263
198
fn split_long_word(word: &str, max_cols: usize) -> Vec<String> {
264
fn flush_line(lines: &mut Vec<String>, current: &mut String) {
199
let mut chunks = Vec::new();
265
// Drop trailing spaces that only existed as padding before a wrapped word.
200
let mut chunk = String::new();
266
let trimmed = current.trim_end_matches(is_wrap_space).to_string();
201
for ch in word.chars() {
267
if !trimmed.is_empty() {
202
if chunk.chars().count() >= max_cols {
268
lines.push(trimmed);
203
chunks.push(std::mem::take(&mut chunk));
204
}
205
chunk.push(ch);
206
}
269
}
207
if !chunk.is_empty() {
270
current.clear();
208
chunks.push(chunk);
271
}
272
273
fn take_char_prefix(text: &str, max_chars: usize) -> String {
274
text.chars().take(max_chars).collect()
275
}
276
277
fn char_slice_from(text: &str, skip_chars: usize) -> &str {
278
match text.char_indices().nth(skip_chars) {
279
Some((idx, _)) => &text[idx..],
280
None => "",
209
}
281
}
210
chunks
211
}
282
}
212
283
213
#[cfg(test)]
284
#[cfg(test)]
@@ -257,7 +328,10 @@ mod tests {257
fn hanging_wrap_hard_breaks_url_without_hanging() {
328
fn hanging_wrap_hard_breaks_url_without_hanging() {
258
let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
329
let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
259
let lines = wrap_bullet_item(url, 32);
330
let lines = wrap_bullet_item(url, 32);
260
assert!(lines.len() >= 2, "expected hard-break into multiple lines: {lines:?}");
331
assert!(
332
lines.len() >= 2,
333
"expected hard-break into multiple lines: {lines:?}"
334
);
261
assert!(lines[0].starts_with("* https://"));
335
assert!(lines[0].starts_with("* https://"));
262
let joined: String = lines
336
let joined: String = lines
263
.iter()
337
.iter()
@@ -277,4 +351,35 @@ mod tests {277
assert!(lines.len() >= 2);
351
assert!(lines.len() >= 2);
278
assert_eq!(lines.concat(), url);
352
assert_eq!(lines.concat(), url);
279
}
353
}
354
355
#[test]
356
fn preserves_multiple_spaces_within_line() {
357
let lines = wrap_text("Item 12.00", 32);
358
assert_eq!(lines, vec!["Item 12.00"]);
359
}
360
361
#[test]
362
fn preserves_multiple_spaces_when_wrapping() {
363
// "aa" + 4 spaces + "bb" = 8; budget 6 wraps before bb, spaces not leading next line.
364
let lines = wrap_text("aa bb", 6);
365
assert_eq!(lines, vec!["aa", "bb"]);
366
}
367
368
#[test]
369
fn preserves_leading_spaces() {
370
let lines = wrap_text(" hello", 32);
371
assert_eq!(lines, vec![" hello"]);
372
}
373
374
#[test]
375
fn space_only_line_is_preserved() {
376
let lines = wrap_text(" ", 32);
377
assert_eq!(lines, vec![" "]);
378
}
379
380
#[test]
381
fn bullet_preserves_multiple_spaces() {
382
let lines = wrap_bullet_item("A B", 32);
383
assert_eq!(lines, vec!["* A B"]);
384
}
280
}
385
}