summaryrefslogtreecommitdiffstats
path: root/third_party/rust/textwrap/src/refill.rs
blob: 1be85f04eb39b7e1273fea8d824d5783a4bbab40 (plain)
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
//! Functionality for unfilling and refilling text.

use crate::core::display_width;
use crate::line_ending::NonEmptyLines;
use crate::{fill, LineEnding, Options};

/// Unpack a paragraph of already-wrapped text.
///
/// This function attempts to recover the original text from a single
/// paragraph of wrapped text, such as what [`fill()`] would produce.
/// This means that it turns
///
/// ```text
/// textwrap: a small
/// library for
/// wrapping text.
/// ```
///
/// back into
///
/// ```text
/// textwrap: a small library for wrapping text.
/// ```
///
/// In addition, it will recognize a common prefix and a common line
/// ending among the lines.
///
/// The prefix of the first line is returned in
/// [`Options::initial_indent`] and the prefix (if any) of the the
/// other lines is returned in [`Options::subsequent_indent`].
///
/// Line ending is returned in [`Options::line_ending`]. If line ending
/// can not be confidently detected (mixed or no line endings in the
/// input), [`LineEnding::LF`] will be returned.
///
/// In addition to `' '`, the prefixes can consist of characters used
/// for unordered lists (`'-'`, `'+'`, and `'*'`) and block quotes
/// (`'>'`) in Markdown as well as characters often used for inline
/// comments (`'#'` and `'/'`).
///
/// The text must come from a single wrapped paragraph. This means
/// that there can be no empty lines (`"\n\n"` or `"\r\n\r\n"`) within
/// the text. It is unspecified what happens if `unfill` is called on
/// more than one paragraph of text.
///
/// # Examples
///
/// ```
/// use textwrap::{LineEnding, unfill};
///
/// let (text, options) = unfill("\
/// * This is an
///   example of
///   a list item.
/// ");
///
/// assert_eq!(text, "This is an example of a list item.\n");
/// assert_eq!(options.initial_indent, "* ");
/// assert_eq!(options.subsequent_indent, "  ");
/// assert_eq!(options.line_ending, LineEnding::LF);
/// ```
pub fn unfill(text: &str) -> (String, Options<'_>) {
    let prefix_chars: &[_] = &[' ', '-', '+', '*', '>', '#', '/'];

    let mut options = Options::new(0);
    for (idx, line) in text.lines().enumerate() {
        options.width = std::cmp::max(options.width, display_width(line));
        let without_prefix = line.trim_start_matches(prefix_chars);
        let prefix = &line[..line.len() - without_prefix.len()];

        if idx == 0 {
            options.initial_indent = prefix;
        } else if idx == 1 {
            options.subsequent_indent = prefix;
        } else if idx > 1 {
            for ((idx, x), y) in prefix.char_indices().zip(options.subsequent_indent.chars()) {
                if x != y {
                    options.subsequent_indent = &prefix[..idx];
                    break;
                }
            }
            if prefix.len() < options.subsequent_indent.len() {
                options.subsequent_indent = prefix;
            }
        }
    }

    let mut unfilled = String::with_capacity(text.len());
    let mut detected_line_ending = None;

    for (idx, (line, ending)) in NonEmptyLines(text).enumerate() {
        if idx == 0 {
            unfilled.push_str(&line[options.initial_indent.len()..]);
        } else {
            unfilled.push(' ');
            unfilled.push_str(&line[options.subsequent_indent.len()..]);
        }
        match (detected_line_ending, ending) {
            (None, Some(_)) => detected_line_ending = ending,
            (Some(LineEnding::CRLF), Some(LineEnding::LF)) => detected_line_ending = ending,
            _ => (),
        }
    }

    // Add back a line ending if `text` ends with the one we detect.
    if let Some(line_ending) = detected_line_ending {
        if text.ends_with(line_ending.as_str()) {
            unfilled.push_str(line_ending.as_str());
        }
    }

    options.line_ending = detected_line_ending.unwrap_or(LineEnding::LF);
    (unfilled, options)
}

