qem 0.6.3

High-performance cross-platform text engine for massive files.
Documentation
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
use super::*;
use crate::{
    CompactionPolicy, CompactionRecommendation, DocumentEncodingErrorKind,
    DocumentMaintenanceStatus, FragmentationStats, IdleCompactionOutcome, LiteralSearchIter,
    MaintenanceAction,
};
use std::time::Duration;

/// Backend-first document session wrapper with async open/save helpers and no
/// GUI-level cursor or widget assumptions.
///
/// This is the recommended entry point for most frontend integrations. It
/// keeps the engine-side session lifecycle, progress polling, and typed
/// document helpers together while leaving cursor movement and visual widget
/// behavior to the caller.
#[derive(Debug)]
pub struct DocumentSession {
    core: SessionCore,
}

impl Default for DocumentSession {
    fn default() -> Self {
        Self::new()
    }
}

impl DocumentSession {
    /// Creates a new empty document session.
    ///
    /// Most applications should start here rather than building directly on
    /// the lower-level [`Document`] API.
    pub fn new() -> Self {
        Self {
            core: SessionCore::new(),
        }
    }

    /// Returns the session generation counter.
    pub fn generation(&self) -> u64 {
        self.core.generation()
    }

    /// Returns `true` while a background save is in progress.
    pub fn is_saving(&self) -> bool {
        self.core.is_saving()
    }

    /// Returns `true` while a background load is in progress.
    pub fn is_loading(&self) -> bool {
        self.core.is_loading()
    }

    /// Returns `true` while any background worker is active.
    pub fn is_busy(&self) -> bool {
        self.core.is_busy()
    }

    /// Returns `true` while document-local indexing is still running.
    pub fn is_indexing(&self) -> bool {
        self.core.document().is_indexing()
    }

