pub(crate) const LF: char = '\n';
pub(crate) const NEWLINE: &str = "\n";
pub(crate) fn join(lines: &[String]) -> String {
lines.join(NEWLINE)
}
pub(crate) fn terminated(line: &str) -> String {
let mut text = line.to_owned();
text.push(LF);
text
}
pub(crate) fn line_start(source: &str, at: usize) -> usize {
source[..at].rfind(LF).map_or(0, |newline| newline + 1)
}
pub(crate) fn line_end(source: &str, at: usize) -> usize {
source[at..]
.find(LF)
.map_or(source.len(), |newline| at + newline + 1)
}
pub(crate) fn trim_end(source: &str, start: usize, end: usize) -> usize {
start + source[start..end].trim_end().len()
}
pub(crate) fn column(source: &str, at: usize) -> usize {
source[line_start(source, at)..at].chars().count()
}
pub(crate) fn starts_line(source: &str, at: usize) -> bool {
source[line_start(source, at)..at].trim().is_empty()
}
pub(crate) fn has_blank_line(source: &str, from: usize, to: usize) -> bool {
source[from..to].lines().any(|line| line.trim().is_empty())
}
pub(crate) fn indent(lines: &[String], indent: usize) -> Vec<String> {
let pad = " ".repeat(indent);
lines
.iter()
.map(|line| {
if line.is_empty() {
String::new()
} else {
format!("{pad}{line}")
}
})
.collect()
}
pub(crate) fn dedent(text: &str, by: usize) -> String {
text.split_inclusive(LF)
.map(|line| {
let spaces = line.len() - line.trim_start_matches(' ').len();
&line[spaces.min(by)..]
})
.collect()
}