use continuity_text::Position;
use crate::selection_edit::IndentUnit;
fn leading_run<F: Fn(char) -> bool>(s: &str, predicate: F) -> usize {
s.chars()
.take_while(|c| predicate(*c))
.map(char::len_utf8)
.sum()
}
pub(crate) fn outdent_drop_len(slice: &str, unit: IndentUnit) -> usize {
match unit {
IndentUnit::Tab => {
if slice.starts_with('\t') {
1
} else {
leading_run(slice, |c| c == ' ').min(8)
}
}
IndentUnit::Spaces(n) => {
let n = n as usize;
let leading = leading_run(slice, |c| c == ' ');
if leading >= n {
n
} else if slice.starts_with('\t') {
1
} else {
leading
}
}
}
}
pub(crate) fn shift_after_indent(
p: Position,
indented_lines: &[usize],
prefix_len: u32,
) -> Position {
if indented_lines.contains(&(p.line as usize)) {
Position::new(p.line, p.byte_in_line + prefix_len)
} else {
p
}
}
pub(crate) fn shift_after_outdent(p: Position, drops: &[(usize, u32)]) -> Position {
let line = p.line as usize;
let Some(&(_, drop_len)) = drops.iter().find(|(l, _)| *l == line) else {
return p;
};
if p.byte_in_line > drop_len {
Position::new(p.line, p.byte_in_line - drop_len)
} else {
Position::new(p.line, 0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn indent_shift_only_touches_indented_lines() {
let p = shift_after_indent(Position::new(1, 3), &[1], 2);
assert_eq!(p, Position::new(1, 5));
let p = shift_after_indent(Position::new(2, 3), &[1], 2);
assert_eq!(p, Position::new(2, 3));
}
#[test]
fn outdent_shift_clamps_inside_dropped_run() {
let drops = &[(0_usize, 4_u32)];
assert_eq!(
shift_after_outdent(Position::new(0, 6), drops),
Position::new(0, 2)
);
assert_eq!(
shift_after_outdent(Position::new(0, 3), drops),
Position::new(0, 0)
);
assert_eq!(
shift_after_outdent(Position::new(0, 4), drops),
Position::new(0, 0)
);
assert_eq!(
shift_after_outdent(Position::new(1, 6), drops),
Position::new(1, 6)
);
}
}