use std::sync::LazyLock;
use crate::js::js_trim;
use crate::pattern::Pattern;
use crate::read::{RX, ReadOptions, Reading, read};
use crate::text::literal;
use crate::types::{Form, Node};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LineInfo {
pub class: &'static str,
pub label_end: usize,
pub keyword: String,
pub kind: String,
}
impl LineInfo {
fn class(class: &'static str) -> LineInfo {
LineInfo { class, ..LineInfo::default() }
}
}
struct Rx {
label_lead: Pattern,
label: Pattern,
reason: Pattern,
fence_start: Pattern,
}
static LRX: LazyLock<Rx> = LazyLock::new(|| {
let kw = crate::registry::keyword_names();
let sp = crate::js::JS_SPACES;
Rx {
label_lead: Pattern::must(r"^(?:[ \t]*>[ \t]?)*[ \t]*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)?"),
label: Pattern::must(&format!(r"^(?:\*\*)?(?:{kw})(?:\[[^\]{sp}]*\])?(?: \(if [^()\r\n]*\))?:(?:\*\*)?")),
reason: Pattern::must(r"^(?:\*\*)?BECAUSE:(?:\*\*)?"),
fence_start: Pattern::must(r"^(?:[ \t]*>)*[ \t]*(`{3,}|~{3,})"),
}
});
pub fn classify_lines(r: &Reading) -> Vec<LineInfo> {
let mut out = vec![LineInfo::class("prose"); r.lines.len()];
for &n in &r.comments {
set(&mut out, n, LineInfo::class("comment"));
}
if let Some(fr) = r.front_range {
span(&mut out, fr.start, fr.end, "front-matter");
}
if let Some(br) = r.back_range {
span(&mut out, br.start, br.end, "backmatter");
}
walk(r, &r.document.body, &mut out);
out
}
fn set(out: &mut [LineInfo], n: u32, info: LineInfo) {
if n >= 1 && (n as usize) <= out.len() {
out[n as usize - 1] = info;
}
}
fn span(out: &mut [LineInfo], from: u32, to: u32, class: &'static str) {
for n in from..=to {
set(out, n, LineInfo::class(class));
}
}
fn line_at(r: &Reading, n: u32) -> &str {
if n >= 1 && (n as usize) <= r.lines.len() { &r.lines[n as usize - 1] } else { "" }
}
fn reason(r: &Reading, node: &Node, out: &mut [LineInfo]) {
let Some(at) = node.reason else { return };
set(out, at.start, LineInfo { label_end: label_end(line_at(r, at.start), &LRX.reason), ..LineInfo::class("reason") });
if at.end > at.start {
span(out, at.start + 1, at.end, "prose");
}
}
fn walk(r: &Reading, nodes: &[Node], out: &mut [LineInfo]) {
for node in nodes {
let Some(rg) = node.range else { continue };
if node.is_markdown() {
classify_markdown(r, rg.start, rg.end, out);
continue;
}
if matches!(node.form, Some(Form::Keyword | Form::Alert)) {
walk(r, node.children(), out);
let keyword = node.keyword.clone().unwrap_or_default();
if node.form == Some(Form::Alert) {
set(out, rg.start, LineInfo { keyword, ..LineInfo::class("alert") });
} else {
set(
out,
rg.start,
LineInfo { label_end: label_end(line_at(r, rg.start), &LRX.label), keyword, ..LineInfo::class("keyword") },
);
}
reason(r, node, out);
continue;
}
let mut last = rg.start;
if node.form == Some(Form::Container) && rg.end > rg.start && RX.close.is_match(line_at(r, rg.end)) {
last = rg.end;
}
if node.form == Some(Form::Container) {
if node.value.is_some() {
if last > rg.start + 1 {
span(out, rg.start + 1, last - 1, "data");
}
} else if literal(node) {
if last > rg.start + 1 {
span(out, rg.start + 1, last - 1, "literal");
}
} else {
walk(r, node.children(), out);
}
reason(r, node, out);
}
set(out, rg.start, LineInfo { kind: node.kind.clone(), ..LineInfo::class("directive") });
if last != rg.start {
set(out, last, LineInfo { kind: node.kind.clone(), ..LineInfo::class("directive") });
}
}
}
fn classify_markdown(r: &Reading, from: u32, to: u32, out: &mut [LineInfo]) {
let mut open = String::new();
let mut n = from;
while n <= to && (n as usize) <= out.len() {
let line = &r.lines[n as usize - 1];
let f = LRX.fence_start.captures(line);
let i = n as usize - 1;
n += 1;
if !open.is_empty() {
out[i] = LineInfo::class("code");
if let Some(f) = &f {
let run = f.get(line, 1).unwrap_or("");
let whole = f.get(line, 0).unwrap_or("");
if run.as_bytes()[0] == open.as_bytes()[0] && run.len() >= open.len() && js_trim(line) == js_trim(whole) {
open.clear();
}
}
continue;
}
if let Some(f) = &f {
open = f.get(line, 1).unwrap_or("```").to_string();
out[i] = LineInfo::class("code");
continue;
}
if out[i].class == "comment" {
continue;
}
if RX.heading.is_match(line) {
out[i] = LineInfo::class("heading");
}
}
}
fn label_end(line: &str, label: &Pattern) -> usize {
let lead = LRX.label_lead.find_str(line).unwrap_or("");
lead.len() + label.find_str(&line[lead.len()..]).map_or(0, str::len)
}
pub fn format(text: &str) -> String {
let bom = if text.starts_with('\u{feff}') { "\u{feff}" } else { "" };
let r = read(text, &ReadOptions::default());
let classes = classify_lines(&r);
let lines: Vec<&str> = r
.lines
.iter()
.enumerate()
.map(|(i, l)| if classes[i].class == "directive" { l.trim_end_matches([' ', '\t']) } else { l.as_str() })
.collect();
let joined = lines.join("\n");
let body = joined.trim_end_matches('\n');
if body.is_empty() {
return bom.to_string();
}
format!("{bom}{body}\n")
}