1use regex::Regex;
4use unicode_properties::{GeneralCategory, UnicodeGeneralCategory};
5use unicode_segmentation::UnicodeSegmentation;
6
7use crate::config::Config;
8use crate::shape::Shape;
9use crate::utils::{unicode_str_width, wrap_str};
10
11const MIN_STRING: usize = 10;
12
13pub(crate) struct StringFormat<'a> {
15 pub(crate) opener: &'a str,
17 pub(crate) closer: &'a str,
19 pub(crate) line_start: &'a str,
21 pub(crate) line_end: &'a str,
23 pub(crate) shape: Shape,
25 pub(crate) trim_end: bool,
27 pub(crate) config: &'a Config,
28}
29
30impl<'a> StringFormat<'a> {
31 pub(crate) fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> {
32 StringFormat {
33 opener: "\"",
34 closer: "\"",
35 line_start: " ",
36 line_end: "\\",
37 shape,
38 trim_end: false,
39 config,
40 }
41 }
42
43 fn max_width_with_indent(&self) -> Option<usize> {
48 Some(
49 self.shape
50 .width
51 .checked_sub(self.opener.len() + self.line_end.len() + 1)?
52 + 1,
53 )
54 }
55
56 fn max_width_without_indent(&self) -> Option<usize> {
60 self.config.max_width().checked_sub(self.line_end.len())
61 }
62}
63
64pub(crate) fn rewrite_string<'a>(
65 orig: &str,
66 fmt: &StringFormat<'a>,
67 newline_max_chars: usize,
68) -> Option<String> {
69 let max_width_with_indent = fmt.max_width_with_indent()?;
70 let max_width_without_indent = fmt.max_width_without_indent()?;
71 let indent_with_newline = fmt.shape.indent.to_string_with_newline(fmt.config);
72 let indent_without_newline = fmt.shape.indent.to_string(fmt.config);
73
74 let strip_line_breaks_re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
77 let stripped_str = strip_line_breaks_re.replace_all(orig, "$1");
78
79 let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
80
81 let mut cur_start = 0;
83 let mut result = String::with_capacity(
84 stripped_str
85 .len()
86 .checked_next_power_of_two()
87 .unwrap_or(usize::MAX),
88 );
89 result.push_str(fmt.opener);
90
91 let mut cur_max_width = max_width_with_indent;
94 let is_bareline_ok = fmt.line_start.is_empty() || is_whitespace(fmt.line_start);
95 loop {
96 if graphemes_width(&graphemes[cur_start..]) <= cur_max_width {
98 for (i, grapheme) in graphemes[cur_start..].iter().enumerate() {
99 if is_new_line(grapheme) {
100 result = trim_end_but_line_feed(fmt.trim_end, result);
102 result.push('\n');
103 if !is_bareline_ok && cur_start + i + 1 < graphemes.len() {
104 result.push_str(&indent_without_newline);
105 result.push_str(fmt.line_start);
106 }
107 } else {
108 result.push_str(grapheme);
109 }
110 }
111 result = trim_end_but_line_feed(fmt.trim_end, result);
112 break;
113 }
114
115 match break_string(
117 cur_max_width,
118 fmt.trim_end,
119 fmt.line_end,
120 &graphemes[cur_start..],
121 ) {
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_width = newline_max_chars;
128 cur_start += len;
129 }
130 SnippetState::EndWithLineFeed(line, len) => {
131 if line == "\n" && fmt.trim_end {
132 result = result.trim_end().to_string();
133 }
134 result.push_str(&line);
135 if is_bareline_ok {
136 cur_max_width = max_width_without_indent;
138 } else {
139 result.push_str(&indent_without_newline);
140 result.push_str(fmt.line_start);
141 cur_max_width = max_width_with_indent;
142 }
143 cur_start += len;
144 }
145 SnippetState::EndOfInput(line) => {
146 result.push_str(&line);
147 break;
148 }
149 }
150 }
151
152 result.push_str(fmt.closer);
153 wrap_str(result, fmt.config.max_width(), fmt.shape)
154}
155
156fn detect_url(s: &[&str], index: usize) -> Option<usize> {
159 let start = match s[..=index].iter().rposition(|g| is_whitespace(g)) {
160 Some(pos) => pos + 1,
161 None => 0,
162 };
163 if s.len() < start + 8 {
165 return None;
166 }
167 let split = s[start..].concat();
168 if split.contains("https://")
169 || split.contains("http://")
170 || split.contains("ftp://")
171 || split.contains("file://")
172 {
173 match s[index..].iter().position(|g| is_whitespace(g)) {
174 Some(pos) => Some(index + pos - 1),
175 None => Some(s.len() - 1),
176 }
177 } else {
178 None
179 }
180}
181
182fn trim_end_but_line_feed(trim_end: bool, result: String) -> String {
184 let whitespace_except_line_feed = |c: char| c.is_whitespace() && c != '\n';
185 if trim_end && result.ends_with(whitespace_except_line_feed) {
186 result
187 .trim_end_matches(whitespace_except_line_feed)
188 .to_string()
189 } else {
190 result
191 }
192}
193
194#[derive(Debug, PartialEq)]
197enum SnippetState {
198 EndOfInput(String),
200 LineEnd(String, usize),
207 EndWithLineFeed(String, usize),
215}
216
217fn not_whitespace_except_line_feed(g: &str) -> bool {
218 is_new_line(g) || !is_whitespace(g)
219}
220
221fn break_string(max_width: usize, trim_end: bool, line_end: &str, input: &[&str]) -> SnippetState {
225 let break_at = |index | {
226 let index_minus_ws = input[0..=index]
229 .iter()
230 .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
231 .unwrap_or(index);
232 for (i, grapheme) in input[0..=index].iter().enumerate() {
236 if is_new_line(grapheme) {
237 if i <= index_minus_ws {
238 let mut line = &input[0..i].concat()[..];
239 if trim_end {
240 line = line.trim_end();
241 }
242 return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
243 }
244 break;
245 }
246 }
247
248 let mut index_plus_ws = index;
249 for (i, grapheme) in input[index + 1..].iter().enumerate() {
250 if !trim_end && is_new_line(grapheme) {
251 return SnippetState::EndWithLineFeed(
252 input[0..=index + 1 + i].concat(),
253 index + 2 + i,
254 );
255 } else if not_whitespace_except_line_feed(grapheme) {
256 index_plus_ws = index + i;
257 break;
258 }
259 }
260
261 if trim_end {
262 SnippetState::LineEnd(input[0..=index_minus_ws].concat(), index_plus_ws + 1)
263 } else {
264 SnippetState::LineEnd(input[0..=index_plus_ws].concat(), index_plus_ws + 1)
265 }
266 };
267
268 let max_width_index_in_input = {
270 let mut cur_width = 0;
271 let mut cur_index = 0;
272 for (i, grapheme) in input.iter().enumerate() {
273 cur_width += unicode_str_width(grapheme);
274 cur_index = i;
275 if cur_width > max_width {
276 break;
277 }
278 }
279 cur_index
280 };
281 if max_width_index_in_input == 0 {
282 return SnippetState::EndOfInput(input.concat());
283 }
284
285 if line_end.is_empty()
287 && trim_end
288 && !is_whitespace(input[max_width_index_in_input - 1])
289 && is_whitespace(input[max_width_index_in_input])
290 {
291 return break_at(max_width_index_in_input - 1);
296 }
297 if let Some(url_index_end) = detect_url(input, max_width_index_in_input) {
298 let index_plus_ws = url_index_end
299 + input[url_index_end..]
300 .iter()
301 .skip(1)
302 .position(|grapheme| not_whitespace_except_line_feed(grapheme))
303 .unwrap_or(0);
304 return if trim_end {
305 SnippetState::LineEnd(input[..=url_index_end].concat(), index_plus_ws + 1)
306 } else {
307 SnippetState::LineEnd(input[..=index_plus_ws].concat(), index_plus_ws + 1)
308 };
309 }
310
311 match input[0..max_width_index_in_input]
312 .iter()
313 .rposition(|grapheme| is_whitespace(grapheme))
314 {
315 Some(index) if index >= MIN_STRING => break_at(index),
317 _ => match (0..max_width_index_in_input)
319 .rev()
320 .skip_while(|pos| !is_valid_linebreak(input, *pos))
321 .next()
322 {
323 Some(index) if index >= MIN_STRING => break_at(index),
325 _ => match (max_width_index_in_input..input.len())
328 .skip_while(|pos| !is_valid_linebreak(input, *pos))
329 .next()
330 {
331 Some(index) => break_at(index),
333 None => SnippetState::EndOfInput(input.concat()),
335 },
336 },
337 }
338}
339
340fn is_valid_linebreak(input: &[&str], pos: usize) -> bool {
341 let is_whitespace = is_whitespace(input[pos]);
342 if is_whitespace {
343 return true;
344 }
345 let is_punctuation = is_punctuation(input[pos]);
346 if is_punctuation && !is_part_of_type(input, pos) {
347 return true;
348 }
349 false
350}
351
352fn is_part_of_type(input: &[&str], pos: usize) -> bool {
353 input.get(pos..=pos + 1) == Some(&[":", ":"])
354 || input.get(pos.saturating_sub(1)..=pos) == Some(&[":", ":"])
355}
356
357fn is_new_line(grapheme: &str) -> bool {
358 let bytes = grapheme.as_bytes();
359 bytes.starts_with(b"\n") || bytes.starts_with(b"\r\n")
360}
361
362fn is_whitespace(grapheme: &str) -> bool {
363 grapheme
371 .chars()
372 .all(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C'))
373}
374
375fn is_punctuation(grapheme: &str) -> bool {
376 grapheme
377 .chars()
378 .all(|c| c.general_category() == GeneralCategory::OtherPunctuation)
379}
380
381fn graphemes_width(graphemes: &[&str]) -> usize {
382 graphemes.iter().map(|s| unicode_str_width(s)).sum()
383}
384
385#[cfg(test)]
386mod test {
387 use super::{SnippetState, StringFormat, break_string, detect_url, rewrite_string};
388 use crate::config::Config;
389 use crate::shape::{Indent, Shape};
390 use unicode_segmentation::UnicodeSegmentation;
391
392 #[test]
393 fn issue343() {
394 let config = Default::default();
395 let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
396 rewrite_string("eq_", &fmt, 2);
397 }
398
399 #[test]
400 fn line_break_at_valid_points_test() {
401 let string = "[TheName](Dont::break::my::type::That::would::be::very::nice) break here";
402 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
403 assert_eq!(
404 break_string(20, false, "", &graphemes[..]),
405 SnippetState::LineEnd(
406 "[TheName](Dont::break::my::type::That::would::be::very::nice) ".to_string(),
407 62
408 )
409 );
410 }
411
412 #[test]
413 fn should_break_on_whitespace() {
414 let string = "Placerat felis. Mauris porta ante sagittis purus.";
415 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
416 assert_eq!(
417 break_string(20, false, "", &graphemes[..]),
418 SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
419 );
420 assert_eq!(
421 break_string(20, true, "", &graphemes[..]),
422 SnippetState::LineEnd("Placerat felis.".to_string(), 16)
423 );
424 }
425
426 #[test]
427 fn should_break_on_punctuation() {
428 let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
429 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
430 assert_eq!(
431 break_string(20, false, "", &graphemes[..]),
432 SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
433 );
434 }
435
436 #[test]
437 fn should_break_forward() {
438 let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
439 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
440 assert_eq!(
441 break_string(20, false, "", &graphemes[..]),
442 SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
443 );
444 assert_eq!(
445 break_string(20, true, "", &graphemes[..]),
446 SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
447 );
448 }
449
450 #[test]
451 fn nothing_to_break() {
452 let string = "Venenatis_tellus_vel_tellus";
453 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
454 assert_eq!(
455 break_string(20, false, "", &graphemes[..]),
456 SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
457 );
458 }
459
460 #[test]
461 fn significant_whitespaces() {
462 let string = "Neque in sem. \n Pellentesque tellus augue.";
463 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
464 assert_eq!(
465 break_string(15, false, "", &graphemes[..]),
466 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
467 );
468 assert_eq!(
469 break_string(25, false, "", &graphemes[..]),
470 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
471 );
472
473 assert_eq!(
474 break_string(15, true, "", &graphemes[..]),
475 SnippetState::LineEnd("Neque in sem.".to_string(), 19)
476 );
477 assert_eq!(
478 break_string(25, true, "", &graphemes[..]),
479 SnippetState::EndWithLineFeed("Neque in sem.\n".to_string(), 20)
480 );
481 }
482
483 #[test]
484 fn big_whitespace() {
485 let string = "Neque in sem. Pellentesque tellus augue.";
486 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
487 assert_eq!(
488 break_string(20, false, "", &graphemes[..]),
489 SnippetState::LineEnd("Neque in sem. ".to_string(), 25)
490 );
491 assert_eq!(
492 break_string(20, true, "", &graphemes[..]),
493 SnippetState::LineEnd("Neque in sem.".to_string(), 25)
494 );
495 }
496
497 #[test]
498 fn newline_in_candidate_line() {
499 let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
500
501 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
502 assert_eq!(
503 break_string(25, false, "", &graphemes[..]),
504 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
505 );
506 assert_eq!(
507 break_string(25, true, "", &graphemes[..]),
508 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
509 );
510
511 let mut config: Config = Default::default();
512 config.set().max_width(27);
513 let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
514 let rewritten_string = rewrite_string(string, &fmt, 27);
515 assert_eq!(
516 rewritten_string,
517 Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
518 );
519 }
520
521 #[test]
522 fn last_line_fit_with_trailing_whitespaces() {
523 let string = "Vivamus id mi. ";
524 let config: Config = Default::default();
525 let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
526
527 fmt.trim_end = true;
528 let rewritten_string = rewrite_string(string, &fmt, 25);
529 assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
530
531 fmt.trim_end = false; let rewritten_string = rewrite_string(string, &fmt, 25);
533 assert_eq!(rewritten_string, Some("\"Vivamus id mi. \"".to_string()));
534 }
535
536 #[test]
537 fn last_line_fit_with_newline() {
538 let string = "Vivamus id mi.\nVivamus id mi.";
539 let config: Config = Default::default();
540 let fmt = StringFormat {
541 opener: "",
542 closer: "",
543 line_start: "// ",
544 line_end: "",
545 shape: Shape::legacy(100, Indent::from_width(&config, 4)),
546 trim_end: true,
547 config: &config,
548 };
549
550 let rewritten_string = rewrite_string(string, &fmt, 100);
551 assert_eq!(
552 rewritten_string,
553 Some("Vivamus id mi.\n // Vivamus id mi.".to_string())
554 );
555 }
556
557 #[test]
558 fn overflow_in_non_string_content() {
559 let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
560 let config: Config = Default::default();
561 let fmt = StringFormat {
562 opener: "",
563 closer: "",
564 line_start: "// ",
565 line_end: "",
566 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
567 trim_end: true,
568 config: &config,
569 };
570
571 assert_eq!(
572 rewrite_string(comment, &fmt, 30),
573 Some(
574 "Aenean metus.\n // Vestibulum ac lacus. Vivamus\n // porttitor"
575 .to_string()
576 )
577 );
578 }
579
580 #[test]
581 fn overflow_in_non_string_content_with_line_end() {
582 let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
583 let config: Config = Default::default();
584 let fmt = StringFormat {
585 opener: "",
586 closer: "",
587 line_start: "// ",
588 line_end: "@",
589 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
590 trim_end: true,
591 config: &config,
592 };
593
594 assert_eq!(
595 rewrite_string(comment, &fmt, 30),
596 Some(
597 "Aenean metus.\n // Vestibulum ac lacus. Vivamus@\n // porttitor"
598 .to_string()
599 )
600 );
601 }
602
603 #[test]
604 fn blank_line_with_non_empty_line_start() {
605 let config: Config = Default::default();
606 let mut fmt = StringFormat {
607 opener: "",
608 closer: "",
609 line_start: "// ",
610 line_end: "",
611 shape: Shape::legacy(30, Indent::from_width(&config, 4)),
612 trim_end: true,
613 config: &config,
614 };
615
616 let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
617 assert_eq!(
618 rewrite_string(comment, &fmt, 30),
619 Some(
620 "Aenean metus. Vestibulum\n //\n // ac lacus. Vivamus porttitor".to_string()
621 )
622 );
623
624 fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
625 let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
626 assert_eq!(
627 rewrite_string(comment, &fmt, 15),
628 Some(
629 r#"Aenean
630 //
631 // metus. Vestibulum
632 // ac lacus. Vivamus
633 // porttitor"#
634 .to_string()
635 )
636 );
637 }
638
639 #[test]
640 fn retain_blank_lines() {
641 let config: Config = Default::default();
642 let fmt = StringFormat {
643 opener: "",
644 closer: "",
645 line_start: "// ",
646 line_end: "",
647 shape: Shape::legacy(20, Indent::from_width(&config, 4)),
648 trim_end: true,
649 config: &config,
650 };
651
652 let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
653 assert_eq!(
654 rewrite_string(comment, &fmt, 20),
655 Some(
656 "Aenean\n //\n // metus. Vestibulum ac\n // lacus.\n //\n".to_string()
657 )
658 );
659
660 let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
661 assert_eq!(
662 rewrite_string(comment, &fmt, 20),
663 Some("Aenean\n //\n // metus. Vestibulum ac\n // lacus.\n".to_string())
664 );
665
666 let comment = "Aenean\n \nmetus. Vestibulum ac lacus.";
667 assert_eq!(
668 rewrite_string(comment, &fmt, 20),
669 Some("Aenean\n //\n // metus. Vestibulum ac\n // lacus.".to_string())
670 );
671 }
672
673 #[test]
674 fn boundary_on_edge() {
675 let config: Config = Default::default();
676 let mut fmt = StringFormat {
677 opener: "",
678 closer: "",
679 line_start: "// ",
680 line_end: "",
681 shape: Shape::legacy(13, Indent::from_width(&config, 4)),
682 trim_end: true,
683 config: &config,
684 };
685
686 let comment = "Aenean metus. Vestibulum ac lacus.";
687 assert_eq!(
688 rewrite_string(comment, &fmt, 13),
689 Some("Aenean metus.\n // Vestibulum ac\n // lacus.".to_string())
690 );
691
692 fmt.trim_end = false;
693 let comment = "Vestibulum ac lacus.";
694 assert_eq!(
695 rewrite_string(comment, &fmt, 13),
696 Some("Vestibulum \n // ac lacus.".to_string())
697 );
698
699 fmt.trim_end = true;
700 fmt.line_end = "\\";
701 let comment = "Vestibulum ac lacus.";
702 assert_eq!(
703 rewrite_string(comment, &fmt, 13),
704 Some("Vestibulum\\\n // ac lacus.".to_string())
705 );
706 }
707
708 #[test]
709 fn detect_urls() {
710 let string = "aaa http://example.org something";
711 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
712 assert_eq!(detect_url(&graphemes, 8), Some(21));
713
714 let string = "https://example.org something";
715 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
716 assert_eq!(detect_url(&graphemes, 0), Some(18));
717
718 let string = "aaa ftp://example.org something";
719 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
720 assert_eq!(detect_url(&graphemes, 8), Some(20));
721
722 let string = "aaa file://example.org something";
723 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
724 assert_eq!(detect_url(&graphemes, 8), Some(21));
725
726 let string = "aaa http not an url";
727 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
728 assert_eq!(detect_url(&graphemes, 6), None);
729
730 let string = "aaa file://example.org";
731 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
732 assert_eq!(detect_url(&graphemes, 8), Some(21));
733 }
734}