text_document/lib.rs
1//! # text-document
2//!
3//! A rich text document model for Rust.
4//!
5//! Provides a [`TextDocument`] as the main entry point and [`TextCursor`] for
6//! cursor-based editing, inspired by Qt's QTextDocument/QTextCursor API.
7//!
8//! ```rust,no_run
9//! use text_document::{TextDocument, MoveMode, MoveOperation};
10//!
11//! let doc = TextDocument::new();
12//! doc.set_plain_text("Hello world").unwrap();
13//!
14//! let cursor = doc.cursor();
15//! cursor.move_position(MoveOperation::EndOfWord, MoveMode::KeepAnchor, 1);
16//! cursor.insert_text("Goodbye").unwrap(); // replaces "Hello"
17//!
18//! // Multiple cursors on the same document
19//! let c1 = doc.cursor();
20//! let c2 = doc.cursor_at(5);
21//! c1.insert_text("A").unwrap();
22//! // c2's position is automatically adjusted
23//!
24//! doc.undo().unwrap();
25//! ```
26
27mod backend;
28mod batch;
29mod convert;
30mod cursor;
31mod document;
32mod error;
33mod events;
34mod flow;
35mod fragment;
36mod highlight;
37mod inner;
38mod link_extent;
39mod operation;
40
41mod streaming;
42mod text_block;
43mod text_frame;
44mod text_list;
45mod text_table;
46pub mod transient;
47pub use transient::TransientLayerId;
48
49// ── Re-exports from entity DTOs (enums that consumers need) ──────
50pub use backend::DocumentBackend;
51pub use frontend::block::dtos::{Alignment, MarkerType};
52pub use frontend::block::dtos::{CharVerticalAlignment, InlineContent, UnderlineStyle};
53pub use frontend::common::format_runs::ReplaceFormatPolicy;
54pub use frontend::common::parser_tools::{
55 CommentReply, CountMethod, DjotExportOptions, DjotImportOptions, DocumentComment,
56 DocumentComments, DocumentMark, DocumentMarks, DocxExportOptions, DocxHeadingStyle,
57 EpubExportOptions, ExportImage, ExportImages, HTML_FOOTNOTE_ATTR, HtmlExportOptions,
58 HtmlImageMode, LINE_SEPARATOR, LatexExportOptions, MAX_BOOKMARK_NAME_LEN,
59 MarkdownExportOptions, OdtExportOptions, OdtHeadingStyle, PdfExportOptions,
60 PlainTextExportOptions, Sentence, TABLE_ANCHOR, WordCharCounts, count, count_djot,
61 djot_round_trip_is_lossy, djot_to_plain_text, escape_djot_inline, guard_djot_block_start,
62 needs_djot_escaping, plain_text_to_djot, sentence_bounds, sentences,
63};
64
65/// The matcher, as a pure function over `&str` — no document, no store, no threads.
66///
67/// A host app searching a whole project cannot afford to build a document per row just
68/// to ask "does this contain that": it would parse every scene in the manuscript on
69/// every keystroke. It extracts the prose cheaply and matches it here instead.
70///
71/// Exposing it is what keeps there being **one** definition of a match. An app that
72/// rolled its own would disagree with this crate's in-document find about whole-word
73/// rules and case folding, and a writer would meet that as "the editor found it but the
74/// search panel didn't".
75/// The same goes for **folding** and for **case preservation**: an app that lowercased its
76/// own corpus would miss `Straße` and half-rename a Turkish manuscript. `FoldLocale` is how
77/// a per-scene language reaches the fold.
78/// [`FoldedText`](matching::FoldedText) is the *prepared* form: a haystack folded once and
79/// searched many times. A search box re-searches the same corpus on every keystroke, and
80/// folding it costs several times what scanning it does — so an app that searches a whole
81/// project keeps one of these per scene rather than rebuilding the fold per character typed.
82pub mod matching {
83 pub use frontend::document_search::matching::{
84 FoldLocale, FoldSpec, FoldedText, Match, MatchOptions, find_all, preserve_case,
85 };
86}
87pub use frontend::document::dtos::{TextDirection, WrapMode};
88pub use frontend::frame::dtos::FramePosition;
89pub use frontend::list::dtos::ListStyle;
90pub use frontend::resource::dtos::ResourceType;
91
92// ── Error type ───────────────────────────────────────────────────
93pub use batch::BatchDocument;
94pub use error::{DocumentError, Result, TransientRefusal};
95
96// ── Public API types ─────────────────────────────────────────────
97pub use cursor::TextCursor;
98pub use document::TextDocument;
99pub use events::{DocumentEvent, EventHold, InsertionOrigin, Subscription};
100pub use fragment::DocumentFragment;
101pub use highlight::{
102 HighlightContext, HighlightFormat, HighlightMask, HighlightSpan, RangeHighlight, SessionId,
103 SessionVisibility, SyntaxHighlighter,
104};
105pub use operation::{
106 DocxExportResult, EpubExportResult, HtmlImportResult, MarkdownImportResult, OdtExportResult,
107 Operation, PdfExportResult,
108};
109
110// ── Layout engine API types ─────────────────────────────────────
111pub use flow::{
112 AddressablePiece, BlockSnapshot, CellFormat, CellRange, CellSnapshot, CellVerticalAlignment,
113 FlowElement, FlowElementSnapshot, FlowSnapshot, FormatChangeKind, FragmentContent, FrameRef,
114 FrameSnapshot, ListInfo, PaintHighlightSpan, SelectionKind, TableCellContext, TableCellRef,
115 TableFormat, TableSnapshot,
116};
117pub use link_extent::LinkExtent;
118pub use text_block::TextBlock;
119pub use text_frame::TextFrame;
120pub use text_list::TextList;
121pub use text_table::{TextTable, TextTableCell};
122
123// All public handle types are Send + Sync (all fields are Arc<Mutex<...>> + Copy).
124const _: () = {
125 #[allow(dead_code)]
126 fn assert_send_sync<T: Send + Sync>() {}
127 fn _assert_all() {
128 assert_send_sync::<TextDocument>();
129 assert_send_sync::<TextCursor>();
130 assert_send_sync::<TextBlock>();
131 assert_send_sync::<TextFrame>();
132 assert_send_sync::<TextTable>();
133 assert_send_sync::<TextTableCell>();
134 assert_send_sync::<TextList>();
135 }
136};
137
138// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
139// Color
140// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
141
142/// An RGBA color value. Each component is 0–255.
143#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
144pub struct Color {
145 pub red: u8,
146 pub green: u8,
147 pub blue: u8,
148 pub alpha: u8,
149}
150
151impl Color {
152 /// Create an opaque color (alpha = 255).
153 pub fn rgb(red: u8, green: u8, blue: u8) -> Self {
154 Self {
155 red,
156 green,
157 blue,
158 alpha: 255,
159 }
160 }
161
162 /// Create a color with explicit alpha.
163 pub fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
164 Self {
165 red,
166 green,
167 blue,
168 alpha,
169 }
170 }
171}
172
173// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
174// Public format types
175// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
176
177/// Character/text formatting. All fields are optional: `None` means
178/// "not set — inherit from the block's default or the document's default."
179#[derive(Debug, Clone, Default, PartialEq, Eq)]
180pub struct TextFormat {
181 pub font_family: Option<String>,
182 pub font_point_size: Option<u32>,
183 pub font_weight: Option<u32>,
184 pub font_bold: Option<bool>,
185 pub font_italic: Option<bool>,
186 pub font_underline: Option<bool>,
187 pub font_overline: Option<bool>,
188 pub font_strikeout: Option<bool>,
189 pub letter_spacing: Option<i32>,
190 pub word_spacing: Option<i32>,
191 pub underline_style: Option<UnderlineStyle>,
192 pub vertical_alignment: Option<CharVerticalAlignment>,
193 pub anchor_href: Option<String>,
194 pub anchor_names: Vec<String>,
195 pub is_anchor: Option<bool>,
196 pub tooltip: Option<String>,
197 /// Remove the range's link, rather than pointing it somewhere else.
198 ///
199 /// Every other field here merges — `None` means "leave this alone" — so
200 /// without a flag there is no way to express removal at all. Takes
201 /// precedence over `anchor_href`. Mirrors [`BlockFormat::clear_direction`].
202 ///
203 /// Write-only: reading a format back never sets it, since it describes an
204 /// edit rather than a state.
205 pub clear_link: bool,
206 pub foreground_color: Option<Color>,
207 pub background_color: Option<Color>,
208 pub underline_color: Option<Color>,
209}
210
211/// Block (paragraph) formatting. All fields are optional.
212#[derive(Debug, Clone, Default, PartialEq)]
213pub struct BlockFormat {
214 pub alignment: Option<Alignment>,
215 pub top_margin: Option<i32>,
216 pub bottom_margin: Option<i32>,
217 pub left_margin: Option<i32>,
218 pub right_margin: Option<i32>,
219 pub heading_level: Option<u8>,
220 pub indent: Option<u8>,
221 pub text_indent: Option<i32>,
222 pub marker: Option<MarkerType>,
223 pub tab_positions: Vec<i32>,
224 pub line_height: Option<f32>,
225 pub non_breakable_lines: Option<bool>,
226 /// Start this block on a new page, where the target format can paginate.
227 pub page_break_before: Option<bool>,
228 pub direction: Option<TextDirection>,
229 /// Unset the block's direction rather than setting one.
230 ///
231 /// Every other field merges (`None` = "don't change this"), so this
232 /// is the only way to take a paragraph back to automatic direction
233 /// detection once a direction has been stored. Wins over
234 /// `direction` if both are set.
235 pub clear_direction: bool,
236 pub background_color: Option<String>,
237 pub is_code_block: Option<bool>,
238 pub code_language: Option<String>,
239 /// Enable automatic + soft-hyphen hyphenation for this block.
240 pub hyphenate: Option<bool>,
241 /// Block natural language as an ISO 639-1 code (e.g. "en", "fr").
242 /// Selects the hyphenation dictionary.
243 pub language: Option<String>,
244}
245
246/// List formatting. All fields are optional: `None` means
247/// "not set — don't change this property."
248#[derive(Debug, Clone, Default, PartialEq, Eq)]
249pub struct ListFormat {
250 pub style: Option<ListStyle>,
251 pub indent: Option<u8>,
252 pub prefix: Option<String>,
253 pub suffix: Option<String>,
254}
255
256/// Frame formatting. All fields are optional.
257#[derive(Debug, Clone, Default, PartialEq, Eq)]
258pub struct FrameFormat {
259 pub height: Option<i32>,
260 pub width: Option<i32>,
261 pub top_margin: Option<i32>,
262 pub bottom_margin: Option<i32>,
263 pub left_margin: Option<i32>,
264 pub right_margin: Option<i32>,
265 pub padding: Option<i32>,
266 pub border: Option<i32>,
267 pub position: Option<FramePosition>,
268 pub is_blockquote: Option<bool>,
269}
270
271// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
272// Enums for cursor movement
273// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
274
275/// Controls whether a movement collapses or extends the selection.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum MoveMode {
278 /// Move both position and anchor — collapses selection.
279 MoveAnchor,
280 /// Move only position, keep anchor — creates or extends selection.
281 KeepAnchor,
282}
283
284/// Semantic cursor movement operations.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum MoveOperation {
287 NoMove,
288 Start,
289 End,
290 StartOfLine,
291 EndOfLine,
292 StartOfBlock,
293 EndOfBlock,
294 StartOfWord,
295 EndOfWord,
296 PreviousBlock,
297 NextBlock,
298 PreviousCharacter,
299 NextCharacter,
300 PreviousWord,
301 NextWord,
302 Up,
303 Down,
304 Left,
305 Right,
306 WordLeft,
307 WordRight,
308 /// The start of the sentence the cursor is in. Already there → the previous sentence's
309 /// start, so repeating it walks backwards.
310 StartOfSentence,
311 /// The end of the sentence the cursor is in, at its terminator rather than at the space
312 /// after it. Already there → the next sentence's end.
313 EndOfSentence,
314 /// The start of the previous sentence — [`StartOfSentence`](Self::StartOfSentence) applied
315 /// from just before the current one.
316 PreviousSentence,
317 /// The start of the next sentence.
318 NextSentence,
319}
320
321/// Quick-select a region around the cursor.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum SelectionType {
324 WordUnderCursor,
325 /// The sentence the cursor is in, tailored to the cursor's
326 /// [`content_locale`](crate::TextCursor::set_content_locale). Trailing whitespace is
327 /// excluded, so the selection ends at the terminator.
328 SentenceUnderCursor,
329 LineUnderCursor,
330 BlockUnderCursor,
331 Document,
332}
333
334// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
335// Read-only info types
336// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
337
338/// Document-level statistics. O(1) cached.
339#[derive(Debug, Clone, PartialEq, Eq)]
340pub struct DocumentStats {
341 pub character_count: usize,
342 pub word_count: usize,
343 pub block_count: usize,
344 pub frame_count: usize,
345 pub image_count: usize,
346 pub list_count: usize,
347 pub table_count: usize,
348}
349
350/// Info about a block at a given position.
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub struct BlockInfo {
353 pub block_id: usize,
354 pub block_number: usize,
355 pub start: usize,
356 pub length: usize,
357}
358
359/// A single search match.
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub struct FindMatch {
362 pub position: usize,
363 pub length: usize,
364 /// The text that was actually matched, sliced from the document's own search text.
365 ///
366 /// Carried here so no caller ever slices it themselves — and with folding on, that is no
367 /// longer a convenience. A search for `cafe` matches `café`; a search for `strasse`
368 /// matches `straße`. The query is **not** the matched text, `length` is not the query's
369 /// length, and the whole-document string a caller reaches for first
370 /// ([`TextDocument::to_plain_text`]) does not even use the same offset space — it drops
371 /// the `U+FFFC` anchor an embedded table occupies. (The string that does share this
372 /// offset space is [`TextDocument::to_addressable_text`].)
373 pub matched_text: String,
374}
375
376/// Options for find / find_all / replace operations.
377///
378/// Both folding toggles default to **off = folded**, which is what a writer means by
379/// "search": `aurelien` finds `Aurélien`, `strasse` finds `Straße`, `احمد` finds `أَحْمَد`.
380/// Turn one on to be literal about it.
381#[derive(Debug, Clone, Default)]
382pub struct FindOptions {
383 pub case_sensitive: bool,
384 pub whole_word: bool,
385 /// `false` (the default) folds diacritics, ligatures and Arabic orthography.
386 pub diacritic_sensitive: bool,
387 /// The BCP-47 tag of the text being searched — **per document**, not per search.
388 ///
389 /// Only Turkish and Azerbaijani (`tr`, `az`) change how text folds: there the dotted
390 /// and dotless `i` are different letters, and merging them turns one word into another.
391 /// Every other tag — including an empty or malformed one — folds untailored, so this is
392 /// safe to leave alone and safe to feed a user's raw project setting.
393 ///
394 /// It decides *how* to fold, never *whether* to: the toggles above stay global across a
395 /// search, or the same checkbox would mean different things in different chapters.
396 pub language: String,
397 pub use_regex: bool,
398 pub search_backward: bool,
399}
400
401/// Options for a replace: how to *find* the text, and what the replacement wears where
402/// it overwrites formatted prose.
403///
404/// The format policy is deliberately not on [`FindOptions`] — it means nothing to a
405/// find, and a search option that silently only applies to half the calls that take it
406/// is how dead toggles are born.
407#[derive(Debug, Clone, Default)]
408pub struct ReplaceOptions {
409 pub find: FindOptions,
410 /// Defaults to [`ReplaceFormatPolicy::InheritPreceding`] — the behaviour that has
411 /// always shipped, which drops the formatting under the replaced range. Choose
412 /// another policy when the range may be formatted and losing that would be wrong
413 /// (a character rename landing on a partly-bold name).
414 pub format_policy: ReplaceFormatPolicy,
415}
416
417/// One range to replace, with **its own** replacement text.
418///
419/// `position` and `length` are **char** offsets into the document's text — the same space
420/// [`FindMatch`] reports in, so a match can be turned into a range directly.
421#[derive(Debug, Clone, PartialEq, Eq)]
422pub struct ReplaceRange {
423 pub position: usize,
424 pub length: usize,
425 pub replacement: String,
426}
427
428impl ReplaceOptions {
429 /// A replace that finds the text exactly as `find` describes and keeps the default
430 /// (historical) format policy.
431 pub fn new(find: FindOptions) -> Self {
432 Self {
433 find,
434 format_policy: ReplaceFormatPolicy::default(),
435 }
436 }
437
438 pub fn with_format_policy(mut self, policy: ReplaceFormatPolicy) -> Self {
439 self.format_policy = policy;
440 self
441 }
442}
443
444/// How many documents are alive in this process right now.
445///
446/// A [`TextDocument`] is a handle onto a shared body, so a single surviving clone
447/// keeps that document's rope, block table and store resident. A host that opens a
448/// document per scene and closes a project has no other way to ask whether it
449/// actually let go: the memory shows up under the rope and the block table
450/// whoever is holding them, and an allocation profile names the allocation site
451/// rather than the owner.
452///
453/// Counted on the body, not on the handle, so cloning a `TextDocument` does not
454/// move it. It rises by one for each document successfully created and falls by
455/// one when the last handle to it is dropped.
456pub fn live_document_count() -> usize {
457 inner::LIVE_DOCUMENTS.load(std::sync::atomic::Ordering::Relaxed)
458}