//! Syntax-level passes shared by search, the section store, and notebooks. //! //! [`flatten_document`] turns Typst markup into plain text per block with a //! byte map back to the raw source, so FTS hits land in the editor. //! [`extract_sections`] finds `#typbase.section(kind: "...")[...]` calls and //! reports their content ranges, populating the page doc's `sections` list. //! [`extract_cells`] finds notebook cell attributes (`//%`) and reports their //! spans in UTF-16, ready for CodeMirror. use serde::{Deserialize, Serialize}; use tsify::Tsify; use typst_syntax::{ LinkedNode, SyntaxKind, ast::{Arg, AstNode, Expr, FuncCall}, }; /// One flattened source block. `map[i]` is the raw byte offset of plain byte /// `i`. FTS offsets in `plain` translate through it to editor positions. #[derive(Tsify, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct FlattenedBlock { pub kind: String, pub plain: String, pub range_start: usize, pub range_end: usize, pub map: Vec, } /// A `#typbase.section(kind: ...)[...]` block. Ranges are raw source bytes. /// `content_start..content_end` is the markup inside the brackets. #[derive(Tsify, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct SectionSpan { pub kind: String, pub content_start: usize, pub content_end: usize, pub full_start: usize, pub full_end: usize, pub title: String, } /// A top-level heading for the page outline. Ranges are UTF-16 offsets into /// the raw source, so they are editor positions. #[derive(Tsify, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct HeadingSpan { /// 1 through 6, from the number of `=` markers. pub level: u8, /// Heading text with markup markers removed. pub title: String, /// UTF-16 range of the whole heading line. pub from: usize, pub to: usize, } /// One math equation, in UTF-16 offsets into the raw source. #[derive(Tsify, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct EquationSpan { pub from: usize, pub to: usize, } /// One code expression embedded with `#`, in UTF-16 offsets into the raw /// source. The editor sets these ranges in a monospaced face. #[derive(Tsify, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct CodeSpan { pub from: usize, pub to: usize, } /// A notebook cell: one `//%` attribute line plus the content below it, up to /// the next boundary or the end of the document. Ranges are UTF-16 offsets into /// the raw source, so they can be used as editor positions directly. #[derive(Tsify, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct CellSpan { /// `"prose"`, `"code"`, `"log"`, or `"hidden"`. pub kind: String, /// `name=` from the attribute line, when it has one. pub name: Option, /// Attribute line range, excluding the newline. Both zero on a cell that /// began at a heading and on the implicit cell above the first boundary. pub marker_start: usize, pub marker_end: usize, /// Content range. Blank lines below the content belong to the gap before /// the next boundary and are excluded. pub content_start: usize, pub content_end: usize, } /// Flattens a whole document into per-block plain text. pub fn flatten_document(text: &str) -> Vec { let root = typst_syntax::parse(text); flatten_document_root(&root, text) } /// `flatten_document` over a tree the caller already has. pub fn flatten_document_root(root: &typst_syntax::SyntaxNode, text: &str) -> Vec { let linked = LinkedNode::new(root); let children: Vec = linked.children().collect(); let mut out = Vec::new(); let mut run: Vec = Vec::new(); // Inline markup splits prose across several top-level nodes (Text/"Strong" // etc), so gather a run of flow nodes into one paragraph block. Block // starts (headings, list items, raw, math) each get their own block. for child in &children { match child.kind() { SyntaxKind::Heading | SyntaxKind::ListItem | SyntaxKind::EnumItem | SyntaxKind::TermItem | SyntaxKind::Raw | SyntaxKind::Equation | SyntaxKind::Math => { emit_run(&mut run, &mut out, text, "paragraph"); emit_node(child, &mut out, text); } SyntaxKind::Parbreak => { emit_run(&mut run, &mut out, text, "paragraph"); } _ => run.push(child.clone()), } } emit_run(&mut run, &mut out, text, "paragraph"); out } fn emit_run(run: &mut Vec, out: &mut Vec, text: &str, kind: &str) { if run.is_empty() { return; } let first = run.first().unwrap(); let last = run.last().unwrap(); let range = first.range().start..last.range().end; let mut plain = String::new(); let mut map = Vec::new(); for node in run.drain(..) { flatten_node(&node, text, &mut plain, &mut map); } push_block(out, kind.to_string(), plain, map, range, text); } fn emit_node(node: &LinkedNode, out: &mut Vec, text: &str) { let kind = block_kind(node.kind()); let range = node.range(); let mut plain = String::new(); let mut map = Vec::new(); flatten_node(node, text, &mut plain, &mut map); push_block(out, kind, plain, map, range, text); } fn push_block( out: &mut Vec, kind: String, plain: String, map: Vec, range: std::ops::Range, _text: &str, ) { if plain.trim().is_empty() { return; } // Trim keeps the map aligned: drop the same window from both. let leading = plain.len() - plain.trim_start().len(); let trailing = plain.len() - plain.trim_end().len(); let plain = plain.trim().to_string(); let map = if leading == 0 && trailing == 0 { map } else { let end = map.len() - trailing.min(map.len()); map[leading.min(map.len())..end].to_vec() }; out.push(FlattenedBlock { kind, plain, range_start: range.start, range_end: range.end, map, }); } fn block_kind(kind: SyntaxKind) -> String { match kind { SyntaxKind::Heading => "heading", SyntaxKind::ListItem | SyntaxKind::EnumItem | SyntaxKind::TermItem => "list", SyntaxKind::Raw => "raw", SyntaxKind::Equation | SyntaxKind::Math => "math", _ => "other", } .to_string() } /// Recursively collects leaf text, skipping markup markers. Plain bytes and /// raw byte offsets stay in lockstep. fn flatten_node(node: &LinkedNode, src: &str, plain: &mut String, map: &mut Vec) { match node.kind() { SyntaxKind::Text | SyntaxKind::Code | SyntaxKind::Space | SyntaxKind::Linebreak | SyntaxKind::MathIdent | SyntaxKind::MathText | SyntaxKind::Str => { let range = node.range(); let Some(chunk) = src.get(range.clone()) else { return; }; if chunk == "\n" { plain.push(' '); map.push(range.start as u32); } else { plain.push_str(chunk); map.extend(range.clone().map(|offset| offset as u32)); } } _ => { for child in node.children() { flatten_node(&child, src, plain, map); } } } } /// Finds every `typbase.section` call and its content block. pub fn extract_sections(text: &str) -> Vec { let root = typst_syntax::parse(text); extract_sections_root(&root, text) } /// `extract_sections` over a tree the caller already has. pub fn extract_sections_root(root: &typst_syntax::SyntaxNode, text: &str) -> Vec { let mut sections = Vec::new(); let mut stack = vec![LinkedNode::new(root)]; while let Some(node) = stack.pop() { if let Some(call) = node.get().cast::() { if is_section_call(&call) { if let Some(span) = section_span(&call, &node, text) { sections.push(span); } } } for child in node.children() { stack.push(child); } } sections.sort_by_key(|section| section.content_start); sections } /// Finds every top-level heading for the outline. Titles have markup markers /// stripped and labels skipped. One UTF-16 pass over the source converts every /// range together, so a long note does not rescan the text per heading. pub fn extract_headings(text: &str) -> Vec { let root = typst_syntax::parse(text); extract_headings_root(&root, text) } /// `extract_headings` over a tree the caller already has. pub fn extract_headings_root(root: &typst_syntax::SyntaxNode, text: &str) -> Vec { let linked = LinkedNode::new(root); let mut found: Vec<(u8, String, std::ops::Range)> = Vec::new(); for node in linked.children() { if node.kind() != SyntaxKind::Heading { continue; } let range = node.range(); let level = text[range.clone()] .bytes() .take_while(|byte| *byte == b'=') .count() .clamp(1, 6) as u8; let mut plain = String::new(); let mut map = Vec::new(); for child in node.children() { // `