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 block_header(source: &str, text: usize) -> Option<usize> {
let mut line = line_start(source, text);
let own = &source[line..text];
if own.trim().is_empty() {
while line > 0 {
line = line_start(source, line - 1);
if !source[line..line_end(source, line)].trim().is_empty() {
break;
}
}
}
let end = if own.trim().is_empty() {
line_end(source, line)
} else {
text
};
let mut header = None;
let mut at = line;
for token in source[line..end].split_inclusive(char::is_whitespace) {
let word = token.trim_end();
if word.starts_with('#') {
break;
}
if word.starts_with(['|', '>']) {
header = Some(at);
}
at += token.len();
}
header
}
pub(crate) fn comment_start(line: &str) -> Option<usize> {
line.char_indices()
.find(|&(at, c)| {
c == '#' && (line[..at].trim().is_empty() || line[..at].ends_with([' ', '\t']))
})
.map(|(at, _)| at)
}
pub(crate) fn spaced(parts: &[&str]) -> String {
parts
.iter()
.copied()
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
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 dash_before(source: &str, at: usize) -> usize {
let line = line_start(source, at);
source[line..at]
.rfind('-')
.map_or(at, |offset| line + offset)
}
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 pad(text: &str, by: usize) -> String {
let spaces = " ".repeat(by);
text.split_inclusive(LF)
.map(|line| {
if line == NEWLINE {
line.to_owned()
} else {
format!("{spaces}{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()
}