    /// Returns document indexing progress as `(indexed_bytes, total_bytes)`.
    ///
    /// Prefer [`DocumentSession::indexing_state`] in new code when you want a
    /// typed progress value.
    #[doc(hidden)]
    #[deprecated(
        since = "0.3.0",
        note = "use indexing_state() for typed progress instead"
    )]
    pub fn indexing_progress(&self) -> Option<(usize, usize)> {
        self.core.indexing_progress()
    }

    /// Returns typed indexing progress while background indexing is active.
    pub fn indexing_state(&self) -> Option<ByteProgress> {
        self.core.indexing_state()
    }

    /// Returns typed background-load progress.
    ///
    /// This covers the asynchronous open path itself. Once the document is
    /// ready, follow `indexing_state()` for any continued background line
    /// indexing.
    pub fn loading_state(&self) -> Option<FileProgress> {
        self.core.loading_state()
    }

    /// Returns the current loading phase when a background open is active.
    pub fn loading_phase(&self) -> Option<LoadPhase> {
        self.core.loading_phase()
    }

    /// Returns background-load progress.
    ///
    /// Prefer [`DocumentSession::loading_state`] in new code when you want a
    /// typed progress value.
    #[doc(hidden)]
    #[deprecated(
        since = "0.3.0",
        note = "use loading_state() for typed progress instead"
    )]
    pub fn loading_progress(&self) -> Option<(u64, u64, PathBuf)> {
        self.core.loading_progress()
    }

    /// Polls the background-load state.
    pub fn poll_load_job(&mut self) -> Option<Result<(), DocumentError>> {
        self.core.poll_load_job()
    }

    /// Polls the background-save state.
    pub fn poll_save_job(&mut self) -> Option<Result<(), DocumentError>> {
        self.core.poll_save_job()
    }

    /// Polls whichever background job is active.
    pub fn poll_background_job(&mut self) -> Option<Result<(), DocumentError>> {
        self.core.poll_background_job()
    }

    /// Returns immutable access to the current document.
    pub fn document(&self) -> &Document {
        self.core.document()
    }

    /// Returns mutable access to the current document.
    ///
    /// This is an escape hatch for callers that fully coordinate their own
    /// background job lifecycle. The typed edit helpers on
    /// [`DocumentSession`] reject edits while `is_busy()` is `true`; mutating
    /// the raw [`Document`] through this reference during a background
    /// open/save marks the in-flight worker result as stale, so the next poll
    /// surfaces an error instead of applying an outdated load/save result over
    /// the current document. If a `close_file()` was deferred while that job
    /// was active, this raw mutation also cancels the deferred close because
    /// the session state has changed again.
    pub fn document_mut(&mut self) -> &mut Document {
        self.core.document_mut()
    }

    /// Returns the full document text as a `String`.
    ///
    /// This materializes the entire current document through
    /// [`Document::text_lossy`]. This is an advanced convenience helper rather
    /// than the recommended UI path. Prefer `read_viewport(...)` or
    /// `read_text(...)` when a frontend only needs a visible window or a
    /// bounded selection.
    pub fn text(&self) -> String {
        self.core.document().text_lossy()
    }

    /// Returns the current document path, if one is set.
    pub fn current_path(&self) -> Option<&Path> {
        self.core.current_path()
    }

    /// Returns `true` if the document has unsaved changes.
    pub fn is_dirty(&self) -> bool {
        self.core.is_dirty()
    }

    /// Returns the current document line count with exact/estimated semantics.
    pub fn line_count(&self) -> LineCount {
        self.core.document().line_count()
    }

    /// Returns the exact document line count when it is known.
    pub fn exact_line_count(&self) -> Option<usize> {
        self.core.document().exact_line_count()
    }

    /// Returns the current best-effort line count for viewport sizing and scrolling.
    pub fn display_line_count(&self) -> usize {
        self.core.document().display_line_count()
    }

    /// Returns `true` when the current line count is exact.
    pub fn is_line_count_exact(&self) -> bool {
        self.core.document().is_line_count_exact()
    }

    /// Blocks until the exact line count is known or the timeout expires.
    pub fn wait_for_exact_line_count(&self, timeout: Duration) -> Option<usize> {
        self.core.document().wait_for_exact_line_count(timeout)
    }

    /// Returns the current document length in bytes.
    pub fn file_len(&self) -> usize {
        self.core.document().file_len()
    }

    /// Returns the currently detected line ending style.
    pub fn line_ending(&self) -> LineEnding {
        self.core.document().line_ending()
    }

    /// Returns the current document encoding contract.
    pub fn encoding(&self) -> DocumentEncoding {
        self.core.document().encoding()
    }

    /// Returns the typed reason why preserve-save would currently fail, if any.
    pub fn preserve_save_error(&self) -> Option<DocumentEncodingErrorKind> {
        self.core.document().preserve_save_error()
    }

    /// Returns `true` when preserve-save is currently allowed for this session document.
    pub fn can_preserve_save(&self) -> bool {
        self.core.document().can_preserve_save()
    }

    /// Returns the typed reason why the requested save options would currently fail, if any.
    pub fn save_error_for_options(
        &self,
        options: DocumentSaveOptions,
    ) -> Option<DocumentEncodingErrorKind> {
        self.core.document().save_error_for_options(options)
    }

    /// Returns `true` when the requested save options are currently valid.
    pub fn can_save_with_options(&self, options: DocumentSaveOptions) -> bool {
        self.core.document().can_save_with_options(options)
    }

    /// Returns the typed reason why an explicit save conversion would currently fail, if any.
    pub fn save_error_for_encoding(
        &self,
        encoding: DocumentEncoding,
    ) -> Option<DocumentEncodingErrorKind> {
        self.core.document().save_error_for_encoding(encoding)
    }

    /// Returns `true` when saving through the given explicit encoding is currently valid.
    pub fn can_save_with_encoding(&self, encoding: DocumentEncoding) -> bool {
        self.core.document().can_save_with_encoding(encoding)
    }

    /// Returns how the current encoding contract was chosen.
    pub fn encoding_origin(&self) -> DocumentEncodingOrigin {
        self.core.document().encoding_origin()
    }

    /// Returns `true` when the last open required replacement-character decoding.
    pub fn decoding_had_errors(&self) -> bool {
        self.core.document().decoding_had_errors()
    }

    /// Returns the visible line length in text columns, excluding line endings.
    pub fn line_len_chars(&self, line0: usize) -> usize {
        self.core.document().line_len_chars(line0)
    }

    /// Clamps a typed position into the currently known document bounds.
    pub fn clamp_position(&self, position: TextPosition) -> TextPosition {
        self.core.document().clamp_position(position)
    }

    /// Returns the typed document position for a full-text character index.
    pub fn position_for_char_index(&self, char_index: usize) -> TextPosition {
        self.core.document().position_for_char_index(char_index)
    }

    /// Returns the full-text character index for a typed document position.
    pub fn char_index_for_position(&self, position: TextPosition) -> usize {
        self.core.document().char_index_for_position(position)
    }

    /// Returns the ordered pair of two clamped positions.
    pub fn ordered_positions(
        &self,
        first: TextPosition,
        second: TextPosition,
    ) -> (TextPosition, TextPosition) {
        self.core.document().ordered_positions(first, second)
    }

    /// Clamps a selection into the currently known document bounds.
    pub fn clamp_selection(&self, selection: TextSelection) -> TextSelection {
        self.core.document().clamp_selection(selection)
    }

    /// Returns the number of edit text units between two positions.
    pub fn text_units_between(&self, start: TextPosition, end: TextPosition) -> usize {
        self.core.document().text_units_between(start, end)
    }

    /// Builds a typed edit range between two positions.
    pub fn text_range_between(&self, start: TextPosition, end: TextPosition) -> TextRange {
        self.core.document().text_range_between(start, end)
    }

    /// Builds a typed edit range from an anchor/head selection.
    pub fn text_range_for_selection(&self, selection: TextSelection) -> TextRange {
        self.core.document().text_range_for_selection(selection)
    }

    /// Returns whether the requested position is editable and whether it would
    /// require a backend promotion first.
    pub fn edit_capability_at(&self, position: TextPosition) -> EditCapability {
        self.core.document().edit_capability_at(position)
    }

    /// Returns editability for a typed edit range.
    pub fn edit_capability_for_range(&self, range: TextRange) -> EditCapability {
        self.core.document().edit_capability_for_range(range)
    }

    /// Returns editability for an anchor/head selection.
    pub fn edit_capability_for_selection(&self, selection: TextSelection) -> EditCapability {
        self.core
            .document()
            .edit_capability_for_selection(selection)
    }

    /// Reads a typed text range from the current document.
    pub fn read_text(&self, range: TextRange) -> TextSlice {
        self.core.document().read_text(range)
    }

    /// Reads the current selection as a typed text slice.
    pub fn read_selection(&self, selection: TextSelection) -> TextSlice {
        self.core.document().read_selection(selection)
    }

    /// Returns current piece-table fragmentation metrics.
    pub fn fragmentation_stats(&self) -> Option<FragmentationStats> {
        self.core.document().fragmentation_stats()
    }

    /// Returns fragmentation metrics using a caller-provided small-piece threshold.
    pub fn fragmentation_stats_with_threshold(
        &self,
        small_piece_threshold_bytes: usize,
    ) -> Option<FragmentationStats> {
        self.core
            .document()
            .fragmentation_stats_with_threshold(small_piece_threshold_bytes)
    }

    /// Returns a piece-table compaction recommendation using the default policy.
    pub fn compaction_recommendation(&self) -> Option<CompactionRecommendation> {
        self.core.document().compaction_recommendation()
    }

    /// Returns a piece-table compaction recommendation using a caller policy.
    pub fn compaction_recommendation_with_policy(
        &self,
        policy: CompactionPolicy,
    ) -> Option<CompactionRecommendation> {
        self.core
            .document()
            .compaction_recommendation_with_policy(policy)
    }

    /// Returns a maintenance-focused snapshot using the default compaction policy.
    pub fn maintenance_status(&self) -> DocumentMaintenanceStatus {
        self.core.document().maintenance_status()
    }

    /// Returns the high-level maintenance action suggested by the default policy.
    pub fn maintenance_action(&self) -> MaintenanceAction {
        self.core.document().maintenance_action()
    }

    /// Returns a maintenance-focused snapshot using a caller-provided compaction policy.
    pub fn maintenance_status_with_policy(
        &self,
        policy: CompactionPolicy,
    ) -> DocumentMaintenanceStatus {
        self.core.document().maintenance_status_with_policy(policy)
    }

    /// Returns the high-level maintenance action suggested by a caller-provided policy.
    pub fn maintenance_action_with_policy(&self, policy: CompactionPolicy) -> MaintenanceAction {
        self.core.document().maintenance_action_with_policy(policy)
    }

    /// Finds the next literal match starting at `from`.
    pub fn find_next(&self, needle: &str, from: TextPosition) -> Option<SearchMatch> {
        self.core.document().find_next(needle, from)
    }

    /// Finds the next literal match using a reusable compiled query.
    pub fn find_next_query(
        &self,
        query: &LiteralSearchQuery,
        from: TextPosition,
    ) -> Option<SearchMatch> {
        self.core.document().find_next_query(query, from)
    }

    /// Finds the previous literal match whose end is at or before `before`.
    pub fn find_prev(&self, needle: &str, before: TextPosition) -> Option<SearchMatch> {
        self.core.document().find_prev(needle, before)
    }

    /// Finds the previous literal match using a reusable compiled query.
    pub fn find_prev_query(
        &self,
        query: &LiteralSearchQuery,
        before: TextPosition,
    ) -> Option<SearchMatch> {
        self.core.document().find_prev_query(query, before)
    }

    /// Iterates non-overlapping literal matches in the whole document.
    pub fn find_all(&self, needle: impl Into<String>) -> LiteralSearchIter<'_> {
        self.core.document().find_all(needle)
    }

    /// Iterates non-overlapping literal matches in the whole document using a
    /// reusable compiled query.
    pub fn find_all_query(&self, query: &LiteralSearchQuery) -> LiteralSearchIter<'_> {
        self.core.document().find_all_query(query)
    }

    /// Iterates non-overlapping literal matches from `from` onward.
    pub fn find_all_from(
        &self,
        needle: impl Into<String>,
        from: TextPosition,
    ) -> LiteralSearchIter<'_> {
        self.core.document().find_all_from(needle, from)
    }

    /// Iterates non-overlapping literal matches from `from` onward using a
    /// reusable compiled query.
    pub fn find_all_query_from(
        &self,
        query: &LiteralSearchQuery,
        from: TextPosition,
    ) -> LiteralSearchIter<'_> {
        self.core.document().find_all_query_from(query, from)
    }

    /// Iterates non-overlapping literal matches fully contained within `range`.
    pub fn find_all_in_range(
        &self,
        needle: impl Into<String>,
        range: TextRange,
    ) -> LiteralSearchIter<'_> {
        self.core.document().find_all_in_range(needle, range)
    }

    /// Iterates non-overlapping literal matches fully contained within `range`
    /// using a reusable compiled query.
    pub fn find_all_query_in_range(
        &self,
        query: &LiteralSearchQuery,
        range: TextRange,
    ) -> LiteralSearchIter<'_> {
        self.core.document().find_all_query_in_range(query, range)
    }

    /// Iterates non-overlapping literal matches between two typed positions.
    pub fn find_all_between(
        &self,
        needle: impl Into<String>,
        start: TextPosition,
        end: TextPosition,
    ) -> LiteralSearchIter<'_> {
        self.core.document().find_all_between(needle, start, end)
    }

    /// Iterates non-overlapping literal matches between two typed positions
    /// using a reusable compiled query.
    pub fn find_all_query_between(
        &self,
        query: &LiteralSearchQuery,
        start: TextPosition,
        end: TextPosition,
    ) -> LiteralSearchIter<'_> {
        self.core
            .document()
            .find_all_query_between(query, start, end)
    }

    /// Finds the first literal match fully contained within `range`.
    pub fn find_next_in_range(&self, needle: &str, range: TextRange) -> Option<SearchMatch> {
        self.core.document().find_next_in_range(needle, range)
    }

    /// Finds the first literal match fully contained between two typed positions.
    pub fn find_next_between(
        &self,
        needle: &str,
        start: TextPosition,
        end: TextPosition,
    ) -> Option<SearchMatch> {
        self.core.document().find_next_between(needle, start, end)
    }

    /// Finds the last literal match fully contained within `range`.
    pub fn find_prev_in_range(&self, needle: &str, range: TextRange) -> Option<SearchMatch> {
        self.core.document().find_prev_in_range(needle, range)
    }

    /// Finds the last literal match fully contained between two typed positions.
    pub fn find_prev_between(
        &self,
        needle: &str,
        start: TextPosition,
        end: TextPosition,
    ) -> Option<SearchMatch> {
        self.core.document().find_prev_between(needle, start, end)
    }

    /// Finds the first query match fully contained within `range`.
    pub fn find_next_query_in_range(
        &self,
        query: &LiteralSearchQuery,
        range: TextRange,
    ) -> Option<SearchMatch> {
        self.core.document().find_next_query_in_range(query, range)
    }

    /// Finds the first query match fully contained between two typed positions.
    pub fn find_next_query_between(
        &self,
        query: &LiteralSearchQuery,
        start: TextPosition,
        end: TextPosition,
    ) -> Option<SearchMatch> {
        self.core
            .document()
            .find_next_query_between(query, start, end)
    }

    /// Finds the last query match fully contained within `range`.
    pub fn find_prev_query_in_range(
        &self,
        query: &LiteralSearchQuery,
        range: TextRange,
    ) -> Option<SearchMatch> {
        self.core.document().find_prev_query_in_range(query, range)
    }

    /// Finds the last query match fully contained between two typed positions.
    pub fn find_prev_query_between(
        &self,
        query: &LiteralSearchQuery,
        start: TextPosition,
        end: TextPosition,
    ) -> Option<SearchMatch> {
        self.core
            .document()
            .find_prev_query_between(query, start, end)
    }

    /// Compacts the current piece-table document if one is active.
    pub fn compact_piece_table(&mut self) -> Result<bool, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        let path = self
            .core
            .document()
            .path()
            .map(|path| path.to_path_buf())
            .unwrap_or_default();
        self.core
            .document_mut()
            .compact_piece_table()
            .map_err(|source| DocumentError::Write { path, source })
    }

    /// Compacts the current piece-table document when the policy recommends it.
    pub fn compact_piece_table_if_recommended(
        &mut self,
        policy: CompactionPolicy,
    ) -> Result<Option<CompactionRecommendation>, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        let path = self
            .core
            .document()
            .path()
            .map(|path| path.to_path_buf())
            .unwrap_or_default();
        self.core
            .document_mut()
            .compact_piece_table_if_recommended(policy)
            .map_err(|source| DocumentError::Write { path, source })
    }

    /// Runs a deferred idle compaction pass with the default policy.
    pub fn run_idle_compaction(&mut self) -> Result<IdleCompactionOutcome, DocumentError> {
        self.run_idle_compaction_with_policy(CompactionPolicy::default())
    }

    /// Runs a deferred idle compaction pass using a caller-provided policy.
    ///
    /// Forced recommendations are surfaced as `ForcedPending` without
    /// rewriting the piece table, which lets the caller reserve that heavier
    /// maintenance step for an explicit save or operator action.
    pub fn run_idle_compaction_with_policy(
        &mut self,
        policy: CompactionPolicy,
    ) -> Result<IdleCompactionOutcome, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        let path = self
            .core
            .document()
            .path()
            .map(|path| path.to_path_buf())
            .unwrap_or_default();
        self.core
            .document_mut()
            .run_idle_compaction_with_policy(policy)
            .map_err(|source| DocumentError::Write { path, source })
    }

    /// Applies a typed insert directly through the session.
    pub fn try_insert(
        &mut self,
        position: TextPosition,
        text: &str,
    ) -> Result<TextPosition, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_insert(position, text)
    }

    /// Applies a typed replacement directly through the session.
    pub fn try_replace(
        &mut self,
        range: TextRange,
        text: &str,
    ) -> Result<TextPosition, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_replace(range, text)
    }

    /// Replaces the current selection and returns the resulting caret position.
    pub fn try_replace_selection(
        &mut self,
        selection: TextSelection,
        text: &str,
    ) -> Result<TextPosition, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core
            .document_mut()
            .try_replace_selection(selection, text)
    }

    /// Applies a typed backspace directly through the session.
    pub fn try_backspace(&mut self, position: TextPosition) -> Result<EditResult, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_backspace(position)
    }

    /// Applies a backspace command to an anchor/head selection.
    pub fn try_backspace_selection(
        &mut self,
        selection: TextSelection,
    ) -> Result<EditResult, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_backspace_selection(selection)
    }

    /// Deletes the text unit at the cursor and keeps the resulting caret position.
    pub fn try_delete_forward(
        &mut self,
        position: TextPosition,
    ) -> Result<EditResult, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_delete_forward(position)
    }

    /// Applies a forward-delete command to an anchor/head selection.
    pub fn try_delete_forward_selection(
        &mut self,
        selection: TextSelection,
    ) -> Result<EditResult, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core
            .document_mut()
            .try_delete_forward_selection(selection)
    }

    /// Deletes the current selection and returns the resulting caret position.
    pub fn try_delete_selection(
        &mut self,
        selection: TextSelection,
    ) -> Result<EditResult, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_delete_selection(selection)
    }

    /// Cuts the current selection and returns the removed text together with the edit result.
    pub fn try_cut_selection(
        &mut self,
        selection: TextSelection,
    ) -> Result<CutResult, DocumentError> {
        self.core.ensure_idle_for_edit()?;
        self.core.document_mut().try_cut_selection(selection)
    }

    /// Opens a file synchronously.
    pub fn open_file(&mut self, path: PathBuf) -> Result<(), DocumentError> {
        self.core.open_file(path)
    }

    /// Opens a file synchronously using explicit open options.
    pub fn open_file_with_options(
        &mut self,
        path: PathBuf,
        options: DocumentOpenOptions,
    ) -> Result<(), DocumentError> {
        self.core.open_file_with_options(path, options)
    }

    /// Opens a file synchronously using the lightweight auto-detect path.
    pub fn open_file_with_auto_encoding_detection(
        &mut self,
        path: PathBuf,
    ) -> Result<(), DocumentError> {
        self.open_file_with_options(
            path,
            DocumentOpenOptions::new().with_auto_encoding_detection(),
        )
    }

    /// Opens a file synchronously using auto-detect first and an explicit fallback encoding.
    pub fn open_file_with_auto_encoding_detection_and_fallback(
        &mut self,
        path: PathBuf,
        encoding: DocumentEncoding,
    ) -> Result<(), DocumentError> {
        self.open_file_with_options(
            path,
            DocumentOpenOptions::new().with_auto_encoding_detection_and_fallback(encoding),
        )
    }

    /// Opens a file synchronously using an explicit text encoding.
    pub fn open_file_with_encoding(
        &mut self,
        path: PathBuf,
        encoding: DocumentEncoding,
    ) -> Result<(), DocumentError> {
        self.open_file_with_options(path, DocumentOpenOptions::new().with_encoding(encoding))
    }

    /// Starts opening a file on a background worker.
    pub fn open_file_async(&mut self, path: PathBuf) -> Result<(), DocumentError> {
        self.core.open_file_async(path)
    }

    /// Starts opening a file on a background worker using explicit open options.
    pub fn open_file_async_with_options(
        &mut self,
        path: PathBuf,
        options: DocumentOpenOptions,
    ) -> Result<(), DocumentError> {
        self.core.open_file_async_with_options(path, options)
    }

    /// Starts opening a file on a background worker using the lightweight auto-detect path.
    pub fn open_file_async_with_auto_encoding_detection(
        &mut self,
        path: PathBuf,
    ) -> Result<(), DocumentError> {
        self.open_file_async_with_options(
            path,
            DocumentOpenOptions::new().with_auto_encoding_detection(),
        )
    }

    /// Starts opening a file on a background worker using auto-detect first and an explicit fallback encoding.
    pub fn open_file_async_with_auto_encoding_detection_and_fallback(
        &mut self,
        path: PathBuf,
        encoding: DocumentEncoding,
    ) -> Result<(), DocumentError> {
        self.open_file_async_with_options(
            path,
            DocumentOpenOptions::new().with_auto_encoding_detection_and_fallback(encoding),
        )
    }

    /// Starts opening a file on a background worker using an explicit encoding.
    pub fn open_file_async_with_encoding(
        &mut self,
        path: PathBuf,
        encoding: DocumentEncoding,
    ) -> Result<(), DocumentError> {
        self.open_file_async_with_options(path, DocumentOpenOptions::new().with_encoding(encoding))
    }

    /// Closes the current document and replaces it with an empty one.
    ///
    /// If a background open/save is still running, the close is deferred until
    /// that job finishes so the session keeps tracking the active worker
    /// result. Deferred closes after background saves are only applied when
    /// the save succeeds; failed saves leave the dirty document open.
    pub fn close_file(&mut self) {
        self.core.close_file();
    }

    /// Clears a deferred dirty flag scheduled after a clean document open.
    pub fn after_document_frame(&mut self) {
        self.core.after_document_frame();
    }

    /// Cancels the deferred dirty-flag clear scheduled after a clean open.
    pub fn cancel_clear_dirty_after_open(&mut self) {
        self.core.cancel_clear_dirty_after_open();
    }

    /// Saves the document synchronously to its current path.
    pub fn save(&mut self) -> Result<(), SaveError> {
        self.core.save()
    }

    /// Saves the document synchronously to a new path.
    pub fn save_as(&mut self, path: PathBuf) -> Result<(), DocumentError> {
        self.core.save_as(path)
    }

    /// Saves the document synchronously to a new path using explicit save options.
    pub fn save_as_with_options(
        &mut self,
        path: PathBuf,
        options: DocumentSaveOptions,
    ) -> Result<(), DocumentError> {
        self.core.save_as_with_options(path, options)
    }

    /// Saves the document synchronously to a new path using an explicit target encoding.
    pub fn save_as_with_encoding(
        &mut self,
        path: PathBuf,
        encoding: DocumentEncoding,
    ) -> Result<(), DocumentError> {
        self.save_as_with_options(path, DocumentSaveOptions::new().with_encoding(encoding))
    }

    /// Sets the document path without saving.
    ///
    /// When used while a background open/save is active, the path change is
    /// applied immediately to the current document and the in-flight worker
    /// result is marked stale so the next poll returns an error instead of
    /// applying outdated state. If a `close_file()` was deferred while that job
    /// was active, changing the path also cancels that deferred close.
    pub fn set_path(&mut self, path: PathBuf) {
        self.core.set_path(path);
    }

    /// Returns typed background-save progress.
    pub fn save_state(&self) -> Option<FileProgress> {
        self.core.save_state()
    }

    /// Returns background-save progress.
    ///
    /// Prefer [`DocumentSession::save_state`] in new code when you want a
    /// typed progress value.
    #[doc(hidden)]
    #[deprecated(since = "0.3.0", note = "use save_state() for typed progress instead")]
    pub fn save_progress(&self) -> Option<(u64, u64, PathBuf)> {
        self.core.save_progress()
    }

    /// Starts a background save to the current path.
    ///
    /// The write itself runs on a worker thread, but save preparation still
    /// snapshots the current document before that worker starts. For large
    /// edited buffers, the call itself can therefore take noticeable time.
    pub fn save_async(&mut self) -> Result<bool, SaveError> {
        self.core.save_async()
    }

    /// Starts a background save to a new path.
    ///
    /// The write itself runs on a worker thread, but save preparation still
    /// snapshots the current document before that worker starts. For large
    /// edited buffers, the call itself can therefore take noticeable time.
    pub fn save_as_async(&mut self, path: PathBuf) -> Result<bool, DocumentError> {
        self.core.save_as_async(path)
    }

    /// Starts a background save to a new path using explicit save options.
    pub fn save_as_async_with_options(
        &mut self,
        path: PathBuf,
        options: DocumentSaveOptions,
    ) -> Result<bool, DocumentError> {
        self.core.save_as_async_with_options(path, options)
    }

    /// Starts a background save to a new path using an explicit target encoding.
    pub fn save_as_async_with_encoding(
        &mut self,
        path: PathBuf,
        encoding: DocumentEncoding,
    ) -> Result<bool, DocumentError> {
        self.save_as_async_with_options(path, DocumentSaveOptions::new().with_encoding(encoding))
    }

    /// Returns the current background activity for the session.
    pub fn background_activity(&self) -> BackgroundActivity {
        self.core.background_activity()
    }

    /// Returns the most recent background open/save problem, if one is being retained.
    pub fn background_issue(&self) -> Option<&BackgroundIssue> {
        self.core.background_issue()
    }

    /// Takes and clears the most recent retained background open/save problem.
    ///
    /// This is useful for frontends that want to acknowledge a background error
    /// once it has been surfaced to the user instead of keeping it visible until
    /// a later successful operation clears it implicitly.
    pub fn take_background_issue(&mut self) -> Option<BackgroundIssue> {
        self.core.take_background_issue()
    }

    /// Returns `true` when `close_file()` has been requested and is waiting for
    /// the active background open/save to finish.
    pub fn close_pending(&self) -> bool {
        self.core.close_pending()
    }

    /// Returns a frontend-friendly snapshot of the current session state.
    pub fn status(&self) -> DocumentSessionStatus {
        self.core.status()
    }

    /// Reads a visible viewport directly from the current document.
    pub fn read_viewport(&self, request: ViewportRequest) -> Viewport {
        self.core.read_viewport(request)
    }
}