file_editor/
utils.rs

1/// Return the leading whitespace of the line that contains `pos`.
2///
3/// ```
4/// use file_editor::utils::line_indent;
5/// let txt = "   indented\nnext";
6/// let pos = txt.find('i').unwrap();
7/// assert_eq!(line_indent(txt, pos), "   ");
8/// ```
9pub fn line_indent(buf: &str, pos: usize) -> String {
10    let line_start = buf[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
11    buf[line_start..pos]
12        .chars()
13        .take_while(|c| c.is_whitespace())
14        .collect()
15}
16
17#[cfg(test)]
18mod tests {
19    use super::line_indent;
20
21    #[test]
22    fn indent_first_line() {
23        let txt = "   leading spaces\nnext";
24        let pos = txt.find('l').unwrap();
25        assert_eq!(line_indent(txt, pos), "   ");
26    }
27
28    #[test]
29    fn indent_after_newline() {
30        let txt = "no indent\n\t\tindented";
31        let pos = txt.find("indented").unwrap();
32        assert_eq!(line_indent(txt, pos), "\t\t");
33    }
34}