use std::cell::RefCell;
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span};
use unicode_width::{UnicodeWidthChar as _, UnicodeWidthStr as _};
use crate::highlight::{CodeColors, Role, syntax_for};
use crate::srcmap::LineOffsets;
use crate::theme::palette;
use crate::wrap::{Row, split_line};
#[cfg(test)]
pub(crate) const BAR: char = '▐';
pub(super) const BAR_PREFIX: &str = "▐ ";
pub(super) const BAR_WIDTH: usize = 2;
const UNLABELLED: [&str; 4] = ["text", "txt", "plain", "plaintext"];
#[derive(Debug)]
pub(crate) struct Code {
lang: String,
label: Option<String>,
colors: RefCell<Colors>,
}
#[derive(Debug)]
enum Colors {
Unresolved,
Plain,
Known(Box<CodeColors>),
}
impl Code {
pub(crate) fn new(info: &str) -> Self {
let lang = info.split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or_default();
let label = lang.trim_matches(|c: char| matches!(c, '{' | '}' | '.'));
let named = !label.is_empty() && !UNLABELLED.iter().any(|word| word.eq_ignore_ascii_case(label));
Self {
lang: lang.to_owned(),
label: named.then(|| label.to_owned()),
colors: RefCell::new(Colors::Unresolved),
}
}
pub(crate) fn rows(&self, lines: &[Line<'_>], offsets: &[LineOffsets], width: usize) -> Vec<Row> {
let bar = Span::styled(BAR_PREFIX, Style::new().fg(palette().code_comment));
let mut rows = Vec::with_capacity(lines.len());
for (line, offsets) in lines.iter().zip(offsets) {
split_line(&mut rows, &bar, line, offsets, width);
}
if rows.is_empty() {
rows.push(Row { line: Line::from(bar), cells: vec![None; BAR_WIDTH] });
}
if let (Some(label), Some(first)) = (&self.label, rows.first_mut()) {
let used = first.cells.len();
if used + 1 + label.width() <= width {
let pad = width - label.width() - used;
first.line.spans.push(Span::raw(" ".repeat(pad)));
first.line.spans.push(Span::styled(label.clone(), Style::new().fg(palette().code_comment)));
first.cells.extend(std::iter::repeat_n(None, pad + label.width()));
}
}
rows
}
pub(crate) fn paint(
&self,
lines: &[Line<'_>],
offsets: &[LineOffsets],
index: usize,
row: &Row,
) -> Option<Line<'static>> {
self.known().then(|| paint_row(row, |offset| self.shade(lines, offsets, index, offset)))
}
fn known(&self) -> bool {
let mut colors = self.colors.borrow_mut();
if matches!(*colors, Colors::Unresolved) {
*colors = match syntax_for(&self.lang) {
Some(syntax) => Colors::Known(Box::new(CodeColors::new(syntax))),
None => Colors::Plain,
};
}
matches!(*colors, Colors::Known(_))
}
pub(super) fn shade(
&self,
lines: &[Line<'_>],
offsets: &[LineOffsets],
upto: usize,
offset: usize,
) -> Shade {
if !self.known() {
return Shade::Keep;
}
let mut colors = self.colors.borrow_mut();
let Colors::Known(colors) = &mut *colors else { return Shade::Keep };
colors.advance(lines, offsets, upto);
colors.role_at(offset).map_or(Shade::Plain, Shade::Role)
}
}
pub(super) enum Shade {
Keep,
Plain,
Role(Role),
}
pub(super) fn paint_row(row: &Row, mut shade: impl FnMut(usize) -> Shade) -> Line<'static> {
let mut spans: Vec<Span<'static>> = Vec::new();
let mut column = 0;
for span in &row.line.spans {
for ch in span.content.chars() {
let style = match row.cells.get(column).copied().flatten().map_or(Shade::Keep, &mut shade) {
Shade::Role(role) => span.style.patch(role.style()),
Shade::Plain => span.style.fg(Color::Reset),
Shade::Keep => span.style,
};
column += ch.width().unwrap_or(0);
match spans.last_mut() {
Some(last) if last.style == style => last.content.to_mut().push(ch),
_ => spans.push(Span::styled(ch.to_string(), style)),
}
}
}
Line::from(spans).style(row.line.style)
}