1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//! Document model: the source text split into Markdown blocks with byte ranges.
//!
//! The parser is `pulldown-cmark`; this module only walks its event stream and records where
//! each top-level block starts and ends, and, as [`Blocks`] asks, where the items of a
//! top-level list, quote or definition list, or the rows of a top-level table, do.
//! Everything downstream (rendering, anchoring, hit-testing) is keyed by block index and byte
//! range. Nothing here knows what a heading or a list *is*.
use std::ops::Range;
use std::sync::OnceLock;
use plannotator_tui_schema::{DocumentSource, Provenance};
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};
use serde::{Deserialize, Serialize};
mod items;
use items::Items;
/// `[ui.blocks]`: how much of a document one block is, for moving, commenting and
/// clearing, per kind of top-level block. The default cuts as Plannotator does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct Blocks {
/// Each item of a list is a block, and keeps the lists nested in it.
pub(crate) lists: Cut,
/// Each block inside a quote is a block.
pub(crate) quotes: Cut,
/// Each term of a definition list is a block, with its definitions.
pub(crate) definitions: Cut,
/// The header of a table is a block, and each row below it.
pub(crate) tables: Cut,
}
/// Whether a kind of top-level block is one block or is split into its items or rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Cut {
Whole,
Split,
}
impl Blocks {
/// Every kind whole: a top-level block is always one block.
#[cfg(test)]
pub(crate) const WHOLE: Self =
Self { lists: Cut::Whole, quotes: Cut::Whole, definitions: Cut::Whole, tables: Cut::Whole };
/// Every kind split into its items.
pub(crate) const SPLIT: Self =
Self { lists: Cut::Split, quotes: Cut::Split, definitions: Cut::Split, tables: Cut::Split };
}
impl Default for Blocks {
fn default() -> Self {
Self { quotes: Cut::Whole, tables: Cut::Whole, ..Self::SPLIT }
}
}
static BLOCKS: OnceLock<Blocks> = OnceLock::new();
/// Cut every document this process opens as `blocks` says. The first call wins; tests and
/// headless runs get the default.
pub(crate) fn install(blocks: Blocks) {
let _ = BLOCKS.set(blocks);
}
fn installed() -> Blocks {
BLOCKS.get().copied().unwrap_or_default()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BlockKind {
Heading,
Paragraph,
List,
CodeBlock,
BlockQuote,
Table,
DefinitionList,
Rule,
Html,
Other,
}
impl BlockKind {
/// Code and tables keep their columns; everything else word-wraps.
pub(crate) fn preserves_columns(self) -> bool {
matches!(self, BlockKind::CodeBlock | BlockKind::Table)
}
}
#[derive(Debug, Clone)]
pub(crate) struct Block {
pub(crate) range: Range<usize>,
/// An item's kind is its container's: a list item is a `List` block, a row a `Table`.
pub(crate) kind: BlockKind,
pub(crate) opening: Opening,
/// Index of the top-level Markdown block this one is, or is an item or row of.
/// Annotations keep it as their block hint, so the hint doesn't depend on [`Blocks`].
pub(crate) top: usize,
/// Whether the block is drawn right under the one before it, with no row between: an
/// item of a list or a term of a definition list after the first, as the whole list
/// draws them, or a table row after the header.
pub(crate) joined: bool,
/// An item of a loose list. The list's looseness decides how each item's text is drawn,
/// and an item read on its own may look tight.
pub(crate) loose: bool,
}
/// What a block's opening tag says beyond its kind, passed on for the renderer's house style.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum Opening {
#[default]
Plain,
/// A heading's level, 1 to 6.
Heading(u8),
/// A code block's info string: the words after the opening fence, empty for none.
Code(Box<str>),
/// An ordered list item's number in its list, which its own marker may not say: a list
/// written `1.` `1.` `1.` counts 1, 2, 3.
Number(u64),
}
fn opening_of(tag: &Tag<'_>) -> Opening {
match tag {
Tag::Heading { level, .. } => Opening::Heading(*level as u8),
Tag::CodeBlock(CodeBlockKind::Fenced(info)) => Opening::Code(info.trim().into()),
Tag::CodeBlock(CodeBlockKind::Indented) => Opening::Code("".into()),
_ => Opening::Plain,
}
}
#[derive(Debug, Clone)]
pub(crate) struct Document {
pub(crate) source: String,
pub(crate) blocks: Vec<Block>,
}
/// The option set `tui-markdown` enables, so block boundaries agree with its renderer.
pub(crate) fn parse_options() -> Options {
Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_HEADING_ATTRIBUTES
| Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
| Options::ENABLE_SUPERSCRIPT
| Options::ENABLE_SUBSCRIPT
| Options::ENABLE_MATH
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_DEFINITION_LIST
| Options::ENABLE_GFM
| Options::ENABLE_TABLES
}
impl Document {
/// A file's text: YAML front matter at the top is metadata and is not shown.
pub(crate) fn parse(source: String) -> Self {
Self::parse_into(source, installed())
}
/// [`Document::parse`], cut as `blocks` says whatever is installed.
pub(crate) fn parse_into(source: String, blocks: Blocks) -> Self {
let blocks = split_blocks(&source, true, blocks);
Self { source, blocks }
}
/// The document for `source`. Only a file or a Workspaces document can carry front
/// matter; an agent's message or piped text is all content, even when it opens with `---`.
pub(crate) fn of(source: &DocumentSource) -> Self {
let front_matter =
matches!(source.provenance, Provenance::File { .. } | Provenance::Workspace { .. });
let blocks = split_blocks(&source.content, front_matter, installed());
Self { source: source.content.clone(), blocks }
}
/// Source text of block `index`. Empty for an out-of-range index.
pub(crate) fn block_text(&self, index: usize) -> &str {
self.blocks.get(index).map_or("", |b| &self.source[b.range.clone()])
}
/// The block whose range contains `offset`.
pub(crate) fn block_containing(&self, offset: usize) -> Option<usize> {
self.blocks.iter().position(|b| b.range.contains(&offset))
}
/// Whether `range` covers any of block `index`. A note belongs to every block it covers:
/// one made on a whole list is on each of its items.
pub(crate) fn overlaps(&self, index: usize, range: &Range<usize>) -> bool {
self.blocks.get(index).is_some_and(|block| {
if range.is_empty() {
block.range.contains(&range.start)
} else {
range.start < block.range.end && block.range.start < range.end
}
})
}
/// The top-level Markdown block whose range contains `offset`, the space between two of
/// its items included: the same index whatever [`Blocks`] the document was cut into.
pub(crate) fn top_block_containing(&self, offset: usize) -> Option<usize> {
let after = self.blocks.partition_point(|b| b.range.start <= offset);
let block = self.blocks.get(after.checked_sub(1)?)?;
let inside =
offset < block.range.end || self.blocks.get(after).is_some_and(|next| next.top == block.top);
inside.then_some(block.top)
}
}
fn kind_of(tag: &Tag<'_>) -> BlockKind {
match tag {
Tag::Heading { .. } => BlockKind::Heading,
Tag::Paragraph => BlockKind::Paragraph,
Tag::List(_) => BlockKind::List,
Tag::CodeBlock(_) => BlockKind::CodeBlock,
Tag::BlockQuote(_) => BlockKind::BlockQuote,
Tag::Table(_) => BlockKind::Table,
Tag::HtmlBlock => BlockKind::Html,
Tag::DefinitionList => BlockKind::DefinitionList,
_ => BlockKind::Other,
}
}
/// Bytes of the YAML front matter that opens `source`, or 0 when it has none. Front matter
/// starts on the first line and must close; `pulldown-cmark` takes a metadata block at any
/// unindented `---` line, so it is only asked about the first one.
fn front_matter_len(source: &str) -> usize {
if !source.starts_with("---") {
return 0;
}
match Parser::new_ext(source, Options::ENABLE_YAML_STYLE_METADATA_BLOCKS).into_offset_iter().next() {
Some((Event::Start(Tag::MetadataBlock(_)), range)) if range.start == 0 => range.end,
_ => 0,
}
}
/// Walk the event stream and cut the source at depth-zero block boundaries, and at the
/// items of a top-level list, quote or definition list, or the rows of a top-level table,
/// when `cut` asks. Front matter, when `front_matter` allows it, is never a block; every
/// later `---` is Markdown.
fn split_blocks(source: &str, front_matter: bool, cut: Blocks) -> Vec<Block> {
let mut blocks = Vec::new();
let mut depth = 0usize;
let mut open: Option<(usize, BlockKind, Opening)> = None;
let mut items = Items::default();
let mut tops = 0;
let body = if front_matter { front_matter_len(source) } else { 0 };
let mut options = parse_options();
options.remove(Options::ENABLE_YAML_STYLE_METADATA_BLOCKS);
for (event, range) in Parser::new_ext(&source[body..], options).into_offset_iter() {
let range = range.start + body..range.end + body;
let leaf = |kind| Block {
range: range.clone(),
kind,
opening: Opening::Plain,
top: tops,
joined: false,
loose: false,
};
match event {
Event::Start(tag) => {
if depth == 0 {
open = Some((range.start, kind_of(&tag), opening_of(&tag)));
items = Items::of(&tag, cut);
} else if depth == 1 {
items.start(&tag, &range);
} else {
if depth == 2 {
items.inner(&tag);
}
items.inside(Some(&tag), &range);
}
depth += 1;
}
Event::End(_) => {
depth = depth.saturating_sub(1);
if depth == 0
&& let Some((start, kind, opening)) = open.take()
{
let whole = Block {
range: start..items.end(kind, start, range.end),
kind,
opening,
top: tops,
joined: false,
loose: false,
};
match items.blocks(source, &whole) {
Some(each) => blocks.extend(each),
None => blocks.push(whole),
}
tops += 1;
}
}
Event::Rule if depth == 0 => {
blocks.push(leaf(BlockKind::Rule));
tops += 1;
}
// Any other depth-zero leaf (rare: stray html/text) becomes its own block.
_ if depth == 0 => {
blocks.push(leaf(BlockKind::Other));
tops += 1;
}
_ if depth == 1 => items.leaf(&range),
_ => items.inside(None, &range),
}
}
// A definition list never runs into the block after it, nor keeps the blank lines before.
let starts: Vec<usize> = blocks.iter().skip(1).map(|b| b.range.start).collect();
for (block, next) in blocks.iter_mut().zip(starts) {
if block.kind == BlockKind::DefinitionList {
block.range.end = block.range.end.min(next).max(block.range.start);
}
}
// Trailing newlines are not part of a block's text: quotes stay stable across files
// that differ only in final-newline conventions.
for block in &mut blocks {
let text = &source[block.range.clone()];
let trimmed = match block.kind {
BlockKind::DefinitionList => text.trim_end_matches([' ', '\t', '\n', '\r']),
_ => text.trim_end_matches(['\n', '\r']),
};
block.range.end = block.range.start + trimmed.len();
}
blocks.retain(|b| !b.range.is_empty());
// Count the top-level blocks that are left, so a block's `top` is its index when whole.
let mut previous = None;
let mut top = 0;
for block in &mut blocks {
if previous != Some(block.top) {
top += usize::from(previous.is_some());
previous = Some(block.top);
}
block.top = top;
}
blocks
}
#[cfg(test)]
mod tests;