1use std::sync::Arc;
4
5use parking_lot::Mutex;
6
7use crate::{DocumentError, Result};
8
9use crate::ListStyle;
10use frontend::commands::{
11 document_editing_commands, document_formatting_commands, document_inspection_commands,
12 undo_redo_commands,
13};
14
15use unicode_segmentation::UnicodeSegmentation;
16
17use crate::convert::{to_i64, to_usize};
18use crate::events::{DocumentEvent, InsertionOrigin};
19use crate::flow::{CellRange, FlowElement, FrameRef, SelectionKind, TableCellRef};
20use crate::fragment::DocumentFragment;
21use crate::inner::{CursorData, QueuedEvents, TextDocumentInner};
22use crate::link_extent::LinkExtent;
23use crate::text_block::TextBlock;
24use crate::text_table::TextTable;
25use crate::{BlockFormat, FrameFormat, MoveMode, MoveOperation, SelectionType, TextFormat};
26
27use crate::document::get_main_frame_id;
28
29fn main_text_is_empty(inner: &TextDocumentInner) -> bool {
32 let store = inner.ctx.db_context.get_store();
33 match common::database::rope_helpers::main_text_end(store) {
34 Some(end) => end == 0,
35 None => max_cursor_position_of(inner) == Some(0),
36 }
37}
38
39fn max_cursor_position_of(inner: &TextDocumentInner) -> Option<usize> {
62 let store = inner.ctx.db_context.get_store();
63 if common::database::rope_helpers::rope_positions_match_flow(store) {
64 return Some(store.rope.read().len_chars());
65 }
66 let (chars, blocks) = crate::inner::document_counts(inner)?;
67 Some(if blocks > 1 {
68 chars + blocks - 1
69 } else {
70 chars
71 })
72}
73
74fn measured_delete(
84 inner: &TextDocumentInner,
85 pos: usize,
86 anchor: usize,
87) -> Result<(frontend::document_editing::DeleteTextResultDto, usize)> {
88 let before = max_cursor_position_of(inner);
89 let dto = frontend::document_editing::DeleteTextDto {
90 position: to_i64(pos),
91 anchor: to_i64(anchor),
92 };
93 let result =
94 match document_editing_commands::delete_text(&inner.ctx, Some(inner.stack_id), &dto) {
95 Ok(result) => result,
96 Err(error) => match error.downcast_ref::<frontend::document_editing::NothingToDelete>()
100 {
101 Some(nothing) => {
102 return Ok((
103 frontend::document_editing::DeleteTextResultDto {
104 new_position: nothing.new_position,
105 deleted_text: String::new(),
106 },
107 0,
108 ));
109 }
110 None => return Err(error.into()),
111 },
112 };
113 let removed = match (before, max_cursor_position_of(inner)) {
114 (Some(before), Some(after)) => before.saturating_sub(after),
115 _ => pos.max(anchor) - pos.min(anchor),
117 };
118 Ok((result, removed))
119}
120
121fn delete_then<R>(
134 inner: &TextDocumentInner,
135 pos: usize,
136 anchor: usize,
137 insert: impl FnOnce(usize) -> Result<R>,
138) -> Result<(R, usize, usize)> {
139 undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
140 let outcome = measured_delete(inner, pos, anchor).and_then(|(deleted, removed)| {
141 let at = to_usize(deleted.new_position);
142 insert(at).map(|value| (value, removed, at))
143 });
144 match outcome {
145 Ok(done) => {
146 undo_redo_commands::end_composite(&inner.ctx);
147 Ok(done)
148 }
149 Err(error) => {
150 undo_redo_commands::cancel_composite(&inner.ctx);
151 Err(error)
152 }
153 }
154}
155
156fn removed_since(
166 inner: &TextDocumentInner,
167 before: Option<usize>,
168 added: usize,
169 selection: usize,
170) -> usize {
171 match (before, max_cursor_position_of(inner)) {
172 (Some(before), Some(after)) => (before + added).saturating_sub(after),
173 _ => selection,
174 }
175}
176
177#[derive(Debug, Clone, Copy)]
181struct Insertion {
182 at: usize,
183 removed: usize,
184 added: usize,
185}
186
187impl Insertion {
188 fn ending_at(new_pos: usize, added: usize) -> Self {
193 Insertion {
194 at: new_pos.saturating_sub(added),
195 removed: 0,
196 added,
197 }
198 }
199}
200
201pub struct TextCursor {
209 pub(crate) doc: Arc<Mutex<TextDocumentInner>>,
210 pub(crate) data: Arc<Mutex<CursorData>>,
211}
212
213impl Clone for TextCursor {
214 fn clone(&self) -> Self {
215 let (position, anchor, content_locale) = {
216 let d = self.data.lock();
217 (d.position, d.anchor, d.content_locale.clone())
218 };
219 let data = {
220 let mut inner = self.doc.lock();
221 let data = Arc::new(Mutex::new(CursorData {
222 position,
223 anchor,
224 cell_selection_override: None,
225 content_locale,
227 whole_text_selected: false,
228 }));
229 inner.cursors.push(Arc::downgrade(&data));
230 data
231 };
232 TextCursor {
233 doc: self.doc.clone(),
234 data,
235 }
236 }
237}
238
239impl TextCursor {
240 fn read_cursor(&self) -> (usize, usize) {
243 let d = self.data.lock();
244 (d.position, d.anchor)
245 }
246
247 fn finish_edit(
251 &self,
252 inner: &mut TextDocumentInner,
253 edit_pos: usize,
254 removed: usize,
255 inserted: Insertion,
256 new_pos: usize,
257 blocks_affected: usize,
258 ) -> QueuedEvents {
259 self.finish_edit_ext(
260 inner,
261 edit_pos,
262 removed,
263 inserted,
264 new_pos,
265 blocks_affected,
266 true,
267 )
268 }
269
270 #[allow(clippy::too_many_arguments)]
271 fn finish_edit_ext(
272 &self,
273 inner: &mut TextDocumentInner,
274 edit_pos: usize,
275 removed: usize,
276 inserted: Insertion,
277 new_pos: usize,
278 blocks_affected: usize,
279 flow_may_change: bool,
280 ) -> QueuedEvents {
281 self.finish_edit_from(
282 inner,
283 edit_pos,
284 removed,
285 inserted,
286 new_pos,
287 blocks_affected,
288 flow_may_change,
289 InsertionOrigin::Unspecified,
290 )
291 }
292
293 #[allow(clippy::too_many_arguments)]
310 fn finish_edit_from(
311 &self,
312 inner: &mut TextDocumentInner,
313 edit_pos: usize,
314 removed: usize,
315 inserted: Insertion,
316 new_pos: usize,
317 blocks_affected: usize,
318 flow_may_change: bool,
319 origin: InsertionOrigin,
320 ) -> QueuedEvents {
321 let Insertion {
328 at: inserted_at,
329 removed: replaced,
330 added,
331 } = inserted;
332 if inserted_at > edit_pos || replaced > 0 {
333 inner.adjust_cursors(edit_pos, removed, 0);
338 inner.adjust_cursors(inserted_at, replaced, added);
339 } else {
340 inner.adjust_cursors(inserted_at, removed, added);
341 }
342 let removed = removed + replaced;
343 let edit_pos = edit_pos.min(inserted_at);
344 {
345 let mut d = self.data.lock();
346 d.position = new_pos;
347 d.anchor = new_pos;
348 d.whole_text_selected = false;
349 }
350 inner.modified = true;
351 inner.invalidate_text_cache();
352 inner.rehighlight_affected(edit_pos);
353 inner.queue_event(DocumentEvent::ContentsChanged {
354 position: edit_pos,
355 chars_removed: removed,
356 chars_added: added,
357 blocks_affected,
358 });
359 if added > 0 {
363 inner.queue_event(DocumentEvent::TextInserted {
364 position: inserted_at,
365 chars_inserted: added,
366 origin,
367 });
368 }
369 inner.check_block_count_changed();
370 if flow_may_change {
371 inner.check_flow_changed();
372 }
373 self.queue_undo_redo_event(inner)
374 }
375
376 pub fn position(&self) -> usize {
380 self.data.lock().position
381 }
382
383 pub fn anchor(&self) -> usize {
385 self.data.lock().anchor
386 }
387
388 pub fn has_selection(&self) -> bool {
390 let d = self.data.lock();
391 d.position != d.anchor
392 }
393
394 pub fn selection_start(&self) -> usize {
396 let d = self.data.lock();
397 d.position.min(d.anchor)
398 }
399
400 pub fn selection_end(&self) -> usize {
402 let d = self.data.lock();
403 d.position.max(d.anchor)
404 }
405
406 pub fn selected_text(&self) -> Result<String> {
408 let (pos, anchor) = self.read_cursor();
409 if pos == anchor {
410 return Ok(String::new());
411 }
412 let start = pos.min(anchor);
413 let len = pos.max(anchor) - start;
414 let inner = self.doc.lock();
415 let dto = frontend::document_inspection::GetTextAtPositionDto {
416 position: to_i64(start),
417 length: to_i64(len),
418 };
419 let result = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)?;
420 Ok(result.text)
421 }
422
423 pub fn text_before(&self, max_len: usize) -> Result<String> {
436 if max_len == 0 {
437 return Ok(String::new());
438 }
439 let pos = self.position();
440 let inner = self.doc.lock();
441 let store = inner.ctx.db_context.get_store();
442
443 if pos > 0
448 && common::database::rope_helpers::find_block_at_char_position(store, 0).is_none()
449 {
450 let dto = frontend::document_inspection::GetTextAtPositionDto {
451 position: 0,
452 length: to_i64(pos),
453 };
454 let result = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)?;
455 let full = result.text;
456 let total = full.chars().count();
457 let skip = total.saturating_sub(max_len);
458 return Ok(full.chars().skip(skip).collect());
459 }
460
461 let mut pieces: Vec<String> = Vec::new();
462 let mut remaining = max_len;
463 let mut end_pos = pos;
464
465 while remaining > 0 && end_pos > 0 {
466 let query = (end_pos - 1) as i64;
467 let Some((block_id, char_in_block, block_char_start)) =
473 common::database::rope_helpers::find_block_at_char_position(store, query)
474 else {
475 break;
479 };
480 let block_dto = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
481 .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
482 let entity: common::entities::Block = block_dto.into();
483 let block_text =
484 common::database::rope_helpers::block_content_via_store(&entity, store);
485 let block_len = block_text.chars().count() as i64;
486 let block_char_start = block_char_start as usize;
487
488 if char_in_block == block_len {
489 pieces.push("\n".to_string());
491 remaining -= 1;
492 if remaining == 0 {
493 break;
494 }
495 let take = remaining.min(block_len as usize);
496 let local_start = block_len as usize - take;
497 let slice: String = block_text.chars().skip(local_start).take(take).collect();
498 pieces.push(slice);
499 remaining -= take;
500 end_pos = block_char_start + local_start;
501 } else {
502 let available = char_in_block as usize + 1;
504 let take = remaining.min(available);
505 let local_start = available - take;
506 let slice: String = block_text.chars().skip(local_start).take(take).collect();
507 pieces.push(slice);
508 remaining -= take;
509 end_pos = block_char_start + local_start;
510 }
511 }
512
513 pieces.reverse();
514 Ok(pieces.concat())
515 }
516
517 pub fn clear_selection(&self) {
519 let mut d = self.data.lock();
520 d.anchor = d.position;
521 d.whole_text_selected = false;
522 }
523
524 fn caret_block(
535 inner: &TextDocumentInner,
536 position: usize,
537 ) -> Option<frontend::document_inspection::BlockInfoDto> {
538 crate::inner::block_at_caret_dto(&inner.ctx, position).ok()
539 }
540
541 pub fn at_block_start(&self) -> bool {
543 let pos = self.position();
544 let inner = self.doc.lock();
545 Self::caret_block(&inner, pos).is_some_and(|info| pos == to_usize(info.block_start))
546 }
547
548 pub fn at_block_end(&self) -> bool {
551 let pos = self.position();
552 let inner = self.doc.lock();
553 Self::caret_block(&inner, pos)
554 .is_some_and(|info| pos == to_usize(info.block_start) + to_usize(info.block_length))
555 }
556
557 pub fn at_start(&self) -> bool {
559 self.data.lock().position == 0
560 }
561
562 pub fn at_end(&self) -> bool {
564 let pos = self.position();
565 let inner = self.doc.lock();
566 pos >= max_cursor_position_of(&inner).unwrap_or(0)
567 }
568
569 pub fn block_number(&self) -> usize {
571 let pos = self.position();
572 let inner = self.doc.lock();
573 Self::caret_block(&inner, pos).map_or(0, |info| to_usize(info.block_number))
574 }
575
576 pub fn position_in_block(&self) -> usize {
579 let pos = self.position();
580 let inner = self.doc.lock();
581 Self::caret_block(&inner, pos)
582 .map_or(0, |info| pos.saturating_sub(to_usize(info.block_start)))
583 }
584
585 pub fn set_position(&self, position: usize, mode: MoveMode) {
599 let end = {
601 let inner = self.doc.lock();
602 max_cursor_position_of(&inner).unwrap_or(0)
603 };
604 let mut pos = position.min(end);
605
606 if mode == MoveMode::KeepAnchor {
610 let anchor = self.data.lock().anchor;
611 let pos_cell = self.table_cell_at(pos);
612 let anchor_cell = self.selection_anchor_cell(anchor, pos_cell.as_ref());
613 match (&pos_cell, &anchor_cell) {
614 (Some(tc), None) => {
615 let before = anchor < pos;
617 if let Some(boundary) = self.table_boundary_position(tc.table.id(), !before) {
618 pos = boundary;
619 }
620 }
621 (None, Some(tc)) => {
622 let before = pos < anchor;
625 if let Some(boundary) = self.table_boundary_position(tc.table.id(), !before) {
626 pos = boundary;
627 }
628 }
629 _ => {}
630 }
631 }
632
633 {
634 let mut d = self.data.lock();
635 d.position = pos;
636 if mode == MoveMode::MoveAnchor {
637 d.anchor = pos;
638 }
639 d.cell_selection_override = None;
640 d.whole_text_selected = false;
641 }
642 self.snap_position_to_grapheme_boundary();
647 }
648
649 pub fn move_position(&self, operation: MoveOperation, mode: MoveMode, n: usize) -> bool {
659 let old_pos = self.position();
660 let target = self.kept_in_main_text(old_pos, self.resolve_move(operation, n));
661 self.set_position(target, mode);
662 self.position() != old_pos
663 }
664
665 fn kept_in_main_text(&self, from: usize, target: usize) -> usize {
671 if target <= from {
672 return target;
673 }
674 let inner = self.doc.lock();
675 let store = inner.ctx.db_context.get_store();
676 match common::database::rope_helpers::main_text_end(store) {
677 Some(end) if from <= to_usize(end) && target > to_usize(end) => to_usize(end),
678 _ => target,
679 }
680 }
681
682 pub fn select(&self, selection: SelectionType) {
684 match selection {
685 SelectionType::Document => {
686 let end = {
687 let inner = self.doc.lock();
688 max_cursor_position_of(&inner).unwrap_or(0)
689 };
690 let mut d = self.data.lock();
691 d.anchor = 0;
692 d.position = end;
693 d.cell_selection_override = None;
694 d.whole_text_selected = true;
695 }
696 SelectionType::BlockUnderCursor | SelectionType::LineUnderCursor => {
697 let pos = self.position();
698 let inner = self.doc.lock();
699 if let Some(info) = Self::caret_block(&inner, pos) {
701 let start = to_usize(info.block_start);
702 let end = start + to_usize(info.block_length);
703 drop(inner);
704 let mut d = self.data.lock();
705 d.anchor = start;
706 d.position = end;
707 d.cell_selection_override = None;
708 d.whole_text_selected = false;
709 }
710 }
711 SelectionType::WordUnderCursor => {
712 let pos = self.position();
713 let (word_start, word_end) = self.find_word_boundaries(pos);
714 let mut d = self.data.lock();
715 d.anchor = word_start;
716 d.position = word_end;
717 d.cell_selection_override = None;
718 d.whole_text_selected = false;
719 }
720 SelectionType::SentenceUnderCursor => {
721 let pos = self.position();
722 if let Some((start, end)) = self.find_sentence_boundaries(pos) {
725 let mut d = self.data.lock();
726 d.anchor = start;
727 d.position = end;
728 d.cell_selection_override = None;
729 d.whole_text_selected = false;
730 }
731 }
732 }
733 }
734
735 pub fn set_content_locale(&self, locale: Option<&str>) {
744 self.data.lock().content_locale = locale.map(str::to_string);
745 }
746
747 pub fn content_locale(&self) -> Option<String> {
749 self.data.lock().content_locale.clone()
750 }
751
752 pub fn insert_text(&self, text: &str) -> Result<()> {
759 self.insert_text_with_origin(text, InsertionOrigin::Unspecified)
760 }
761
762 pub fn insert_text_with_origin(&self, text: &str, origin: InsertionOrigin) -> Result<()> {
767 let (pos, anchor) = self.read_cursor();
768
769 let dto = frontend::document_editing::InsertTextDto {
771 format_policy: Default::default(),
772 position: to_i64(pos),
773 anchor: to_i64(anchor),
774 text: text.into(),
775 };
776
777 let queued = {
778 let mut inner = self.doc.lock();
779 let edit_pos = pos.min(anchor);
780 let before = max_cursor_position_of(&inner);
781 let result = match document_editing_commands::insert_text(
782 &inner.ctx,
783 Some(inner.stack_id),
784 &dto,
785 ) {
786 Ok(r) => r,
787 Err(_) if pos != anchor => {
790 delete_then(&inner, pos, anchor, |at| {
791 let ins_dto = frontend::document_editing::InsertTextDto {
792 format_policy: Default::default(),
793 position: to_i64(at),
794 anchor: to_i64(at),
795 text: text.into(),
796 };
797 Ok(document_editing_commands::insert_text(
798 &inner.ctx,
799 Some(inner.stack_id),
800 &ins_dto,
801 )?)
802 })?
803 .0
804 }
805 Err(e) => return Err(e.into()),
806 };
807
808 let new_pos = to_usize(result.new_position);
809 let added = text.chars().count();
810 let removed = removed_since(&inner, before, added, pos.max(anchor) - edit_pos);
811 self.finish_edit_from(
812 &mut inner,
813 edit_pos,
814 removed,
815 Insertion::ending_at(new_pos, added),
816 new_pos,
817 to_usize(result.blocks_affected),
818 false,
819 origin,
820 )
821 };
822 crate::inner::dispatch_queued_events(queued);
823 Ok(())
824 }
825
826 pub fn replace(
840 &self,
841 start: usize,
842 end: usize,
843 text: &str,
844 policy: crate::ReplaceFormatPolicy,
845 ) -> Result<()> {
846 let (pos, anchor) = (start, end);
847
848 let dto = frontend::document_editing::InsertTextDto {
849 format_policy: policy,
850 position: to_i64(pos),
851 anchor: to_i64(anchor),
852 text: text.into(),
853 };
854
855 let queued = {
856 let mut inner = self.doc.lock();
857 let edit_pos = pos.min(anchor);
858 let before = max_cursor_position_of(&inner);
859 let result = match document_editing_commands::insert_text(
860 &inner.ctx,
861 Some(inner.stack_id),
862 &dto,
863 ) {
864 Ok(r) => r,
865 Err(_) if pos != anchor => {
869 delete_then(&inner, pos, anchor, |at| {
870 let ins_dto = frontend::document_editing::InsertTextDto {
871 format_policy: Default::default(),
872 position: to_i64(at),
873 anchor: to_i64(at),
874 text: text.into(),
875 };
876 Ok(document_editing_commands::insert_text(
877 &inner.ctx,
878 Some(inner.stack_id),
879 &ins_dto,
880 )?)
881 })?
882 .0
883 }
884 Err(e) => return Err(e.into()),
885 };
886
887 let new_pos = to_usize(result.new_position);
888 let added = text.chars().count();
889 let removed = removed_since(&inner, before, added, pos.max(anchor) - edit_pos);
890 self.finish_edit_ext(
891 &mut inner,
892 edit_pos,
893 removed,
894 Insertion::ending_at(new_pos, added),
895 new_pos,
896 to_usize(result.blocks_affected),
897 false,
898 )
899 };
900 crate::inner::dispatch_queued_events(queued);
901 Ok(())
902 }
903
904 pub fn insert_formatted_text(&self, text: &str, format: &TextFormat) -> Result<()> {
907 self.insert_formatted_text_with_origin(text, format, InsertionOrigin::Unspecified)
908 }
909
910 pub fn insert_formatted_text_with_origin(
913 &self,
914 text: &str,
915 format: &TextFormat,
916 origin: InsertionOrigin,
917 ) -> Result<()> {
918 let (pos, anchor) = self.read_cursor();
919
920 let make_dto = |p: usize, a: usize| frontend::document_editing::InsertFormattedTextDto {
921 position: to_i64(p),
922 anchor: to_i64(a),
923 text: text.into(),
924 font_family: format.font_family.clone().unwrap_or_default(),
925 font_point_size: format.font_point_size.map(|v| v as i64).unwrap_or(0),
926 font_bold: format.font_bold.unwrap_or(false),
927 font_italic: format.font_italic.unwrap_or(false),
928 font_underline: format.font_underline.unwrap_or(false),
929 font_strikeout: format.font_strikeout.unwrap_or(false),
930 };
931
932 let queued = {
933 let mut inner = self.doc.lock();
934 let edit_pos = pos.min(anchor);
935 let before = max_cursor_position_of(&inner);
936 let result = match document_editing_commands::insert_formatted_text(
937 &inner.ctx,
938 Some(inner.stack_id),
939 &make_dto(pos, anchor),
940 ) {
941 Ok(r) => r,
942 Err(_) if pos != anchor => {
944 delete_then(&inner, pos, anchor, |at| {
945 Ok(document_editing_commands::insert_formatted_text(
946 &inner.ctx,
947 Some(inner.stack_id),
948 &make_dto(at, at),
949 )?)
950 })?
951 .0
952 }
953 Err(e) => return Err(e.into()),
954 };
955
956 let new_pos = to_usize(result.new_position);
957 let added = text.chars().count();
958 let removed = removed_since(&inner, before, added, pos.max(anchor) - edit_pos);
959 self.finish_edit_from(
960 &mut inner,
961 edit_pos,
962 removed,
963 Insertion::ending_at(new_pos, added),
964 new_pos,
965 1,
966 false,
967 origin,
968 )
969 };
970 crate::inner::dispatch_queued_events(queued);
971 Ok(())
972 }
973
974 pub fn insert_block(&self) -> Result<()> {
976 let (pos, anchor) = self.read_cursor();
977 let queued = {
978 let mut inner = self.doc.lock();
979
980 let split_at = |at: usize| -> Result<_> {
981 let dto = frontend::document_editing::InsertBlockDto {
982 position: to_i64(at),
983 anchor: to_i64(at),
984 };
985 Ok(document_editing_commands::insert_block(
986 &inner.ctx,
987 Some(inner.stack_id),
988 &dto,
989 )?)
990 };
991 let before = max_cursor_position_of(&inner);
992 let result = if pos != anchor {
993 delete_then(&inner, pos, anchor, split_at)?.0
995 } else {
996 split_at(pos)?
997 };
998
999 let edit_pos = pos.min(anchor);
1000 let new_pos = to_usize(result.new_position);
1001 let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1003 self.finish_edit(
1004 &mut inner,
1005 edit_pos,
1006 removed,
1007 Insertion::ending_at(new_pos, 1),
1008 new_pos,
1009 2,
1010 )
1011 };
1012 crate::inner::dispatch_queued_events(queued);
1013 Ok(())
1014 }
1015
1016 pub fn insert_html_with_origin(&self, html: &str, origin: InsertionOrigin) -> Result<()> {
1020 let frag = DocumentFragment::from_html(html);
1021 self.insert_fragment_with_origin(&frag, origin)
1022 }
1023
1024 pub fn insert_html(&self, html: &str) -> Result<()> {
1029 let frag = DocumentFragment::from_html(html);
1031 self.insert_fragment(&frag)
1032 }
1033
1034 pub fn insert_markdown_with_origin(
1038 &self,
1039 markdown: &str,
1040 origin: InsertionOrigin,
1041 ) -> Result<()> {
1042 let frag = DocumentFragment::from_markdown(markdown);
1043 self.insert_fragment_with_origin(&frag, origin)
1044 }
1045
1046 pub fn insert_markdown(&self, markdown: &str) -> Result<()> {
1047 let frag = DocumentFragment::from_markdown(markdown);
1048 self.insert_fragment(&frag)
1049 }
1050
1051 pub fn insert_djot_with_origin(&self, djot: &str, origin: InsertionOrigin) -> Result<()> {
1055 let frag = DocumentFragment::from_djot(djot);
1056 self.insert_fragment_with_origin(&frag, origin)
1057 }
1058
1059 pub fn insert_djot(&self, djot: &str) -> Result<()> {
1060 let frag = DocumentFragment::from_djot(djot);
1061 self.insert_fragment(&frag)
1062 }
1063
1064 pub fn insert_footnote_reference(&self, label: &str) -> Result<()> {
1080 self.insert_djot(&format!("[^{label}]"))
1081 }
1082
1083 pub fn insert_fragment(&self, fragment: &DocumentFragment) -> Result<()> {
1123 self.insert_fragment_with_origin(fragment, InsertionOrigin::Unspecified)
1124 }
1125
1126 pub fn insert_fragment_with_origin(
1130 &self,
1131 fragment: &DocumentFragment,
1132 origin: InsertionOrigin,
1133 ) -> Result<()> {
1134 let (pos, anchor) = self.read_cursor();
1135 let queued = {
1136 let mut inner = self.doc.lock();
1137 let replacing_an_empty_text = pos == anchor && self.data.lock().whole_text_selected;
1141
1142 let paste_at = |at: usize, replacing: bool| -> Result<_> {
1152 let store = inner.ctx.db_context.get_store();
1153 let rope_before = store.rope.read().clone();
1154 let before = max_cursor_position_of(&inner);
1155 let fragment_data = if replacing {
1156 frontend::common::parser_tools::fragment_schema::replacing_the_text(
1157 fragment.raw_data(),
1158 )
1159 } else {
1160 fragment.raw_data().into()
1161 };
1162 let dto = frontend::document_editing::InsertFragmentDto {
1163 position: to_i64(at),
1164 anchor: to_i64(at),
1165 fragment_data,
1166 };
1167 let result = document_editing_commands::insert_fragment(
1168 &inner.ctx,
1169 Some(inner.stack_id),
1170 &dto,
1171 )?;
1172 let inserted = if common::database::rope_helpers::rope_positions_match_flow(store) {
1173 let (start, old_end, new_end) = common::database::rope_helpers::changed_span(
1174 &rope_before,
1175 &store.rope.read(),
1176 at,
1177 );
1178 Insertion {
1179 at: start,
1180 removed: old_end - start,
1181 added: new_end - start,
1182 }
1183 } else {
1184 let new_pos = to_usize(result.new_position);
1187 let added = before
1188 .zip(max_cursor_position_of(&inner))
1189 .map_or(new_pos.saturating_sub(at), |(before, after)| {
1190 after.saturating_sub(before)
1191 });
1192 Insertion {
1193 at,
1194 removed: 0,
1195 added,
1196 }
1197 };
1198 Ok((result, inserted))
1199 };
1200 let ((result, inserted), removed, deleted_from) = if pos != anchor {
1201 delete_then(&inner, pos, anchor, |at| paste_at(at, true))?
1202 } else {
1203 (paste_at(pos, replacing_an_empty_text)?, 0, pos)
1204 };
1205
1206 let edit_pos = pos.min(anchor).min(deleted_from);
1209 let new_pos = to_usize(result.new_position);
1210 self.finish_edit_from(
1211 &mut inner,
1212 edit_pos,
1213 removed,
1214 inserted,
1215 new_pos,
1216 to_usize(result.blocks_added),
1217 true,
1218 origin,
1219 )
1220 };
1221 crate::inner::dispatch_queued_events(queued);
1222 Ok(())
1223 }
1224
1225 pub fn selection(&self) -> DocumentFragment {
1235 let (pos, anchor) = self.read_cursor();
1236
1237 let (extract_pos, extract_anchor) = match self.selection_kind() {
1240 SelectionKind::Cells(ref range) => match self.cell_range_positions(range) {
1241 Some((start, end)) => (start, end),
1242 None => return DocumentFragment::new(),
1243 },
1244 SelectionKind::Mixed {
1245 ref cell_range,
1246 text_before,
1247 text_after,
1248 } => {
1249 let (cell_start, cell_end) = match self.cell_range_positions(cell_range) {
1250 Some(p) => p,
1251 None => return DocumentFragment::new(),
1252 };
1253 let table_start = self
1257 .table_anchor_position(cell_range.table_id)
1258 .unwrap_or(cell_start)
1259 .min(cell_start);
1260 let start = if text_before {
1261 pos.min(anchor).min(table_start)
1262 } else {
1263 table_start
1264 };
1265 let end = if text_after {
1266 pos.max(anchor)
1267 } else {
1268 cell_end
1269 };
1270 (start.min(cell_start), end.max(cell_end))
1271 }
1272 SelectionKind::None => return DocumentFragment::new(),
1273 SelectionKind::Text => (pos, anchor),
1274 };
1275
1276 if extract_pos == extract_anchor {
1277 return DocumentFragment::new();
1278 }
1279
1280 let inner = self.doc.lock();
1281 let dto = frontend::document_inspection::ExtractFragmentDto {
1282 position: to_i64(extract_pos),
1283 anchor: to_i64(extract_anchor),
1284 };
1285 match document_inspection_commands::extract_fragment(&inner.ctx, &dto) {
1286 Ok(result) => DocumentFragment::from_raw(result.fragment_data, result.plain_text),
1287 Err(_) => DocumentFragment::new(),
1288 }
1289 }
1290
1291 pub fn insert_image(&self, name: &str, alt: &str, width: u32, height: u32) -> Result<()> {
1300 let (pos, anchor) = self.read_cursor();
1301 let queued = {
1302 let mut inner = self.doc.lock();
1303
1304 let image_at = |at: usize| -> Result<_> {
1305 let dto = frontend::document_editing::InsertImageDto {
1306 position: to_i64(at),
1307 anchor: to_i64(at),
1308 image_name: name.into(),
1309 alt: alt.into(),
1310 width: width as i64,
1311 height: height as i64,
1312 quality: 100,
1313 };
1314 Ok(document_editing_commands::insert_image(
1315 &inner.ctx,
1316 Some(inner.stack_id),
1317 &dto,
1318 )?)
1319 };
1320 let before = max_cursor_position_of(&inner);
1321 let result = if pos != anchor {
1322 delete_then(&inner, pos, anchor, image_at)?.0
1323 } else {
1324 image_at(pos)?
1325 };
1326
1327 let edit_pos = pos.min(anchor);
1328 let new_pos = to_usize(result.new_position);
1329 let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1331 self.finish_edit_ext(
1332 &mut inner,
1333 edit_pos,
1334 removed,
1335 Insertion::ending_at(new_pos, 1),
1336 new_pos,
1337 1,
1338 false,
1339 )
1340 };
1341 crate::inner::dispatch_queued_events(queued);
1342 Ok(())
1343 }
1344
1345 pub fn insert_frame(&self) -> Result<()> {
1347 let (pos, anchor) = self.read_cursor();
1348 let queued = {
1349 let mut inner = self.doc.lock();
1350 let dto = frontend::document_editing::InsertFrameDto {
1351 position: to_i64(pos),
1352 anchor: to_i64(anchor),
1353 };
1354 document_editing_commands::insert_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1355 inner.modified = true;
1358 inner.invalidate_text_cache();
1359 inner.rehighlight_affected(pos.min(anchor));
1360 inner.queue_event(DocumentEvent::ContentsChanged {
1361 position: pos.min(anchor),
1362 chars_removed: 0,
1363 chars_added: 0,
1364 blocks_affected: 1,
1365 });
1366 inner.check_block_count_changed();
1367 inner.check_flow_changed();
1368 self.queue_undo_redo_event(&mut inner)
1369 };
1370 crate::inner::dispatch_queued_events(queued);
1371 Ok(())
1372 }
1373
1374 pub fn insert_table(&self, rows: usize, columns: usize) -> Result<TextTable> {
1380 let (pos, anchor) = self.read_cursor();
1381 let (table_id, queued) = {
1382 let mut inner = self.doc.lock();
1383 let dto = frontend::document_editing::InsertTableDto {
1384 position: to_i64(pos),
1385 anchor: to_i64(anchor),
1386 rows: to_i64(rows),
1387 columns: to_i64(columns),
1388 };
1389 let result =
1390 document_editing_commands::insert_table(&inner.ctx, Some(inner.stack_id), &dto)?;
1391 let new_pos = to_usize(result.new_position);
1392 let table_id = to_usize(result.table_id);
1393 inner.adjust_cursors(pos.min(anchor), 0, new_pos - pos.min(anchor));
1394 {
1395 let mut d = self.data.lock();
1396 d.position = new_pos;
1397 d.anchor = new_pos;
1398 d.whole_text_selected = false;
1399 }
1400 inner.modified = true;
1401 inner.invalidate_text_cache();
1402 inner.rehighlight_affected(pos.min(anchor));
1403 inner.queue_event(DocumentEvent::ContentsChanged {
1404 position: pos.min(anchor),
1405 chars_removed: 0,
1406 chars_added: new_pos - pos.min(anchor),
1407 blocks_affected: 1,
1408 });
1409 inner.check_block_count_changed();
1410 inner.check_flow_changed();
1411 (table_id, self.queue_undo_redo_event(&mut inner))
1412 };
1413 crate::inner::dispatch_queued_events(queued);
1414 Ok(TextTable {
1415 doc: self.doc.clone(),
1416 table_id,
1417 })
1418 }
1419
1420 pub fn current_table(&self) -> Option<TextTable> {
1425 self.current_table_cell().map(|c| c.table)
1426 }
1427
1428 pub fn current_table_cell(&self) -> Option<TableCellRef> {
1433 let pos = self.position();
1434 let inner = self.doc.lock();
1435 let block_id = crate::inner::block_at_caret_dto(&inner.ctx, pos)
1438 .ok()?
1439 .block_id as usize;
1440
1441 let block = crate::text_block::TextBlock {
1442 doc: self.doc.clone(),
1443 block_id,
1444 };
1445 drop(inner);
1447 block.table_cell()
1448 }
1449
1450 pub fn current_frame(&self) -> Option<FrameRef> {
1457 let pos = self.position();
1458 let inner = self.doc.lock();
1459 let block_info = Self::caret_block(&inner, pos)?;
1460 let block_id = block_info.block_id as u64;
1461 cursor_frame_ref(&inner, block_id)
1462 }
1463
1464 pub fn is_in_blockquote(&self) -> bool {
1468 self.current_blockquote_frame_id().is_some()
1469 }
1470
1471 pub fn current_blockquote_frame_id(&self) -> Option<usize> {
1474 let pos = self.position();
1475 let inner = self.doc.lock();
1476 let block_info = Self::caret_block(&inner, pos)?;
1477 innermost_blockquote_frame_id(&inner, block_info.block_id as u64)
1478 }
1479
1480 pub fn blockquote_depth_at_cursor(&self) -> usize {
1483 let pos = self.position();
1484 let inner = self.doc.lock();
1485 let Some(block_info) = Self::caret_block(&inner, pos) else {
1486 return 0;
1487 };
1488 blockquote_depth_for_block(&inner, block_info.block_id as u64)
1489 }
1490
1491 pub fn is_first_block_in_current_frame(&self) -> bool {
1497 matches!(
1498 block_position_in_current_frame(self),
1499 Some(BlockEdge::First) | Some(BlockEdge::OnlyOne)
1500 )
1501 }
1502
1503 pub fn is_last_block_in_current_frame(&self) -> bool {
1507 matches!(
1508 block_position_in_current_frame(self),
1509 Some(BlockEdge::Last) | Some(BlockEdge::OnlyOne)
1510 )
1511 }
1512
1513 pub fn current_block_is_empty(&self) -> bool {
1516 let pos = self.position();
1517 let inner = self.doc.lock();
1518 let Some(block_info) = Self::caret_block(&inner, pos) else {
1519 return false;
1520 };
1521 let store = inner.ctx.db_context.get_store();
1522 let block_entity = store
1523 .blocks
1524 .read()
1525 .get(&(block_info.block_id as common::types::EntityId))
1526 .cloned();
1527 match block_entity {
1528 Some(b) => {
1529 let len = common::database::rope_helpers::block_char_length(&b, store);
1530 len == 0
1531 }
1532 None => false,
1533 }
1534 }
1535
1536 pub fn selection_spans_multiple_frames(&self) -> bool {
1540 let (pos, anchor) = self.read_cursor();
1541 if pos == anchor {
1542 return false;
1543 }
1544 let inner = self.doc.lock();
1545 let Some((first, last)) = Self::selection_block_ids(&inner, pos, anchor) else {
1548 return false;
1549 };
1550 crate::text_block::find_parent_frame(&inner, first)
1551 != crate::text_block::find_parent_frame(&inner, last)
1552 }
1553
1554 fn selection_block_ids(
1562 inner: &TextDocumentInner,
1563 pos: usize,
1564 anchor: usize,
1565 ) -> Option<(u64, u64)> {
1566 let (lo, hi) = (pos.min(anchor), pos.max(anchor));
1567 let last = Self::caret_block(inner, hi)?.block_id as u64;
1568 if lo == hi {
1569 return Some((last, last));
1570 }
1571 let first = document_inspection_commands::get_block_at_position(
1572 &inner.ctx,
1573 &frontend::document_inspection::GetBlockAtPositionDto {
1574 position: to_i64(lo),
1575 },
1576 )
1577 .ok()?
1578 .block_id as u64;
1579 Some((first, last))
1580 }
1581
1582 pub fn wrap_selection_in_blockquote(&self) -> Result<()> {
1589 if self.selection_spans_multiple_frames() {
1590 return Err(DocumentError::InvalidArgument(
1591 "Cannot wrap selection in blockquote: selection spans multiple frames".into(),
1592 ));
1593 }
1594 let (start_block_id, end_block_id) = self.resolve_selection_block_range()?;
1595 let dto = frontend::document_editing::WrapBlocksInFrameDto {
1596 start_block_id: start_block_id as i64,
1597 end_block_id: end_block_id as i64,
1598 position: Some(frontend::document_editing::FramePosition::InFlow),
1599 top_margin: None,
1600 bottom_margin: None,
1601 left_margin: None,
1602 right_margin: None,
1603 padding: None,
1604 border: None,
1605 is_blockquote: Some(true),
1606 };
1607 let queued = {
1608 let mut inner = self.doc.lock();
1609 let _result = document_editing_commands::wrap_blocks_in_frame(
1610 &inner.ctx,
1611 Some(inner.stack_id),
1612 &dto,
1613 )?;
1614 inner.modified = true;
1615 inner.queue_event(DocumentEvent::FormatChanged {
1623 position: 0,
1624 length: 0,
1625 kind: crate::flow::FormatChangeKind::Block,
1626 });
1627 self.queue_undo_redo_event(&mut inner)
1628 };
1629 crate::inner::dispatch_queued_events(queued);
1630 Ok(())
1631 }
1632
1633 pub fn insert_blockquote(&self) -> Result<()> {
1637 self.wrap_selection_in_blockquote()
1638 }
1639
1640 pub fn toggle_blockquote(&self) -> Result<()> {
1645 if let Some(frame_id) = self.current_blockquote_frame_id() {
1646 self.unwrap_frame_by_id(frame_id)
1647 } else {
1648 self.wrap_selection_in_blockquote()
1649 }
1650 }
1651
1652 pub fn unwrap_current_frame(&self) -> Result<()> {
1656 let frame_ref = self.current_frame().ok_or_else(|| {
1657 DocumentError::InvalidCursorContext("Cursor is not inside any sub-frame".into())
1658 })?;
1659 self.unwrap_frame_by_id(frame_ref.frame_id)
1660 }
1661
1662 pub fn unwrap_current_block_from_blockquote(&self) -> Result<()> {
1666 if self.current_blockquote_frame_id().is_none() {
1667 return Err(DocumentError::InvalidCursorContext(
1668 "Cursor is not inside a blockquote".into(),
1669 ));
1670 }
1671 let block_id = self.current_block_id_for_mutation()?;
1672 let dto = frontend::document_editing::UnwrapBlockFromFrameDto {
1673 block_id: block_id as i64,
1674 };
1675 let queued = {
1676 let mut inner = self.doc.lock();
1677 let _result = document_editing_commands::unwrap_block_from_frame(
1678 &inner.ctx,
1679 Some(inner.stack_id),
1680 &dto,
1681 )?;
1682 inner.modified = true;
1683 inner.queue_event(DocumentEvent::FormatChanged {
1687 position: 0,
1688 length: 0,
1689 kind: crate::flow::FormatChangeKind::Block,
1690 });
1691 self.queue_undo_redo_event(&mut inner)
1692 };
1693 crate::inner::dispatch_queued_events(queued);
1694 Ok(())
1695 }
1696
1697 pub fn increase_blockquote_depth(&self) -> Result<()> {
1701 self.wrap_selection_in_blockquote()
1702 }
1703
1704 pub fn decrease_blockquote_depth(&self) -> Result<()> {
1710 if self.current_blockquote_frame_id().is_none() {
1711 return Err(DocumentError::InvalidCursorContext(
1712 "Cursor is not inside a blockquote to decrease depth".into(),
1713 ));
1714 }
1715 self.unwrap_current_block_from_blockquote()
1716 }
1717
1718 fn unwrap_frame_by_id(&self, frame_id: usize) -> Result<()> {
1719 let dto = frontend::document_editing::UnwrapFrameDto {
1720 frame_id: frame_id as i64,
1721 };
1722 let queued = {
1723 let mut inner = self.doc.lock();
1724 let _result =
1725 document_editing_commands::unwrap_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1726 inner.modified = true;
1727 inner.queue_event(DocumentEvent::FormatChanged {
1731 position: 0,
1732 length: 0,
1733 kind: crate::flow::FormatChangeKind::Block,
1734 });
1735 self.queue_undo_redo_event(&mut inner)
1736 };
1737 crate::inner::dispatch_queued_events(queued);
1738 Ok(())
1739 }
1740
1741 fn current_block_id_for_mutation(&self) -> Result<usize> {
1744 let pos = self.position();
1745 let inner = self.doc.lock();
1746 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
1747 Ok(block_info.block_id as usize)
1748 }
1749
1750 fn resolve_selection_block_range(&self) -> Result<(usize, usize)> {
1754 let (pos, anchor) = self.read_cursor();
1755 let inner = self.doc.lock();
1756 let (first, last) = Self::selection_block_ids(&inner, pos, anchor)
1757 .ok_or_else(|| DocumentError::NotFound("no block at the selection's ends".into()))?;
1758 Ok((first as usize, last as usize))
1759 }
1760
1761 pub fn remove_table(&self, table_id: usize) -> Result<()> {
1765 let queued = {
1766 let mut inner = self.doc.lock();
1767 let before = crate::document::capture_block_state(&inner);
1774 let dto = frontend::document_editing::RemoveTableDto {
1775 table_id: to_i64(table_id),
1776 };
1777 document_editing_commands::remove_table(&inner.ctx, Some(inner.stack_id), &dto)?;
1778 inner.modified = true;
1779 inner.invalidate_text_cache();
1780 inner.rehighlight_all();
1781 crate::document::emit_content_change_events(&mut inner, &before);
1782 inner.check_block_count_changed();
1783 inner.check_flow_changed();
1784 self.queue_undo_redo_event(&mut inner)
1785 };
1786 crate::inner::dispatch_queued_events(queued);
1787 Ok(())
1788 }
1789
1790 pub fn insert_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
1792 let queued = {
1793 let mut inner = self.doc.lock();
1794 let before = crate::document::capture_block_state(&inner);
1795 let dto = frontend::document_editing::InsertTableRowDto {
1796 table_id: to_i64(table_id),
1797 row_index: to_i64(row_index),
1798 };
1799 document_editing_commands::insert_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
1800 inner.modified = true;
1801 inner.invalidate_text_cache();
1802 inner.rehighlight_all();
1803 crate::document::emit_content_change_events(&mut inner, &before);
1804 inner.check_block_count_changed();
1805 self.queue_undo_redo_event(&mut inner)
1806 };
1807 crate::inner::dispatch_queued_events(queued);
1808 Ok(())
1809 }
1810
1811 pub fn insert_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
1813 let queued = {
1814 let mut inner = self.doc.lock();
1815 let before = crate::document::capture_block_state(&inner);
1816 let dto = frontend::document_editing::InsertTableColumnDto {
1817 table_id: to_i64(table_id),
1818 column_index: to_i64(column_index),
1819 };
1820 document_editing_commands::insert_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
1821 inner.modified = true;
1822 inner.invalidate_text_cache();
1823 inner.rehighlight_all();
1824 crate::document::emit_content_change_events(&mut inner, &before);
1825 inner.check_block_count_changed();
1826 self.queue_undo_redo_event(&mut inner)
1827 };
1828 crate::inner::dispatch_queued_events(queued);
1829 Ok(())
1830 }
1831
1832 pub fn remove_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
1834 let queued = {
1835 let mut inner = self.doc.lock();
1836 let before = crate::document::capture_block_state(&inner);
1837 let dto = frontend::document_editing::RemoveTableRowDto {
1838 table_id: to_i64(table_id),
1839 row_index: to_i64(row_index),
1840 };
1841 document_editing_commands::remove_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
1842 inner.modified = true;
1843 inner.invalidate_text_cache();
1844 inner.rehighlight_all();
1845 crate::document::emit_content_change_events(&mut inner, &before);
1846 inner.check_block_count_changed();
1847 self.queue_undo_redo_event(&mut inner)
1848 };
1849 crate::inner::dispatch_queued_events(queued);
1850 Ok(())
1851 }
1852
1853 pub fn remove_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
1855 let queued = {
1856 let mut inner = self.doc.lock();
1857 let before = crate::document::capture_block_state(&inner);
1858 let dto = frontend::document_editing::RemoveTableColumnDto {
1859 table_id: to_i64(table_id),
1860 column_index: to_i64(column_index),
1861 };
1862 document_editing_commands::remove_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
1863 inner.modified = true;
1864 inner.invalidate_text_cache();
1865 inner.rehighlight_all();
1866 crate::document::emit_content_change_events(&mut inner, &before);
1867 inner.check_block_count_changed();
1868 self.queue_undo_redo_event(&mut inner)
1869 };
1870 crate::inner::dispatch_queued_events(queued);
1871 Ok(())
1872 }
1873
1874 pub fn merge_table_cells(
1876 &self,
1877 table_id: usize,
1878 start_row: usize,
1879 start_column: usize,
1880 end_row: usize,
1881 end_column: usize,
1882 ) -> Result<()> {
1883 let queued = {
1884 let mut inner = self.doc.lock();
1885 let before = crate::document::capture_block_state(&inner);
1886 let dto = frontend::document_editing::MergeTableCellsDto {
1887 table_id: to_i64(table_id),
1888 start_row: to_i64(start_row),
1889 start_column: to_i64(start_column),
1890 end_row: to_i64(end_row),
1891 end_column: to_i64(end_column),
1892 };
1893 document_editing_commands::merge_table_cells(&inner.ctx, Some(inner.stack_id), &dto)?;
1894 inner.modified = true;
1895 inner.invalidate_text_cache();
1896 inner.rehighlight_all();
1897 crate::document::emit_content_change_events(&mut inner, &before);
1898 inner.check_block_count_changed();
1899 self.queue_undo_redo_event(&mut inner)
1900 };
1901 crate::inner::dispatch_queued_events(queued);
1902 Ok(())
1903 }
1904
1905 pub fn split_table_cell(
1907 &self,
1908 cell_id: usize,
1909 split_rows: usize,
1910 split_columns: usize,
1911 ) -> Result<()> {
1912 let queued = {
1913 let mut inner = self.doc.lock();
1914 let before = crate::document::capture_block_state(&inner);
1915 let dto = frontend::document_editing::SplitTableCellDto {
1916 cell_id: to_i64(cell_id),
1917 split_rows: to_i64(split_rows),
1918 split_columns: to_i64(split_columns),
1919 };
1920 document_editing_commands::split_table_cell(&inner.ctx, Some(inner.stack_id), &dto)?;
1921 inner.modified = true;
1922 inner.invalidate_text_cache();
1923 inner.rehighlight_all();
1924 crate::document::emit_content_change_events(&mut inner, &before);
1925 inner.check_block_count_changed();
1926 self.queue_undo_redo_event(&mut inner)
1927 };
1928 crate::inner::dispatch_queued_events(queued);
1929 Ok(())
1930 }
1931
1932 pub fn set_table_format(
1936 &self,
1937 table_id: usize,
1938 format: &crate::flow::TableFormat,
1939 ) -> Result<()> {
1940 let queued = {
1941 let mut inner = self.doc.lock();
1942 let dto = format.to_set_dto(table_id);
1943 document_formatting_commands::set_table_format(&inner.ctx, Some(inner.stack_id), &dto)?;
1944 inner.modified = true;
1945 inner.queue_event(DocumentEvent::FormatChanged {
1946 position: 0,
1947 length: 0,
1948 kind: crate::flow::FormatChangeKind::Block,
1949 });
1950 self.queue_undo_redo_event(&mut inner)
1951 };
1952 crate::inner::dispatch_queued_events(queued);
1953 Ok(())
1954 }
1955
1956 pub fn set_table_cell_format(
1958 &self,
1959 cell_id: usize,
1960 format: &crate::flow::CellFormat,
1961 ) -> Result<()> {
1962 let queued = {
1963 let mut inner = self.doc.lock();
1964 let dto = format.to_set_dto(cell_id);
1965 document_formatting_commands::set_table_cell_format(
1966 &inner.ctx,
1967 Some(inner.stack_id),
1968 &dto,
1969 )?;
1970 inner.modified = true;
1971 inner.queue_event(DocumentEvent::FormatChanged {
1972 position: 0,
1973 length: 0,
1974 kind: crate::flow::FormatChangeKind::Block,
1975 });
1976 self.queue_undo_redo_event(&mut inner)
1977 };
1978 crate::inner::dispatch_queued_events(queued);
1979 Ok(())
1980 }
1981
1982 pub fn remove_current_table(&self) -> Result<()> {
1987 let table = self.current_table().ok_or_else(|| {
1988 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
1989 })?;
1990 self.remove_table(table.id())
1991 }
1992
1993 pub fn insert_row_above(&self) -> Result<()> {
1996 let cell_ref = self.current_table_cell().ok_or_else(|| {
1997 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
1998 })?;
1999 self.insert_table_row(cell_ref.table.id(), cell_ref.row)
2000 }
2001
2002 pub fn insert_row_below(&self) -> Result<()> {
2005 let cell_ref = self.current_table_cell().ok_or_else(|| {
2006 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2007 })?;
2008 self.insert_table_row(cell_ref.table.id(), cell_ref.row + 1)
2009 }
2010
2011 pub fn insert_column_before(&self) -> Result<()> {
2014 let cell_ref = self.current_table_cell().ok_or_else(|| {
2015 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2016 })?;
2017 self.insert_table_column(cell_ref.table.id(), cell_ref.column)
2018 }
2019
2020 pub fn insert_column_after(&self) -> Result<()> {
2023 let cell_ref = self.current_table_cell().ok_or_else(|| {
2024 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2025 })?;
2026 self.insert_table_column(cell_ref.table.id(), cell_ref.column + 1)
2027 }
2028
2029 pub fn remove_current_row(&self) -> Result<()> {
2032 let cell_ref = self.current_table_cell().ok_or_else(|| {
2033 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2034 })?;
2035 self.remove_table_row(cell_ref.table.id(), cell_ref.row)
2036 }
2037
2038 pub fn remove_current_column(&self) -> Result<()> {
2041 let cell_ref = self.current_table_cell().ok_or_else(|| {
2042 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2043 })?;
2044 self.remove_table_column(cell_ref.table.id(), cell_ref.column)
2045 }
2046
2047 pub fn merge_selected_cells(&self) -> Result<()> {
2054 let pos_cell = self.current_table_cell().ok_or_else(|| {
2055 DocumentError::InvalidCursorContext("cursor position is not inside a table".into())
2056 })?;
2057
2058 let (_pos, anchor) = self.read_cursor();
2063 let anchor_cell = self.table_cell_at(anchor).ok_or_else(|| {
2064 DocumentError::InvalidCursorContext("cursor anchor is not inside a table".into())
2065 })?;
2066
2067 if pos_cell.table.id() != anchor_cell.table.id() {
2068 return Err(DocumentError::InvalidArgument(
2069 "position and anchor are in different tables".into(),
2070 ));
2071 }
2072
2073 let start_row = pos_cell.row.min(anchor_cell.row);
2074 let start_col = pos_cell.column.min(anchor_cell.column);
2075 let end_row = pos_cell.row.max(anchor_cell.row);
2076 let end_col = pos_cell.column.max(anchor_cell.column);
2077
2078 self.merge_table_cells(pos_cell.table.id(), start_row, start_col, end_row, end_col)
2079 }
2080
2081 pub fn split_current_cell(&self, split_rows: usize, split_columns: usize) -> Result<()> {
2084 let cell_ref = self.current_table_cell().ok_or_else(|| {
2085 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2086 })?;
2087 let cell = cell_ref
2089 .table
2090 .cell(cell_ref.row, cell_ref.column)
2091 .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2092 self.split_table_cell(cell.id(), split_rows, split_columns)
2094 }
2095
2096 pub fn set_current_table_format(&self, format: &crate::flow::TableFormat) -> Result<()> {
2099 let table = self.current_table().ok_or_else(|| {
2100 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2101 })?;
2102 self.set_table_format(table.id(), format)
2103 }
2104
2105 pub fn set_current_cell_format(&self, format: &crate::flow::CellFormat) -> Result<()> {
2108 let cell_ref = self.current_table_cell().ok_or_else(|| {
2109 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2110 })?;
2111 let cell = cell_ref
2112 .table
2113 .cell(cell_ref.row, cell_ref.column)
2114 .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2115 self.set_table_cell_format(cell.id(), format)
2116 }
2117
2118 pub fn selection_kind(&self) -> crate::flow::SelectionKind {
2126 use crate::flow::{CellRange, SelectionKind};
2127
2128 {
2130 let d = self.data.lock();
2131 if let Some(ref range) = d.cell_selection_override {
2132 return SelectionKind::Cells(range.clone());
2133 }
2134 if d.position == d.anchor {
2135 return SelectionKind::None;
2136 }
2137 }
2138
2139 let (pos, anchor) = self.read_cursor();
2140
2141 let pos_cell = self.table_cell_at(pos);
2143 let anchor_cell = self.selection_anchor_cell(anchor, pos_cell.as_ref());
2144
2145 match (&pos_cell, &anchor_cell) {
2146 (None, None) => {
2147 let (start, end) = (pos.min(anchor), pos.max(anchor));
2151 if let Some(t) = self.find_table_between(start, end) {
2152 let table_id = t.id();
2153 let rows = t.rows();
2154 let cols = t.columns();
2155 let range = CellRange {
2156 table_id,
2157 start_row: 0,
2158 start_col: 0,
2159 end_row: if rows > 0 { rows - 1 } else { 0 },
2160 end_col: if cols > 0 { cols - 1 } else { 0 },
2161 };
2162 let spans = self.collect_cell_spans(table_id);
2163 SelectionKind::Mixed {
2164 cell_range: range.expand_for_spans(&spans),
2165 text_before: true,
2166 text_after: true,
2167 }
2168 } else {
2169 SelectionKind::Text
2170 }
2171 }
2172 (Some(pc), Some(ac)) => {
2173 if pc.table.id() != ac.table.id() {
2174 return SelectionKind::Text;
2176 }
2177 if pc.row == ac.row && pc.column == ac.column {
2178 return SelectionKind::Text;
2180 }
2181 let range = CellRange {
2183 table_id: pc.table.id(),
2184 start_row: pc.row.min(ac.row),
2185 start_col: pc.column.min(ac.column),
2186 end_row: pc.row.max(ac.row),
2187 end_col: pc.column.max(ac.column),
2188 };
2189 let spans = self.collect_cell_spans(pc.table.id());
2190 SelectionKind::Cells(range.expand_for_spans(&spans))
2191 }
2192 (Some(tc), None) | (None, Some(tc)) => {
2193 let table_id = tc.table.id();
2197 let rows = tc.table.rows();
2198 let cols = tc.table.columns();
2199
2200 let inside_pos = if pos_cell.is_some() { pos } else { anchor };
2201 let outside_pos = if pos_cell.is_some() { anchor } else { pos };
2202
2203 let text_before = outside_pos < inside_pos;
2204 let text_after = !text_before;
2205
2206 let range = CellRange {
2207 table_id,
2208 start_row: 0,
2209 start_col: 0,
2210 end_row: if rows > 0 { rows - 1 } else { 0 },
2211 end_col: if cols > 0 { cols - 1 } else { 0 },
2212 };
2213 let spans = self.collect_cell_spans(table_id);
2214 SelectionKind::Mixed {
2215 cell_range: range.expand_for_spans(&spans),
2216 text_before,
2217 text_after,
2218 }
2219 }
2220 }
2221 }
2222
2223 pub fn is_cell_selection(&self) -> bool {
2225 matches!(
2226 self.selection_kind(),
2227 crate::flow::SelectionKind::Cells(_) | crate::flow::SelectionKind::Mixed { .. }
2228 )
2229 }
2230
2231 pub fn selected_cell_range(&self) -> Option<crate::flow::CellRange> {
2233 match self.selection_kind() {
2234 crate::flow::SelectionKind::Cells(r) => Some(r),
2235 crate::flow::SelectionKind::Mixed { cell_range, .. } => Some(cell_range),
2236 _ => None,
2237 }
2238 }
2239
2240 pub fn selected_cells(&self) -> Vec<TableCellRef> {
2242 let range = match self.selected_cell_range() {
2243 Some(r) => r,
2244 None => return Vec::new(),
2245 };
2246 let table = TextTable {
2247 doc: self.doc.clone(),
2248 table_id: range.table_id,
2249 };
2250 let mut cells = Vec::new();
2251 for row in range.start_row..=range.end_row {
2252 for col in range.start_col..=range.end_col {
2253 if table.cell(row, col).is_some() {
2254 cells.push(TableCellRef {
2255 table: table.clone(),
2256 row,
2257 column: col,
2258 });
2259 }
2260 }
2261 }
2262 cells
2263 }
2264
2265 pub fn select_table_cell(&self, table_id: usize, row: usize, col: usize) {
2269 let mut d = self.data.lock();
2270 d.cell_selection_override = Some(crate::flow::CellRange {
2271 table_id,
2272 start_row: row,
2273 start_col: col,
2274 end_row: row,
2275 end_col: col,
2276 });
2277 }
2278
2279 pub fn select_cell_range(
2281 &self,
2282 table_id: usize,
2283 start_row: usize,
2284 start_col: usize,
2285 end_row: usize,
2286 end_col: usize,
2287 ) {
2288 let range = crate::flow::CellRange {
2289 table_id,
2290 start_row,
2291 start_col,
2292 end_row,
2293 end_col,
2294 };
2295 let spans = self.collect_cell_spans(table_id);
2296 let mut d = self.data.lock();
2297 d.cell_selection_override = Some(range.expand_for_spans(&spans));
2298 }
2299
2300 pub fn clear_cell_selection(&self) {
2302 let mut d = self.data.lock();
2303 d.cell_selection_override = None;
2304 }
2305
2306 fn cell_range_positions(&self, range: &CellRange) -> Option<(usize, usize)> {
2309 let inner = self.doc.lock();
2310 let main_frame_id = get_main_frame_id(&inner);
2311 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2313 drop(inner);
2314
2315 let table = flow.into_iter().find_map(|e| match e {
2317 FlowElement::Table(t) if t.id() == range.table_id => Some(t),
2318 _ => None,
2319 })?;
2320
2321 let mut min_pos = usize::MAX;
2322 let mut max_pos = 0usize;
2323
2324 for row in range.start_row..=range.end_row {
2325 for col in range.start_col..=range.end_col {
2326 if let Some(cell) = table.cell(row, col) {
2327 for block in cell.blocks() {
2328 let bp = block.position();
2329 let bl = block.length();
2330 min_pos = min_pos.min(bp);
2331 max_pos = max_pos.max(bp + bl);
2332 }
2333 }
2334 }
2335 }
2336
2337 if min_pos == usize::MAX {
2338 return None;
2339 }
2340
2341 Some((min_pos, max_pos + 1))
2343 }
2344
2345 fn table_anchor_position(&self, table_id: usize) -> Option<usize> {
2350 let inner = self.doc.lock();
2351 let store = inner.ctx.db_context.get_store();
2352 common::database::rope_helpers::table_anchor_position(
2353 store,
2354 table_id as common::types::EntityId,
2355 )
2356 .map(to_usize)
2357 }
2358
2359 fn table_cell_at(&self, position: usize) -> Option<TableCellRef> {
2361 let inner = self.doc.lock();
2362 let block_id = crate::inner::block_at_caret_dto(&inner.ctx, position)
2364 .ok()?
2365 .block_id as usize;
2366
2367 let block = crate::text_block::TextBlock {
2368 doc: self.doc.clone(),
2369 block_id,
2370 };
2371 drop(inner);
2372 block.table_cell()
2373 }
2374
2375 fn selection_anchor_cell(
2392 &self,
2393 anchor: usize,
2394 position_cell: Option<&TableCellRef>,
2395 ) -> Option<TableCellRef> {
2396 let cell = self.table_cell_at(anchor)?;
2397 let on_table_anchor = {
2398 let inner = self.doc.lock();
2399 common::database::rope_helpers::snap_off_table_anchor(
2400 inner.ctx.db_context.get_store(),
2401 to_i64(anchor),
2402 true,
2403 ) != to_i64(anchor)
2404 };
2405 let moving_end_in_the_table =
2406 position_cell.is_some_and(|moving| moving.table.id() == cell.table.id());
2407 (!on_table_anchor || moving_end_in_the_table).then_some(cell)
2408 }
2409
2410 fn back_off_table_anchor(&self, position: usize) -> usize {
2416 let inner = self.doc.lock();
2417 to_usize(common::database::rope_helpers::snap_off_table_anchor(
2418 inner.ctx.db_context.get_store(),
2419 to_i64(position),
2420 false,
2421 ))
2422 }
2423
2424 fn table_boundary_position(&self, table_id: usize, before: bool) -> Option<usize> {
2435 let inner = self.doc.lock();
2436 let main_frame_id = get_main_frame_id(&inner);
2437 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2440 drop(inner);
2441
2442 let idx = flow
2444 .iter()
2445 .position(|e| matches!(e, FlowElement::Table(t) if t.id() == table_id))?;
2446
2447 if before {
2448 for i in (0..idx).rev() {
2450 if let FlowElement::Block(b) = &flow[i] {
2451 return Some(b.position() + b.length());
2452 }
2453 }
2454 } else {
2455 for item in flow.iter().skip(idx + 1) {
2457 if let FlowElement::Block(b) = item {
2458 return Some(b.position());
2459 }
2460 }
2461 }
2462 None
2463 }
2464
2465 fn find_table_between(&self, start: usize, end: usize) -> Option<TextTable> {
2467 let inner = self.doc.lock();
2468 let main_frame_id = get_main_frame_id(&inner);
2469 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2471 drop(inner);
2472
2473 for elem in flow {
2474 if let FlowElement::Table(t) = elem {
2475 if let Some(first_cell) = t.cell(0, 0) {
2478 let blocks = first_cell.blocks();
2479 if let Some(fb) = blocks.first() {
2480 let p = fb.position();
2481 if p > start && p < end {
2482 return Some(t);
2483 }
2484 }
2485 }
2486 }
2487 }
2488 None
2489 }
2490
2491 fn collect_cell_spans(&self, table_id: usize) -> Vec<(usize, usize, usize, usize)> {
2493 let inner = self.doc.lock();
2494 let table_dto =
2495 match frontend::commands::table_commands::get_table(&inner.ctx, &(table_id as u64))
2496 .ok()
2497 .flatten()
2498 {
2499 Some(t) => t,
2500 None => return Vec::new(),
2501 };
2502
2503 let mut spans = Vec::with_capacity(table_dto.cells.len());
2504 for &cell_id in &table_dto.cells {
2505 if let Some(cell) =
2506 frontend::commands::table_cell_commands::get_table_cell(&inner.ctx, &cell_id)
2507 .ok()
2508 .flatten()
2509 {
2510 spans.push((
2511 cell.row as usize,
2512 cell.column as usize,
2513 cell.row_span.max(1) as usize,
2514 cell.column_span.max(1) as usize,
2515 ));
2516 }
2517 }
2518 spans
2519 }
2520
2521 pub fn delete_char(&self) -> Result<()> {
2523 let (pos, anchor) = self.read_cursor();
2524 let (del_pos, del_anchor) = if pos != anchor {
2525 (pos, anchor)
2526 } else {
2527 let end = {
2529 let inner = self.doc.lock();
2530 max_cursor_position_of(&inner).unwrap_or(0)
2531 };
2532 if pos >= end {
2533 return Ok(());
2534 }
2535 let to = self.next_grapheme_boundary(pos);
2539 if to == pos {
2540 return Ok(());
2541 }
2542 (pos, to)
2543 };
2544 self.do_delete(del_pos, del_anchor, pos != anchor)
2545 }
2546
2547 pub fn delete_previous_char(&self) -> Result<()> {
2549 let (pos, anchor) = self.read_cursor();
2550 let (del_pos, del_anchor) = if pos != anchor {
2551 (pos, anchor)
2552 } else if pos > 0 {
2553 let from = self.prev_grapheme_boundary(pos);
2554 if from == pos {
2555 return Ok(());
2556 }
2557 (from, pos)
2558 } else {
2559 return Ok(());
2560 };
2561 self.do_delete(del_pos, del_anchor, pos != anchor)
2562 }
2563
2564 pub fn remove_selected_text(&self) -> Result<String> {
2586 let (pos, anchor) = self.read_cursor();
2587 if pos == anchor {
2588 return Ok(String::new());
2589 }
2590 let queued = {
2591 let mut inner = self.doc.lock();
2592 let (result, removed) = measured_delete(&inner, pos, anchor)?;
2593 let stands_for_the_empty_text = self.finish_delete(
2594 &mut inner,
2595 pos.min(anchor),
2596 removed,
2597 result.new_position,
2598 true,
2599 );
2600 (
2602 result.deleted_text,
2603 self.announce_deletion(&mut inner, stands_for_the_empty_text),
2604 )
2605 };
2606 crate::inner::dispatch_queued_events(queued.1);
2607 Ok(queued.0)
2608 }
2609
2610 pub fn current_list(&self) -> Option<crate::TextList> {
2621 let pos = self.position();
2622 let inner = self.doc.lock();
2623 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos).ok()?;
2624 let block = crate::text_block::TextBlock {
2625 doc: self.doc.clone(),
2626 block_id: block_info.block_id as usize,
2627 };
2628 drop(inner);
2629 block.list()
2630 }
2631
2632 pub fn create_list(&self, style: ListStyle) -> Result<()> {
2640 let (pos, anchor) = self.read_cursor();
2641 let queued = {
2642 let mut inner = self.doc.lock();
2643 let dto = frontend::document_editing::CreateListDto {
2644 position: to_i64(pos),
2645 anchor: to_i64(anchor),
2646 style: style.clone(),
2647 };
2648 document_editing_commands::create_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2649 inner.modified = true;
2650 inner.rehighlight_affected(pos.min(anchor));
2651 inner.queue_event(DocumentEvent::ContentsChanged {
2652 position: pos.min(anchor),
2653 chars_removed: 0,
2654 chars_added: 0,
2655 blocks_affected: 1,
2656 });
2657 self.queue_undo_redo_event(&mut inner)
2658 };
2659 crate::inner::dispatch_queued_events(queued);
2660 Ok(())
2661 }
2662
2663 pub fn insert_list(&self, style: ListStyle) -> Result<()> {
2665 let (pos, anchor) = self.read_cursor();
2666 let queued = {
2667 let mut inner = self.doc.lock();
2668 let dto = frontend::document_editing::InsertListDto {
2669 position: to_i64(pos),
2670 anchor: to_i64(anchor),
2671 style: style.clone(),
2672 };
2673 let result =
2674 document_editing_commands::insert_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2675 let edit_pos = pos.min(anchor);
2676 let removed = pos.max(anchor) - edit_pos;
2677 let new_pos = to_usize(result.new_position);
2678 self.finish_edit_ext(
2679 &mut inner,
2680 edit_pos,
2681 removed,
2682 Insertion {
2683 at: edit_pos,
2684 removed: 0,
2685 added: new_pos.saturating_sub(edit_pos),
2686 },
2687 new_pos,
2688 1,
2689 false,
2690 )
2691 };
2692 crate::inner::dispatch_queued_events(queued);
2693 Ok(())
2694 }
2695
2696 pub fn set_list_format(&self, list_id: usize, format: &crate::ListFormat) -> Result<()> {
2698 let queued = {
2699 let mut inner = self.doc.lock();
2700 let dto = format.to_set_dto(list_id);
2701 document_formatting_commands::set_list_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2702 inner.modified = true;
2703 inner.queue_event(DocumentEvent::FormatChanged {
2704 position: 0,
2705 length: 0,
2706 kind: crate::flow::FormatChangeKind::List,
2707 });
2708 self.queue_undo_redo_event(&mut inner)
2709 };
2710 crate::inner::dispatch_queued_events(queued);
2711 Ok(())
2712 }
2713
2714 pub fn set_current_list_format(&self, format: &crate::ListFormat) -> Result<()> {
2717 let list = self.current_list().ok_or_else(|| {
2718 DocumentError::InvalidCursorContext("cursor is not inside a list".into())
2719 })?;
2720 self.set_list_format(list.id(), format)
2721 }
2722
2723 pub fn add_block_to_list(&self, block_id: usize, list_id: usize) -> Result<()> {
2725 let queued = {
2726 let mut inner = self.doc.lock();
2727 let dto = frontend::document_editing::AddBlockToListDto {
2728 block_id: to_i64(block_id),
2729 list_id: to_i64(list_id),
2730 };
2731 document_editing_commands::add_block_to_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2732 inner.modified = true;
2733 inner.queue_event(DocumentEvent::FormatChanged {
2740 position: 0,
2741 length: 0,
2742 kind: crate::flow::FormatChangeKind::List,
2743 });
2744 self.queue_undo_redo_event(&mut inner)
2745 };
2746 crate::inner::dispatch_queued_events(queued);
2747 Ok(())
2748 }
2749
2750 pub fn add_current_block_to_list(&self, list_id: usize) -> Result<()> {
2753 let pos = self.position();
2754 let inner = self.doc.lock();
2755 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2756 drop(inner);
2757 self.add_block_to_list(block_info.block_id as usize, list_id)
2758 }
2759
2760 pub fn remove_block_from_list(&self, block_id: usize) -> Result<()> {
2762 let queued = {
2763 let mut inner = self.doc.lock();
2764 let dto = frontend::document_editing::RemoveBlockFromListDto {
2765 block_id: to_i64(block_id),
2766 };
2767 document_editing_commands::remove_block_from_list(
2768 &inner.ctx,
2769 Some(inner.stack_id),
2770 &dto,
2771 )?;
2772 inner.modified = true;
2773 inner.queue_event(DocumentEvent::FormatChanged {
2776 position: 0,
2777 length: 0,
2778 kind: crate::flow::FormatChangeKind::List,
2779 });
2780 self.queue_undo_redo_event(&mut inner)
2781 };
2782 crate::inner::dispatch_queued_events(queued);
2783 Ok(())
2784 }
2785
2786 pub fn remove_current_block_from_list(&self) -> Result<()> {
2790 let pos = self.position();
2791 let inner = self.doc.lock();
2792 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2793 drop(inner);
2794 self.remove_block_from_list(block_info.block_id as usize)
2795 }
2796
2797 pub fn remove_list_item(&self, list_id: usize, index: usize) -> Result<()> {
2800 let list = crate::text_list::TextList {
2801 doc: self.doc.clone(),
2802 list_id,
2803 };
2804 let block = list.item(index).ok_or_else(|| {
2805 DocumentError::OutOfRange(format!("list item index {index} out of range"))
2806 })?;
2807 self.remove_block_from_list(block.id())
2808 }
2809
2810 pub fn char_format(&self) -> Result<TextFormat> {
2815 let pos = self.position();
2816 let inner = self.doc.lock();
2817
2818 let dto = frontend::document_inspection::GetBlockAtPositionDto {
2820 position: to_i64(pos),
2821 };
2822 let block_info = document_inspection_commands::get_block_at_position(&inner.ctx, &dto)?;
2823 let block_id = block_info.block_id as u64;
2824 let mut block_dto =
2825 frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
2826 .ok_or_else(|| DocumentError::NotFound("block not found at position".into()))?;
2827 let store = inner.ctx.db_context.get_store();
2828 crate::inner::refresh_block_position(&mut block_dto, store);
2829
2830 let local_char = pos.saturating_sub(block_dto.document_position as usize);
2833 let entity: common::entities::Block = block_dto.clone().into();
2834 let plain_owned = common::database::rope_helpers::block_content_via_store(&entity, store);
2835 let plain: &str = &plain_owned;
2836 let byte_offset: u32 = plain
2837 .char_indices()
2838 .nth(local_char)
2839 .map(|(b, _)| b as u32)
2840 .unwrap_or(plain.len() as u32);
2841
2842 let images = store
2845 .block_images
2846 .read()
2847 .get(&block_id)
2848 .cloned()
2849 .unwrap_or_default();
2850 if let Some(img) = images.iter().find(|i| i.byte_offset == byte_offset) {
2851 return Ok(TextFormat::from(&img.format));
2852 }
2853
2854 let runs = store
2856 .format_runs
2857 .read()
2858 .get(&block_id)
2859 .cloned()
2860 .unwrap_or_default();
2861 let fmt = runs
2862 .iter()
2863 .find(|r| r.byte_start <= byte_offset && byte_offset < r.byte_end)
2864 .map(|r| TextFormat::from(&r.format))
2865 .unwrap_or_default();
2866 Ok(fmt)
2867 }
2868
2869 pub fn block_format(&self) -> Result<BlockFormat> {
2876 let pos = self.position();
2877 let inner = self.doc.lock();
2878 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2879 let block_id = block_info.block_id as u64;
2880 let block = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
2881 .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
2882 Ok(BlockFormat::from(&block))
2883 }
2884
2885 pub fn set_char_format(&self, format: &TextFormat) -> Result<()> {
2889 let (pos, anchor) = self.read_cursor();
2890 let queued = {
2891 let mut inner = self.doc.lock();
2892 let dto = format.to_set_dto(pos, anchor);
2893 document_formatting_commands::set_text_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2894 let start = pos.min(anchor);
2895 let length = pos.max(anchor) - start;
2896 inner.modified = true;
2897 inner.queue_event(DocumentEvent::FormatChanged {
2898 position: start,
2899 length,
2900 kind: crate::flow::FormatChangeKind::Character,
2901 });
2902 self.queue_undo_redo_event(&mut inner)
2903 };
2904 crate::inner::dispatch_queued_events(queued);
2905 Ok(())
2906 }
2907
2908 pub fn link_at_caret(&self) -> Option<LinkExtent> {
2918 let pos = self.position();
2919 let block_id = {
2920 let inner = self.doc.lock();
2921 crate::inner::block_at_caret_dto(&inner.ctx, pos)
2922 .ok()?
2923 .block_id as usize
2924 };
2925 let block = TextBlock {
2926 doc: self.doc.clone(),
2927 block_id,
2928 };
2929 crate::link_extent::link_extent_at(&block, pos)
2930 }
2931
2932 pub fn clear_char_anchor(&self) -> Result<()> {
2944 self.merge_char_format(&TextFormat {
2945 clear_link: true,
2946 ..Default::default()
2947 })
2948 }
2949
2950 pub fn merge_char_format(&self, format: &TextFormat) -> Result<()> {
2952 let (pos, anchor) = self.read_cursor();
2953 let queued = {
2954 let mut inner = self.doc.lock();
2955 let dto = format.to_merge_dto(pos, anchor);
2956 document_formatting_commands::merge_text_format(
2957 &inner.ctx,
2958 Some(inner.stack_id),
2959 &dto,
2960 )?;
2961 let start = pos.min(anchor);
2962 let length = pos.max(anchor) - start;
2963 inner.modified = true;
2964 inner.queue_event(DocumentEvent::FormatChanged {
2965 position: start,
2966 length,
2967 kind: crate::flow::FormatChangeKind::Character,
2968 });
2969 self.queue_undo_redo_event(&mut inner)
2970 };
2971 crate::inner::dispatch_queued_events(queued);
2972 Ok(())
2973 }
2974
2975 pub fn set_block_format(&self, format: &BlockFormat) -> Result<()> {
2982 let (pos, anchor) = self.read_cursor();
2983 let queued = {
2984 let mut inner = self.doc.lock();
2985 let dto = format.to_set_dto(pos, anchor);
2986 document_formatting_commands::set_block_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2987 let start = pos.min(anchor);
2988 let length = pos.max(anchor) - start;
2989 inner.modified = true;
2990 inner.queue_event(DocumentEvent::FormatChanged {
2991 position: start,
2992 length,
2993 kind: crate::flow::FormatChangeKind::Block,
2994 });
2995 self.queue_undo_redo_event(&mut inner)
2996 };
2997 crate::inner::dispatch_queued_events(queued);
2998 Ok(())
2999 }
3000
3001 pub fn set_frame_format(&self, frame_id: usize, format: &FrameFormat) -> Result<()> {
3003 let (pos, anchor) = self.read_cursor();
3004 let queued = {
3005 let mut inner = self.doc.lock();
3006 let dto = format.to_set_dto(pos, anchor, frame_id);
3007 document_formatting_commands::set_frame_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3008 let start = pos.min(anchor);
3009 let length = pos.max(anchor) - start;
3010 inner.modified = true;
3011 inner.queue_event(DocumentEvent::FormatChanged {
3012 position: start,
3013 length,
3014 kind: crate::flow::FormatChangeKind::Block,
3015 });
3016 self.queue_undo_redo_event(&mut inner)
3017 };
3018 crate::inner::dispatch_queued_events(queued);
3019 Ok(())
3020 }
3021
3022 pub fn begin_edit_block(&self) {
3026 let inner = self.doc.lock();
3027 undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
3028 }
3029
3030 pub fn end_edit_block(&self) {
3032 let inner = self.doc.lock();
3033 undo_redo_commands::end_composite(&inner.ctx);
3034 }
3035
3036 pub fn join_previous_edit_block(&self) {
3043 self.begin_edit_block();
3044 }
3045
3046 fn queue_undo_redo_event(&self, inner: &mut TextDocumentInner) -> QueuedEvents {
3050 let can_undo = undo_redo_commands::can_undo(&inner.ctx, Some(inner.stack_id));
3051 let can_redo = undo_redo_commands::can_redo(&inner.ctx, Some(inner.stack_id));
3052 inner.queue_event(DocumentEvent::UndoRedoChanged { can_undo, can_redo });
3053 inner.take_queued_events()
3054 }
3055
3056 fn do_delete(&self, pos: usize, anchor: usize, selection: bool) -> Result<()> {
3057 let queued = {
3058 let mut inner = self.doc.lock();
3059 let (result, removed) = measured_delete(&inner, pos, anchor)?;
3060 let stands_for_the_empty_text = self.finish_delete(
3061 &mut inner,
3062 pos.min(anchor),
3063 removed,
3064 result.new_position,
3065 selection,
3066 );
3067 self.announce_deletion(&mut inner, stands_for_the_empty_text)
3068 };
3069 crate::inner::dispatch_queued_events(queued);
3070 Ok(())
3071 }
3072
3073 fn finish_delete(
3093 &self,
3094 inner: &mut TextDocumentInner,
3095 edit_pos: usize,
3096 removed: usize,
3097 new_position: i64,
3098 selection: bool,
3099 ) -> bool {
3100 let new_pos = to_usize(new_position);
3101 let edit_pos = edit_pos.min(new_pos);
3105 if removed > 0 {
3106 inner.adjust_cursors(edit_pos, removed, 0);
3107 }
3108 let stands_for_the_empty_text =
3109 selection && removed > 0 && new_pos == 0 && main_text_is_empty(inner);
3110 {
3111 let mut d = self.data.lock();
3112 d.position = new_pos;
3113 d.anchor = new_pos;
3114 d.whole_text_selected = false;
3115 }
3116 if removed > 0 {
3117 inner.modified = true;
3118 inner.invalidate_text_cache();
3119 inner.rehighlight_affected(edit_pos);
3120 inner.queue_event(DocumentEvent::ContentsChanged {
3121 position: edit_pos,
3122 chars_removed: removed,
3123 chars_added: 0,
3124 blocks_affected: 1,
3125 });
3126 }
3127 inner.check_block_count_changed();
3128 inner.check_flow_changed();
3129 stands_for_the_empty_text
3130 }
3131
3132 fn announce_deletion(
3137 &self,
3138 inner: &mut TextDocumentInner,
3139 stands_for_the_empty_text: bool,
3140 ) -> QueuedEvents {
3141 let queued = self.queue_undo_redo_event(inner);
3142 self.data.lock().whole_text_selected = stands_for_the_empty_text;
3143 queued
3144 }
3145
3146 fn resolve_move(&self, op: MoveOperation, n: usize) -> usize {
3148 let pos = self.position();
3149 match op {
3150 MoveOperation::NoMove => pos,
3151 MoveOperation::Start => 0,
3152 MoveOperation::End => {
3153 let inner = self.doc.lock();
3154 max_cursor_position_of(&inner).unwrap_or(pos)
3155 }
3156 MoveOperation::NextCharacter | MoveOperation::Right => {
3157 let mut cur = pos;
3158 for _ in 0..n {
3159 let next = self.next_grapheme_boundary(cur);
3160 if next == cur {
3161 break;
3162 }
3163 cur = next;
3164 }
3165 cur
3166 }
3167 MoveOperation::PreviousCharacter | MoveOperation::Left => {
3168 let mut cur = pos;
3169 for _ in 0..n {
3170 let prev = self.prev_grapheme_boundary(cur);
3171 if prev == cur {
3172 break;
3173 }
3174 cur = prev;
3175 }
3176 cur
3177 }
3178 MoveOperation::StartOfBlock | MoveOperation::StartOfLine => {
3179 let inner = self.doc.lock();
3180 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3181 position: to_i64(pos),
3182 };
3183 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3184 .map(|info| to_usize(info.block_start))
3185 .unwrap_or(pos)
3186 }
3187 MoveOperation::EndOfBlock | MoveOperation::EndOfLine => {
3188 let inner = self.doc.lock();
3189 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3190 position: to_i64(pos),
3191 };
3192 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3193 .map(|info| to_usize(info.block_start) + to_usize(info.block_length))
3194 .unwrap_or(pos)
3195 }
3196 MoveOperation::NextBlock => {
3197 let inner = self.doc.lock();
3198 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3199 position: to_i64(pos),
3200 };
3201 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3202 .map(|info| {
3203 to_usize(info.block_start) + to_usize(info.block_length) + 1
3205 })
3206 .unwrap_or(pos)
3207 }
3208 MoveOperation::PreviousBlock => {
3209 let inner = self.doc.lock();
3210 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3211 position: to_i64(pos),
3212 };
3213 let block_start =
3214 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3215 .map(|info| to_usize(info.block_start))
3216 .unwrap_or(pos);
3217 if block_start >= 2 {
3218 let before = common::database::rope_helpers::snap_off_table_anchor(
3222 inner.ctx.db_context.get_store(),
3223 to_i64(block_start - 2),
3224 false,
3225 );
3226 let prev_dto =
3227 frontend::document_inspection::GetBlockAtPositionDto { position: before };
3228 document_inspection_commands::get_block_at_position(&inner.ctx, &prev_dto)
3229 .map(|info| to_usize(info.block_start))
3230 .unwrap_or(0)
3231 } else {
3232 0
3233 }
3234 }
3235 MoveOperation::NextWord | MoveOperation::EndOfWord | MoveOperation::WordRight => {
3236 let (_, end) = self.find_word_boundaries(pos);
3237 if end == pos {
3239 let inner = self.doc.lock();
3241 let max_pos = max_cursor_position_of(&inner).unwrap_or(0);
3242 let scan_len = max_pos.saturating_sub(pos).min(64);
3243 if scan_len == 0 {
3244 return pos;
3245 }
3246 let dto = frontend::document_inspection::GetTextAtPositionDto {
3247 position: to_i64(pos),
3248 length: to_i64(scan_len),
3249 };
3250 if let Ok(r) =
3251 document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3252 {
3253 for (i, ch) in r.text.chars().enumerate() {
3254 if ch.is_alphanumeric() || ch == '_' {
3255 let word_pos = pos + i;
3257 drop(inner);
3258 let (_, word_end) = self.find_word_boundaries(word_pos);
3259 return word_end;
3260 }
3261 }
3262 }
3263 pos + scan_len
3264 } else {
3265 end
3266 }
3267 }
3268 MoveOperation::PreviousWord | MoveOperation::StartOfWord | MoveOperation::WordLeft => {
3269 let (start, _) = self.find_word_boundaries(pos);
3270 if start < pos {
3271 start
3272 } else if pos > 0 {
3273 let mut search = pos - 1;
3276 loop {
3277 search = self.back_off_table_anchor(search);
3281 let (ws, we) = self.find_word_boundaries(search);
3282 if ws < we && ws < pos {
3283 break ws;
3285 }
3286 if search == 0 {
3288 break 0;
3289 }
3290 search -= 1;
3291 }
3292 } else {
3293 0
3294 }
3295 }
3296 MoveOperation::StartOfSentence | MoveOperation::PreviousSentence => {
3297 let mut cur = pos;
3298 for _ in 0..n.max(1) {
3299 let start = match self.find_sentence_boundaries(cur) {
3300 Some((start, _)) => start,
3301 None => break,
3302 };
3303 if start < cur && op == MoveOperation::StartOfSentence {
3306 cur = start;
3307 } else if cur > 0 {
3308 match self.find_sentence_boundaries(self.back_off_table_anchor(cur - 1)) {
3310 Some((prev, _)) if prev < cur => cur = prev,
3311 _ => cur = cur.saturating_sub(1),
3314 }
3315 } else {
3316 break;
3317 }
3318 }
3319 cur
3320 }
3321 MoveOperation::EndOfSentence => {
3322 let mut cur = pos;
3323 for _ in 0..n.max(1) {
3324 let end = match self.find_sentence_boundaries(cur) {
3325 Some((_, end)) => end,
3326 None => break,
3327 };
3328 if end > cur {
3329 cur = end;
3330 } else {
3331 match self.find_sentence_boundaries(cur + 1) {
3332 Some((_, next)) if next > cur => cur = next,
3333 _ => break,
3334 }
3335 }
3336 }
3337 cur
3338 }
3339 MoveOperation::NextSentence => {
3340 let mut cur = pos;
3341 for _ in 0..n.max(1) {
3342 let end = match self.find_sentence_boundaries(cur) {
3345 Some((_, end)) => end,
3346 None => break,
3347 };
3348 match self.find_sentence_boundaries(end + 1) {
3349 Some((start, _)) if start > cur => cur = start,
3350 _ => {
3351 if end > cur {
3352 cur = end;
3353 } else {
3354 break;
3355 }
3356 }
3357 }
3358 }
3359 cur
3360 }
3361 MoveOperation::Up | MoveOperation::Down => {
3362 if matches!(op, MoveOperation::Up) {
3365 self.resolve_move(MoveOperation::PreviousBlock, 1)
3366 } else {
3367 self.resolve_move(MoveOperation::NextBlock, 1)
3368 }
3369 }
3370 }
3371 }
3372
3373 pub(crate) fn snap_position_to_grapheme_boundary(&self) {
3384 let pos = {
3385 let data = self.data.lock();
3386 data.position
3387 };
3388 let snapped = self.forward_grapheme_boundary_at_or_after(pos);
3389 if snapped != pos {
3390 let mut data = self.data.lock();
3391 data.position = snapped;
3392 if data.anchor == pos {
3393 data.anchor = snapped;
3394 }
3395 data.whole_text_selected = false;
3396 }
3397 }
3398
3399 fn forward_grapheme_boundary_at_or_after(&self, pos: usize) -> usize {
3409 let inner = self.doc.lock();
3410 let end = max_cursor_position_of(&inner).unwrap_or(pos);
3411 if pos >= end {
3412 return pos;
3413 }
3414 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3415 position: to_i64(pos),
3416 };
3417 let Ok(block_info) =
3418 document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto)
3419 else {
3420 return pos;
3421 };
3422 let block_start = to_usize(block_info.block_start);
3423 let block_length = to_usize(block_info.block_length);
3424 let offset_in_block = pos.saturating_sub(block_start);
3425 if offset_in_block == 0 || offset_in_block >= block_length {
3427 return pos;
3428 }
3429 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3430 position: to_i64(block_start),
3431 length: to_i64(block_length),
3432 };
3433 let Ok(r) = document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto)
3434 else {
3435 return pos;
3436 };
3437 let text = r.text;
3438 drop(inner);
3439 let mut acc = 0usize;
3442 for g in text.graphemes(true) {
3443 if acc >= offset_in_block {
3444 return block_start + acc;
3445 }
3446 acc += g.chars().count();
3447 }
3448 block_start + acc
3449 }
3450
3451 fn next_grapheme_boundary(&self, pos: usize) -> usize {
3464 let inner = self.doc.lock();
3465 let end = max_cursor_position_of(&inner).unwrap_or(pos);
3466 if pos >= end {
3467 return pos;
3468 }
3469 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3470 position: to_i64(pos),
3471 };
3472 let block_info =
3473 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3474 Ok(info) => info,
3475 Err(_) => return pos + 1,
3476 };
3477 let block_start = to_usize(block_info.block_start);
3478 let block_length = to_usize(block_info.block_length);
3479 let offset_in_block = pos.saturating_sub(block_start);
3480 if offset_in_block >= block_length {
3481 return (pos + 1).min(end);
3484 }
3485 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3486 position: to_i64(pos),
3487 length: to_i64(block_length - offset_in_block),
3488 };
3489 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3490 Ok(r) => r.text,
3491 Err(_) => return pos + 1,
3492 };
3493 drop(inner);
3494 match text.graphemes(true).next() {
3495 Some(g) if !g.is_empty() => (pos + g.chars().count()).min(end),
3496 _ => (pos + 1).min(end),
3497 }
3498 }
3499
3500 fn prev_grapheme_boundary(&self, pos: usize) -> usize {
3504 if pos == 0 {
3505 return 0;
3506 }
3507 let inner = self.doc.lock();
3508 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3509 position: to_i64(pos.saturating_sub(1)),
3510 };
3511 let block_info =
3512 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3513 Ok(info) => info,
3514 Err(_) => return pos - 1,
3515 };
3516 let block_start = to_usize(block_info.block_start);
3517 let block_length = to_usize(block_info.block_length);
3518 let block_end = block_start + block_length;
3519 if pos > block_end {
3523 return pos - 1;
3524 }
3525 if block_length == 0 || pos <= block_start {
3526 return pos.saturating_sub(1);
3527 }
3528 let scan_len = pos - block_start;
3529 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3530 position: to_i64(block_start),
3531 length: to_i64(scan_len),
3532 };
3533 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3534 Ok(r) => r.text,
3535 Err(_) => return pos - 1,
3536 };
3537 drop(inner);
3538 match text.graphemes(true).next_back() {
3539 Some(g) if !g.is_empty() => pos - g.chars().count(),
3540 _ => pos - 1,
3541 }
3542 }
3543
3544 fn find_word_boundaries(&self, pos: usize) -> (usize, usize) {
3550 let inner = self.doc.lock();
3551 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3553 position: to_i64(pos),
3554 };
3555 let block_info =
3556 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3557 Ok(info) => info,
3558 Err(_) => return (pos, pos),
3559 };
3560
3561 let block_start = to_usize(block_info.block_start);
3562 let block_length = to_usize(block_info.block_length);
3563 if block_length == 0 {
3564 return (pos, pos);
3565 }
3566
3567 let dto = frontend::document_inspection::GetTextAtPositionDto {
3568 position: to_i64(block_start),
3569 length: to_i64(block_length),
3570 };
3571 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &dto) {
3572 Ok(r) => r.text,
3573 Err(_) => return (pos, pos),
3574 };
3575
3576 let cursor_offset = pos.saturating_sub(block_start);
3578
3579 let mut last_char_start = 0;
3581 let mut last_char_end = 0;
3582
3583 for (word_byte_start, word) in text.unicode_word_indices() {
3584 let word_char_start = text[..word_byte_start].chars().count();
3586 let word_char_len = word.chars().count();
3587 let word_char_end = word_char_start + word_char_len;
3588
3589 last_char_start = word_char_start;
3590 last_char_end = word_char_end;
3591
3592 if cursor_offset >= word_char_start && cursor_offset < word_char_end {
3593 return (block_start + word_char_start, block_start + word_char_end);
3594 }
3595 }
3596
3597 if cursor_offset == last_char_end && last_char_start < last_char_end {
3599 return (block_start + last_char_start, block_start + last_char_end);
3600 }
3601
3602 (pos, pos)
3603 }
3604
3605 fn find_sentence_boundaries(&self, pos: usize) -> Option<(usize, usize)> {
3611 let locale = self.data.lock().content_locale.clone();
3612
3613 let inner = self.doc.lock();
3614 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3615 position: to_i64(pos),
3616 };
3617 let block_info =
3618 document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto).ok()?;
3619 let block_start = to_usize(block_info.block_start);
3620 let block_length = to_usize(block_info.block_length);
3621 if block_length == 0 {
3622 return None;
3623 }
3624 let dto = frontend::document_inspection::GetTextAtPositionDto {
3625 position: to_i64(block_start),
3626 length: to_i64(block_length),
3627 };
3628 let text = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3629 .ok()?
3630 .text;
3631 drop(inner);
3632
3633 let offset = pos.saturating_sub(block_start);
3634 let (start, end) =
3635 frontend::common::parser_tools::sentence_bounds(&text, offset, locale.as_deref())?;
3636 Some((block_start + start, block_start + end))
3637 }
3638}
3639
3640#[derive(Clone, Copy, PartialEq, Eq)]
3647enum BlockEdge {
3648 First,
3649 Middle,
3650 Last,
3651 OnlyOne,
3652}
3653
3654fn cursor_frame_ref(inner: &TextDocumentInner, block_id: u64) -> Option<FrameRef> {
3658 let parent = crate::text_block::find_parent_frame(inner, block_id)?;
3659 let store = inner.ctx.db_context.get_store();
3660 let frames = store.frames.read();
3661 let frame = frames.get(&parent)?.clone();
3662 frame.parent_frame?;
3663 let is_blockquote = frame.fmt_is_blockquote.unwrap_or(false);
3664
3665 let mut depth = 0;
3666 let mut current = Some(parent);
3667 while let Some(id) = current {
3668 let Some(f) = frames.get(&id) else {
3669 break;
3670 };
3671 if f.parent_frame.is_none() {
3672 break;
3673 }
3674 depth += 1;
3675 current = f.parent_frame;
3676 }
3677
3678 Some(FrameRef {
3679 frame_id: frame.id as usize,
3680 parent_frame_id: frame.parent_frame.map(|id| id as usize),
3681 is_blockquote,
3682 depth,
3683 })
3684}
3685
3686fn innermost_blockquote_frame_id(inner: &TextDocumentInner, block_id: u64) -> Option<usize> {
3690 let mut current = crate::text_block::find_parent_frame(inner, block_id);
3691 let store = inner.ctx.db_context.get_store();
3692 let frames = store.frames.read();
3693 while let Some(id) = current {
3694 let f = frames.get(&id)?;
3695 if f.fmt_is_blockquote == Some(true) {
3696 return Some(f.id as usize);
3697 }
3698 current = f.parent_frame;
3699 }
3700 None
3701}
3702
3703fn blockquote_depth_for_block(inner: &TextDocumentInner, block_id: u64) -> usize {
3706 let mut current = crate::text_block::find_parent_frame(inner, block_id);
3707 let store = inner.ctx.db_context.get_store();
3708 let frames = store.frames.read();
3709 let mut count = 0;
3710 while let Some(id) = current {
3711 let Some(f) = frames.get(&id) else {
3712 break;
3713 };
3714 if f.fmt_is_blockquote == Some(true) {
3715 count += 1;
3716 }
3717 current = f.parent_frame;
3718 }
3719 count
3720}
3721
3722fn block_position_in_current_frame(cursor: &TextCursor) -> Option<BlockEdge> {
3728 let pos = cursor.position();
3729 let inner = cursor.doc.lock();
3730 let block_info = TextCursor::caret_block(&inner, pos)?;
3732 let block_id = block_info.block_id as common::types::EntityId;
3733 let parent_id = crate::text_block::find_parent_frame(&inner, block_info.block_id as u64)?;
3734 let store = inner.ctx.db_context.get_store();
3735 let frames = store.frames.read();
3736 let frame = frames.get(&parent_id)?;
3737 let block_positions: Vec<usize> = frame
3738 .child_order
3739 .iter()
3740 .enumerate()
3741 .filter_map(|(i, &e)| {
3742 if e > 0 {
3743 Some((i, e as common::types::EntityId))
3744 } else {
3745 None
3746 }
3747 })
3748 .filter(|(_, id)| *id == block_id)
3749 .map(|(i, _)| i)
3750 .collect();
3751 let block_idx = *block_positions.first()?;
3752 let positive_entries: Vec<usize> = frame
3753 .child_order
3754 .iter()
3755 .enumerate()
3756 .filter_map(|(i, &e)| if e > 0 { Some(i) } else { None })
3757 .collect();
3758 let first_pos = *positive_entries.first()?;
3759 let last_pos = *positive_entries.last()?;
3760 let is_first = block_idx == first_pos;
3761 let is_last = block_idx == last_pos;
3762 let edge = match (is_first, is_last, positive_entries.len()) {
3763 (_, _, 1) => BlockEdge::OnlyOne,
3764 (true, _, _) => BlockEdge::First,
3765 (_, true, _) => BlockEdge::Last,
3766 _ => BlockEdge::Middle,
3767 };
3768 Some(edge)
3769}