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_overflow_allowed = 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 let last_line = graphemes[cur_start..].join("");
105 result.push_str(&last_line.trim_right());
107 result.push_str(&last_line);
112 // The input starting at cur_start needs to be broken
113 match break_string(cur_max_chars, fmt.trim_end, &graphemes[cur_start..]) {
114 SnippetState::LineEnd(line, len) => {
115 result.push_str(&line);
116 result.push_str(fmt.line_end);
117 result.push_str(&indent_with_newline);
118 result.push_str(fmt.line_start);
119 cur_max_chars = max_chars_with_indent;
122 SnippetState::EndWithLineFeed(line, len) => {
123 result.push_str(&line);
124 if is_overflow_allowed {
125 // the next line can benefit from the full width
126 cur_max_chars = max_chars_without_indent;
128 result.push_str(&indent_without_newline);
129 result.push_str(fmt.line_start);
130 cur_max_chars = max_chars_with_indent;
134 SnippetState::EndOfInput(line) => {
135 result.push_str(&line);
141 result.push_str(fmt.closer);
142 wrap_str(result, fmt.config.max_width(), fmt.shape)
145 /// Result of breaking a string so it fits in a line and the state it ended in.
146 /// The state informs about what to do with the snippet and how to continue the breaking process.
147 #[derive(Debug, PartialEq)]
149 /// The input could not be broken and so rewriting the string is finished.
151 /// The input could be broken and the returned snippet should be ended with a
152 /// `[StringFormat::line_end]`. The next snippet needs to be indented.
154 /// The returned string is the line to print out and the number is the length that got read in
155 /// the text being rewritten. That length may be greater than the returned string if trailing
156 /// whitespaces got trimmed.
157 LineEnd(String, usize),
158 /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
159 /// to be rewritten *could* use more width than what is specified by the given shape. For
160 /// example with a multiline string, the next snippet does not need to be indented, allowing
161 /// more characters to be fit within a line.
163 /// The returned string is the line to print out and the number is the length that got read in
164 /// the text being rewritten.
165 EndWithLineFeed(String, usize),
168 /// Break the input string at a boundary character around the offset `max_chars`. A boundary
169 /// character is either a punctuation or a whitespace.
170 fn break_string(max_chars: usize, trim_end: bool, input: &[&str]) -> SnippetState {
171 let break_at = |index /* grapheme at index is included */| {
172 // Take in any whitespaces to the left/right of `input[index]` and
173 // check if there is a line feed, in which case whitespaces needs to be kept.
174 let mut index_minus_ws = index;
175 for (i, grapheme) in input[0..=index].iter().enumerate().rev() {
176 if !is_whitespace(grapheme) {
181 // Take into account newlines occuring in input[0..=index], i.e., the possible next new
182 // line. If there is one, then text after it could be rewritten in a way that the available
183 // space is fully used.
184 for (i, grapheme) in input[0..=index].iter().enumerate() {
185 if is_line_feed(grapheme) {
186 if i < index_minus_ws || !trim_end {
187 return SnippetState::EndWithLineFeed(input[0..=i].join("").to_string(), i + 1);
193 let mut index_plus_ws = index;
194 for (i, grapheme) in input[index + 1..].iter().enumerate() {
195 if !trim_end && is_line_feed(grapheme) {
196 return SnippetState::EndWithLineFeed(
197 input[0..=index + 1 + i].join("").to_string(),
200 } else if !is_whitespace(grapheme) {
201 index_plus_ws = index + i;
207 SnippetState::LineEnd(
208 input[0..=index_minus_ws].join("").to_string(),
212 SnippetState::LineEnd(
213 input[0..=index_plus_ws].join("").to_string(),
219 // Find the position in input for breaking the string
220 match input[0..max_chars]
222 .rposition(|grapheme| is_whitespace(grapheme))
224 // Found a whitespace and what is on its left side is big enough.
225 Some(index) if index >= MIN_STRING => break_at(index),
226 // No whitespace found, try looking for a punctuation instead
227 _ => match input[0..max_chars]
229 .rposition(|grapheme| is_punctuation(grapheme))
231 // Found a punctuation and what is on its left side is big enough.
232 Some(index) if index >= MIN_STRING => break_at(index),
233 // Either no boundary character was found to the left of `input[max_chars]`, or the line
234 // got too small. We try searching for a boundary character to the right.
235 _ => match input[max_chars..]
237 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
239 // A boundary was found after the line limit
240 Some(index) => break_at(max_chars + index),
241 // No boundary to the right, the input cannot be broken
242 None => SnippetState::EndOfInput(input.join("").to_string()),
248 fn is_line_feed(grapheme: &str) -> bool {
249 grapheme.as_bytes()[0] == b'\n'
252 fn is_whitespace(grapheme: &str) -> bool {
253 grapheme.chars().all(|c| c.is_whitespace())
256 fn is_punctuation(grapheme: &str) -> bool {
257 match grapheme.as_bytes()[0] {
258 b':' | b',' | b';' | b'.' => true,
265 use super::{break_string, rewrite_string, SnippetState, StringFormat};
267 use shape::{Indent, Shape};
268 use unicode_segmentation::UnicodeSegmentation;
272 let config = Default::default();
273 let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
274 rewrite_string("eq_", &fmt);
278 fn should_break_on_whitespace() {
279 let string = "Placerat felis. Mauris porta ante sagittis purus.";
280 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
282 break_string(20, false, &graphemes[..]),
283 SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
286 break_string(20, true, &graphemes[..]),
287 SnippetState::LineEnd("Placerat felis.".to_string(), 16)
292 fn should_break_on_punctuation() {
293 let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
294 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
296 break_string(20, false, &graphemes[..]),
297 SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
302 fn should_break_forward() {
303 let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
304 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
306 break_string(20, false, &graphemes[..]),
307 SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
310 break_string(20, true, &graphemes[..]),
311 SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
316 fn nothing_to_break() {
317 let string = "Venenatis_tellus_vel_tellus";
318 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
320 break_string(20, false, &graphemes[..]),
321 SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
326 fn significant_whitespaces() {
327 let string = "Neque in sem. \n Pellentesque tellus augue.";
328 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
330 break_string(15, false, &graphemes[..]),
331 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
334 break_string(25, false, &graphemes[..]),
335 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
337 // if `StringFormat::line_end` is true, then the line feed does not matter anymore
339 break_string(15, true, &graphemes[..]),
340 SnippetState::LineEnd("Neque in sem.".to_string(), 26)
343 break_string(25, true, &graphemes[..]),
344 SnippetState::LineEnd("Neque in sem.".to_string(), 26)
349 fn big_whitespace() {
350 let string = "Neque in sem. Pellentesque tellus augue.";
351 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
353 break_string(20, false, &graphemes[..]),
354 SnippetState::LineEnd("Neque in sem. ".to_string(), 25)
357 break_string(20, true, &graphemes[..]),
358 SnippetState::LineEnd("Neque in sem.".to_string(), 25)
363 fn newline_in_candidate_line() {
364 let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
366 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
368 break_string(25, false, &graphemes[..]),
369 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
372 break_string(25, true, &graphemes[..]),
373 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
376 let mut config: Config = Default::default();
377 config.set().max_width(27);
378 let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
379 let rewritten_string = rewrite_string(string, &fmt);
382 Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
387 fn last_line_fit_with_trailing_whitespaces() {
388 let string = "Vivamus id mi. ";
389 let config: Config = Default::default();
390 let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
393 let rewritten_string = rewrite_string(string, &fmt);
394 assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
396 fmt.trim_end = false; // default value of trim_end
397 let rewritten_string = rewrite_string(string, &fmt);
398 assert_eq!(rewritten_string, Some("\"Vivamus id mi. \"".to_string()));
402 fn overflow_in_non_string_content() {
403 let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
404 let config: Config = Default::default();
405 let fmt = StringFormat {
410 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
416 rewrite_string(comment, &fmt),
418 "Aenean metus.\n // Vestibulum ac lacus. Vivamus\n // porttitor"
425 fn overflow_in_non_string_content_with_line_end() {
426 let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
427 let config: Config = Default::default();
428 let fmt = StringFormat {
433 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
439 rewrite_string(comment, &fmt),
441 "Aenean metus.\n // Vestibulum ac lacus. Vivamus@\n // porttitor"