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 // trim trailing whitespaces
104 let graphemes_minus_ws = if !fmt.trim_end {
105 &graphemes[cur_start..]
107 match graphemes[cur_start..]
109 .rposition(|grapheme| !is_whitespace(grapheme))
111 Some(index) => &graphemes[cur_start..=cur_start + index],
112 None => &graphemes[cur_start..],
116 // new lines don't need to start with line_start
117 result.push_str(&graphemes_minus_ws.join(""));
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);
125 result.push_str(grapheme);
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;
142 SnippetState::EndWithLineFeed(line, len) => {
143 result.push_str(&line);
145 // the next line can benefit from the full width
146 cur_max_chars = max_chars_without_indent;
148 result.push_str(&indent_without_newline);
149 result.push_str(fmt.line_start);
150 cur_max_chars = max_chars_with_indent;
154 SnippetState::EndOfInput(line) => {
155 result.push_str(&line);
161 result.push_str(fmt.closer);
162 wrap_str(result, fmt.config.max_width(), fmt.shape)
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)]
169 /// The input could not be broken and so rewriting the string is finished.
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.
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.
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),
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]
196 .rposition(|grapheme| !is_whitespace(grapheme))
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);
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(),
217 } else if !is_whitespace(grapheme) {
218 index_plus_ws = index + i;
224 SnippetState::LineEnd(
225 input[0..=index_minus_ws].join("").to_string(),
229 SnippetState::LineEnd(
230 input[0..=index_plus_ws].join("").to_string(),
236 // Find the position in input for breaking the string
237 match input[0..max_chars]
239 .rposition(|grapheme| is_whitespace(grapheme))
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]
246 .rposition(|grapheme| is_punctuation(grapheme))
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..]
254 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
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()),
265 fn is_line_feed(grapheme: &str) -> bool {
266 grapheme.as_bytes()[0] == b'\n'
269 fn is_whitespace(grapheme: &str) -> bool {
270 grapheme.chars().all(|c| c.is_whitespace())
273 fn is_punctuation(grapheme: &str) -> bool {
274 match grapheme.as_bytes()[0] {
275 b':' | b',' | b';' | b'.' => true,
282 use super::{break_string, rewrite_string, SnippetState, StringFormat};
284 use shape::{Indent, Shape};
285 use unicode_segmentation::UnicodeSegmentation;
289 let config = Default::default();
290 let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
291 rewrite_string("eq_", &fmt);
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>>();
299 break_string(20, false, &graphemes[..]),
300 SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
303 break_string(20, true, &graphemes[..]),
304 SnippetState::LineEnd("Placerat felis.".to_string(), 16)
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>>();
313 break_string(20, false, &graphemes[..]),
314 SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
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>>();
323 break_string(20, false, &graphemes[..]),
324 SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
327 break_string(20, true, &graphemes[..]),
328 SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
333 fn nothing_to_break() {
334 let string = "Venenatis_tellus_vel_tellus";
335 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
337 break_string(20, false, &graphemes[..]),
338 SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
343 fn significant_whitespaces() {
344 let string = "Neque in sem. \n Pellentesque tellus augue.";
345 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
347 break_string(15, false, &graphemes[..]),
348 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
351 break_string(25, false, &graphemes[..]),
352 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
354 // if `StringFormat::line_end` is true, then the line feed does not matter anymore
356 break_string(15, true, &graphemes[..]),
357 SnippetState::LineEnd("Neque in sem.".to_string(), 26)
360 break_string(25, true, &graphemes[..]),
361 SnippetState::LineEnd("Neque in sem.".to_string(), 26)
366 fn big_whitespace() {
367 let string = "Neque in sem. Pellentesque tellus augue.";
368 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
370 break_string(20, false, &graphemes[..]),
371 SnippetState::LineEnd("Neque in sem. ".to_string(), 25)
374 break_string(20, true, &graphemes[..]),
375 SnippetState::LineEnd("Neque in sem.".to_string(), 25)
380 fn newline_in_candidate_line() {
381 let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
383 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
385 break_string(25, false, &graphemes[..]),
386 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
389 break_string(25, true, &graphemes[..]),
390 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
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);
399 Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
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);
410 let rewritten_string = rewrite_string(string, &fmt);
411 assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
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()));
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 {
427 shape: Shape::legacy(100, Indent::from_width(&config, 4)),
432 let rewritten_string = rewrite_string(string, &fmt);
435 Some("Vivamus id mi.\n // Vivamus id mi.".to_string())
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 {
448 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
454 rewrite_string(comment, &fmt),
456 "Aenean metus.\n // Vestibulum ac lacus. Vivamus\n // porttitor"
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 {
471 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
477 rewrite_string(comment, &fmt),
479 "Aenean metus.\n // Vestibulum ac lacus. Vivamus@\n // porttitor"