]> git.lizzy.rs Git - rust.git/blob - src/string.rs
rewrite_string: handle newlines in the last line that fits in the shape for cases...
[rust.git] / src / string.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Format string literals.
12
13 use regex::Regex;
14 use unicode_segmentation::UnicodeSegmentation;
15
16 use config::Config;
17 use shape::Shape;
18 use utils::wrap_str;
19
20 const MIN_STRING: usize = 10;
21
22 /// Describes the layout of a piece of text.
23 pub struct StringFormat<'a> {
24     /// The opening sequence of characters for the piece of text
25     pub opener: &'a str,
26     /// The closing sequence of characters for the piece of text
27     pub closer: &'a str,
28     /// The opening sequence of characters for a line
29     pub line_start: &'a str,
30     /// The closing sequence of characters for a line
31     pub line_end: &'a str,
32     /// The allocated box to fit the text into
33     pub shape: Shape,
34     /// Trim trailing whitespaces
35     pub trim_end: bool,
36     pub config: &'a Config,
37 }
38
39 impl<'a> StringFormat<'a> {
40     pub fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> {
41         StringFormat {
42             opener: "\"",
43             closer: "\"",
44             line_start: " ",
45             line_end: "\\",
46             shape,
47             trim_end: false,
48             config,
49         }
50     }
51
52     /// Returns the maximum number of graphemes that is possible on a line while taking the
53     /// indentation into account.
54     ///
55     /// If we cannot put at least a single character per line, the rewrite won't succeed.
56     fn max_chars_with_indent(&self) -> Option<usize> {
57         Some(
58             self.shape
59                 .width
60                 .checked_sub(self.opener.len() + self.line_end.len() + 1)?
61                 + 1,
62         )
63     }
64
65     /// Like max_chars_with_indent but the indentation is not substracted.
66     /// This allows to fit more graphemes from the string on a line when
67     /// SnippetState::EndWithLineFeed.
68     fn max_chars_without_indent(&self) -> Option<usize> {
69         Some(self.config.max_width().checked_sub(self.line_end.len())?)
70     }
71 }
72
73 pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {
74     let max_chars_with_indent = fmt.max_chars_with_indent()?;
75     let max_chars_without_indent = fmt.max_chars_without_indent()?;
76     let indent_with_newline = fmt.shape.indent.to_string_with_newline(fmt.config);
77     let indent_without_newline = fmt.shape.indent.to_string(fmt.config);
78
79     // Strip line breaks.
80     // With this regex applied, all remaining whitespaces are significant
81     let strip_line_breaks_re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
82     let stripped_str = strip_line_breaks_re.replace_all(orig, "$1");
83
84     let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
85
86     // `cur_start` is the position in `orig` of the start of the current line.
87     let mut cur_start = 0;
88     let mut result = String::with_capacity(
89         stripped_str
90             .len()
91             .checked_next_power_of_two()
92             .unwrap_or(usize::max_value()),
93     );
94     result.push_str(fmt.opener);
95
96     // Snip a line at a time from `stripped_str` until it is used up. Push the snippet
97     // onto result.
98     let mut cur_max_chars = max_chars_with_indent;
99     let is_bareline_ok = fmt.line_start.is_empty() || is_whitespace(fmt.line_start);
100     loop {
101         // All the input starting at cur_start fits on the current line
102         if graphemes.len() - cur_start <= cur_max_chars {
103             // trim trailing whitespaces
104             let graphemes_minus_ws = if !fmt.trim_end {
105                 &graphemes[cur_start..]
106             } else {
107                 match graphemes[cur_start..]
108                     .iter()
109                     .rposition(|grapheme| !is_whitespace(grapheme))
110                 {
111                     Some(index) => &graphemes[cur_start..=cur_start + index],
112                     None => &graphemes[cur_start..],
113                 }
114             };
115             if is_bareline_ok {
116                 // new lines don't need to start with line_start
117                 result.push_str(&graphemes_minus_ws.join(""));
118             } else {
119                 // new lines need to be indented and prefixed with line_start
120                 for grapheme in graphemes_minus_ws {
121                     if is_line_feed(grapheme) {
122                         result.push_str(&indent_with_newline);
123                         result.push_str(fmt.line_start);
124                     } else {
125                         result.push_str(grapheme);
126                     }
127                 }
128             }
129             break;
130         }
131
132         // The input starting at cur_start needs to be broken
133         match break_string(cur_max_chars, fmt.trim_end, &graphemes[cur_start..]) {
134             SnippetState::LineEnd(line, len) => {
135                 result.push_str(&line);
136                 result.push_str(fmt.line_end);
137                 result.push_str(&indent_with_newline);
138                 result.push_str(fmt.line_start);
139                 cur_max_chars = max_chars_with_indent;
140                 cur_start += len;
141             }
142             SnippetState::EndWithLineFeed(line, len) => {
143                 result.push_str(&line);
144                 if is_bareline_ok {
145                     // the next line can benefit from the full width
146                     cur_max_chars = max_chars_without_indent;
147                 } else {
148                     result.push_str(&indent_without_newline);
149                     result.push_str(fmt.line_start);
150                     cur_max_chars = max_chars_with_indent;
151                 }
152                 cur_start += len;
153             }
154             SnippetState::EndOfInput(line) => {
155                 result.push_str(&line);
156                 break;
157             }
158         }
159     }
160
161     result.push_str(fmt.closer);
162     wrap_str(result, fmt.config.max_width(), fmt.shape)
163 }
164
165 /// Result of breaking a string so it fits in a line and the state it ended in.
166 /// The state informs about what to do with the snippet and how to continue the breaking process.
167 #[derive(Debug, PartialEq)]
168 enum SnippetState {
169     /// The input could not be broken and so rewriting the string is finished.
170     EndOfInput(String),
171     /// The input could be broken and the returned snippet should be ended with a
172     /// `[StringFormat::line_end]`. The next snippet needs to be indented.
173     ///
174     /// The returned string is the line to print out and the number is the length that got read in
175     /// the text being rewritten. That length may be greater than the returned string if trailing
176     /// whitespaces got trimmed.
177     LineEnd(String, usize),
178     /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
179     /// to be rewritten *could* use more width than what is specified by the given shape. For
180     /// example with a multiline string, the next snippet does not need to be indented, allowing
181     /// more characters to be fit within a line.
182     ///
183     /// The returned string is the line to print out and the number is the length that got read in
184     /// the text being rewritten.
185     EndWithLineFeed(String, usize),
186 }
187
188 /// Break the input string at a boundary character around the offset `max_chars`. A boundary
189 /// character is either a punctuation or a whitespace.
190 fn break_string(max_chars: usize, trim_end: bool, input: &[&str]) -> SnippetState {
191     let break_at = |index /* grapheme at index is included */| {
192         // Take in any whitespaces to the left/right of `input[index]` and
193         // check if there is a line feed, in which case whitespaces needs to be kept.
194         let index_minus_ws = input[0..=index]
195             .iter()
196             .rposition(|grapheme| !is_whitespace(grapheme))
197             .unwrap_or(index);
198         // Take into account newlines occuring in input[0..=index], i.e., the possible next new
199         // line. If there is one, then text after it could be rewritten in a way that the available
200         // space is fully used.
201         for (i, grapheme) in input[0..=index].iter().enumerate() {
202             if is_line_feed(grapheme) {
203                 if i < index_minus_ws || !trim_end {
204                     return SnippetState::EndWithLineFeed(input[0..=i].join("").to_string(), i + 1);
205                 }
206                 break;
207             }
208         }
209
210         let mut index_plus_ws = index;
211         for (i, grapheme) in input[index + 1..].iter().enumerate() {
212             if !trim_end && is_line_feed(grapheme) {
213                 return SnippetState::EndWithLineFeed(
214                     input[0..=index + 1 + i].join("").to_string(),
215                     index + 2 + i,
216                 );
217             } else if !is_whitespace(grapheme) {
218                 index_plus_ws = index + i;
219                 break;
220             }
221         }
222
223         if trim_end {
224             SnippetState::LineEnd(
225                 input[0..=index_minus_ws].join("").to_string(),
226                 index_plus_ws + 1,
227             )
228         } else {
229             SnippetState::LineEnd(
230                 input[0..=index_plus_ws].join("").to_string(),
231                 index_plus_ws + 1,
232             )
233         }
234     };
235
236     // Find the position in input for breaking the string
237     match input[0..max_chars]
238         .iter()
239         .rposition(|grapheme| is_whitespace(grapheme))
240     {
241         // Found a whitespace and what is on its left side is big enough.
242         Some(index) if index >= MIN_STRING => break_at(index),
243         // No whitespace found, try looking for a punctuation instead
244         _ => match input[0..max_chars]
245             .iter()
246             .rposition(|grapheme| is_punctuation(grapheme))
247         {
248             // Found a punctuation and what is on its left side is big enough.
249             Some(index) if index >= MIN_STRING => break_at(index),
250             // Either no boundary character was found to the left of `input[max_chars]`, or the line
251             // got too small. We try searching for a boundary character to the right.
252             _ => match input[max_chars..]
253                 .iter()
254                 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
255             {
256                 // A boundary was found after the line limit
257                 Some(index) => break_at(max_chars + index),
258                 // No boundary to the right, the input cannot be broken
259                 None => SnippetState::EndOfInput(input.join("").to_string()),
260             },
261         },
262     }
263 }
264
265 fn is_line_feed(grapheme: &str) -> bool {
266     grapheme.as_bytes()[0] == b'\n'
267 }
268
269 fn is_whitespace(grapheme: &str) -> bool {
270     grapheme.chars().all(|c| c.is_whitespace())
271 }
272
273 fn is_punctuation(grapheme: &str) -> bool {
274     match grapheme.as_bytes()[0] {
275         b':' | b',' | b';' | b'.' => true,
276         _ => false,
277     }
278 }
279
280 #[cfg(test)]
281 mod test {
282     use super::{break_string, rewrite_string, SnippetState, StringFormat};
283     use config::Config;
284     use shape::{Indent, Shape};
285     use unicode_segmentation::UnicodeSegmentation;
286
287     #[test]
288     fn issue343() {
289         let config = Default::default();
290         let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
291         rewrite_string("eq_", &fmt);
292     }
293
294     #[test]
295     fn should_break_on_whitespace() {
296         let string = "Placerat felis. Mauris porta ante sagittis purus.";
297         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
298         assert_eq!(
299             break_string(20, false, &graphemes[..]),
300             SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
301         );
302         assert_eq!(
303             break_string(20, true, &graphemes[..]),
304             SnippetState::LineEnd("Placerat felis.".to_string(), 16)
305         );
306     }
307
308     #[test]
309     fn should_break_on_punctuation() {
310         let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
311         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
312         assert_eq!(
313             break_string(20, false, &graphemes[..]),
314             SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
315         );
316     }
317
318     #[test]
319     fn should_break_forward() {
320         let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
321         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
322         assert_eq!(
323             break_string(20, false, &graphemes[..]),
324             SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
325         );
326         assert_eq!(
327             break_string(20, true, &graphemes[..]),
328             SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
329         );
330     }
331
332     #[test]
333     fn nothing_to_break() {
334         let string = "Venenatis_tellus_vel_tellus";
335         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
336         assert_eq!(
337             break_string(20, false, &graphemes[..]),
338             SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
339         );
340     }
341
342     #[test]
343     fn significant_whitespaces() {
344         let string = "Neque in sem.      \n      Pellentesque tellus augue.";
345         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
346         assert_eq!(
347             break_string(15, false, &graphemes[..]),
348             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
349         );
350         assert_eq!(
351             break_string(25, false, &graphemes[..]),
352             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
353         );
354         // if `StringFormat::line_end` is true, then the line feed does not matter anymore
355         assert_eq!(
356             break_string(15, true, &graphemes[..]),
357             SnippetState::LineEnd("Neque in sem.".to_string(), 26)
358         );
359         assert_eq!(
360             break_string(25, true, &graphemes[..]),
361             SnippetState::LineEnd("Neque in sem.".to_string(), 26)
362         );
363     }
364
365     #[test]
366     fn big_whitespace() {
367         let string = "Neque in sem.            Pellentesque tellus augue.";
368         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
369         assert_eq!(
370             break_string(20, false, &graphemes[..]),
371             SnippetState::LineEnd("Neque in sem.            ".to_string(), 25)
372         );
373         assert_eq!(
374             break_string(20, true, &graphemes[..]),
375             SnippetState::LineEnd("Neque in sem.".to_string(), 25)
376         );
377     }
378
379     #[test]
380     fn newline_in_candidate_line() {
381         let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
382
383         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
384         assert_eq!(
385             break_string(25, false, &graphemes[..]),
386             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
387         );
388         assert_eq!(
389             break_string(25, true, &graphemes[..]),
390             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
391         );
392
393         let mut config: Config = Default::default();
394         config.set().max_width(27);
395         let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
396         let rewritten_string = rewrite_string(string, &fmt);
397         assert_eq!(
398             rewritten_string,
399             Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
400         );
401     }
402
403     #[test]
404     fn last_line_fit_with_trailing_whitespaces() {
405         let string = "Vivamus id mi.  ";
406         let config: Config = Default::default();
407         let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
408
409         fmt.trim_end = true;
410         let rewritten_string = rewrite_string(string, &fmt);
411         assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
412
413         fmt.trim_end = false; // default value of trim_end
414         let rewritten_string = rewrite_string(string, &fmt);
415         assert_eq!(rewritten_string, Some("\"Vivamus id mi.  \"".to_string()));
416     }
417
418     #[test]
419     fn last_line_fit_with_newline() {
420         let string = "Vivamus id mi.\nVivamus id mi.";
421         let config: Config = Default::default();
422         let fmt = StringFormat {
423             opener: "",
424             closer: "",
425             line_start: "// ",
426             line_end: "",
427             shape: Shape::legacy(100, Indent::from_width(&config, 4)),
428             trim_end: true,
429             config: &config,
430         };
431
432         let rewritten_string = rewrite_string(string, &fmt);
433         assert_eq!(
434             rewritten_string,
435             Some("Vivamus id mi.\n    // Vivamus id mi.".to_string())
436         );
437     }
438
439     #[test]
440     fn overflow_in_non_string_content() {
441         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
442         let config: Config = Default::default();
443         let fmt = StringFormat {
444             opener: "",
445             closer: "",
446             line_start: "// ",
447             line_end: "",
448             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
449             trim_end: true,
450             config: &config,
451         };
452
453         assert_eq!(
454             rewrite_string(comment, &fmt),
455             Some(
456                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus\n        // porttitor"
457                     .to_string()
458             )
459         );
460     }
461
462     #[test]
463     fn overflow_in_non_string_content_with_line_end() {
464         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
465         let config: Config = Default::default();
466         let fmt = StringFormat {
467             opener: "",
468             closer: "",
469             line_start: "// ",
470             line_end: "@",
471             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
472             trim_end: true,
473             config: &config,
474         };
475
476         assert_eq!(
477             rewrite_string(comment, &fmt),
478             Some(
479                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus@\n        // porttitor"
480                     .to_string()
481             )
482         );
483     }
484 }