use std::{borrow::Cow, ops::Range};
use serde::{Deserialize, Serialize};
use super::{Anchor, Change, Dialect, Reading, apply, parse, plain_text, reading, slug};
use crate::{RepoPath, text};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BlockKind {
Prose,
BulletList,
NumberedList,
Table,
Code,
Blockquote,
Image,
Region,
Html,
ThematicBreak,
References,
Group,
Heading,
}
impl BlockKind {
pub fn name(self) -> &'static str {
match self {
BlockKind::Prose => "prose",
BlockKind::BulletList => "bullet-list",
BlockKind::NumberedList => "numbered-list",
BlockKind::Table => "table",
BlockKind::Code => "code",
BlockKind::Blockquote => "blockquote",
BlockKind::Image => "image",
BlockKind::Region => "region",
BlockKind::Html => "html",
BlockKind::ThematicBreak => "thematic-break",
BlockKind::References => "references",
BlockKind::Group => "group",
BlockKind::Heading => "heading",
}
}
pub fn name_in(self, dialect: &Dialect) -> &'static str {
match (self, dialect.region) {
(BlockKind::Region, Some(region)) => region,
_ => self.name(),
}
}
pub(crate) fn spoken_in(self, dialect: &Dialect) -> String {
let name = self.name_in(dialect);
format!("{} {name}", text::article(name))
}
pub fn parse_in(s: &str, dialect: &Dialect) -> Option<Self> {
if dialect.region == Some(s) {
return Some(BlockKind::Region);
}
Self::parse(s).filter(|k| *k != BlockKind::Region)
}
pub fn parse(s: &str) -> Option<Self> {
[
BlockKind::Prose,
BlockKind::BulletList,
BlockKind::NumberedList,
BlockKind::Table,
BlockKind::Code,
BlockKind::Blockquote,
BlockKind::Image,
BlockKind::Region,
BlockKind::Html,
BlockKind::ThematicBreak,
BlockKind::References,
BlockKind::Group,
]
.into_iter()
.find(|k| k.name() == s)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlockDetail {
None,
Code {
lang: String,
fence: usize,
},
Table {
columns: Vec<String>,
#[serde(default)]
readings: Vec<String>,
},
Region {
target: String,
},
Quote {
headings: Vec<Heading>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Block {
pub kind: BlockKind,
pub line: usize,
pub end_line: usize,
pub units: Vec<Unit>,
pub detail: BlockDetail,
pub html_lines: Vec<usize>,
}
impl Block {
pub(crate) fn new(kind: BlockKind, line: usize, end_line: usize, units: Vec<Unit>) -> Self {
Block {
kind,
line,
end_line,
units,
detail: BlockDetail::None,
html_lines: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Unit {
pub text: String,
#[serde(default)]
pub reading: Reading,
pub line: usize,
#[serde(default)]
pub end_line: usize,
pub nested: Vec<Block>,
#[serde(default)]
pub pieces: Vec<Piece>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Piece {
pub offset: usize,
pub line: usize,
pub col: usize,
}
impl Unit {
pub(crate) fn leaf(text: String, line: usize, end_line: usize) -> Self {
Unit {
reading: Reading::written(&text),
text,
line,
end_line,
nested: Vec::new(),
pieces: Vec::new(),
}
}
pub fn position(&self, offset: usize) -> Option<(usize, usize)> {
position(&self.pieces, offset)
}
pub(crate) fn in_joint(&self, offset: usize) -> bool {
self.pieces
.iter()
.find(|p| p.offset > offset)
.and_then(|next| self.text.get(offset..next.offset))
.is_some_and(|gap| !gap.is_empty() && gap.bytes().all(|b| b == b' ' || b == b'|'))
}
pub(crate) fn position_after(&self, offset: usize) -> Option<(usize, usize)> {
let piece = self.pieces.iter().find(|p| p.offset >= offset)?;
Some((piece.line, piece.col))
}
}
pub(super) fn position(pieces: &[Piece], offset: usize) -> Option<(usize, usize)> {
let piece = pieces.iter().rev().find(|p| p.offset <= offset)?;
Some((piece.line, piece.col + (offset - piece.offset)))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Heading {
pub level: u8,
pub text: String,
#[serde(default)]
pub reading: Reading,
pub slug: String,
pub line: usize,
pub end_line: usize,
pub setext: bool,
}
impl Heading {
pub(crate) fn new(
level: u8,
text: String,
reading: Reading,
(line, end_line): (usize, usize),
setext: bool,
) -> Self {
Heading {
level,
reading,
slug: slug(&plain_text(&text)),
text,
line,
end_line,
setext,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum LinkTarget {
Host(String),
Reference(String),
Repo {
path: RepoPath,
fragment: Option<String>,
#[serde(default)]
dir: bool,
},
Relative {
target: String,
fragment: Option<String>,
},
Url(String),
Anchor(String),
Invalid(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Link {
pub target: LinkTarget,
pub line: usize,
pub is_image: bool,
#[serde(default)]
pub end_line: usize,
#[serde(default)]
pub inline: Option<String>,
}
impl Link {
pub fn lines(&self) -> (usize, usize) {
(self.line, self.end_line.max(self.line))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CodeBlock {
pub bytes: Range<usize>,
pub fenced: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Body {
pub blocks: Vec<Block>,
pub headings: Vec<Heading>,
pub links: Vec<Link>,
pub footnote_refs: Vec<(String, usize)>,
pub footnote_defs: Vec<(String, usize)>,
pub ref_defs: Vec<(String, String, usize)>,
pub inline_html: Vec<usize>,
pub fenced: Vec<(usize, usize)>,
#[serde(default)]
pub code_blocks: Vec<CodeBlock>,
#[serde(default)]
pub code_spans: Vec<(usize, usize, usize)>,
#[serde(default)]
pub link_spans: Vec<(usize, usize, usize)>,
#[serde(default)]
pub anchors: Vec<Anchor>,
#[serde(default)]
pub reading_changes: Vec<(usize, usize, usize, String)>,
pub first_line: usize,
}
impl Body {
pub fn nested_headings(&self) -> Vec<Heading> {
let mut out = headings_in(&self.blocks);
out.sort_by_key(|h| h.line);
out
}
pub fn blocks_between(&self, from: usize, to: usize) -> Vec<&Block> {
self.blocks
.iter()
.filter(|b| b.line > from && b.line < to)
.collect()
}
pub fn in_code(&self, line: usize) -> bool {
self.fenced.iter().any(|&(s, e)| s <= line && line <= e)
}
pub fn clean_line<'a>(&self, line: usize, text: &'a str) -> std::borrow::Cow<'a, str> {
let mut on_line: Vec<&Anchor> = self.anchors.iter().filter(|a| a.line == line).collect();
if on_line.is_empty() {
return std::borrow::Cow::Borrowed(text);
}
on_line.sort_by_key(|a| std::cmp::Reverse(a.raw_col));
let mut out = text.to_string();
for a in on_line {
let end = a.raw_col + a.rendered().len();
if end <= out.len() && out.is_char_boundary(a.raw_col) && out.is_char_boundary(end) {
out.replace_range(a.raw_col..end, "");
}
}
std::borrow::Cow::Owned(out)
}
pub fn read_line(&self, line: usize, text: &str) -> Reading {
let first = self.reading_changes.partition_point(|c| c.0 < line);
let changes: Vec<Change> = self.reading_changes[first..]
.iter()
.take_while(|c| c.0 == line)
.map(|(_, start, end, with)| Change {
range: *start..*end,
with: with.clone(),
})
.collect();
apply(text, &changes)
}
pub fn in_code_span(&self, line: usize, col: usize) -> bool {
self.code_spans
.iter()
.any(|&(l, s, e)| l == line && s <= col && col < e)
}
pub(crate) fn code_in(&self, unit: &Unit) -> Vec<std::ops::Range<usize>> {
let mut out = Vec::new();
for (k, piece) in unit.pieces.iter().enumerate() {
let next = unit.pieces.get(k + 1);
let width = next.map_or(unit.text.len(), |p| p.offset) - piece.offset;
let mut stop_col = piece.col + width;
if let Some(p) = next.filter(|p| p.line == piece.line) {
stop_col = stop_col.min(p.col);
}
let first = self
.code_spans
.partition_point(|&(line, _, _)| line < piece.line);
for &(_, start, end) in self.code_spans[first..]
.iter()
.take_while(|&&(line, _, _)| line == piece.line)
{
let from = start.max(piece.col);
let to = end.min(stop_col);
if from < to {
out.push(piece.offset + (from - piece.col)..piece.offset + (to - piece.col));
}
}
}
out
}
pub fn span_around(&self, line: usize, col: usize) -> Option<usize> {
self.code_spans
.iter()
.chain(&self.link_spans)
.filter(|&&(l, s, e)| l == line && s < col && col < e)
.map(|&(_, s, _)| s)
.min()
}
pub fn mask_spans<'a>(&self, line: usize, text: &'a str) -> Cow<'a, str> {
let lead = text.len() - parse::strip_prefix(text).len();
let spans: Vec<std::ops::Range<usize>> = self
.code_spans
.iter()
.filter(|&&(l, _, _)| l == line)
.map(|&(_, s, e)| if s == 0 { lead.min(e)..e } else { s..e })
.collect();
mask_code(text, &spans)
}
}
pub(crate) fn mask_code<'a>(text: &'a str, code: &[std::ops::Range<usize>]) -> Cow<'a, str> {
if code.is_empty() {
return Cow::Borrowed(text);
}
let mut out = text.to_string();
for r in code {
let start = text.floor_char_boundary(r.start.min(text.len()));
let end = text.ceil_char_boundary(r.end.min(text.len()));
out.replace_range(start..end, &"`".repeat(end - start));
}
Cow::Owned(out)
}
pub(super) fn headings_in(blocks: &[Block]) -> Vec<Heading> {
let mut out = Vec::new();
for b in blocks {
match (&b.kind, &b.detail) {
(BlockKind::Heading, _) => out.extend(b.units.iter().map(nested_heading)),
(_, BlockDetail::Quote { headings }) => out.extend(headings.iter().cloned()),
_ => {
for u in &b.units {
out.extend(headings_in(&u.nested));
}
}
}
}
out
}
fn nested_heading(unit: &Unit) -> Heading {
let (hashes, text) = unit.text.split_once(' ').unwrap_or((&unit.text, ""));
let level = u8::try_from(hashes.len()).unwrap_or(6);
Heading::new(
level,
text.to_string(),
reading(text),
(unit.line, unit.end_line),
unit.end_line > unit.line,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_headings_are_the_headings_inside_an_item_or_a_quote() {
let text = "# Top\n\n> ## Inner\n>\n> Text.\n\n- ## In item\n- Set\n text\n ---\n";
let segments = crate::markdown::segments(text, 1, &Dialect::default());
let body = crate::markdown::parse(text, 1, &segments, &Dialect::default());
let nested = body.nested_headings();
let seen: Vec<(usize, u8, &str, &str)> = nested
.iter()
.map(|h| (h.line, h.level, h.text.as_str(), h.slug.as_str()))
.collect();
assert_eq!(
seen,
vec![
(3, 2, "Inner", "inner"),
(7, 2, "In item", "in-item"),
(8, 2, "Set text", "set-text")
]
);
assert_eq!(body.headings.len(), 1);
}
#[test]
fn kinds_round_trip_through_their_names() {
for name in [
"prose",
"bullet-list",
"numbered-list",
"table",
"code",
"blockquote",
"image",
"region",
"html",
"thematic-break",
"references",
"group",
] {
assert_eq!(BlockKind::parse(name).unwrap().name(), name);
}
assert!(BlockKind::parse("paragraph").is_none());
let host = Dialect {
region: Some("include"),
..Dialect::default()
};
assert_eq!(
BlockKind::parse_in("include", &host),
Some(BlockKind::Region)
);
assert_eq!(BlockKind::parse_in("region", &host), None);
assert_eq!(BlockKind::Region.name_in(&host), "include");
assert_eq!(BlockKind::parse_in("include", &Dialect::default()), None);
}
#[test]
fn blocks_between_and_in_code() {
let block = |line| Block {
kind: BlockKind::Prose,
line,
end_line: line,
units: vec![],
detail: BlockDetail::None,
html_lines: vec![],
};
let body = Body {
blocks: vec![block(2), block(5), block(9)],
fenced: vec![(4, 6)],
..Body::default()
};
let lines: Vec<usize> = body.blocks_between(1, 9).iter().map(|b| b.line).collect();
assert_eq!(lines, vec![2, 5]);
assert!(body.in_code(5));
assert!(!body.in_code(7));
}
}