/// Refill a paragraph of wrapped text with a new width.
///
/// This function will first use [`unfill()`] to remove newlines from
/// the text. Afterwards the text is filled again using [`fill()`].
///
/// The `new_width_or_options` argument specify the new width and can
/// specify other options as well — except for
/// [`Options::initial_indent`] and [`Options::subsequent_indent`],
/// which are deduced from `filled_text`.
///
/// # Examples
///
/// ```
/// use textwrap::refill;
///
/// // Some loosely wrapped text. The "> " prefix is recognized automatically.
/// let text = "\
/// > Memory
/// > safety without garbage
/// > collection.
/// ";
///
/// assert_eq!(refill(text, 20), "\
/// > Memory safety
/// > without garbage
/// > collection.
/// ");
///
/// assert_eq!(refill(text, 40), "\
/// > Memory safety without garbage
/// > collection.
/// ");
///
/// assert_eq!(refill(text, 60), "\
/// > Memory safety without garbage collection.
/// ");
/// ```
///
/// You can also reshape bullet points:
///
/// ```
/// use textwrap::refill;
///
/// let text = "\
/// - This is my
///   list item.
/// ";
///
/// assert_eq!(refill(text, 20), "\
/// - This is my list
///   item.
/// ");
/// ```
pub fn refill<'a, Opt>(filled_text: &str, new_width_or_options: Opt) -> String
where
    Opt: Into<Options<'a>>,
{
    let mut new_options = new_width_or_options.into();
    let (text, options) = unfill(filled_text);
    // The original line ending is kept by `unfill`.
    let stripped = text.strip_suffix(options.line_ending.as_str());
    let new_line_ending = new_options.line_ending.as_str();

    new_options.initial_indent = options.initial_indent;
    new_options.subsequent_indent = options.subsequent_indent;
    let mut refilled = fill(stripped.unwrap_or(&text), new_options);

    // Add back right line ending if we stripped one off above.
    if stripped.is_some() {
        refilled.push_str(new_line_ending);
    }
    refilled
}

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

    #[test]
    fn unfill_simple() {
        let (text, options) = unfill("foo\nbar");
        assert_eq!(text, "foo bar");
        assert_eq!(options.width, 3);
        assert_eq!(options.line_ending, LineEnding::LF);
    }

    #[test]
    fn unfill_no_new_line() {
        let (text, options) = unfill("foo bar");
        assert_eq!(text, "foo bar");
        assert_eq!(options.width, 7);
        assert_eq!(options.line_ending, LineEnding::LF);
    }

    #[test]
    fn unfill_simple_crlf() {
        let (text, options) = unfill("foo\r\nbar");
        assert_eq!(text, "foo bar");
        assert_eq!(options.width, 3);
        assert_eq!(options.line_ending, LineEnding::CRLF);
    }

    #[test]
    fn unfill_mixed_new_lines() {
        let (text, options) = unfill("foo\r\nbar\nbaz");
        assert_eq!(text, "foo bar baz");
        assert_eq!(options.width, 3);
        assert_eq!(options.line_ending, LineEnding::LF);
    }

    #[test]
    fn test_unfill_consecutive_different_prefix() {
        let (text, options) = unfill("foo\n*\n/");
        assert_eq!(text, "foo * /");
        assert_eq!(options.width, 3);
        assert_eq!(options.line_ending, LineEnding::LF);
    }

    #[test]
    fn unfill_trailing_newlines() {
        let (text, options) = unfill("foo\nbar\n\n\n");
        assert_eq!(text, "foo bar\n");
        assert_eq!(options.width, 3);
    }

    #[test]
    fn unfill_mixed_trailing_newlines() {
        let (text, options) = unfill("foo\r\nbar\n\r\n\n");
        assert_eq!(text, "foo bar\n");
        assert_eq!(options.width, 3);
        assert_eq!(options.line_ending, LineEnding::LF);
    }

    #[test]
    fn unfill_trailing_crlf() {
        let (text, options) = unfill("foo bar\r\n");
        assert_eq!(text, "foo bar\r\n");
        assert_eq!(options.width, 7);
        assert_eq!(options.line_ending, LineEnding::CRLF);
    }

    #[test]
    fn unfill_initial_indent() {
        let (text, options) = unfill("  foo\nbar\nbaz");
        assert_eq!(text, "foo bar baz");
        assert_eq!(options.width, 5);
        assert_eq!(options.initial_indent, "  ");
    }

    #[test]
    fn unfill_differing_indents() {
        let (text, options) = unfill("  foo\n    bar\n  baz");
        assert_eq!(text, "foo   bar baz");
        assert_eq!(options.width, 7);
        assert_eq!(options.initial_indent, "  ");
        assert_eq!(options.subsequent_indent, "  ");
    }

    #[test]
    fn unfill_list_item() {
        let (text, options) = unfill("* foo\n  bar\n  baz");
        assert_eq!(text, "foo bar baz");
        assert_eq!(options.width, 5);
        assert_eq!(options.initial_indent, "* ");
        assert_eq!(options.subsequent_indent, "  ");
    }

    #[test]
    fn unfill_multiple_char_prefix() {
        let (text, options) = unfill("    // foo bar\n    // baz\n    // quux");
        assert_eq!(text, "foo bar baz quux");
        assert_eq!(options.width, 14);
        assert_eq!(options.initial_indent, "    // ");
        assert_eq!(options.subsequent_indent, "    // ");
    }

    #[test]
    fn unfill_block_quote() {
        let (text, options) = unfill("> foo\n> bar\n> baz");
        assert_eq!(text, "foo bar baz");
        assert_eq!(options.width, 5);
        assert_eq!(options.initial_indent, "> ");
        assert_eq!(options.subsequent_indent, "> ");
    }

    #[test]
    fn unfill_only_prefixes_issue_466() {
        // Test that we don't crash if the first line has only prefix
        // chars *and* the second line is shorter than the first line.
        let (text, options) = unfill("######\nfoo");
        assert_eq!(text, " foo");
        assert_eq!(options.width, 6);
        assert_eq!(options.initial_indent, "######");
        assert_eq!(options.subsequent_indent, "");
    }

    #[test]
    fn unfill_trailing_newlines_issue_466() {
        // Test that we don't crash on a '\r' following a string of
        // '\n'. The problem was that we removed both kinds of
        // characters in one code path, but not in the other.
        let (text, options) = unfill("foo\n##\n\n\r");
        // The \n\n changes subsequent_indent to "".
        assert_eq!(text, "foo ## \r");
        assert_eq!(options.width, 3);
        assert_eq!(options.initial_indent, "");
        assert_eq!(options.subsequent_indent, "");
    }

    #[test]
    fn unfill_whitespace() {
        assert_eq!(unfill("foo   bar").0, "foo   bar");
    }

    #[test]
    fn refill_convert_lf_to_crlf() {
        let options = Options::new(5).line_ending(LineEnding::CRLF);
        assert_eq!(refill("foo\nbar\n", options), "foo\r\nbar\r\n",);
    }

    #[test]
    fn refill_convert_crlf_to_lf() {
        let options = Options::new(5).line_ending(LineEnding::LF);
        assert_eq!(refill("foo\r\nbar\r\n", options), "foo\nbar\n",);
    }

    #[test]
    fn refill_convert_mixed_newlines() {
        let options = Options::new(5).line_ending(LineEnding::CRLF);
        assert_eq!(refill("foo\r\nbar\n", options), "foo\r\nbar\r\n",);
    }

    #[test]
    fn refill_defaults_to_lf() {
        assert_eq!(refill("foo bar baz", 5), "foo\nbar\nbaz");
    }
}