text_utils/utils/
text_align.rs

1/// Removes common leading whitespace from each line.
2pub fn dedent(text: impl AsRef<str>) -> String {
3    textwrap::dedent(text.as_ref())
4}
5
6/// Adds spaces to each non-empty line.
7pub fn indent(text: impl AsRef<str>, space: usize) -> String {
8    textwrap::indent(text.as_ref(), &" ".repeat(space))
9}
10
11/// Adds prefix to each non-empty line.
12pub fn indent_with(text: impl AsRef<str>, prefix: &str) -> String {
13    textwrap::indent(text.as_ref(), prefix)
14}
15
16/// Removes at most n leading whitespace from each line
17pub fn dedent_less_than(text: impl AsRef<str>, max: usize) -> String {
18    // https://stackoverflow.com/questions/60337455/how-to-trim-space-less-than-n-times
19    text.as_ref()
20        .lines()
21        .map(|line| {
22            let mut max = max;
23            line.chars()
24                // Skip while `c` is a whitespace and at most `max` spaces
25                .skip_while(|c| {
26                    if max == 0 {
27                        false
28                    }
29                    else {
30                        max -= 1;
31                        c.is_whitespace()
32                    }
33                })
34                .collect::<String>()
35        })
36        .collect::<Vec<_>>()
37        .join("\n")
38}
39
40/// Calculate how much space the first line has
41pub fn indent_count(text: impl AsRef<str>) -> usize {
42    let mut spaces = 0;
43    for c in text.as_ref().chars() {
44        match c {
45            ' ' => spaces += 1,
46            _ => break,
47        }
48    }
49    return spaces;
50}