Skip to main content

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", with one exception: a `style` that turns a bullet
248/// list into a numbered one, or the reverse, replaces the `prefix` and `suffix` the caller
249/// leaves `None` with those of the new kind (no prefix, and `.` or no suffix), because the
250/// affixes of a numbered list ("1." or "(1)") do not belong on a bullet. A style that stays
251/// in its kind (two numbered styles, two bullets) keeps them, and a `prefix` or `suffix`
252/// that is given always wins.
253#[derive(Debug, Clone, Default, PartialEq, Eq)]
254pub struct ListFormat {
255    pub style: Option<ListStyle>,
256    pub indent: Option<u8>,
257    pub prefix: Option<String>,
258    pub suffix: Option<String>,
259}
260
261/// Frame formatting. All fields are optional.
262#[derive(Debug, Clone, Default, PartialEq, Eq)]
263pub struct FrameFormat {
264    pub height: Option<i32>,
265    pub width: Option<i32>,
266    pub top_margin: Option<i32>,
267    pub bottom_margin: Option<i32>,
268    pub left_margin: Option<i32>,
269    pub right_margin: Option<i32>,
270    pub padding: Option<i32>,
271    pub border: Option<i32>,
272    pub position: Option<FramePosition>,
273    pub is_blockquote: Option<bool>,
274}
275
276// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
277// Enums for cursor movement
278// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
279
280/// Controls whether a movement collapses or extends the selection.
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282pub enum MoveMode {
283    /// Move both position and anchor — collapses selection.
284    MoveAnchor,
285    /// Move only position, keep anchor — creates or extends selection.
286    KeepAnchor,
287}
288
289/// Semantic cursor movement operations.
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub enum MoveOperation {
292    NoMove,
293    Start,
294    End,
295    StartOfLine,
296    EndOfLine,
297    StartOfBlock,
298    EndOfBlock,
299    StartOfWord,
300    EndOfWord,
301    PreviousBlock,
302    NextBlock,
303    PreviousCharacter,
304    NextCharacter,
305    PreviousWord,
306    NextWord,
307    Up,
308    Down,
309    Left,
310    Right,
311    WordLeft,
312    WordRight,
313    /// The start of the sentence the cursor is in. Already there → the previous sentence's
314    /// start, so repeating it walks backwards.
315    StartOfSentence,
316    /// The end of the sentence the cursor is in, at its terminator rather than at the space
317    /// after it. Already there → the next sentence's end.
318    EndOfSentence,
319    /// The start of the previous sentence — [`StartOfSentence`](Self::StartOfSentence) applied
320    /// from just before the current one.
321    PreviousSentence,
322    /// The start of the next sentence.
323    NextSentence,
324}
325
326/// Quick-select a region around the cursor.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub enum SelectionType {
329    WordUnderCursor,
330    /// The sentence the cursor is in, tailored to the cursor's
331    /// [`content_locale`](crate::TextCursor::set_content_locale). Trailing whitespace is
332    /// excluded, so the selection ends at the terminator.
333    SentenceUnderCursor,
334    LineUnderCursor,
335    BlockUnderCursor,
336    Document,
337}
338
339// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
340// Read-only info types
341// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
342
343/// Document-level statistics. O(1) cached.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct DocumentStats {
346    pub character_count: usize,
347    pub word_count: usize,
348    pub block_count: usize,
349    pub frame_count: usize,
350    pub image_count: usize,
351    pub list_count: usize,
352    pub table_count: usize,
353}
354
355/// Info about a block at a given position.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct BlockInfo {
358    pub block_id: usize,
359    pub block_number: usize,
360    pub start: usize,
361    pub length: usize,
362}
363
364/// A single search match.
365#[derive(Debug, Clone, PartialEq, Eq)]
366pub struct FindMatch {
367    pub position: usize,
368    pub length: usize,
369    /// The text that was actually matched, sliced from the document's own search text.
370    ///
371    /// Carried here so no caller ever slices it themselves — and with folding on, that is no
372    /// longer a convenience. A search for `cafe` matches `café`; a search for `strasse`
373    /// matches `straße`. The query is **not** the matched text, `length` is not the query's
374    /// length, and the whole-document string a caller reaches for first
375    /// ([`TextDocument::to_plain_text`]) does not even use the same offset space — it drops
376    /// the `U+FFFC` anchor an embedded table occupies. (The string that does share this
377    /// offset space is [`TextDocument::to_addressable_text`].)
378    pub matched_text: String,
379}
380
381/// Options for find / find_all / replace operations.
382///
383/// Both folding toggles default to **off = folded**, which is what a writer means by
384/// "search": `aurelien` finds `Aurélien`, `strasse` finds `Straße`, `احمد` finds `أَحْمَد`.
385/// Turn one on to be literal about it.
386#[derive(Debug, Clone, Default)]
387pub struct FindOptions {
388    pub case_sensitive: bool,
389    pub whole_word: bool,
390    /// `false` (the default) folds diacritics, ligatures and Arabic orthography.
391    pub diacritic_sensitive: bool,
392    /// The BCP-47 tag of the text being searched — **per document**, not per search.
393    ///
394    /// Only Turkish and Azerbaijani (`tr`, `az`) change how text folds: there the dotted
395    /// and dotless `i` are different letters, and merging them turns one word into another.
396    /// Every other tag — including an empty or malformed one — folds untailored, so this is
397    /// safe to leave alone and safe to feed a user's raw project setting.
398    ///
399    /// It decides *how* to fold, never *whether* to: the toggles above stay global across a
400    /// search, or the same checkbox would mean different things in different chapters.
401    pub language: String,
402    pub use_regex: bool,
403    pub search_backward: bool,
404}
405
406/// Options for a replace: how to *find* the text, and what the replacement wears where
407/// it overwrites formatted prose.
408///
409/// The format policy is deliberately not on [`FindOptions`] — it means nothing to a
410/// find, and a search option that silently only applies to half the calls that take it
411/// is how dead toggles are born.
412#[derive(Debug, Clone, Default)]
413pub struct ReplaceOptions {
414    pub find: FindOptions,
415    /// Defaults to [`ReplaceFormatPolicy::InheritPreceding`] — the behaviour that has
416    /// always shipped, which drops the formatting under the replaced range. Choose
417    /// another policy when the range may be formatted and losing that would be wrong
418    /// (a character rename landing on a partly-bold name).
419    pub format_policy: ReplaceFormatPolicy,
420}
421
422/// One range to replace, with **its own** replacement text.
423///
424/// `position` and `length` are **char** offsets into the document's text — the same space
425/// [`FindMatch`] reports in, so a match can be turned into a range directly.
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct ReplaceRange {
428    pub position: usize,
429    pub length: usize,
430    pub replacement: String,
431}
432
433impl ReplaceOptions {
434    /// A replace that finds the text exactly as `find` describes and keeps the default
435    /// (historical) format policy.
436    pub fn new(find: FindOptions) -> Self {
437        Self {
438            find,
439            format_policy: ReplaceFormatPolicy::default(),
440        }
441    }
442
443    pub fn with_format_policy(mut self, policy: ReplaceFormatPolicy) -> Self {
444        self.format_policy = policy;
445        self
446    }
447}
448
449/// How many documents are alive in this process right now.
450///
451/// A [`TextDocument`] is a handle onto a shared body, so a single surviving clone
452/// keeps that document's rope, block table and store resident. A host that opens a
453/// document per scene and closes a project has no other way to ask whether it
454/// actually let go: the memory shows up under the rope and the block table
455/// whoever is holding them, and an allocation profile names the allocation site
456/// rather than the owner.
457///
458/// Counted on the body, not on the handle, so cloning a `TextDocument` does not
459/// move it. It rises by one for each document successfully created and falls by
460/// one when the last handle to it is dropped.
461pub fn live_document_count() -> usize {
462    inner::LIVE_DOCUMENTS.load(std::sync::atomic::Ordering::Relaxed)
463}