]> git.lizzy.rs Git - rust.git/blob - src/string.rs
Merge pull request #3284 from scampi/issue-3270
[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_categories::UnicodeCategories;
15 use unicode_segmentation::UnicodeSegmentation;
16
17 use config::Config;
18 use shape::Shape;
19 use utils::{unicode_str_width, wrap_str};
20
21 const MIN_STRING: usize = 10;
22
23 /// Describes the layout of a piece of text.
24 pub struct StringFormat<'a> {
25     /// The opening sequence of characters for the piece of text
26     pub opener: &'a str,
27     /// The closing sequence of characters for the piece of text
28     pub closer: &'a str,
29     /// The opening sequence of characters for a line
30     pub line_start: &'a str,
31     /// The closing sequence of characters for a line
32     pub line_end: &'a str,
33     /// The allocated box to fit the text into
34     pub shape: Shape,
35     /// Trim trailing whitespaces
36     pub trim_end: bool,
37     pub config: &'a Config,
38 }
39
40 impl<'a> StringFormat<'a> {
41     pub fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> {
42         StringFormat {
43             opener: "\"",
44             closer: "\"",
45             line_start: " ",
46             line_end: "\\",
47             shape,
48             trim_end: false,
49             config,
50         }
51     }
52
53     /// Returns the maximum number of graphemes that is possible on a line while taking the
54     /// indentation into account.
55     ///
56     /// If we cannot put at least a single character per line, the rewrite won't succeed.
57     fn max_width_with_indent(&self) -> Option<usize> {
58         Some(
59             self.shape
60                 .width
61                 .checked_sub(self.opener.len() + self.line_end.len() + 1)?
62                 + 1,
63         )
64     }
65
66     /// Like max_width_with_indent but the indentation is not subtracted.
67     /// This allows to fit more graphemes from the string on a line when
68     /// SnippetState::EndWithLineFeed.
69     fn max_width_without_indent(&self) -> Option<usize> {
70         Some(self.config.max_width().checked_sub(self.line_end.len())?)
71     }
72 }
73
74 pub fn rewrite_string<'a>(
75     orig: &str,
76     fmt: &StringFormat<'a>,
77     newline_max_chars: usize,
78 ) -> Option<String> {
79     let max_width_with_indent = fmt.max_width_with_indent()?;
80     let max_width_without_indent = fmt.max_width_without_indent()?;
81     let indent_with_newline = fmt.shape.indent.to_string_with_newline(fmt.config);
82     let indent_without_newline = fmt.shape.indent.to_string(fmt.config);
83
84     // Strip line breaks.
85     // With this regex applied, all remaining whitespaces are significant
86     let strip_line_breaks_re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
87     let stripped_str = strip_line_breaks_re.replace_all(orig, "$1");
88
89     let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
90
91     // `cur_start` is the position in `orig` of the start of the current line.
92     let mut cur_start = 0;
93     let mut result = String::with_capacity(
94         stripped_str
95             .len()
96             .checked_next_power_of_two()
97             .unwrap_or(usize::max_value()),
98     );
99     result.push_str(fmt.opener);
100
101     // Snip a line at a time from `stripped_str` until it is used up. Push the snippet
102     // onto result.
103     let mut cur_max_width = max_width_with_indent;
104     let is_bareline_ok = fmt.line_start.is_empty() || is_whitespace(fmt.line_start);
105     loop {
106         // All the input starting at cur_start fits on the current line
107         if graphemes_width(&graphemes[cur_start..]) <= cur_max_width {
108             for (i, grapheme) in graphemes[cur_start..].iter().enumerate() {
109                 if is_new_line(grapheme) {
110                     // take care of blank lines
111                     result = trim_end_but_line_feed(fmt.trim_end, result);
112                     result.push_str("\n");
113                     if !is_bareline_ok && cur_start + i + 1 < graphemes.len() {
114                         result.push_str(&indent_without_newline);
115                         result.push_str(fmt.line_start);
116                     }
117                 } else {
118                     result.push_str(grapheme);
119                 }
120             }
121             result = trim_end_but_line_feed(fmt.trim_end, result);
122             break;
123         }
124
125         // The input starting at cur_start needs to be broken
126         match break_string(
127             cur_max_width,
128             fmt.trim_end,
129             fmt.line_end,
130             &graphemes[cur_start..],
131         ) {
132             SnippetState::LineEnd(line, len) => {
133                 result.push_str(&line);
134                 result.push_str(fmt.line_end);
135                 result.push_str(&indent_with_newline);
136                 result.push_str(fmt.line_start);
137                 cur_max_width = newline_max_chars;
138                 cur_start += len;
139             }
140             SnippetState::EndWithLineFeed(line, len) => {
141                 if line == "\n" && fmt.trim_end {
142                     result = result.trim_end().to_string();
143                 }
144                 result.push_str(&line);
145                 if is_bareline_ok {
146                     // the next line can benefit from the full width
147                     cur_max_width = max_width_without_indent;
148                 } else {
149                     result.push_str(&indent_without_newline);
150                     result.push_str(fmt.line_start);
151                     cur_max_width = max_width_with_indent;
152                 }
153                 cur_start += len;
154             }
155             SnippetState::EndOfInput(line) => {
156                 result.push_str(&line);
157                 break;
158             }
159         }
160     }
161
162     result.push_str(fmt.closer);
163     wrap_str(result, fmt.config.max_width(), fmt.shape)
164 }
165
166 /// Returns the index to the end of the url if the given string includes an
167 /// URL or alike. Otherwise, returns None;
168 fn detect_url(s: &[&str], index: usize) -> Option<usize> {
169     let start = match s[..=index].iter().rposition(|g| is_whitespace(g)) {
170         Some(pos) => pos + 1,
171         None => 0,
172     };
173     if s.len() < start + 8 {
174         return None;
175     }
176     let prefix = s[start..start + 8].concat();
177     if prefix.starts_with("https://")
178         || prefix.starts_with("http://")
179         || prefix.starts_with("ftp://")
180         || prefix.starts_with("file://")
181     {
182         match s[index..].iter().position(|g| is_whitespace(g)) {
183             Some(pos) => Some(index + pos - 1),
184             None => Some(s.len() - 1),
185         }
186     } else {
187         None
188     }
189 }
190
191 /// Trims whitespaces to the right except for the line feed character.
192 fn trim_end_but_line_feed(trim_end: bool, result: String) -> String {
193     let whitespace_except_line_feed = |c: char| c.is_whitespace() && c != '\n';
194     if trim_end && result.ends_with(whitespace_except_line_feed) {
195         result
196             .trim_end_matches(whitespace_except_line_feed)
197             .to_string()
198     } else {
199         result
200     }
201 }
202
203 /// Result of breaking a string so it fits in a line and the state it ended in.
204 /// The state informs about what to do with the snippet and how to continue the breaking process.
205 #[derive(Debug, PartialEq)]
206 enum SnippetState {
207     /// The input could not be broken and so rewriting the string is finished.
208     EndOfInput(String),
209     /// The input could be broken and the returned snippet should be ended with a
210     /// `[StringFormat::line_end]`. The next snippet needs to be indented.
211     ///
212     /// The returned string is the line to print out and the number is the length that got read in
213     /// the text being rewritten. That length may be greater than the returned string if trailing
214     /// whitespaces got trimmed.
215     LineEnd(String, usize),
216     /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
217     /// to be rewritten *could* use more width than what is specified by the given shape. For
218     /// example with a multiline string, the next snippet does not need to be indented, allowing
219     /// more characters to be fit within a line.
220     ///
221     /// The returned string is the line to print out and the number is the length that got read in
222     /// the text being rewritten.
223     EndWithLineFeed(String, usize),
224 }
225
226 fn not_whitespace_except_line_feed(g: &str) -> bool {
227     is_new_line(g) || !is_whitespace(g)
228 }
229
230 /// Break the input string at a boundary character around the offset `max_width`. A boundary
231 /// character is either a punctuation or a whitespace.
232 /// FIXME(issue#3281): We must follow UAX#14 algorithm instead of this.
233 fn break_string(max_width: usize, trim_end: bool, line_end: &str, input: &[&str]) -> SnippetState {
234     let break_at = |index /* grapheme at index is included */| {
235         // Take in any whitespaces to the left/right of `input[index]` while
236         // preserving line feeds
237         let index_minus_ws = input[0..=index]
238             .iter()
239             .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
240             .unwrap_or(index);
241         // Take into account newlines occurring in input[0..=index], i.e., the possible next new
242         // line. If there is one, then text after it could be rewritten in a way that the available
243         // space is fully used.
244         for (i, grapheme) in input[0..=index].iter().enumerate() {
245             if is_new_line(grapheme) {
246                 if i <= index_minus_ws {
247                     let mut line = &input[0..i].concat()[..];
248                     if trim_end {
249                         line = line.trim_end();
250                     }
251                     return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
252                 }
253                 break;
254             }
255         }
256
257         let mut index_plus_ws = index;
258         for (i, grapheme) in input[index + 1..].iter().enumerate() {
259             if !trim_end && is_new_line(grapheme) {
260                 return SnippetState::EndWithLineFeed(
261                     input[0..=index + 1 + i].concat(),
262                     index + 2 + i,
263                 );
264             } else if not_whitespace_except_line_feed(grapheme) {
265                 index_plus_ws = index + i;
266                 break;
267             }
268         }
269
270         if trim_end {
271             SnippetState::LineEnd(input[0..=index_minus_ws].concat(), index_plus_ws + 1)
272         } else {
273             SnippetState::LineEnd(input[0..=index_plus_ws].concat(), index_plus_ws + 1)
274         }
275     };
276
277     // find a first index where the unicode width of input[0..x] become > max_width
278     let max_width_index_in_input = {
279         let mut cur_width = 0;
280         let mut cur_index = 0;
281         for (i, grapheme) in input.iter().enumerate() {
282             cur_width += unicode_str_width(grapheme);
283             cur_index = i;
284             if cur_width > max_width {
285                 break;
286             }
287         }
288         cur_index
289     };
290
291     // Find the position in input for breaking the string
292     if line_end.is_empty()
293         && trim_end
294         && !is_whitespace(input[max_width_index_in_input - 1])
295         && is_whitespace(input[max_width_index_in_input])
296     {
297         // At a breaking point already
298         // The line won't invalidate the rewriting because:
299         // - no extra space needed for the line_end character
300         // - extra whitespaces to the right can be trimmed
301         return break_at(max_width_index_in_input - 1);
302     }
303     if let Some(url_index_end) = detect_url(input, max_width_index_in_input) {
304         let index_plus_ws = url_index_end
305             + input[url_index_end..]
306                 .iter()
307                 .skip(1)
308                 .position(|grapheme| not_whitespace_except_line_feed(grapheme))
309                 .unwrap_or(0);
310         return if trim_end {
311             SnippetState::LineEnd(input[..=url_index_end].concat(), index_plus_ws + 1)
312         } else {
313             return SnippetState::LineEnd(input[..=index_plus_ws].concat(), index_plus_ws + 1);
314         };
315     }
316
317     match input[0..max_width_index_in_input]
318         .iter()
319         .rposition(|grapheme| is_whitespace(grapheme))
320     {
321         // Found a whitespace and what is on its left side is big enough.
322         Some(index) if index >= MIN_STRING => break_at(index),
323         // No whitespace found, try looking for a punctuation instead
324         _ => match input[0..max_width_index_in_input]
325             .iter()
326             .rposition(|grapheme| is_punctuation(grapheme))
327         {
328             // Found a punctuation and what is on its left side is big enough.
329             Some(index) if index >= MIN_STRING => break_at(index),
330             // Either no boundary character was found to the left of `input[max_chars]`, or the line
331             // got too small. We try searching for a boundary character to the right.
332             _ => match input[max_width_index_in_input..]
333                 .iter()
334                 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
335             {
336                 // A boundary was found after the line limit
337                 Some(index) => break_at(max_width_index_in_input + index),
338                 // No boundary to the right, the input cannot be broken
339                 None => SnippetState::EndOfInput(input.concat()),
340             },
341         },
342     }
343 }
344
345 fn is_new_line(grapheme: &str) -> bool {
346     let bytes = grapheme.as_bytes();
347     bytes.starts_with(b"\n") || bytes.starts_with(b"\r\n")
348 }
349
350 fn is_whitespace(grapheme: &str) -> bool {
351     grapheme.chars().all(|c| c.is_whitespace())
352 }
353
354 fn is_punctuation(grapheme: &str) -> bool {
355     grapheme.chars().all(|c| c.is_punctuation_other())
356 }
357
358 fn graphemes_width(graphemes: &[&str]) -> usize {
359     graphemes.iter().map(|s| unicode_str_width(s)).sum()
360 }
361
362 #[cfg(test)]
363 mod test {
364     use super::{break_string, detect_url, rewrite_string, SnippetState, StringFormat};
365     use config::Config;
366     use shape::{Indent, Shape};
367     use unicode_segmentation::UnicodeSegmentation;
368
369     #[test]
370     fn issue343() {
371         let config = Default::default();
372         let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
373         rewrite_string("eq_", &fmt, 2);
374     }
375
376     #[test]
377     fn should_break_on_whitespace() {
378         let string = "Placerat felis. Mauris porta ante sagittis purus.";
379         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
380         assert_eq!(
381             break_string(20, false, "", &graphemes[..]),
382             SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
383         );
384         assert_eq!(
385             break_string(20, true, "", &graphemes[..]),
386             SnippetState::LineEnd("Placerat felis.".to_string(), 16)
387         );
388     }
389
390     #[test]
391     fn should_break_on_punctuation() {
392         let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
393         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
394         assert_eq!(
395             break_string(20, false, "", &graphemes[..]),
396             SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
397         );
398     }
399
400     #[test]
401     fn should_break_forward() {
402         let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
403         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
404         assert_eq!(
405             break_string(20, false, "", &graphemes[..]),
406             SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
407         );
408         assert_eq!(
409             break_string(20, true, "", &graphemes[..]),
410             SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
411         );
412     }
413
414     #[test]
415     fn nothing_to_break() {
416         let string = "Venenatis_tellus_vel_tellus";
417         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
418         assert_eq!(
419             break_string(20, false, "", &graphemes[..]),
420             SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
421         );
422     }
423
424     #[test]
425     fn significant_whitespaces() {
426         let string = "Neque in sem.      \n      Pellentesque tellus augue.";
427         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
428         assert_eq!(
429             break_string(15, false, "", &graphemes[..]),
430             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
431         );
432         assert_eq!(
433             break_string(25, false, "", &graphemes[..]),
434             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
435         );
436
437         assert_eq!(
438             break_string(15, true, "", &graphemes[..]),
439             SnippetState::LineEnd("Neque in sem.".to_string(), 19)
440         );
441         assert_eq!(
442             break_string(25, true, "", &graphemes[..]),
443             SnippetState::EndWithLineFeed("Neque in sem.\n".to_string(), 20)
444         );
445     }
446
447     #[test]
448     fn big_whitespace() {
449         let string = "Neque in sem.            Pellentesque tellus augue.";
450         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
451         assert_eq!(
452             break_string(20, false, "", &graphemes[..]),
453             SnippetState::LineEnd("Neque in sem.            ".to_string(), 25)
454         );
455         assert_eq!(
456             break_string(20, true, "", &graphemes[..]),
457             SnippetState::LineEnd("Neque in sem.".to_string(), 25)
458         );
459     }
460
461     #[test]
462     fn newline_in_candidate_line() {
463         let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
464
465         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
466         assert_eq!(
467             break_string(25, false, "", &graphemes[..]),
468             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
469         );
470         assert_eq!(
471             break_string(25, true, "", &graphemes[..]),
472             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
473         );
474
475         let mut config: Config = Default::default();
476         config.set().max_width(27);
477         let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
478         let rewritten_string = rewrite_string(string, &fmt, 27);
479         assert_eq!(
480             rewritten_string,
481             Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
482         );
483     }
484
485     #[test]
486     fn last_line_fit_with_trailing_whitespaces() {
487         let string = "Vivamus id mi.  ";
488         let config: Config = Default::default();
489         let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
490
491         fmt.trim_end = true;
492         let rewritten_string = rewrite_string(string, &fmt, 25);
493         assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
494
495         fmt.trim_end = false; // default value of trim_end
496         let rewritten_string = rewrite_string(string, &fmt, 25);
497         assert_eq!(rewritten_string, Some("\"Vivamus id mi.  \"".to_string()));
498     }
499
500     #[test]
501     fn last_line_fit_with_newline() {
502         let string = "Vivamus id mi.\nVivamus id mi.";
503         let config: Config = Default::default();
504         let fmt = StringFormat {
505             opener: "",
506             closer: "",
507             line_start: "// ",
508             line_end: "",
509             shape: Shape::legacy(100, Indent::from_width(&config, 4)),
510             trim_end: true,
511             config: &config,
512         };
513
514         let rewritten_string = rewrite_string(string, &fmt, 100);
515         assert_eq!(
516             rewritten_string,
517             Some("Vivamus id mi.\n    // Vivamus id mi.".to_string())
518         );
519     }
520
521     #[test]
522     fn overflow_in_non_string_content() {
523         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
524         let config: Config = Default::default();
525         let fmt = StringFormat {
526             opener: "",
527             closer: "",
528             line_start: "// ",
529             line_end: "",
530             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
531             trim_end: true,
532             config: &config,
533         };
534
535         assert_eq!(
536             rewrite_string(comment, &fmt, 30),
537             Some(
538                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus\n        // porttitor"
539                     .to_string()
540             )
541         );
542     }
543
544     #[test]
545     fn overflow_in_non_string_content_with_line_end() {
546         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
547         let config: Config = Default::default();
548         let fmt = StringFormat {
549             opener: "",
550             closer: "",
551             line_start: "// ",
552             line_end: "@",
553             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
554             trim_end: true,
555             config: &config,
556         };
557
558         assert_eq!(
559             rewrite_string(comment, &fmt, 30),
560             Some(
561                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus@\n        // porttitor"
562                     .to_string()
563             )
564         );
565     }
566
567     #[test]
568     fn blank_line_with_non_empty_line_start() {
569         let config: Config = Default::default();
570         let mut fmt = StringFormat {
571             opener: "",
572             closer: "",
573             line_start: "// ",
574             line_end: "",
575             shape: Shape::legacy(30, Indent::from_width(&config, 4)),
576             trim_end: true,
577             config: &config,
578         };
579
580         let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
581         assert_eq!(
582             rewrite_string(comment, &fmt, 30),
583             Some(
584                 "Aenean metus. Vestibulum\n    //\n    // ac lacus. Vivamus porttitor".to_string()
585             )
586         );
587
588         fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
589         let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
590         assert_eq!(
591             rewrite_string(comment, &fmt, 15),
592             Some(
593                 r#"Aenean
594     //
595     // metus. Vestibulum
596     // ac lacus. Vivamus
597     // porttitor"#
598                     .to_string()
599             )
600         );
601     }
602
603     #[test]
604     fn retain_blank_lines() {
605         let config: Config = Default::default();
606         let fmt = StringFormat {
607             opener: "",
608             closer: "",
609             line_start: "// ",
610             line_end: "",
611             shape: Shape::legacy(20, Indent::from_width(&config, 4)),
612             trim_end: true,
613             config: &config,
614         };
615
616         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
617         assert_eq!(
618             rewrite_string(comment, &fmt, 20),
619             Some(
620                 "Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n    //\n".to_string()
621             )
622         );
623
624         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
625         assert_eq!(
626             rewrite_string(comment, &fmt, 20),
627             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n".to_string())
628         );
629
630         let comment = "Aenean\n        \nmetus. Vestibulum ac lacus.";
631         assert_eq!(
632             rewrite_string(comment, &fmt, 20),
633             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.".to_string())
634         );
635     }
636
637     #[test]
638     fn boundary_on_edge() {
639         let config: Config = Default::default();
640         let mut fmt = StringFormat {
641             opener: "",
642             closer: "",
643             line_start: "// ",
644             line_end: "",
645             shape: Shape::legacy(13, Indent::from_width(&config, 4)),
646             trim_end: true,
647             config: &config,
648         };
649
650         let comment = "Aenean metus. Vestibulum ac lacus.";
651         assert_eq!(
652             rewrite_string(comment, &fmt, 13),
653             Some("Aenean metus.\n    // Vestibulum ac\n    // lacus.".to_string())
654         );
655
656         fmt.trim_end = false;
657         let comment = "Vestibulum ac lacus.";
658         assert_eq!(
659             rewrite_string(comment, &fmt, 13),
660             Some("Vestibulum \n    // ac lacus.".to_string())
661         );
662
663         fmt.trim_end = true;
664         fmt.line_end = "\\";
665         let comment = "Vestibulum ac lacus.";
666         assert_eq!(
667             rewrite_string(comment, &fmt, 13),
668             Some("Vestibulum\\\n    // ac lacus.".to_string())
669         );
670     }
671
672     #[test]
673     fn detect_urls() {
674         let string = "aaa http://example.org something";
675         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
676         assert_eq!(detect_url(&graphemes, 8), Some(21));
677
678         let string = "https://example.org something";
679         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
680         assert_eq!(detect_url(&graphemes, 0), Some(18));
681
682         let string = "aaa ftp://example.org something";
683         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
684         assert_eq!(detect_url(&graphemes, 8), Some(20));
685
686         let string = "aaa file://example.org something";
687         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
688         assert_eq!(detect_url(&graphemes, 8), Some(21));
689
690         let string = "aaa http not an url";
691         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
692         assert_eq!(detect_url(&graphemes, 6), None);
693
694         let string = "aaa file://example.org";
695         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
696         assert_eq!(detect_url(&graphemes, 8), Some(21));
697     }
698 }