]> git.lizzy.rs Git - rust.git/blob - src/string.rs
Remove BlockIndentStyle::Inherit
[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 unicode_segmentation::UnicodeSegmentation;
14 use regex::Regex;
15
16 use Shape;
17 use config::Config;
18 use utils::wrap_str;
19
20 use MIN_STRING;
21
22 pub struct StringFormat<'a> {
23     pub opener: &'a str,
24     pub closer: &'a str,
25     pub line_start: &'a str,
26     pub line_end: &'a str,
27     pub shape: Shape,
28     pub trim_end: bool,
29     pub config: &'a Config,
30 }
31
32 // FIXME: simplify this!
33 pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {
34     // Strip line breaks.
35     let re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
36     let stripped_str = re.replace_all(orig, "$1");
37
38     let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
39     let shape = fmt.shape.visual_indent(0);
40     let indent = shape.indent.to_string(fmt.config);
41     let punctuation = ":,;.";
42
43     // `cur_start` is the position in `orig` of the start of the current line.
44     let mut cur_start = 0;
45     let mut result = String::with_capacity(stripped_str.len()
46                                                .checked_next_power_of_two()
47                                                .unwrap_or(usize::max_value()));
48     result.push_str(fmt.opener);
49
50     let ender_length = fmt.line_end.len();
51     // If we cannot put at least a single character per line, the rewrite won't
52     // succeed.
53     let max_chars = try_opt!(shape.width.checked_sub(fmt.opener.len() + ender_length + 1)) + 1;
54
55     // Snip a line at a time from `orig` until it is used up. Push the snippet
56     // onto result.
57     'outer: loop {
58         // `cur_end` will be where we break the line, as an offset into `orig`.
59         // Initialised to the maximum it could be (which may be beyond `orig`).
60         let mut cur_end = cur_start + max_chars;
61
62         // We can fit the rest of the string on this line, so we're done.
63         if cur_end >= graphemes.len() {
64             let line = &graphemes[cur_start..].join("");
65             result.push_str(line);
66             break 'outer;
67         }
68
69         // Push cur_end left until we reach whitespace (or the line is too small).
70         while !graphemes[cur_end - 1].trim().is_empty() {
71             cur_end -= 1;
72             if cur_end < cur_start + MIN_STRING {
73                 // We couldn't find whitespace before the string got too small.
74                 // So start again at the max length and look for punctuation.
75                 cur_end = cur_start + max_chars;
76                 while !punctuation.contains(graphemes[cur_end - 1]) {
77                     cur_end -= 1;
78
79                     // If we can't break at whitespace or punctuation, grow the string instead.
80                     if cur_end < cur_start + MIN_STRING {
81                         cur_end = cur_start + max_chars;
82                         while !(punctuation.contains(graphemes[cur_end - 1]) ||
83                                 graphemes[cur_end - 1].trim().is_empty()) {
84                             if cur_end >= graphemes.len() {
85                                 let line = &graphemes[cur_start..].join("");
86                                 result.push_str(line);
87                                 break 'outer;
88                             }
89                             cur_end += 1;
90                         }
91                         break;
92                     }
93                 }
94                 break;
95             }
96         }
97         // Make sure there is no whitespace to the right of the break.
98         while cur_end < stripped_str.len() && graphemes[cur_end].trim().is_empty() {
99             cur_end += 1;
100         }
101
102         // Make the current line and add it on to result.
103         let raw_line = graphemes[cur_start..cur_end].join("");
104         let line = if fmt.trim_end {
105             raw_line.trim()
106         } else {
107             raw_line.as_str()
108         };
109
110         result.push_str(line);
111         result.push_str(fmt.line_end);
112         result.push('\n');
113         result.push_str(&indent);
114         result.push_str(fmt.line_start);
115
116         // The next line starts where the current line ends.
117         cur_start = cur_end;
118     }
119
120     result.push_str(fmt.closer);
121     wrap_str(result, fmt.config.max_width, fmt.shape)
122 }
123
124 #[cfg(test)]
125 mod test {
126     use super::{StringFormat, rewrite_string};
127
128     #[test]
129     fn issue343() {
130         let config = Default::default();
131         let fmt = StringFormat {
132             opener: "\"",
133             closer: "\"",
134             line_start: " ",
135             line_end: "\\",
136             shape: ::Shape::legacy(2, ::Indent::empty()),
137             trim_end: false,
138             config: &config,
139         };
140
141         rewrite_string("eq_", &fmt);
142     }
143 }