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.
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.
11 // Format string literals.
14 use unicode_segmentation::UnicodeSegmentation;
20 const MIN_STRING: usize = 10;
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
26 /// The closing sequence of characters for the piece of text
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
34 /// Trim trailing whitespaces
36 pub config: &'a Config,
39 impl<'a> StringFormat<'a> {
40 pub fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> {
52 /// Returns the maximum number of graphemes that is possible on a line while taking the
53 /// indentation into account.
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> {
60 .checked_sub(self.opener.len() + self.line_end.len() + 1)?
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())?)
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);
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");
84 let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
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(
91 .checked_next_power_of_two()
92 .unwrap_or(usize::max_value()),
94 result.push_str(fmt.opener);
96 // Snip a line at a time from `stripped_str` until it is used up. Push the snippet
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);
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);
113 result.push_str(grapheme);
116 result = trim_right_but_line_feed(fmt.trim_end, result);
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;
130 SnippetState::EndWithLineFeed(line, len) => {
131 if line == "\n" && fmt.trim_end {
132 result = result.trim_right().to_string();
134 result.push_str(&line);
136 // the next line can benefit from the full width
137 cur_max_chars = max_chars_without_indent;
139 result.push_str(&indent_without_newline);
140 result.push_str(fmt.line_start);
141 cur_max_chars = max_chars_with_indent;
145 SnippetState::EndOfInput(line) => {
146 result.push_str(&line);
152 result.push_str(fmt.closer);
153 wrap_str(result, fmt.config.max_width(), fmt.shape)
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) {
161 .trim_right_matches(whitespace_except_line_feed)
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)]
172 /// The input could not be broken and so rewriting the string is finished.
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.
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.
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),
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]
200 .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
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("");
210 line = line.trim_right().to_string();
212 return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
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(),
225 } else if not_whitespace_except_line_feed(grapheme) {
226 index_plus_ws = index + i;
232 SnippetState::LineEnd(
233 input[0..=index_minus_ws].join("").to_string(),
237 SnippetState::LineEnd(
238 input[0..=index_plus_ws].join("").to_string(),
244 // Find the position in input for breaking the string
245 match input[0..max_chars]
247 .rposition(|grapheme| is_whitespace(grapheme))
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]
254 .rposition(|grapheme| is_punctuation(grapheme))
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..]
262 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
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()),
273 fn is_line_feed(grapheme: &str) -> bool {
274 grapheme.as_bytes()[0] == b'\n'
277 fn is_whitespace(grapheme: &str) -> bool {
278 grapheme.chars().all(|c| c.is_whitespace())
281 fn is_punctuation(grapheme: &str) -> bool {
282 match grapheme.as_bytes()[0] {
283 b':' | b',' | b';' | b'.' => true,
290 use super::{break_string, rewrite_string, SnippetState, StringFormat};
292 use shape::{Indent, Shape};
293 use unicode_segmentation::UnicodeSegmentation;
297 let config = Default::default();
298 let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
299 rewrite_string("eq_", &fmt);
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>>();
307 break_string(20, false, &graphemes[..]),
308 SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
311 break_string(20, true, &graphemes[..]),
312 SnippetState::LineEnd("Placerat felis.".to_string(), 16)
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>>();
321 break_string(20, false, &graphemes[..]),
322 SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
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>>();
331 break_string(20, false, &graphemes[..]),
332 SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
335 break_string(20, true, &graphemes[..]),
336 SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
341 fn nothing_to_break() {
342 let string = "Venenatis_tellus_vel_tellus";
343 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
345 break_string(20, false, &graphemes[..]),
346 SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
351 fn significant_whitespaces() {
352 let string = "Neque in sem. \n Pellentesque tellus augue.";
353 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
355 break_string(15, false, &graphemes[..]),
356 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
359 break_string(25, false, &graphemes[..]),
360 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
362 // if `StringFormat::line_end` is true, then the line feed does not matter anymore
364 break_string(15, true, &graphemes[..]),
365 SnippetState::LineEnd("Neque in sem.".to_string(), 26)
368 break_string(25, true, &graphemes[..]),
369 SnippetState::LineEnd("Neque in sem.".to_string(), 26)
374 fn big_whitespace() {
375 let string = "Neque in sem. Pellentesque tellus augue.";
376 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
378 break_string(20, false, &graphemes[..]),
379 SnippetState::LineEnd("Neque in sem. ".to_string(), 25)
382 break_string(20, true, &graphemes[..]),
383 SnippetState::LineEnd("Neque in sem.".to_string(), 25)
388 fn newline_in_candidate_line() {
389 let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
391 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
393 break_string(25, false, &graphemes[..]),
394 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
397 break_string(25, true, &graphemes[..]),
398 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
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);
407 Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
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);
418 let rewritten_string = rewrite_string(string, &fmt);
419 assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
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()));
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 {
435 shape: Shape::legacy(100, Indent::from_width(&config, 4)),
440 let rewritten_string = rewrite_string(string, &fmt);
443 Some("Vivamus id mi.\n // Vivamus id mi.".to_string())
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 {
456 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
462 rewrite_string(comment, &fmt),
464 "Aenean metus.\n // Vestibulum ac lacus. Vivamus\n // porttitor"
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 {
479 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
485 rewrite_string(comment, &fmt),
487 "Aenean metus.\n // Vestibulum ac lacus. Vivamus@\n // porttitor"
494 fn blank_line_with_non_empty_line_start() {
495 let config: Config = Default::default();
496 let mut fmt = StringFormat {
501 shape: Shape::legacy(30, Indent::from_width(&config, 4)),
506 let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
508 rewrite_string(comment, &fmt),
510 "Aenean metus. Vestibulum\n //\n // ac lacus. Vivamus porttitor".to_string()
514 fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
515 let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
517 rewrite_string(comment, &fmt),
530 fn retain_blank_lines() {
531 let config: Config = Default::default();
532 let fmt = StringFormat {
537 shape: Shape::legacy(20, Indent::from_width(&config, 4)),
542 let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
544 rewrite_string(comment, &fmt),
546 "Aenean\n //\n // metus. Vestibulum ac\n // lacus.\n //\n".to_string()
550 let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
552 rewrite_string(comment, &fmt),
553 Some("Aenean\n //\n // metus. Vestibulum ac\n // lacus.\n".to_string())
556 let comment = "Aenean\n \nmetus. Vestibulum ac lacus.";
558 rewrite_string(comment, &fmt),
559 Some("Aenean\n //\n // metus. Vestibulum ac\n // lacus.".to_string())