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(
154 result,
155 fmt.config.max_width(),
156 fmt.config.tab_spaces(),
157 fmt.shape,
158 )
159}
160
161fn detect_url(s: &[&str], index: usize) -> Option<usize> {
164 let start = match s[..=index].iter().rposition(|g| is_whitespace(g)) {
165 Some(pos) => pos + 1,
166 None => 0,
167 };
168 if s.len() < start + 8 {
170 return None;
171 }
172 let split = s[start..].concat();
173 if split.contains("https://")
174 || split.contains("http://")
175 || split.contains("ftp://")
176 || split.contains("file://")
177 {
178 match s[index..].iter().position(|g| is_whitespace(g)) {
179 Some(pos) => Some(index + pos - 1),
180 None => Some(s.len() - 1),
181 }
182 } else {
183 None
184 }
185}
186
187fn trim_end_but_line_feed(trim_end: bool, result: String) -> String {
189 let whitespace_except_line_feed = |c: char| c.is_whitespace() && c != '\n';
190 if trim_end && result.ends_with(whitespace_except_line_feed) {
191 result
192 .trim_end_matches(whitespace_except_line_feed)
193 .to_string()
194 } else {
195 result
196 }
197}
198
199#[derive(Debug, PartialEq)]
202enum SnippetState {
203 EndOfInput(String),
205 LineEnd(String, usize),
212 EndWithLineFeed(String, usize),
220}
221
222fn not_whitespace_except_line_feed(g: &str) -> bool {
223 is_new_line(g) || !is_whitespace(g)
224}
225
226fn break_string(max_width: usize, trim_end: bool, line_end: &str, input: &[&str]) -> SnippetState {
230 let break_at = |index | {
231 let index_minus_ws = input[0..=index]
234 .iter()
235 .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
236 .unwrap_or(index);
237 for (i, grapheme) in input[0..=index].iter().enumerate() {
241 if is_new_line(grapheme) {
242 if i <= index_minus_ws {
243 let mut line = &input[0..i].concat()[..];
244 if trim_end {
245 line = line.trim_end();
246 }
247 return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
248 }
249 break;
250 }
251 }
252
253 let mut index_plus_ws = index;
254 for (i, grapheme) in input[index + 1..].iter().enumerate() {
255 if !trim_end && is_new_line(grapheme) {
256 return SnippetState::EndWithLineFeed(
257 input[0..=index + 1 + i].concat(),
258 index + 2 + i,
259 );
260 } else if not_whitespace_except_line_feed(grapheme) {
261 index_plus_ws = index + i;
262 break;
263 }
264 }
265
266 if trim_end {
267 SnippetState::LineEnd(input[0..=index_minus_ws].concat(), index_plus_ws + 1)
268 } else {
269 SnippetState::LineEnd(input[0..=index_plus_ws].concat(), index_plus_ws + 1)
270 }
271 };
272
273 let max_width_index_in_input = {
275 let mut cur_width = 0;
276 let mut cur_index = 0;
277 for (i, grapheme) in input.iter().enumerate() {
278 cur_width += unicode_str_width(grapheme);
279 cur_index = i;
280 if cur_width > max_width {
281 break;
282 }
283 }
284 cur_index
285 };
286 if max_width_index_in_input == 0 {
287 return SnippetState::EndOfInput(input.concat());
288 }
289
290 if line_end.is_empty()
292 && trim_end
293 && !is_whitespace(input[max_width_index_in_input - 1])
294 && is_whitespace(input[max_width_index_in_input])
295 {
296 return break_at(max_width_index_in_input - 1);
301 }
302 if let Some(url_index_end) = detect_url(input, max_width_index_in_input) {
303 let index_plus_ws = url_index_end
304 + input[url_index_end..]
305 .iter()
306 .skip(1)
307 .position(|grapheme| not_whitespace_except_line_feed(grapheme))
308 .unwrap_or(0);
309 return if trim_end {
310 SnippetState::LineEnd(input[..=url_index_end].concat(), index_plus_ws + 1)
311 } else {
312 SnippetState::LineEnd(input[..=index_plus_ws].concat(), index_plus_ws + 1)
313 };
314 }
315
316 match input[0..max_width_index_in_input]
317 .iter()
318 .rposition(|grapheme| is_whitespace(grapheme))
319 {
320 Some(index) if index >= MIN_STRING => break_at(index),
322 _ => match (0..max_width_index_in_input)
324 .rev()
325 .skip_while(|pos| !is_valid_linebreak(input, *pos))
326 .next()
327 {
328 Some(index) if index >= MIN_STRING => break_at(index),
330 _ => match (max_width_index_in_input..input.len())
333 .skip_while(|pos| !is_valid_linebreak(input, *pos))
334 .next()
335 {
336 Some(index) => break_at(index),
338 None => SnippetState::EndOfInput(input.concat()),
340 },
341 },
342 }
343}
344
345fn is_valid_linebreak(input: &[&str], pos: usize) -> bool {
346 let is_whitespace = is_whitespace(input[pos]);
347 if is_whitespace {
348 return true;
349 }
350 let is_punctuation = is_punctuation(input[pos]);
351 if is_punctuation && !is_part_of_type(input, pos) {
352 return true;
353 }
354 false
355}
356
357fn is_part_of_type(input: &[&str], pos: usize) -> bool {
358 input.get(pos..=pos + 1) == Some(&[":", ":"])
359 || input.get(pos.saturating_sub(1)..=pos) == Some(&[":", ":"])
360}
361
362fn is_new_line(grapheme: &str) -> bool {
363 let bytes = grapheme.as_bytes();
364 bytes.starts_with(b"\n") || bytes.starts_with(b"\r\n")
365}
366
367fn is_whitespace(grapheme: &str) -> bool {
368 grapheme
376 .chars()
377 .all(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C'))
378}
379
380fn is_punctuation(grapheme: &str) -> bool {
381 grapheme
382 .chars()
383 .all(|c| c.general_category() == GeneralCategory::OtherPunctuation)
384}
385
386fn graphemes_width(graphemes: &[&str]) -> usize {
387 graphemes.iter().map(|s| unicode_str_width(s)).sum()
388}
389
390#[cfg(test)]
391mod test {
392 use super::{SnippetState, StringFormat, break_string, detect_url, rewrite_string};
393 use crate::config::Config;
394 use crate::shape::{Indent, Shape};
395 use unicode_segmentation::UnicodeSegmentation;
396
397 #[test]
398 fn issue343() {
399 let config = Default::default();
400 let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
401 rewrite_string("eq_", &fmt, 2);
402 }
403
404 #[test]
405 fn line_break_at_valid_points_test() {
406 let string = "[TheName](Dont::break::my::type::That::would::be::very::nice) break here";
407 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
408 assert_eq!(
409 break_string(20, false, "", &graphemes[..]),
410 SnippetState::LineEnd(
411 "[TheName](Dont::break::my::type::That::would::be::very::nice) ".to_string(),
412 62
413 )
414 );
415 }
416
417 #[test]
418 fn should_break_on_whitespace() {
419 let string = "Placerat felis. Mauris porta ante sagittis purus.";
420 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
421 assert_eq!(
422 break_string(20, false, "", &graphemes[..]),
423 SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
424 );
425 assert_eq!(
426 break_string(20, true, "", &graphemes[..]),
427 SnippetState::LineEnd("Placerat felis.".to_string(), 16)
428 );
429 }
430
431 #[test]
432 fn should_break_on_punctuation() {
433 let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
434 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
435 assert_eq!(
436 break_string(20, false, "", &graphemes[..]),
437 SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
438 );
439 }
440
441 #[test]
442 fn should_break_forward() {
443 let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
444 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
445 assert_eq!(
446 break_string(20, false, "", &graphemes[..]),
447 SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
448 );
449 assert_eq!(
450 break_string(20, true, "", &graphemes[..]),
451 SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
452 );
453 }
454
455 #[test]
456 fn nothing_to_break() {
457 let string = "Venenatis_tellus_vel_tellus";
458 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
459 assert_eq!(
460 break_string(20, false, "", &graphemes[..]),
461 SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
462 );
463 }
464
465 #[test]
466 fn significant_whitespaces() {
467 let string = "Neque in sem. \n Pellentesque tellus augue.";
468 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
469 assert_eq!(
470 break_string(15, false, "", &graphemes[..]),
471 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
472 );
473 assert_eq!(
474 break_string(25, false, "", &graphemes[..]),
475 SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20)
476 );
477
478 assert_eq!(
479 break_string(15, true, "", &graphemes[..]),
480 SnippetState::LineEnd("Neque in sem.".to_string(), 19)
481 );
482 assert_eq!(
483 break_string(25, true, "", &graphemes[..]),
484 SnippetState::EndWithLineFeed("Neque in sem.\n".to_string(), 20)
485 );
486 }
487
488 #[test]
489 fn big_whitespace() {
490 let string = "Neque in sem. Pellentesque tellus augue.";
491 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
492 assert_eq!(
493 break_string(20, false, "", &graphemes[..]),
494 SnippetState::LineEnd("Neque in sem. ".to_string(), 25)
495 );
496 assert_eq!(
497 break_string(20, true, "", &graphemes[..]),
498 SnippetState::LineEnd("Neque in sem.".to_string(), 25)
499 );
500 }
501
502 #[test]
503 fn newline_in_candidate_line() {
504 let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
505
506 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
507 assert_eq!(
508 break_string(25, false, "", &graphemes[..]),
509 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
510 );
511 assert_eq!(
512 break_string(25, true, "", &graphemes[..]),
513 SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
514 );
515
516 let mut config: Config = Default::default();
517 config.set().max_width(27);
518 let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
519 let rewritten_string = rewrite_string(string, &fmt, 27);
520 assert_eq!(
521 rewritten_string,
522 Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
523 );
524 }
525
526 #[test]
527 fn last_line_fit_with_trailing_whitespaces() {
528 let string = "Vivamus id mi. ";
529 let config: Config = Default::default();
530 let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
531
532 fmt.trim_end = true;
533 let rewritten_string = rewrite_string(string, &fmt, 25);
534 assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
535
536 fmt.trim_end = false; let rewritten_string = rewrite_string(string, &fmt, 25);
538 assert_eq!(rewritten_string, Some("\"Vivamus id mi. \"".to_string()));
539 }
540
541 #[test]
542 fn last_line_fit_with_newline() {
543 let string = "Vivamus id mi.\nVivamus id mi.";
544 let config: Config = Default::default();
545 let fmt = StringFormat {
546 opener: "",
547 closer: "",
548 line_start: "// ",
549 line_end: "",
550 shape: Shape::legacy(100, Indent::from_width(&config, 4)),
551 trim_end: true,
552 config: &config,
553 };
554
555 let rewritten_string = rewrite_string(string, &fmt, 100);
556 assert_eq!(
557 rewritten_string,
558 Some("Vivamus id mi.\n // Vivamus id mi.".to_string())
559 );
560 }
561
562 #[test]
563 fn overflow_in_non_string_content() {
564 let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
565 let config: Config = Default::default();
566 let fmt = StringFormat {
567 opener: "",
568 closer: "",
569 line_start: "// ",
570 line_end: "",
571 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
572 trim_end: true,
573 config: &config,
574 };
575
576 assert_eq!(
577 rewrite_string(comment, &fmt, 30),
578 Some(
579 "Aenean metus.\n // Vestibulum ac lacus. Vivamus\n // porttitor"
580 .to_string()
581 )
582 );
583 }
584
585 #[test]
586 fn overflow_in_non_string_content_with_line_end() {
587 let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
588 let config: Config = Default::default();
589 let fmt = StringFormat {
590 opener: "",
591 closer: "",
592 line_start: "// ",
593 line_end: "@",
594 shape: Shape::legacy(30, Indent::from_width(&config, 8)),
595 trim_end: true,
596 config: &config,
597 };
598
599 assert_eq!(
600 rewrite_string(comment, &fmt, 30),
601 Some(
602 "Aenean metus.\n // Vestibulum ac lacus. Vivamus@\n // porttitor"
603 .to_string()
604 )
605 );
606 }
607
608 #[test]
609 fn blank_line_with_non_empty_line_start() {
610 let config: Config = Default::default();
611 let mut fmt = StringFormat {
612 opener: "",
613 closer: "",
614 line_start: "// ",
615 line_end: "",
616 shape: Shape::legacy(30, Indent::from_width(&config, 4)),
617 trim_end: true,
618 config: &config,
619 };
620
621 let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
622 assert_eq!(
623 rewrite_string(comment, &fmt, 30),
624 Some(
625 "Aenean metus. Vestibulum\n //\n // ac lacus. Vivamus porttitor".to_string()
626 )
627 );
628
629 fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
630 let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
631 assert_eq!(
632 rewrite_string(comment, &fmt, 15),
633 Some(
634 r#"Aenean
635 //
636 // metus. Vestibulum
637 // ac lacus. Vivamus
638 // porttitor"#
639 .to_string()
640 )
641 );
642 }
643
644 #[test]
645 fn retain_blank_lines() {
646 let config: Config = Default::default();
647 let fmt = StringFormat {
648 opener: "",
649 closer: "",
650 line_start: "// ",
651 line_end: "",
652 shape: Shape::legacy(20, Indent::from_width(&config, 4)),
653 trim_end: true,
654 config: &config,
655 };
656
657 let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
658 assert_eq!(
659 rewrite_string(comment, &fmt, 20),
660 Some(
661 "Aenean\n //\n // metus. Vestibulum ac\n // lacus.\n //\n".to_string()
662 )
663 );
664
665 let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
666 assert_eq!(
667 rewrite_string(comment, &fmt, 20),
668 Some("Aenean\n //\n // metus. Vestibulum ac\n // lacus.\n".to_string())
669 );
670
671 let comment = "Aenean\n \nmetus. Vestibulum ac lacus.";
672 assert_eq!(
673 rewrite_string(comment, &fmt, 20),
674 Some("Aenean\n //\n // metus. Vestibulum ac\n // lacus.".to_string())
675 );
676 }
677
678 #[test]
679 fn boundary_on_edge() {
680 let config: Config = Default::default();
681 let mut fmt = StringFormat {
682 opener: "",
683 closer: "",
684 line_start: "// ",
685 line_end: "",
686 shape: Shape::legacy(13, Indent::from_width(&config, 4)),
687 trim_end: true,
688 config: &config,
689 };
690
691 let comment = "Aenean metus. Vestibulum ac lacus.";
692 assert_eq!(
693 rewrite_string(comment, &fmt, 13),
694 Some("Aenean metus.\n // Vestibulum ac\n // lacus.".to_string())
695 );
696
697 fmt.trim_end = false;
698 let comment = "Vestibulum ac lacus.";
699 assert_eq!(
700 rewrite_string(comment, &fmt, 13),
701 Some("Vestibulum \n // ac lacus.".to_string())
702 );
703
704 fmt.trim_end = true;
705 fmt.line_end = "\\";
706 let comment = "Vestibulum ac lacus.";
707 assert_eq!(
708 rewrite_string(comment, &fmt, 13),
709 Some("Vestibulum\\\n // ac lacus.".to_string())
710 );
711 }
712
713 #[test]
714 fn detect_urls() {
715 let string = "aaa http://example.org something";
716 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
717 assert_eq!(detect_url(&graphemes, 8), Some(21));
718
719 let string = "https://example.org something";
720 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
721 assert_eq!(detect_url(&graphemes, 0), Some(18));
722
723 let string = "aaa ftp://example.org something";
724 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
725 assert_eq!(detect_url(&graphemes, 8), Some(20));
726
727 let string = "aaa file://example.org something";
728 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
729 assert_eq!(detect_url(&graphemes, 8), Some(21));
730
731 let string = "aaa http not an url";
732 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
733 assert_eq!(detect_url(&graphemes, 6), None);
734
735 let string = "aaa file://example.org";
736 let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
737 assert_eq!(detect_url(&graphemes, 8), Some(21));
738 }
739}