//! TABLES — Markdown pipe tables, read into rows and cells for the phone to //! draw as a real table, and edited by row, column and cell. //! //! A table is a header line holding a `|`, then a delimiter line of as many //! cells, each `---` with an optional `:` either side (`:--` left, `:-:` //! centre, `--:` right), then every following line that holds a `|`, until a //! blank line or a line of another kind. Leading and trailing pipes are //! optional; `\|` is a pipe inside a cell. A body row with fewer cells has //! empty ones; extra cells are kept as written but drawn in no column. //! //! The edits ([`super::format::Action`]) rewrite the whole table neatly //! (`| a | b |`, one space inside each edge) only when its shape changes; a //! cell edit replaces that cell's words alone. use serde::{Deserialize, Serialize}; use super::Offsets; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Align { None, Left, Center, Right, } /// One cell, UTF-16: where its words are (trimmed; an empty cell is an empty /// range where words would go) and the words themselves. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Cell { pub start: u32, pub end: u32, pub text: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Table { /// UTF-16 range of the whole table. pub start: u32, pub end: u32, pub align: Vec, /// The header row first, then the body rows; the delimiter line is not a row. pub rows: Vec>, } /// One cell in bytes. #[derive(Debug, Clone, PartialEq)] pub(crate) struct RawCell { pub start: usize, pub end: usize, } /// The cells of a row line, in bytes: each cell's trimmed words. pub(crate) fn cells(text: &str, start: usize, end: usize) -> Vec { let bytes = text.as_bytes(); let mut bars = Vec::new(); let mut k = start; let mut code = false; while k < end { match bytes[k] { b'\\' => k += 1, b'`' => code = !code, b'|' if !code => bars.push(k), _ => {} } k += 1; } let mut edges = vec![]; let trimmed_start = start + text[start..end].len() - text[start..end].trim_start().len(); let trimmed_end = start + text[start..end].trim_end().len(); let leads = bars.first() == Some(&trimmed_start); let trails = bars.last().is_some_and(|&bar| bar + 1 == trimmed_end) && !(leads && bars.len() == 1); let mut from = if leads { trimmed_start + 1 } else { start }; for (index, &bar) in bars.iter().enumerate() { if leads && index == 0 { continue; } edges.push((from, bar)); from = bar + 1; } if !trails { edges.push((from, end)); } edges .into_iter() .map(|(a, b)| { let words = &text[a..b]; let lead = words.len() - words.trim_start().len(); let s = a + lead; let e = (a + words.trim_end().len()).max(s); // An empty cell: its words go after the first space, when there is one. if s == e { let at = if b > a + 1 { a + 1 } else { a }; RawCell { start: at, end: at } } else { RawCell { start: s, end: e } } }) .collect() } /// A delimiter row's alignments, or none when the line is not one. pub(crate) fn delimiter(text: &str, start: usize, end: usize) -> Option> { let line = &text[start..end]; if !line.contains('-') || !line.bytes().all(|b| matches!(b, b'|' | b'-' | b':' | b' ' | b'\t')) { return None; } let cells = cells(text, start, end); let mut out = Vec::with_capacity(cells.len()); for cell in cells { let said = text[cell.start..cell.end].trim(); if said.is_empty() || !said.trim_matches(':').bytes().all(|b| b == b'-') || said.trim_matches(':').is_empty() { return None; } out.push(match (said.starts_with(':'), said.ends_with(':')) { (true, true) => Align::Center, (true, false) => Align::Left, (false, true) => Align::Right, (false, false) => Align::None, }); } Some(out) } pub(crate) fn to_table(text: &str, offsets: &Offsets, rows: &[(usize, usize)], align: Vec, whole: (usize, usize)) -> Table { Table { start: offsets.u16(whole.0), end: offsets.u16(whole.1), rows: rows .iter() .map(|&(s, e)| { let mut row: Vec = cells(text, s, e).into_iter().map(|cell| Cell { start: offsets.u16(cell.start), end: offsets.u16(cell.end), text: unescape(&text[cell.start..cell.end]) }).collect(); row.truncate(align.len()); while row.len() < align.len() { let at = offsets.u16(e); row.push(Cell { start: at, end: at, text: String::new() }); } row }) .collect(), align, } } pub(crate) fn unescape(cell: &str) -> String { cell.replace("\\|", "|") } pub(crate) fn escape(cell: &str) -> String { cell.replace('\n', " ").replace('|', "\\|") } /// A table written neatly from its cells (header, delimiter, body). pub(crate) fn write(align: &[Align], rows: &[Vec]) -> String { let mut out = String::new(); for (index, row) in rows.iter().enumerate() { out.push('|'); for cell in row { out.push(' '); out.push_str(cell); out.push_str(" |"); } out.push('\n'); if index == 0 { out.push('|'); for a in align { out.push_str(match a { Align::None => " --- |", Align::Left => " :-- |", Align::Center => " :-: |", Align::Right => " --: |", }); } out.push('\n'); } } out.pop(); out }