]> git.lizzy.rs Git - rust.git/blob - src/string.rs
rewrite_string: retain blank lines that are trailing
[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             for (i, grapheme) in graphemes[cur_start..].iter().enumerate() {
104                 if is_line_feed(grapheme) {
105                     // take care of blank lines
106                     result = trim_right_but_line_feed(fmt.trim_end, result);
107                     result.push_str("\n");
108                     if !is_bareline_ok && cur_start + i + 1 < graphemes.len() {
109                         result.push_str(&indent_without_newline);
110                         result.push_str(fmt.line_start);
111                     }
112                 } else {
113                     result.push_str(grapheme);
114                 }
115             }
116             result = trim_right_but_line_feed(fmt.trim_end, result);
117             break;
118         }
119
120         // The input starting at cur_start needs to be broken
121         match break_string(cur_max_chars, fmt.trim_end, &graphemes[cur_start..]) {
122             SnippetState::LineEnd(line, len) => {
123                 result.push_str(&line);
124                 result.push_str(fmt.line_end);
125                 result.push_str(&indent_with_newline);
126                 result.push_str(fmt.line_start);
127                 cur_max_chars = max_chars_with_indent;
128                 cur_start += len;
129             }
130             SnippetState::EndWithLineFeed(line, len) => {
131                 if line == "\n" && fmt.trim_end {
132                     result = result.trim_right().to_string();
133                 }
134                 result.push_str(&line);
135                 if is_bareline_ok {
136                     // the next line can benefit from the full width
137                     cur_max_chars = max_chars_without_indent;
138                 } else {
139                     result.push_str(&indent_without_newline);
140                     result.push_str(fmt.line_start);
141                     cur_max_chars = max_chars_with_indent;
142                 }
143                 cur_start += len;
144             }
145             SnippetState::EndOfInput(line) => {
146                 result.push_str(&line);
147                 break;
148             }
149         }
150     }
151
152     result.push_str(fmt.closer);
153     wrap_str(result, fmt.config.max_width(), fmt.shape)
154 }
155
156 /// Trims whitespaces to the right except for the line feed character.
157 fn trim_right_but_line_feed(trim_end: bool, result: String) -> String {
158     let whitespace_except_line_feed = |c: char| c.is_whitespace() && c != '\n';
159     if trim_end && result.ends_with(whitespace_except_line_feed) {
160         result
161             .trim_right_matches(whitespace_except_line_feed)
162             .to_string()
163     } else {
164         result
165     }
166 }
167
168 /// Result of breaking a string so it fits in a line and the state it ended in.
169 /// The state informs about what to do with the snippet and how to continue the breaking process.
170 #[derive(Debug, PartialEq)]
171 enum SnippetState {
172     /// The input could not be broken and so rewriting the string is finished.
173     EndOfInput(String),
174     /// The input could be broken and the returned snippet should be ended with a
175     /// `[StringFormat::line_end]`. The next snippet needs to be indented.
176     ///
177     /// The returned string is the line to print out and the number is the length that got read in
178     /// the text being rewritten. That length may be greater than the returned string if trailing
179     /// whitespaces got trimmed.
180     LineEnd(String, usize),
181     /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
182     /// to be rewritten *could* use more width than what is specified by the given shape. For
183     /// example with a multiline string, the next snippet does not need to be indented, allowing
184     /// more characters to be fit within a line.
185     ///
186     /// The returned string is the line to print out and the number is the length that got read in
187     /// the text being rewritten.
188     EndWithLineFeed(String, usize),
189 }
190
191 /// Break the input string at a boundary character around the offset `max_chars`. A boundary
192 /// character is either a punctuation or a whitespace.
193 fn break_string(max_chars: usize, trim_end: bool, input: &[&str]) -> SnippetState {
194     let break_at = |index /* grapheme at index is included */| {
195         // Take in any whitespaces to the left/right of `input[index]` while
196         // preserving line feeds
197         let not_whitespace_except_line_feed = |g| is_line_feed(g) || !is_whitespace(g);
198         let index_minus_ws = input[0..=index]
199             .iter()
200             .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
201             .unwrap_or(index);
202         // Take into account newlines occuring in input[0..=index], i.e., the possible next new
203         // line. If there is one, then text after it could be rewritten in a way that the available
204         // space is fully used.
205         for (i, grapheme) in input[0..=index].iter().enumerate() {
206             if is_line_feed(grapheme) {
207                 if i <= index_minus_ws {
208                     let mut line = input[0..i].join("");
209                     if trim_end {
210                         line = line.trim_right().to_string();
211                     }
212                     return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
213                 }
214                 break;
215             }
216         }
217
218         let mut index_plus_ws = index;
219         for (i, grapheme) in input[index + 1..].iter().enumerate() {
220             if !trim_end && is_line_feed(grapheme) {
221                 return SnippetState::EndWithLineFeed(
222                     input[0..=index + 1 + i].join("").to_string(),
223                     index + 2 + i,
224                 );
225             } else if not_whitespace_except_line_feed(grapheme) {
226                 index_plus_ws = index + i;
227                 break;
228             }
229         }
230
231         if trim_end {
232             SnippetState::LineEnd(
233                 input[0..=index_minus_ws].join("").to_string(),
234                 index_plus_ws + 1,
235             )
236         } else {
237             SnippetState::LineEnd(
238                 input[0..=index_plus_ws].join("").to_string(),
239                 index_plus_ws + 1,
240             )
241         }
242     };
243
244     // Find the position in input for breaking the string
245     match input[0..max_chars]
246         .iter()
247         .rposition(|grapheme| is_whitespace(grapheme))
248     {
249         // Found a whitespace and what is on its left side is big enough.
250         Some(index) if index >= MIN_STRING => break_at(index),
251         // No whitespace found, try looking for a punctuation instead
252         _ => match input[0..max_chars]
253             .iter()
254             .rposition(|grapheme| is_punctuation(grapheme))
255         {
256             // Found a punctuation and what is on its left side is big enough.
257             Some(index) if index >= MIN_STRING => break_at(index),
258             // Either no boundary character was found to the left of `input[max_chars]`, or the line
259             // got too small. We try searching for a boundary character to the right.
260             _ => match input[max_chars..]
261                 .iter()
262                 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
263             {
264                 // A boundary was found after the line limit
265                 Some(index) => break_at(max_chars + index),
266                 // No boundary to the right, the input cannot be broken
267                 None => SnippetState::EndOfInput(input.join("").to_string()),
268             },
269         },
270     }
271 }
272
273 fn is_line_feed(grapheme: &str) -> bool {
274     grapheme.as_bytes()[0] == b'\n'
275 }
276
277 fn is_whitespace(grapheme: &str) -> bool {
278     grapheme.chars().all(|c| c.is_whitespace())
279 }
280
281 fn is_punctuation(grapheme: &str) -> bool {
282     match grapheme.as_bytes()[0] {
283         b':' | b',' | b';' | b'.' => true,
284         _ => false,
285     }
286 }
287
288 #[cfg(test)]
289 mod test {
290     use super::{break_string, rewrite_string, SnippetState, StringFormat};
291     use config::Config;
292     use shape::{Indent, Shape};
293     use unicode_segmentation::UnicodeSegmentation;
294
295     #[test]
296     fn issue343() {
297         let config = Default::default();
298         let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
299         rewrite_string("eq_", &fmt);
300     }
301
302     #[test]
303     fn should_break_on_whitespace() {
304         let string = "Placerat felis. Mauris porta ante sagittis purus.";
305         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
306         assert_eq!(
307             break_string(20, false, &graphemes[..]),
308             SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
309         );
310         assert_eq!(
311             break_string(20, true, &graphemes[..]),
312             SnippetState::LineEnd("Placerat felis.".to_string(), 16)
313         );
314     }
315
316     #[test]
317     fn should_break_on_punctuation() {
318         let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
319         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
320         assert_eq!(
321             break_string(20, false, &graphemes[..]),
322             SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
323         );
324     }
325
326     #[test]
327     fn should_break_forward() {
328         let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
329         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
330         assert_eq!(
331             break_string(20, false, &graphemes[..]),
332             SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
333         );
334         assert_eq!(
335             break_string(20, true, &graphemes[..]),
336             SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
337         );
338     }
339
340     #[test]
341     fn nothing_to_break() {
342         let string = "Venenatis_tellus_vel_tellus";
343         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
344         assert_eq!(
345             break_string(20, false, &graphemes[..]),
346             SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
347         );
348     }
349
350     #[test]
351     fn significant_whitespaces() {
352         let string = "Neque in sem.      \n      Pellentesque tellus augue.";
353         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
354         assert_eq!(
355             break_string(15, false, &graphemes[..]),
356             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
357         );
358         assert_eq!(
359             break_string(25, false, &graphemes[..]),
360             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
361         );
362         // if `StringFormat::line_end` is true, then the line feed does not matter anymore
363         assert_eq!(
364             break_string(15, true, &graphemes[..]),
365             SnippetState::LineEnd("Neque in sem.".to_string(), 26)
366         );
367         assert_eq!(
368             break_string(25, true, &graphemes[..]),
369             SnippetState::LineEnd("Neque in sem.".to_string(), 26)
370         );
371     }
372
373     #[test]
374     fn big_whitespace() {
375         let string = "Neque in sem.            Pellentesque tellus augue.";
376         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
377         assert_eq!(
378             break_string(20, false, &graphemes[..]),
379             SnippetState::LineEnd("Neque in sem.            ".to_string(), 25)
380         );
381         assert_eq!(
382             break_string(20, true, &graphemes[..]),
383             SnippetState::LineEnd("Neque in sem.".to_string(), 25)
384         );
385     }
386
387     #[test]
388     fn newline_in_candidate_line() {
389         let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
390
391         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
392         assert_eq!(
393             break_string(25, false, &graphemes[..]),
394             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
395         );
396         assert_eq!(
397             break_string(25, true, &graphemes[..]),
398             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
399         );
400
401         let mut config: Config = Default::default();
402         config.set().max_width(27);
403         let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
404         let rewritten_string = rewrite_string(string, &fmt);
405         assert_eq!(
406             rewritten_string,
407             Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
408         );
409     }
410
411     #[test]
412     fn last_line_fit_with_trailing_whitespaces() {
413         let string = "Vivamus id mi.  ";
414         let config: Config = Default::default();
415         let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
416
417         fmt.trim_end = true;
418         let rewritten_string = rewrite_string(string, &fmt);
419         assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
420
421         fmt.trim_end = false; // default value of trim_end
422         let rewritten_string = rewrite_string(string, &fmt);
423         assert_eq!(rewritten_string, Some("\"Vivamus id mi.  \"".to_string()));
424     }
425
426     #[test]
427     fn last_line_fit_with_newline() {
428         let string = "Vivamus id mi.\nVivamus id mi.";
429         let config: Config = Default::default();
430         let fmt = StringFormat {
431             opener: "",
432             closer: "",
433             line_start: "// ",
434             line_end: "",
435             shape: Shape::legacy(100, Indent::from_width(&config, 4)),
436             trim_end: true,
437             config: &config,
438         };
439
440         let rewritten_string = rewrite_string(string, &fmt);
441         assert_eq!(
442             rewritten_string,
443             Some("Vivamus id mi.\n    // Vivamus id mi.".to_string())
444         );
445     }
446
447     #[test]
448     fn overflow_in_non_string_content() {
449         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
450         let config: Config = Default::default();
451         let fmt = StringFormat {
452             opener: "",
453             closer: "",
454             line_start: "// ",
455             line_end: "",
456             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
457             trim_end: true,
458             config: &config,
459         };
460
461         assert_eq!(
462             rewrite_string(comment, &fmt),
463             Some(
464                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus\n        // porttitor"
465                     .to_string()
466             )
467         );
468     }
469
470     #[test]
471     fn overflow_in_non_string_content_with_line_end() {
472         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
473         let config: Config = Default::default();
474         let fmt = StringFormat {
475             opener: "",
476             closer: "",
477             line_start: "// ",
478             line_end: "@",
479             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
480             trim_end: true,
481             config: &config,
482         };
483
484         assert_eq!(
485             rewrite_string(comment, &fmt),
486             Some(
487                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus@\n        // porttitor"
488                     .to_string()
489             )
490         );
491     }
492
493     #[test]
494     fn blank_line_with_non_empty_line_start() {
495         let config: Config = Default::default();
496         let mut fmt = StringFormat {
497             opener: "",
498             closer: "",
499             line_start: "// ",
500             line_end: "",
501             shape: Shape::legacy(30, Indent::from_width(&config, 4)),
502             trim_end: true,
503             config: &config,
504         };
505
506         let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
507         assert_eq!(
508             rewrite_string(comment, &fmt),
509             Some(
510                 "Aenean metus. Vestibulum\n    //\n    // ac lacus. Vivamus porttitor".to_string()
511             )
512         );
513
514         fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
515         let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
516         assert_eq!(
517             rewrite_string(comment, &fmt),
518             Some(
519                 r#"Aenean
520     //
521     // metus. Vestibulum
522     // ac lacus. Vivamus
523     // porttitor"#
524                     .to_string()
525             )
526         );
527     }
528
529     #[test]
530     fn retain_blank_lines() {
531         let config: Config = Default::default();
532         let fmt = StringFormat {
533             opener: "",
534             closer: "",
535             line_start: "// ",
536             line_end: "",
537             shape: Shape::legacy(20, Indent::from_width(&config, 4)),
538             trim_end: true,
539             config: &config,
540         };
541
542         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
543         assert_eq!(
544             rewrite_string(comment, &fmt),
545             Some(
546                 "Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n    //\n".to_string()
547             )
548         );
549
550         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
551         assert_eq!(
552             rewrite_string(comment, &fmt),
553             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n".to_string())
554         );
555
556         let comment = "Aenean\n        \nmetus. Vestibulum ac lacus.";
557         assert_eq!(
558             rewrite_string(comment, &fmt),
559             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.".to_string())
560         );
561     }
562 }