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(
89 inner: &TextDocumentInner,
90 pos: usize,
91 anchor: usize,
92 selection: bool,
93) -> Result<(frontend::document_editing::DeleteTextResultDto, usize)> {
94 let (pos, anchor) = if selection {
95 whole_tables_selected(inner, pos, anchor)
96 } else {
97 (pos, anchor)
98 };
99 let before = max_cursor_position_of(inner);
100 let dto = frontend::document_editing::DeleteTextDto {
101 position: to_i64(pos),
102 anchor: to_i64(anchor),
103 };
104 let result =
105 match document_editing_commands::delete_text(&inner.ctx, Some(inner.stack_id), &dto) {
106 Ok(result) => result,
107 Err(error) => match error.downcast_ref::<frontend::document_editing::NothingToDelete>()
111 {
112 Some(nothing) => {
113 return Ok((
114 frontend::document_editing::DeleteTextResultDto {
115 new_position: nothing.new_position,
116 deleted_text: String::new(),
117 },
118 0,
119 ));
120 }
121 None => return Err(error.into()),
122 },
123 };
124 let removed = match (before, max_cursor_position_of(inner)) {
125 (Some(before), Some(after)) => before.saturating_sub(after),
126 _ => pos.max(anchor) - pos.min(anchor),
128 };
129 Ok((result, removed))
130}
131
132fn whole_tables_selected(inner: &TextDocumentInner, pos: usize, anchor: usize) -> (usize, usize) {
139 let (start, end) = common::database::rope_helpers::take_whole_tables(
140 inner.ctx.db_context.get_store(),
141 to_i64(pos.min(anchor)),
142 to_i64(pos.max(anchor)),
143 );
144 (to_usize(start), to_usize(end))
145}
146
147fn delete_then<R>(
160 inner: &TextDocumentInner,
161 pos: usize,
162 anchor: usize,
163 insert: impl FnOnce(usize) -> Result<R>,
164) -> Result<(R, usize, usize)> {
165 undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
166 let outcome = measured_delete(inner, pos, anchor, true).and_then(|(deleted, removed)| {
167 let at = to_usize(deleted.new_position);
168 insert(at).map(|value| (value, removed, at))
169 });
170 match outcome {
171 Ok(done) => {
172 undo_redo_commands::end_composite(&inner.ctx);
173 Ok(done)
174 }
175 Err(error) => {
176 undo_redo_commands::cancel_composite(&inner.ctx);
177 Err(error)
178 }
179 }
180}
181
182fn removed_since(
192 inner: &TextDocumentInner,
193 before: Option<usize>,
194 added: usize,
195 selection: usize,
196) -> usize {
197 match (before, max_cursor_position_of(inner)) {
198 (Some(before), Some(after)) => (before + added).saturating_sub(after),
199 _ => selection,
200 }
201}
202
203#[derive(Debug, Clone, Copy)]
207struct Insertion {
208 at: usize,
209 removed: usize,
210 added: usize,
211}
212
213impl Insertion {
214 fn ending_at(new_pos: usize, added: usize) -> Self {
219 Insertion {
220 at: new_pos.saturating_sub(added),
221 removed: 0,
222 added,
223 }
224 }
225}
226
227pub struct TextCursor {
235 pub(crate) doc: Arc<Mutex<TextDocumentInner>>,
236 pub(crate) data: Arc<Mutex<CursorData>>,
237}
238
239impl Clone for TextCursor {
240 fn clone(&self) -> Self {
241 let (position, anchor, content_locale, anchor_in_table) = {
242 let d = self.data.lock();
243 (
244 d.position,
245 d.anchor,
246 d.content_locale.clone(),
247 d.anchor_in_table,
248 )
249 };
250 let data = {
251 let mut inner = self.doc.lock();
252 let data = Arc::new(Mutex::new(CursorData {
253 position,
254 anchor,
255 cell_selection_override: None,
256 content_locale,
258 whole_text_selected: false,
259 anchor_in_table,
261 }));
262 inner.cursors.push(Arc::downgrade(&data));
263 data
264 };
265 TextCursor {
266 doc: self.doc.clone(),
267 data,
268 }
269 }
270}
271
272impl TextCursor {
273 fn read_cursor(&self) -> (usize, usize) {
276 let d = self.data.lock();
277 (d.position, d.anchor)
278 }
279
280 fn finish_edit(
284 &self,
285 inner: &mut TextDocumentInner,
286 edit_pos: usize,
287 removed: usize,
288 inserted: Insertion,
289 new_pos: usize,
290 blocks_affected: usize,
291 ) -> QueuedEvents {
292 self.finish_edit_ext(
293 inner,
294 edit_pos,
295 removed,
296 inserted,
297 new_pos,
298 blocks_affected,
299 true,
300 )
301 }
302
303 #[allow(clippy::too_many_arguments)]
304 fn finish_edit_ext(
305 &self,
306 inner: &mut TextDocumentInner,
307 edit_pos: usize,
308 removed: usize,
309 inserted: Insertion,
310 new_pos: usize,
311 blocks_affected: usize,
312 flow_may_change: bool,
313 ) -> QueuedEvents {
314 self.finish_edit_from(
315 inner,
316 edit_pos,
317 removed,
318 inserted,
319 new_pos,
320 blocks_affected,
321 flow_may_change,
322 InsertionOrigin::Unspecified,
323 )
324 }
325
326 #[allow(clippy::too_many_arguments)]
343 fn finish_edit_from(
344 &self,
345 inner: &mut TextDocumentInner,
346 edit_pos: usize,
347 removed: usize,
348 inserted: Insertion,
349 new_pos: usize,
350 blocks_affected: usize,
351 flow_may_change: bool,
352 origin: InsertionOrigin,
353 ) -> QueuedEvents {
354 let Insertion {
361 at: inserted_at,
362 removed: replaced,
363 added,
364 } = inserted;
365 if inserted_at > edit_pos || replaced > 0 {
366 inner.adjust_cursors(edit_pos, removed, 0);
371 inner.adjust_cursors(inserted_at, replaced, added);
372 } else {
373 inner.adjust_cursors(inserted_at, removed, added);
374 }
375 let removed = removed + replaced;
376 let edit_pos = edit_pos.min(inserted_at);
377 {
378 let mut d = self.data.lock();
379 d.position = new_pos;
380 d.anchor = new_pos;
381 d.whole_text_selected = false;
382 d.anchor_in_table = None;
383 }
384 inner.modified = true;
385 inner.invalidate_text_cache();
386 inner.rehighlight_affected(edit_pos);
387 inner.queue_event(DocumentEvent::ContentsChanged {
388 position: edit_pos,
389 chars_removed: removed,
390 chars_added: added,
391 blocks_affected,
392 });
393 if added > 0 {
397 inner.queue_event(DocumentEvent::TextInserted {
398 position: inserted_at,
399 chars_inserted: added,
400 origin,
401 });
402 }
403 inner.check_block_count_changed();
404 if flow_may_change {
405 inner.check_flow_changed();
406 }
407 self.queue_undo_redo_event(inner)
408 }
409
410 pub fn position(&self) -> usize {
414 self.data.lock().position
415 }
416
417 pub fn anchor(&self) -> usize {
419 self.data.lock().anchor
420 }
421
422 pub fn has_selection(&self) -> bool {
424 let d = self.data.lock();
425 d.position != d.anchor
426 }
427
428 pub fn selection_start(&self) -> usize {
430 let d = self.data.lock();
431 d.position.min(d.anchor)
432 }
433
434 pub fn selection_end(&self) -> usize {
436 let d = self.data.lock();
437 d.position.max(d.anchor)
438 }
439
440 pub fn selected_text(&self) -> Result<String> {
442 let (pos, anchor) = self.read_cursor();
443 if pos == anchor {
444 return Ok(String::new());
445 }
446 let start = pos.min(anchor);
447 let len = pos.max(anchor) - start;
448 let inner = self.doc.lock();
449 let dto = frontend::document_inspection::GetTextAtPositionDto {
450 position: to_i64(start),
451 length: to_i64(len),
452 };
453 let result = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)?;
454 Ok(result.text)
455 }
456
457 pub fn text_before(&self, max_len: usize) -> Result<String> {
470 if max_len == 0 {
471 return Ok(String::new());
472 }
473 let pos = self.position();
474 let inner = self.doc.lock();
475 let store = inner.ctx.db_context.get_store();
476
477 if pos > 0
482 && common::database::rope_helpers::find_block_at_char_position(store, 0).is_none()
483 {
484 let dto = frontend::document_inspection::GetTextAtPositionDto {
485 position: 0,
486 length: to_i64(pos),
487 };
488 let result = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)?;
489 let full = result.text;
490 let total = full.chars().count();
491 let skip = total.saturating_sub(max_len);
492 return Ok(full.chars().skip(skip).collect());
493 }
494
495 let mut pieces: Vec<String> = Vec::new();
496 let mut remaining = max_len;
497 let mut end_pos = pos;
498
499 while remaining > 0 && end_pos > 0 {
500 let query = (end_pos - 1) as i64;
501 let Some((block_id, char_in_block, block_char_start)) =
507 common::database::rope_helpers::find_block_at_char_position(store, query)
508 else {
509 break;
513 };
514 let block_dto = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
515 .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
516 let entity: common::entities::Block = block_dto.into();
517 let block_text =
518 common::database::rope_helpers::block_content_via_store(&entity, store);
519 let block_len = block_text.chars().count() as i64;
520 let block_char_start = block_char_start as usize;
521
522 if char_in_block == block_len {
523 pieces.push("\n".to_string());
525 remaining -= 1;
526 if remaining == 0 {
527 break;
528 }
529 let take = remaining.min(block_len as usize);
530 let local_start = block_len as usize - take;
531 let slice: String = block_text.chars().skip(local_start).take(take).collect();
532 pieces.push(slice);
533 remaining -= take;
534 end_pos = block_char_start + local_start;
535 } else {
536 let available = char_in_block as usize + 1;
538 let take = remaining.min(available);
539 let local_start = available - take;
540 let slice: String = block_text.chars().skip(local_start).take(take).collect();
541 pieces.push(slice);
542 remaining -= take;
543 end_pos = block_char_start + local_start;
544 }
545 }
546
547 pieces.reverse();
548 Ok(pieces.concat())
549 }
550
551 pub fn clear_selection(&self) {
553 let mut d = self.data.lock();
554 d.anchor = d.position;
555 d.whole_text_selected = false;
556 d.anchor_in_table = None;
557 }
558
559 fn caret_block(
570 inner: &TextDocumentInner,
571 position: usize,
572 ) -> Option<frontend::document_inspection::BlockInfoDto> {
573 crate::inner::block_at_caret_dto(&inner.ctx, position).ok()
574 }
575
576 pub fn at_block_start(&self) -> bool {
578 let pos = self.position();
579 let inner = self.doc.lock();
580 Self::caret_block(&inner, pos).is_some_and(|info| pos == to_usize(info.block_start))
581 }
582
583 pub fn at_block_end(&self) -> bool {
586 let pos = self.position();
587 let inner = self.doc.lock();
588 Self::caret_block(&inner, pos)
589 .is_some_and(|info| pos == to_usize(info.block_start) + to_usize(info.block_length))
590 }
591
592 pub fn at_start(&self) -> bool {
594 self.data.lock().position == 0
595 }
596
597 pub fn at_end(&self) -> bool {
599 let pos = self.position();
600 let inner = self.doc.lock();
601 pos >= max_cursor_position_of(&inner).unwrap_or(0)
602 }
603
604 pub fn block_number(&self) -> usize {
606 let pos = self.position();
607 let inner = self.doc.lock();
608 Self::caret_block(&inner, pos).map_or(0, |info| to_usize(info.block_number))
609 }
610
611 pub fn position_in_block(&self) -> usize {
614 let pos = self.position();
615 let inner = self.doc.lock();
616 Self::caret_block(&inner, pos)
617 .map_or(0, |info| pos.saturating_sub(to_usize(info.block_start)))
618 }
619
620 pub fn set_position(&self, position: usize, mode: MoveMode) {
653 let end = {
655 let inner = self.doc.lock();
656 max_cursor_position_of(&inner).unwrap_or(0)
657 };
658 let mut pos = position.min(end);
659
660 let mut kept_anchor: Option<(usize, Option<usize>)> = None;
661 if mode == MoveMode::KeepAnchor {
662 let fixed = {
665 let d = self.data.lock();
666 d.anchor_in_table.unwrap_or(d.anchor)
667 };
668 let pos_cell = self.table_cell_at(pos);
669 let fixed_cell = self.selection_anchor_cell(fixed, pos_cell.as_ref());
670 let same_table = |one: &TableCellRef, other: &Option<TableCellRef>| {
671 other
672 .as_ref()
673 .is_some_and(|other| other.table.id() == one.table.id())
674 };
675 if let Some(moving) = &pos_cell
681 && !same_table(moving, &fixed_cell)
682 {
683 let forward = fixed < pos;
684 pos = self.table_edge(moving.table.id(), forward).unwrap_or(pos);
685 }
686 let anchor = match &fixed_cell {
689 Some(started_in) if !same_table(started_in, &pos_cell) => {
690 let table_id = started_in.table.id();
691 match self.table_edge(table_id, pos < fixed) {
692 Some(edge) => (edge, Some(fixed)),
693 None => (fixed, None),
694 }
695 }
696 _ => (fixed, None),
697 };
698 kept_anchor = Some(anchor);
699 }
700
701 {
702 let mut d = self.data.lock();
703 d.position = pos;
704 match kept_anchor {
705 Some((anchor, anchor_in_table)) => {
706 d.anchor = anchor;
707 d.anchor_in_table = anchor_in_table;
708 }
709 None => {
710 d.anchor = pos;
711 d.anchor_in_table = None;
712 }
713 }
714 d.cell_selection_override = None;
715 d.whole_text_selected = false;
716 }
717 self.snap_position_to_grapheme_boundary();
722 }
723
724 fn table_edge(&self, table_id: usize, at_end: bool) -> Option<usize> {
728 let inner = self.doc.lock();
729 let extent = common::database::rope_helpers::table_extent(
730 inner.ctx.db_context.get_store(),
731 table_id as common::types::EntityId,
732 )?;
733 Some(to_usize(if at_end { extent.end } else { extent.anchor }))
734 }
735
736 pub fn move_position(&self, operation: MoveOperation, mode: MoveMode, n: usize) -> bool {
750 let old_pos = self.position();
751 let mut target = self.kept_in_main_text(old_pos, self.resolve_move(operation, n));
752 if mode == MoveMode::KeepAnchor {
753 target = self.past_a_table_given_back(old_pos, target);
754 }
755 self.set_position(target, mode);
756 self.position() != old_pos
757 }
758
759 fn past_a_table_given_back(&self, from: usize, target: usize) -> usize {
767 let fixed = {
768 let d = self.data.lock();
769 d.anchor_in_table.unwrap_or(d.anchor)
770 };
771 let back = (fixed < from && target < from) || (fixed > from && target > from);
772 let no_table = {
773 let inner = self.doc.lock();
774 inner.ctx.db_context.get_store().tables.read().is_empty()
775 };
776 if !back || no_table {
777 return target;
778 }
779 let Some(cell) = self.table_cell_at(target) else {
780 return target;
781 };
782 let started_in_it = self
783 .selection_anchor_cell(fixed, Some(&cell))
784 .is_some_and(|started_in| started_in.table.id() == cell.table.id());
785 if started_in_it {
786 return target;
787 }
788 let (Some(start), Some(end)) = (
789 self.table_edge(cell.table.id(), false),
790 self.table_edge(cell.table.id(), true),
791 ) else {
792 return target;
793 };
794 if fixed < start && from == end {
795 start.saturating_sub(1)
797 } else if fixed > end && from == start {
798 end + 1
800 } else {
801 target
802 }
803 }
804
805 fn kept_in_main_text(&self, from: usize, target: usize) -> usize {
811 if target <= from {
812 return target;
813 }
814 let inner = self.doc.lock();
815 let store = inner.ctx.db_context.get_store();
816 match common::database::rope_helpers::main_text_end(store) {
817 Some(end) if from <= to_usize(end) && target > to_usize(end) => to_usize(end),
818 _ => target,
819 }
820 }
821
822 pub fn select(&self, selection: SelectionType) {
824 match selection {
825 SelectionType::Document => {
826 let end = {
827 let inner = self.doc.lock();
828 max_cursor_position_of(&inner).unwrap_or(0)
829 };
830 let mut d = self.data.lock();
831 d.anchor = 0;
832 d.position = end;
833 d.cell_selection_override = None;
834 d.whole_text_selected = true;
835 d.anchor_in_table = None;
836 }
837 SelectionType::BlockUnderCursor | SelectionType::LineUnderCursor => {
838 let pos = self.position();
839 let inner = self.doc.lock();
840 if let Some(info) = Self::caret_block(&inner, pos) {
842 let start = to_usize(info.block_start);
843 let end = start + to_usize(info.block_length);
844 drop(inner);
845 let mut d = self.data.lock();
846 d.anchor = start;
847 d.position = end;
848 d.cell_selection_override = None;
849 d.whole_text_selected = false;
850 d.anchor_in_table = None;
851 }
852 }
853 SelectionType::WordUnderCursor => {
854 let pos = self.position();
855 let (word_start, word_end) = self.find_word_boundaries(pos);
856 let mut d = self.data.lock();
857 d.anchor = word_start;
858 d.position = word_end;
859 d.cell_selection_override = None;
860 d.whole_text_selected = false;
861 d.anchor_in_table = None;
862 }
863 SelectionType::SentenceUnderCursor => {
864 let pos = self.position();
865 if let Some((start, end)) = self.find_sentence_boundaries(pos) {
868 let mut d = self.data.lock();
869 d.anchor = start;
870 d.position = end;
871 d.cell_selection_override = None;
872 d.whole_text_selected = false;
873 d.anchor_in_table = None;
874 }
875 }
876 }
877 }
878
879 pub fn set_content_locale(&self, locale: Option<&str>) {
888 self.data.lock().content_locale = locale.map(str::to_string);
889 }
890
891 pub fn content_locale(&self) -> Option<String> {
893 self.data.lock().content_locale.clone()
894 }
895
896 pub fn insert_text(&self, text: &str) -> Result<()> {
903 self.insert_text_with_origin(text, InsertionOrigin::Unspecified)
904 }
905
906 pub fn insert_text_with_origin(&self, text: &str, origin: InsertionOrigin) -> Result<()> {
911 let (pos, anchor) = self.read_cursor();
912
913 let dto = frontend::document_editing::InsertTextDto {
915 format_policy: Default::default(),
916 position: to_i64(pos),
917 anchor: to_i64(anchor),
918 text: text.into(),
919 };
920
921 let queued = {
922 let mut inner = self.doc.lock();
923 let edit_pos = pos.min(anchor);
924 let before = max_cursor_position_of(&inner);
925 let result = match document_editing_commands::insert_text(
926 &inner.ctx,
927 Some(inner.stack_id),
928 &dto,
929 ) {
930 Ok(r) => r,
931 Err(_) if pos != anchor => {
934 delete_then(&inner, pos, anchor, |at| {
935 let ins_dto = frontend::document_editing::InsertTextDto {
936 format_policy: Default::default(),
937 position: to_i64(at),
938 anchor: to_i64(at),
939 text: text.into(),
940 };
941 Ok(document_editing_commands::insert_text(
942 &inner.ctx,
943 Some(inner.stack_id),
944 &ins_dto,
945 )?)
946 })?
947 .0
948 }
949 Err(e) => return Err(e.into()),
950 };
951
952 let new_pos = to_usize(result.new_position);
953 let added = text.chars().count();
954 let removed = removed_since(&inner, before, added, pos.max(anchor) - edit_pos);
955 self.finish_edit_from(
956 &mut inner,
957 edit_pos,
958 removed,
959 Insertion::ending_at(new_pos, added),
960 new_pos,
961 to_usize(result.blocks_affected),
962 false,
963 origin,
964 )
965 };
966 crate::inner::dispatch_queued_events(queued);
967 Ok(())
968 }
969
970 pub fn replace(
984 &self,
985 start: usize,
986 end: usize,
987 text: &str,
988 policy: crate::ReplaceFormatPolicy,
989 ) -> Result<()> {
990 let (pos, anchor) = (start, end);
991
992 let dto = frontend::document_editing::InsertTextDto {
993 format_policy: policy,
994 position: to_i64(pos),
995 anchor: to_i64(anchor),
996 text: text.into(),
997 };
998
999 let queued = {
1000 let mut inner = self.doc.lock();
1001 let edit_pos = pos.min(anchor);
1002 let before = max_cursor_position_of(&inner);
1003 let result = match document_editing_commands::insert_text(
1004 &inner.ctx,
1005 Some(inner.stack_id),
1006 &dto,
1007 ) {
1008 Ok(r) => r,
1009 Err(_) if pos != anchor => {
1013 delete_then(&inner, pos, anchor, |at| {
1014 let ins_dto = frontend::document_editing::InsertTextDto {
1015 format_policy: Default::default(),
1016 position: to_i64(at),
1017 anchor: to_i64(at),
1018 text: text.into(),
1019 };
1020 Ok(document_editing_commands::insert_text(
1021 &inner.ctx,
1022 Some(inner.stack_id),
1023 &ins_dto,
1024 )?)
1025 })?
1026 .0
1027 }
1028 Err(e) => return Err(e.into()),
1029 };
1030
1031 let new_pos = to_usize(result.new_position);
1032 let added = text.chars().count();
1033 let removed = removed_since(&inner, before, added, pos.max(anchor) - edit_pos);
1034 self.finish_edit_ext(
1035 &mut inner,
1036 edit_pos,
1037 removed,
1038 Insertion::ending_at(new_pos, added),
1039 new_pos,
1040 to_usize(result.blocks_affected),
1041 false,
1042 )
1043 };
1044 crate::inner::dispatch_queued_events(queued);
1045 Ok(())
1046 }
1047
1048 pub fn insert_formatted_text(&self, text: &str, format: &TextFormat) -> Result<()> {
1051 self.insert_formatted_text_with_origin(text, format, InsertionOrigin::Unspecified)
1052 }
1053
1054 pub fn insert_formatted_text_with_origin(
1057 &self,
1058 text: &str,
1059 format: &TextFormat,
1060 origin: InsertionOrigin,
1061 ) -> Result<()> {
1062 let (pos, anchor) = self.read_cursor();
1063
1064 let make_dto = |p: usize, a: usize| frontend::document_editing::InsertFormattedTextDto {
1065 position: to_i64(p),
1066 anchor: to_i64(a),
1067 text: text.into(),
1068 font_family: format.font_family.clone().unwrap_or_default(),
1069 font_point_size: format.font_point_size.map(|v| v as i64).unwrap_or(0),
1070 font_bold: format.font_bold.unwrap_or(false),
1071 font_italic: format.font_italic.unwrap_or(false),
1072 font_underline: format.font_underline.unwrap_or(false),
1073 font_strikeout: format.font_strikeout.unwrap_or(false),
1074 };
1075
1076 let queued = {
1077 let mut inner = self.doc.lock();
1078 let edit_pos = pos.min(anchor);
1079 let before = max_cursor_position_of(&inner);
1080 let result = match document_editing_commands::insert_formatted_text(
1081 &inner.ctx,
1082 Some(inner.stack_id),
1083 &make_dto(pos, anchor),
1084 ) {
1085 Ok(r) => r,
1086 Err(_) if pos != anchor => {
1088 delete_then(&inner, pos, anchor, |at| {
1089 Ok(document_editing_commands::insert_formatted_text(
1090 &inner.ctx,
1091 Some(inner.stack_id),
1092 &make_dto(at, at),
1093 )?)
1094 })?
1095 .0
1096 }
1097 Err(e) => return Err(e.into()),
1098 };
1099
1100 let new_pos = to_usize(result.new_position);
1101 let added = text.chars().count();
1102 let removed = removed_since(&inner, before, added, pos.max(anchor) - edit_pos);
1103 self.finish_edit_from(
1104 &mut inner,
1105 edit_pos,
1106 removed,
1107 Insertion::ending_at(new_pos, added),
1108 new_pos,
1109 1,
1110 false,
1111 origin,
1112 )
1113 };
1114 crate::inner::dispatch_queued_events(queued);
1115 Ok(())
1116 }
1117
1118 pub fn insert_block(&self) -> Result<()> {
1120 let (pos, anchor) = self.read_cursor();
1121 let queued = {
1122 let mut inner = self.doc.lock();
1123
1124 let split_at = |at: usize| -> Result<_> {
1125 let dto = frontend::document_editing::InsertBlockDto {
1126 position: to_i64(at),
1127 anchor: to_i64(at),
1128 };
1129 Ok(document_editing_commands::insert_block(
1130 &inner.ctx,
1131 Some(inner.stack_id),
1132 &dto,
1133 )?)
1134 };
1135 let before = max_cursor_position_of(&inner);
1136 let result = if pos != anchor {
1137 delete_then(&inner, pos, anchor, split_at)?.0
1139 } else {
1140 split_at(pos)?
1141 };
1142
1143 let edit_pos = pos.min(anchor);
1144 let new_pos = to_usize(result.new_position);
1145 let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1147 self.finish_edit(
1148 &mut inner,
1149 edit_pos,
1150 removed,
1151 Insertion::ending_at(new_pos, 1),
1152 new_pos,
1153 2,
1154 )
1155 };
1156 crate::inner::dispatch_queued_events(queued);
1157 Ok(())
1158 }
1159
1160 pub fn insert_html_with_origin(&self, html: &str, origin: InsertionOrigin) -> Result<()> {
1164 let frag = DocumentFragment::from_html(html);
1165 self.insert_fragment_with_origin(&frag, origin)
1166 }
1167
1168 pub fn insert_html(&self, html: &str) -> Result<()> {
1173 let frag = DocumentFragment::from_html(html);
1175 self.insert_fragment(&frag)
1176 }
1177
1178 pub fn insert_markdown_with_origin(
1182 &self,
1183 markdown: &str,
1184 origin: InsertionOrigin,
1185 ) -> Result<()> {
1186 let frag = DocumentFragment::from_markdown(markdown);
1187 self.insert_fragment_with_origin(&frag, origin)
1188 }
1189
1190 pub fn insert_markdown(&self, markdown: &str) -> Result<()> {
1191 let frag = DocumentFragment::from_markdown(markdown);
1192 self.insert_fragment(&frag)
1193 }
1194
1195 pub fn insert_djot_with_origin(&self, djot: &str, origin: InsertionOrigin) -> Result<()> {
1199 let frag = DocumentFragment::from_djot(djot);
1200 self.insert_fragment_with_origin(&frag, origin)
1201 }
1202
1203 pub fn insert_djot(&self, djot: &str) -> Result<()> {
1204 let frag = DocumentFragment::from_djot(djot);
1205 self.insert_fragment(&frag)
1206 }
1207
1208 pub fn insert_footnote_reference(&self, label: &str) -> Result<()> {
1224 self.insert_djot(&format!("[^{label}]"))
1225 }
1226
1227 pub fn insert_fragment(&self, fragment: &DocumentFragment) -> Result<()> {
1271 self.insert_fragment_with_origin(fragment, InsertionOrigin::Unspecified)
1272 }
1273
1274 pub fn insert_fragment_with_origin(
1278 &self,
1279 fragment: &DocumentFragment,
1280 origin: InsertionOrigin,
1281 ) -> Result<()> {
1282 let (pos, anchor) = self.read_cursor();
1283 let queued = {
1284 let mut inner = self.doc.lock();
1285 let replacing_an_empty_text = pos == anchor && self.data.lock().whole_text_selected;
1289 let into_an_emptied_text =
1294 pos == anchor && !replacing_an_empty_text && inner.is_the_emptied_text();
1295
1296 let paste_at = |at: usize, replacing: bool| -> Result<_> {
1306 let store = inner.ctx.db_context.get_store();
1307 let rope_before = store.rope.read().clone();
1308 let before = max_cursor_position_of(&inner);
1309 let fragment_data = if replacing {
1310 frontend::common::parser_tools::fragment_schema::replacing_the_text(
1311 fragment.raw_data(),
1312 )
1313 } else if into_an_emptied_text {
1314 frontend::common::parser_tools::fragment_schema::into_an_emptied_text(
1315 fragment.raw_data(),
1316 )
1317 } else {
1318 fragment.raw_data().into()
1319 };
1320 let dto = frontend::document_editing::InsertFragmentDto {
1321 position: to_i64(at),
1322 anchor: to_i64(at),
1323 fragment_data,
1324 };
1325 let result = document_editing_commands::insert_fragment(
1326 &inner.ctx,
1327 Some(inner.stack_id),
1328 &dto,
1329 )?;
1330 let inserted = if common::database::rope_helpers::rope_positions_match_flow(store) {
1331 let (start, old_end, new_end) = common::database::rope_helpers::changed_span(
1332 &rope_before,
1333 &store.rope.read(),
1334 at,
1335 );
1336 Insertion {
1337 at: start,
1338 removed: old_end - start,
1339 added: new_end - start,
1340 }
1341 } else {
1342 let new_pos = to_usize(result.new_position);
1345 let added = before
1346 .zip(max_cursor_position_of(&inner))
1347 .map_or(new_pos.saturating_sub(at), |(before, after)| {
1348 after.saturating_sub(before)
1349 });
1350 Insertion {
1351 at,
1352 removed: 0,
1353 added,
1354 }
1355 };
1356 Ok((result, inserted))
1357 };
1358 let ((result, inserted), removed, deleted_from) = if pos != anchor {
1359 delete_then(&inner, pos, anchor, |at| paste_at(at, true))?
1360 } else {
1361 (paste_at(pos, replacing_an_empty_text)?, 0, pos)
1362 };
1363
1364 let edit_pos = pos.min(anchor).min(deleted_from);
1367 let new_pos = to_usize(result.new_position);
1368 self.finish_edit_from(
1369 &mut inner,
1370 edit_pos,
1371 removed,
1372 inserted,
1373 new_pos,
1374 to_usize(result.blocks_added),
1375 true,
1376 origin,
1377 )
1378 };
1379 crate::inner::dispatch_queued_events(queued);
1380 Ok(())
1381 }
1382
1383 pub fn selection(&self) -> DocumentFragment {
1394 let (pos, anchor) = self.read_cursor();
1395
1396 let (extract_pos, extract_anchor) = match self.selection_kind() {
1399 SelectionKind::Cells(ref range) => match self.cell_range_positions(range) {
1400 Some((start, end)) => (start, end),
1401 None => return DocumentFragment::new(),
1402 },
1403 SelectionKind::Mixed {
1404 ref cell_range,
1405 text_before,
1406 text_after,
1407 } => {
1408 let (cell_start, cell_end) = match self.cell_range_positions(cell_range) {
1409 Some(p) => p,
1410 None => return DocumentFragment::new(),
1411 };
1412 let table_start = self
1416 .table_anchor_position(cell_range.table_id)
1417 .unwrap_or(cell_start)
1418 .min(cell_start);
1419 let start = if text_before {
1420 pos.min(anchor).min(table_start)
1421 } else {
1422 table_start
1423 };
1424 let end = if text_after {
1425 pos.max(anchor)
1426 } else {
1427 cell_end
1428 };
1429 (start.min(cell_start), end.max(cell_end))
1430 }
1431 SelectionKind::None => return DocumentFragment::new(),
1432 SelectionKind::Text => (pos, anchor),
1433 };
1434
1435 if extract_pos == extract_anchor {
1436 return DocumentFragment::new();
1437 }
1438
1439 let inner = self.doc.lock();
1440 let dto = frontend::document_inspection::ExtractFragmentDto {
1441 position: to_i64(extract_pos),
1442 anchor: to_i64(extract_anchor),
1443 };
1444 match document_inspection_commands::extract_fragment(&inner.ctx, &dto) {
1445 Ok(result) => DocumentFragment::from_raw(result.fragment_data, result.plain_text),
1446 Err(_) => DocumentFragment::new(),
1447 }
1448 }
1449
1450 pub fn insert_image(&self, name: &str, alt: &str, width: u32, height: u32) -> Result<()> {
1459 let (pos, anchor) = self.read_cursor();
1460 let queued = {
1461 let mut inner = self.doc.lock();
1462
1463 let image_at = |at: usize| -> Result<_> {
1464 let dto = frontend::document_editing::InsertImageDto {
1465 position: to_i64(at),
1466 anchor: to_i64(at),
1467 image_name: name.into(),
1468 alt: alt.into(),
1469 width: width as i64,
1470 height: height as i64,
1471 quality: 100,
1472 };
1473 Ok(document_editing_commands::insert_image(
1474 &inner.ctx,
1475 Some(inner.stack_id),
1476 &dto,
1477 )?)
1478 };
1479 let before = max_cursor_position_of(&inner);
1480 let result = if pos != anchor {
1481 delete_then(&inner, pos, anchor, image_at)?.0
1482 } else {
1483 image_at(pos)?
1484 };
1485
1486 let edit_pos = pos.min(anchor);
1487 let new_pos = to_usize(result.new_position);
1488 let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1490 self.finish_edit_ext(
1491 &mut inner,
1492 edit_pos,
1493 removed,
1494 Insertion::ending_at(new_pos, 1),
1495 new_pos,
1496 1,
1497 false,
1498 )
1499 };
1500 crate::inner::dispatch_queued_events(queued);
1501 Ok(())
1502 }
1503
1504 pub fn insert_frame(&self) -> Result<()> {
1506 let (pos, anchor) = self.read_cursor();
1507 let queued = {
1508 let mut inner = self.doc.lock();
1509 let dto = frontend::document_editing::InsertFrameDto {
1510 position: to_i64(pos),
1511 anchor: to_i64(anchor),
1512 };
1513 document_editing_commands::insert_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1514 inner.modified = true;
1517 inner.invalidate_text_cache();
1518 inner.rehighlight_affected(pos.min(anchor));
1519 inner.queue_event(DocumentEvent::ContentsChanged {
1520 position: pos.min(anchor),
1521 chars_removed: 0,
1522 chars_added: 0,
1523 blocks_affected: 1,
1524 });
1525 inner.check_block_count_changed();
1526 inner.check_flow_changed();
1527 self.queue_undo_redo_event(&mut inner)
1528 };
1529 crate::inner::dispatch_queued_events(queued);
1530 Ok(())
1531 }
1532
1533 pub fn insert_table(&self, rows: usize, columns: usize) -> Result<TextTable> {
1539 let (pos, anchor) = self.read_cursor();
1540 let (table_id, queued) = {
1541 let mut inner = self.doc.lock();
1542 let dto = frontend::document_editing::InsertTableDto {
1543 position: to_i64(pos),
1544 anchor: to_i64(anchor),
1545 rows: to_i64(rows),
1546 columns: to_i64(columns),
1547 };
1548 let result =
1549 document_editing_commands::insert_table(&inner.ctx, Some(inner.stack_id), &dto)?;
1550 let new_pos = to_usize(result.new_position);
1551 let table_id = to_usize(result.table_id);
1552 inner.adjust_cursors(pos.min(anchor), 0, new_pos - pos.min(anchor));
1553 {
1554 let mut d = self.data.lock();
1555 d.position = new_pos;
1556 d.anchor = new_pos;
1557 d.whole_text_selected = false;
1558 d.anchor_in_table = None;
1559 }
1560 inner.modified = true;
1561 inner.invalidate_text_cache();
1562 inner.rehighlight_affected(pos.min(anchor));
1563 inner.queue_event(DocumentEvent::ContentsChanged {
1564 position: pos.min(anchor),
1565 chars_removed: 0,
1566 chars_added: new_pos - pos.min(anchor),
1567 blocks_affected: 1,
1568 });
1569 inner.check_block_count_changed();
1570 inner.check_flow_changed();
1571 (table_id, self.queue_undo_redo_event(&mut inner))
1572 };
1573 crate::inner::dispatch_queued_events(queued);
1574 Ok(TextTable {
1575 doc: self.doc.clone(),
1576 table_id,
1577 })
1578 }
1579
1580 pub fn current_table(&self) -> Option<TextTable> {
1585 self.current_table_cell().map(|c| c.table)
1586 }
1587
1588 pub fn current_table_cell(&self) -> Option<TableCellRef> {
1593 let pos = self.position();
1594 let inner = self.doc.lock();
1595 let block_id = crate::inner::block_at_caret_dto(&inner.ctx, pos)
1598 .ok()?
1599 .block_id as usize;
1600
1601 let block = crate::text_block::TextBlock {
1602 doc: self.doc.clone(),
1603 block_id,
1604 };
1605 drop(inner);
1607 block.table_cell()
1608 }
1609
1610 pub fn current_frame(&self) -> Option<FrameRef> {
1617 let pos = self.position();
1618 let inner = self.doc.lock();
1619 let block_info = Self::caret_block(&inner, pos)?;
1620 let block_id = block_info.block_id as u64;
1621 cursor_frame_ref(&inner, block_id)
1622 }
1623
1624 pub fn is_in_blockquote(&self) -> bool {
1628 self.current_blockquote_frame_id().is_some()
1629 }
1630
1631 pub fn current_blockquote_frame_id(&self) -> Option<usize> {
1634 let pos = self.position();
1635 let inner = self.doc.lock();
1636 let block_info = Self::caret_block(&inner, pos)?;
1637 innermost_blockquote_frame_id(&inner, block_info.block_id as u64)
1638 }
1639
1640 pub fn blockquote_depth_at_cursor(&self) -> usize {
1643 let pos = self.position();
1644 let inner = self.doc.lock();
1645 let Some(block_info) = Self::caret_block(&inner, pos) else {
1646 return 0;
1647 };
1648 blockquote_depth_for_block(&inner, block_info.block_id as u64)
1649 }
1650
1651 pub fn is_first_block_in_current_frame(&self) -> bool {
1657 matches!(
1658 block_position_in_current_frame(self),
1659 Some(BlockEdge::First) | Some(BlockEdge::OnlyOne)
1660 )
1661 }
1662
1663 pub fn is_last_block_in_current_frame(&self) -> bool {
1667 matches!(
1668 block_position_in_current_frame(self),
1669 Some(BlockEdge::Last) | Some(BlockEdge::OnlyOne)
1670 )
1671 }
1672
1673 pub fn current_block_is_empty(&self) -> bool {
1676 let pos = self.position();
1677 let inner = self.doc.lock();
1678 let Some(block_info) = Self::caret_block(&inner, pos) else {
1679 return false;
1680 };
1681 let store = inner.ctx.db_context.get_store();
1682 let block_entity = store
1683 .blocks
1684 .read()
1685 .get(&(block_info.block_id as common::types::EntityId))
1686 .cloned();
1687 match block_entity {
1688 Some(b) => {
1689 let len = common::database::rope_helpers::block_char_length(&b, store);
1690 len == 0
1691 }
1692 None => false,
1693 }
1694 }
1695
1696 pub fn selection_spans_multiple_frames(&self) -> bool {
1700 let (pos, anchor) = self.read_cursor();
1701 if pos == anchor {
1702 return false;
1703 }
1704 let inner = self.doc.lock();
1705 let Some((first, last)) = Self::selection_block_ids(&inner, pos, anchor) else {
1708 return false;
1709 };
1710 crate::text_block::find_parent_frame(&inner, first)
1711 != crate::text_block::find_parent_frame(&inner, last)
1712 }
1713
1714 fn selection_block_ids(
1722 inner: &TextDocumentInner,
1723 pos: usize,
1724 anchor: usize,
1725 ) -> Option<(u64, u64)> {
1726 let (lo, hi) = (pos.min(anchor), pos.max(anchor));
1727 let last = Self::caret_block(inner, hi)?.block_id as u64;
1728 if lo == hi {
1729 return Some((last, last));
1730 }
1731 let first = document_inspection_commands::get_block_at_position(
1732 &inner.ctx,
1733 &frontend::document_inspection::GetBlockAtPositionDto {
1734 position: to_i64(lo),
1735 },
1736 )
1737 .ok()?
1738 .block_id as u64;
1739 Some((first, last))
1740 }
1741
1742 pub fn wrap_selection_in_blockquote(&self) -> Result<()> {
1749 if self.selection_spans_multiple_frames() {
1750 return Err(DocumentError::InvalidArgument(
1751 "Cannot wrap selection in blockquote: selection spans multiple frames".into(),
1752 ));
1753 }
1754 let (start_block_id, end_block_id) = self.resolve_selection_block_range()?;
1755 let dto = frontend::document_editing::WrapBlocksInFrameDto {
1756 start_block_id: start_block_id as i64,
1757 end_block_id: end_block_id as i64,
1758 position: Some(frontend::document_editing::FramePosition::InFlow),
1759 top_margin: None,
1760 bottom_margin: None,
1761 left_margin: None,
1762 right_margin: None,
1763 padding: None,
1764 border: None,
1765 is_blockquote: Some(true),
1766 };
1767 let queued = {
1768 let mut inner = self.doc.lock();
1769 let _result = document_editing_commands::wrap_blocks_in_frame(
1770 &inner.ctx,
1771 Some(inner.stack_id),
1772 &dto,
1773 )?;
1774 inner.modified = true;
1775 inner.queue_event(DocumentEvent::FormatChanged {
1783 position: 0,
1784 length: 0,
1785 kind: crate::flow::FormatChangeKind::Block,
1786 });
1787 self.queue_undo_redo_event(&mut inner)
1788 };
1789 crate::inner::dispatch_queued_events(queued);
1790 Ok(())
1791 }
1792
1793 pub fn insert_blockquote(&self) -> Result<()> {
1797 self.wrap_selection_in_blockquote()
1798 }
1799
1800 pub fn toggle_blockquote(&self) -> Result<()> {
1805 if let Some(frame_id) = self.current_blockquote_frame_id() {
1806 self.unwrap_frame_by_id(frame_id)
1807 } else {
1808 self.wrap_selection_in_blockquote()
1809 }
1810 }
1811
1812 pub fn unwrap_current_frame(&self) -> Result<()> {
1816 let frame_ref = self.current_frame().ok_or_else(|| {
1817 DocumentError::InvalidCursorContext("Cursor is not inside any sub-frame".into())
1818 })?;
1819 self.unwrap_frame_by_id(frame_ref.frame_id)
1820 }
1821
1822 pub fn unwrap_current_block_from_blockquote(&self) -> Result<()> {
1826 if self.current_blockquote_frame_id().is_none() {
1827 return Err(DocumentError::InvalidCursorContext(
1828 "Cursor is not inside a blockquote".into(),
1829 ));
1830 }
1831 let block_id = self.current_block_id_for_mutation()?;
1832 let dto = frontend::document_editing::UnwrapBlockFromFrameDto {
1833 block_id: block_id as i64,
1834 };
1835 let queued = {
1836 let mut inner = self.doc.lock();
1837 let _result = document_editing_commands::unwrap_block_from_frame(
1838 &inner.ctx,
1839 Some(inner.stack_id),
1840 &dto,
1841 )?;
1842 inner.modified = true;
1843 inner.queue_event(DocumentEvent::FormatChanged {
1847 position: 0,
1848 length: 0,
1849 kind: crate::flow::FormatChangeKind::Block,
1850 });
1851 self.queue_undo_redo_event(&mut inner)
1852 };
1853 crate::inner::dispatch_queued_events(queued);
1854 Ok(())
1855 }
1856
1857 pub fn increase_blockquote_depth(&self) -> Result<()> {
1861 self.wrap_selection_in_blockquote()
1862 }
1863
1864 pub fn decrease_blockquote_depth(&self) -> Result<()> {
1870 if self.current_blockquote_frame_id().is_none() {
1871 return Err(DocumentError::InvalidCursorContext(
1872 "Cursor is not inside a blockquote to decrease depth".into(),
1873 ));
1874 }
1875 self.unwrap_current_block_from_blockquote()
1876 }
1877
1878 fn unwrap_frame_by_id(&self, frame_id: usize) -> Result<()> {
1879 let dto = frontend::document_editing::UnwrapFrameDto {
1880 frame_id: frame_id as i64,
1881 };
1882 let queued = {
1883 let mut inner = self.doc.lock();
1884 let _result =
1885 document_editing_commands::unwrap_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1886 inner.modified = true;
1887 inner.queue_event(DocumentEvent::FormatChanged {
1891 position: 0,
1892 length: 0,
1893 kind: crate::flow::FormatChangeKind::Block,
1894 });
1895 self.queue_undo_redo_event(&mut inner)
1896 };
1897 crate::inner::dispatch_queued_events(queued);
1898 Ok(())
1899 }
1900
1901 fn current_block_id_for_mutation(&self) -> Result<usize> {
1904 let pos = self.position();
1905 let inner = self.doc.lock();
1906 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
1907 Ok(block_info.block_id as usize)
1908 }
1909
1910 fn resolve_selection_block_range(&self) -> Result<(usize, usize)> {
1914 let (pos, anchor) = self.read_cursor();
1915 let inner = self.doc.lock();
1916 let (first, last) = Self::selection_block_ids(&inner, pos, anchor)
1917 .ok_or_else(|| DocumentError::NotFound("no block at the selection's ends".into()))?;
1918 Ok((first as usize, last as usize))
1919 }
1920
1921 pub fn remove_table(&self, table_id: usize) -> Result<()> {
1925 let queued = {
1926 let mut inner = self.doc.lock();
1927 let before = crate::document::capture_block_state(&inner);
1934 let dto = frontend::document_editing::RemoveTableDto {
1935 table_id: to_i64(table_id),
1936 };
1937 document_editing_commands::remove_table(&inner.ctx, Some(inner.stack_id), &dto)?;
1938 inner.modified = true;
1939 inner.invalidate_text_cache();
1940 inner.rehighlight_all();
1941 crate::document::emit_content_change_events(&mut inner, &before);
1942 inner.check_block_count_changed();
1943 inner.check_flow_changed();
1944 self.queue_undo_redo_event(&mut inner)
1945 };
1946 crate::inner::dispatch_queued_events(queued);
1947 Ok(())
1948 }
1949
1950 pub fn insert_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
1952 let queued = {
1953 let mut inner = self.doc.lock();
1954 let before = crate::document::capture_block_state(&inner);
1955 let dto = frontend::document_editing::InsertTableRowDto {
1956 table_id: to_i64(table_id),
1957 row_index: to_i64(row_index),
1958 };
1959 document_editing_commands::insert_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
1960 inner.modified = true;
1961 inner.invalidate_text_cache();
1962 inner.rehighlight_all();
1963 crate::document::emit_content_change_events(&mut inner, &before);
1964 inner.check_block_count_changed();
1965 self.queue_undo_redo_event(&mut inner)
1966 };
1967 crate::inner::dispatch_queued_events(queued);
1968 Ok(())
1969 }
1970
1971 pub fn insert_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
1973 let queued = {
1974 let mut inner = self.doc.lock();
1975 let before = crate::document::capture_block_state(&inner);
1976 let dto = frontend::document_editing::InsertTableColumnDto {
1977 table_id: to_i64(table_id),
1978 column_index: to_i64(column_index),
1979 };
1980 document_editing_commands::insert_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
1981 inner.modified = true;
1982 inner.invalidate_text_cache();
1983 inner.rehighlight_all();
1984 crate::document::emit_content_change_events(&mut inner, &before);
1985 inner.check_block_count_changed();
1986 self.queue_undo_redo_event(&mut inner)
1987 };
1988 crate::inner::dispatch_queued_events(queued);
1989 Ok(())
1990 }
1991
1992 pub fn remove_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
1994 let queued = {
1995 let mut inner = self.doc.lock();
1996 let before = crate::document::capture_block_state(&inner);
1997 let dto = frontend::document_editing::RemoveTableRowDto {
1998 table_id: to_i64(table_id),
1999 row_index: to_i64(row_index),
2000 };
2001 document_editing_commands::remove_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
2002 inner.modified = true;
2003 inner.invalidate_text_cache();
2004 inner.rehighlight_all();
2005 crate::document::emit_content_change_events(&mut inner, &before);
2006 inner.check_block_count_changed();
2007 self.queue_undo_redo_event(&mut inner)
2008 };
2009 crate::inner::dispatch_queued_events(queued);
2010 Ok(())
2011 }
2012
2013 pub fn remove_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
2015 let queued = {
2016 let mut inner = self.doc.lock();
2017 let before = crate::document::capture_block_state(&inner);
2018 let dto = frontend::document_editing::RemoveTableColumnDto {
2019 table_id: to_i64(table_id),
2020 column_index: to_i64(column_index),
2021 };
2022 document_editing_commands::remove_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
2023 inner.modified = true;
2024 inner.invalidate_text_cache();
2025 inner.rehighlight_all();
2026 crate::document::emit_content_change_events(&mut inner, &before);
2027 inner.check_block_count_changed();
2028 self.queue_undo_redo_event(&mut inner)
2029 };
2030 crate::inner::dispatch_queued_events(queued);
2031 Ok(())
2032 }
2033
2034 pub fn merge_table_cells(
2036 &self,
2037 table_id: usize,
2038 start_row: usize,
2039 start_column: usize,
2040 end_row: usize,
2041 end_column: usize,
2042 ) -> Result<()> {
2043 let queued = {
2044 let mut inner = self.doc.lock();
2045 let before = crate::document::capture_block_state(&inner);
2046 let dto = frontend::document_editing::MergeTableCellsDto {
2047 table_id: to_i64(table_id),
2048 start_row: to_i64(start_row),
2049 start_column: to_i64(start_column),
2050 end_row: to_i64(end_row),
2051 end_column: to_i64(end_column),
2052 };
2053 document_editing_commands::merge_table_cells(&inner.ctx, Some(inner.stack_id), &dto)?;
2054 inner.modified = true;
2055 inner.invalidate_text_cache();
2056 inner.rehighlight_all();
2057 crate::document::emit_content_change_events(&mut inner, &before);
2058 inner.check_block_count_changed();
2059 self.queue_undo_redo_event(&mut inner)
2060 };
2061 crate::inner::dispatch_queued_events(queued);
2062 Ok(())
2063 }
2064
2065 pub fn split_table_cell(
2067 &self,
2068 cell_id: usize,
2069 split_rows: usize,
2070 split_columns: usize,
2071 ) -> Result<()> {
2072 let queued = {
2073 let mut inner = self.doc.lock();
2074 let before = crate::document::capture_block_state(&inner);
2075 let dto = frontend::document_editing::SplitTableCellDto {
2076 cell_id: to_i64(cell_id),
2077 split_rows: to_i64(split_rows),
2078 split_columns: to_i64(split_columns),
2079 };
2080 document_editing_commands::split_table_cell(&inner.ctx, Some(inner.stack_id), &dto)?;
2081 inner.modified = true;
2082 inner.invalidate_text_cache();
2083 inner.rehighlight_all();
2084 crate::document::emit_content_change_events(&mut inner, &before);
2085 inner.check_block_count_changed();
2086 self.queue_undo_redo_event(&mut inner)
2087 };
2088 crate::inner::dispatch_queued_events(queued);
2089 Ok(())
2090 }
2091
2092 pub fn set_table_format(
2096 &self,
2097 table_id: usize,
2098 format: &crate::flow::TableFormat,
2099 ) -> Result<()> {
2100 let queued = {
2101 let mut inner = self.doc.lock();
2102 let dto = format.to_set_dto(table_id);
2103 document_formatting_commands::set_table_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2104 inner.modified = true;
2105 inner.queue_event(DocumentEvent::FormatChanged {
2106 position: 0,
2107 length: 0,
2108 kind: crate::flow::FormatChangeKind::Block,
2109 });
2110 self.queue_undo_redo_event(&mut inner)
2111 };
2112 crate::inner::dispatch_queued_events(queued);
2113 Ok(())
2114 }
2115
2116 pub fn set_table_cell_format(
2118 &self,
2119 cell_id: usize,
2120 format: &crate::flow::CellFormat,
2121 ) -> Result<()> {
2122 let queued = {
2123 let mut inner = self.doc.lock();
2124 let dto = format.to_set_dto(cell_id);
2125 document_formatting_commands::set_table_cell_format(
2126 &inner.ctx,
2127 Some(inner.stack_id),
2128 &dto,
2129 )?;
2130 inner.modified = true;
2131 inner.queue_event(DocumentEvent::FormatChanged {
2132 position: 0,
2133 length: 0,
2134 kind: crate::flow::FormatChangeKind::Block,
2135 });
2136 self.queue_undo_redo_event(&mut inner)
2137 };
2138 crate::inner::dispatch_queued_events(queued);
2139 Ok(())
2140 }
2141
2142 pub fn remove_current_table(&self) -> Result<()> {
2147 let table = self.current_table().ok_or_else(|| {
2148 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2149 })?;
2150 self.remove_table(table.id())
2151 }
2152
2153 pub fn insert_row_above(&self) -> Result<()> {
2156 let cell_ref = self.current_table_cell().ok_or_else(|| {
2157 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2158 })?;
2159 self.insert_table_row(cell_ref.table.id(), cell_ref.row)
2160 }
2161
2162 pub fn insert_row_below(&self) -> Result<()> {
2165 let cell_ref = self.current_table_cell().ok_or_else(|| {
2166 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2167 })?;
2168 self.insert_table_row(cell_ref.table.id(), cell_ref.row + 1)
2169 }
2170
2171 pub fn insert_column_before(&self) -> Result<()> {
2174 let cell_ref = self.current_table_cell().ok_or_else(|| {
2175 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2176 })?;
2177 self.insert_table_column(cell_ref.table.id(), cell_ref.column)
2178 }
2179
2180 pub fn insert_column_after(&self) -> Result<()> {
2183 let cell_ref = self.current_table_cell().ok_or_else(|| {
2184 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2185 })?;
2186 self.insert_table_column(cell_ref.table.id(), cell_ref.column + 1)
2187 }
2188
2189 pub fn remove_current_row(&self) -> Result<()> {
2192 let cell_ref = self.current_table_cell().ok_or_else(|| {
2193 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2194 })?;
2195 self.remove_table_row(cell_ref.table.id(), cell_ref.row)
2196 }
2197
2198 pub fn remove_current_column(&self) -> Result<()> {
2201 let cell_ref = self.current_table_cell().ok_or_else(|| {
2202 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2203 })?;
2204 self.remove_table_column(cell_ref.table.id(), cell_ref.column)
2205 }
2206
2207 pub fn merge_selected_cells(&self) -> Result<()> {
2214 let pos_cell = self.current_table_cell().ok_or_else(|| {
2215 DocumentError::InvalidCursorContext("cursor position is not inside a table".into())
2216 })?;
2217
2218 let (_pos, anchor) = self.read_cursor();
2223 let anchor_cell = self.table_cell_at(anchor).ok_or_else(|| {
2224 DocumentError::InvalidCursorContext("cursor anchor is not inside a table".into())
2225 })?;
2226
2227 if pos_cell.table.id() != anchor_cell.table.id() {
2228 return Err(DocumentError::InvalidArgument(
2229 "position and anchor are in different tables".into(),
2230 ));
2231 }
2232
2233 let start_row = pos_cell.row.min(anchor_cell.row);
2234 let start_col = pos_cell.column.min(anchor_cell.column);
2235 let end_row = pos_cell.row.max(anchor_cell.row);
2236 let end_col = pos_cell.column.max(anchor_cell.column);
2237
2238 self.merge_table_cells(pos_cell.table.id(), start_row, start_col, end_row, end_col)
2239 }
2240
2241 pub fn split_current_cell(&self, split_rows: usize, split_columns: usize) -> Result<()> {
2244 let cell_ref = self.current_table_cell().ok_or_else(|| {
2245 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2246 })?;
2247 let cell = cell_ref
2249 .table
2250 .cell(cell_ref.row, cell_ref.column)
2251 .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2252 self.split_table_cell(cell.id(), split_rows, split_columns)
2254 }
2255
2256 pub fn set_current_table_format(&self, format: &crate::flow::TableFormat) -> Result<()> {
2259 let table = self.current_table().ok_or_else(|| {
2260 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2261 })?;
2262 self.set_table_format(table.id(), format)
2263 }
2264
2265 pub fn set_current_cell_format(&self, format: &crate::flow::CellFormat) -> Result<()> {
2268 let cell_ref = self.current_table_cell().ok_or_else(|| {
2269 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2270 })?;
2271 let cell = cell_ref
2272 .table
2273 .cell(cell_ref.row, cell_ref.column)
2274 .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2275 self.set_table_cell_format(cell.id(), format)
2276 }
2277
2278 pub fn selection_kind(&self) -> crate::flow::SelectionKind {
2286 use crate::flow::{CellRange, SelectionKind};
2287
2288 {
2290 let d = self.data.lock();
2291 if let Some(ref range) = d.cell_selection_override {
2292 return SelectionKind::Cells(range.clone());
2293 }
2294 if d.position == d.anchor {
2295 return SelectionKind::None;
2296 }
2297 }
2298
2299 let (pos, anchor) = self.read_cursor();
2300
2301 let pos_cell = self.table_cell_at(pos);
2303 let anchor_cell = self.selection_anchor_cell(anchor, pos_cell.as_ref());
2304
2305 match (&pos_cell, &anchor_cell) {
2306 (None, None) => {
2307 let (start, end) = (pos.min(anchor), pos.max(anchor));
2311 if let Some(t) = self.find_table_between(start, end) {
2312 let table_id = t.id();
2313 let rows = t.rows();
2314 let cols = t.columns();
2315 let range = CellRange {
2316 table_id,
2317 start_row: 0,
2318 start_col: 0,
2319 end_row: if rows > 0 { rows - 1 } else { 0 },
2320 end_col: if cols > 0 { cols - 1 } else { 0 },
2321 };
2322 let spans = self.collect_cell_spans(table_id);
2323 SelectionKind::Mixed {
2324 cell_range: range.expand_for_spans(&spans),
2325 text_before: true,
2326 text_after: true,
2327 }
2328 } else {
2329 SelectionKind::Text
2330 }
2331 }
2332 (Some(pc), Some(ac)) => {
2333 if pc.table.id() != ac.table.id() {
2334 return SelectionKind::Text;
2336 }
2337 if pc.row == ac.row && pc.column == ac.column {
2338 return SelectionKind::Text;
2340 }
2341 let range = CellRange {
2343 table_id: pc.table.id(),
2344 start_row: pc.row.min(ac.row),
2345 start_col: pc.column.min(ac.column),
2346 end_row: pc.row.max(ac.row),
2347 end_col: pc.column.max(ac.column),
2348 };
2349 let spans = self.collect_cell_spans(pc.table.id());
2350 SelectionKind::Cells(range.expand_for_spans(&spans))
2351 }
2352 (Some(tc), None) | (None, Some(tc)) => {
2353 let table_id = tc.table.id();
2357 let rows = tc.table.rows();
2358 let cols = tc.table.columns();
2359
2360 let inside_pos = if pos_cell.is_some() { pos } else { anchor };
2361 let outside_pos = if pos_cell.is_some() { anchor } else { pos };
2362
2363 let text_before = outside_pos < inside_pos;
2364 let text_after = !text_before;
2365
2366 let range = CellRange {
2367 table_id,
2368 start_row: 0,
2369 start_col: 0,
2370 end_row: if rows > 0 { rows - 1 } else { 0 },
2371 end_col: if cols > 0 { cols - 1 } else { 0 },
2372 };
2373 let spans = self.collect_cell_spans(table_id);
2374 SelectionKind::Mixed {
2375 cell_range: range.expand_for_spans(&spans),
2376 text_before,
2377 text_after,
2378 }
2379 }
2380 }
2381 }
2382
2383 pub fn is_cell_selection(&self) -> bool {
2385 matches!(
2386 self.selection_kind(),
2387 crate::flow::SelectionKind::Cells(_) | crate::flow::SelectionKind::Mixed { .. }
2388 )
2389 }
2390
2391 pub fn selected_cell_range(&self) -> Option<crate::flow::CellRange> {
2393 match self.selection_kind() {
2394 crate::flow::SelectionKind::Cells(r) => Some(r),
2395 crate::flow::SelectionKind::Mixed { cell_range, .. } => Some(cell_range),
2396 _ => None,
2397 }
2398 }
2399
2400 pub fn selected_cells(&self) -> Vec<TableCellRef> {
2402 let range = match self.selected_cell_range() {
2403 Some(r) => r,
2404 None => return Vec::new(),
2405 };
2406 let table = TextTable {
2407 doc: self.doc.clone(),
2408 table_id: range.table_id,
2409 };
2410 let mut cells = Vec::new();
2411 for row in range.start_row..=range.end_row {
2412 for col in range.start_col..=range.end_col {
2413 if table.cell(row, col).is_some() {
2414 cells.push(TableCellRef {
2415 table: table.clone(),
2416 row,
2417 column: col,
2418 });
2419 }
2420 }
2421 }
2422 cells
2423 }
2424
2425 pub fn select_table_cell(&self, table_id: usize, row: usize, col: usize) {
2429 let mut d = self.data.lock();
2430 d.cell_selection_override = Some(crate::flow::CellRange {
2431 table_id,
2432 start_row: row,
2433 start_col: col,
2434 end_row: row,
2435 end_col: col,
2436 });
2437 }
2438
2439 pub fn select_cell_range(
2441 &self,
2442 table_id: usize,
2443 start_row: usize,
2444 start_col: usize,
2445 end_row: usize,
2446 end_col: usize,
2447 ) {
2448 let range = crate::flow::CellRange {
2449 table_id,
2450 start_row,
2451 start_col,
2452 end_row,
2453 end_col,
2454 };
2455 let spans = self.collect_cell_spans(table_id);
2456 let mut d = self.data.lock();
2457 d.cell_selection_override = Some(range.expand_for_spans(&spans));
2458 }
2459
2460 pub fn clear_cell_selection(&self) {
2462 let mut d = self.data.lock();
2463 d.cell_selection_override = None;
2464 }
2465
2466 fn cell_range_positions(&self, range: &CellRange) -> Option<(usize, usize)> {
2469 let inner = self.doc.lock();
2470 let main_frame_id = get_main_frame_id(&inner);
2471 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2473 drop(inner);
2474
2475 let table = flow.into_iter().find_map(|e| match e {
2477 FlowElement::Table(t) if t.id() == range.table_id => Some(t),
2478 _ => None,
2479 })?;
2480
2481 let mut min_pos = usize::MAX;
2482 let mut max_pos = 0usize;
2483
2484 for row in range.start_row..=range.end_row {
2485 for col in range.start_col..=range.end_col {
2486 if let Some(cell) = table.cell(row, col) {
2487 for block in cell.blocks() {
2488 let bp = block.position();
2489 let bl = block.length();
2490 min_pos = min_pos.min(bp);
2491 max_pos = max_pos.max(bp + bl);
2492 }
2493 }
2494 }
2495 }
2496
2497 if min_pos == usize::MAX {
2498 return None;
2499 }
2500
2501 Some((min_pos, max_pos + 1))
2503 }
2504
2505 fn table_anchor_position(&self, table_id: usize) -> Option<usize> {
2510 let inner = self.doc.lock();
2511 let store = inner.ctx.db_context.get_store();
2512 common::database::rope_helpers::table_anchor_position(
2513 store,
2514 table_id as common::types::EntityId,
2515 )
2516 .map(to_usize)
2517 }
2518
2519 fn table_cell_at(&self, position: usize) -> Option<TableCellRef> {
2521 let inner = self.doc.lock();
2522 let block_id = crate::inner::block_at_caret_dto(&inner.ctx, position)
2524 .ok()?
2525 .block_id as usize;
2526
2527 let block = crate::text_block::TextBlock {
2528 doc: self.doc.clone(),
2529 block_id,
2530 };
2531 drop(inner);
2532 block.table_cell()
2533 }
2534
2535 fn selection_anchor_cell(
2552 &self,
2553 anchor: usize,
2554 position_cell: Option<&TableCellRef>,
2555 ) -> Option<TableCellRef> {
2556 let cell = self.table_cell_at(anchor)?;
2557 let on_table_anchor = {
2558 let inner = self.doc.lock();
2559 common::database::rope_helpers::snap_off_table_anchor(
2560 inner.ctx.db_context.get_store(),
2561 to_i64(anchor),
2562 true,
2563 ) != to_i64(anchor)
2564 };
2565 let moving_end_in_the_table =
2566 position_cell.is_some_and(|moving| moving.table.id() == cell.table.id());
2567 (!on_table_anchor || moving_end_in_the_table).then_some(cell)
2568 }
2569
2570 fn back_off_table_anchor(&self, position: usize) -> usize {
2576 let inner = self.doc.lock();
2577 to_usize(common::database::rope_helpers::snap_off_table_anchor(
2578 inner.ctx.db_context.get_store(),
2579 to_i64(position),
2580 false,
2581 ))
2582 }
2583
2584 fn find_table_between(&self, start: usize, end: usize) -> Option<TextTable> {
2586 let inner = self.doc.lock();
2587 let main_frame_id = get_main_frame_id(&inner);
2588 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2590 drop(inner);
2591
2592 for elem in flow {
2593 if let FlowElement::Table(t) = elem {
2594 if let Some(first_cell) = t.cell(0, 0) {
2597 let blocks = first_cell.blocks();
2598 if let Some(fb) = blocks.first() {
2599 let p = fb.position();
2600 if p > start && p < end {
2601 return Some(t);
2602 }
2603 }
2604 }
2605 }
2606 }
2607 None
2608 }
2609
2610 fn collect_cell_spans(&self, table_id: usize) -> Vec<(usize, usize, usize, usize)> {
2612 let inner = self.doc.lock();
2613 let table_dto =
2614 match frontend::commands::table_commands::get_table(&inner.ctx, &(table_id as u64))
2615 .ok()
2616 .flatten()
2617 {
2618 Some(t) => t,
2619 None => return Vec::new(),
2620 };
2621
2622 let mut spans = Vec::with_capacity(table_dto.cells.len());
2623 for &cell_id in &table_dto.cells {
2624 if let Some(cell) =
2625 frontend::commands::table_cell_commands::get_table_cell(&inner.ctx, &cell_id)
2626 .ok()
2627 .flatten()
2628 {
2629 spans.push((
2630 cell.row as usize,
2631 cell.column as usize,
2632 cell.row_span.max(1) as usize,
2633 cell.column_span.max(1) as usize,
2634 ));
2635 }
2636 }
2637 spans
2638 }
2639
2640 pub fn delete_char(&self) -> Result<()> {
2642 let (pos, anchor) = self.read_cursor();
2643 let (del_pos, del_anchor) = if pos != anchor {
2644 (pos, anchor)
2645 } else {
2646 let end = {
2648 let inner = self.doc.lock();
2649 max_cursor_position_of(&inner).unwrap_or(0)
2650 };
2651 if pos >= end {
2652 return Ok(());
2653 }
2654 let to = self.next_grapheme_boundary(pos);
2658 if to == pos {
2659 return Ok(());
2660 }
2661 (pos, to)
2662 };
2663 self.do_delete(del_pos, del_anchor, pos != anchor)
2664 }
2665
2666 pub fn delete_previous_char(&self) -> Result<()> {
2668 let (pos, anchor) = self.read_cursor();
2669 let (del_pos, del_anchor) = if pos != anchor {
2670 (pos, anchor)
2671 } else if pos > 0 {
2672 let from = self.prev_grapheme_boundary(pos);
2673 if from == pos {
2674 return Ok(());
2675 }
2676 (from, pos)
2677 } else {
2678 return Ok(());
2679 };
2680 self.do_delete(del_pos, del_anchor, pos != anchor)
2681 }
2682
2683 pub fn remove_selected_text(&self) -> Result<String> {
2711 let (pos, anchor) = self.read_cursor();
2712 if pos == anchor {
2713 return Ok(String::new());
2714 }
2715 let queued = {
2716 let mut inner = self.doc.lock();
2717 let (result, removed) = measured_delete(&inner, pos, anchor, true)?;
2718 let stands_for_the_empty_text = self.finish_delete(
2719 &mut inner,
2720 pos.min(anchor),
2721 removed,
2722 result.new_position,
2723 true,
2724 );
2725 (
2727 result.deleted_text,
2728 self.announce_deletion(&mut inner, stands_for_the_empty_text),
2729 )
2730 };
2731 crate::inner::dispatch_queued_events(queued.1);
2732 Ok(queued.0)
2733 }
2734
2735 pub fn current_list(&self) -> Option<crate::TextList> {
2746 let pos = self.position();
2747 let inner = self.doc.lock();
2748 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos).ok()?;
2749 let block = crate::text_block::TextBlock {
2750 doc: self.doc.clone(),
2751 block_id: block_info.block_id as usize,
2752 };
2753 drop(inner);
2754 block.list()
2755 }
2756
2757 pub fn create_list(&self, style: ListStyle) -> Result<()> {
2765 let (pos, anchor) = self.read_cursor();
2766 let queued = {
2767 let mut inner = self.doc.lock();
2768 let dto = frontend::document_editing::CreateListDto {
2769 position: to_i64(pos),
2770 anchor: to_i64(anchor),
2771 style: style.clone(),
2772 };
2773 document_editing_commands::create_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2774 inner.modified = true;
2775 inner.rehighlight_affected(pos.min(anchor));
2776 inner.queue_event(DocumentEvent::ContentsChanged {
2777 position: pos.min(anchor),
2778 chars_removed: 0,
2779 chars_added: 0,
2780 blocks_affected: 1,
2781 });
2782 self.queue_undo_redo_event(&mut inner)
2783 };
2784 crate::inner::dispatch_queued_events(queued);
2785 Ok(())
2786 }
2787
2788 pub fn insert_list(&self, style: ListStyle) -> Result<()> {
2790 let (pos, anchor) = self.read_cursor();
2791 let queued = {
2792 let mut inner = self.doc.lock();
2793 let dto = frontend::document_editing::InsertListDto {
2794 position: to_i64(pos),
2795 anchor: to_i64(anchor),
2796 style: style.clone(),
2797 };
2798 let result =
2799 document_editing_commands::insert_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2800 let edit_pos = pos.min(anchor);
2801 let removed = pos.max(anchor) - edit_pos;
2802 let new_pos = to_usize(result.new_position);
2803 self.finish_edit_ext(
2804 &mut inner,
2805 edit_pos,
2806 removed,
2807 Insertion {
2808 at: edit_pos,
2809 removed: 0,
2810 added: new_pos.saturating_sub(edit_pos),
2811 },
2812 new_pos,
2813 1,
2814 false,
2815 )
2816 };
2817 crate::inner::dispatch_queued_events(queued);
2818 Ok(())
2819 }
2820
2821 pub fn set_list_format(&self, list_id: usize, format: &crate::ListFormat) -> Result<()> {
2823 let queued = {
2824 let mut inner = self.doc.lock();
2825 let dto = format.to_set_dto(list_id);
2826 document_formatting_commands::set_list_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2827 inner.modified = true;
2828 inner.queue_event(DocumentEvent::FormatChanged {
2829 position: 0,
2830 length: 0,
2831 kind: crate::flow::FormatChangeKind::List,
2832 });
2833 self.queue_undo_redo_event(&mut inner)
2834 };
2835 crate::inner::dispatch_queued_events(queued);
2836 Ok(())
2837 }
2838
2839 pub fn set_current_list_format(&self, format: &crate::ListFormat) -> Result<()> {
2842 let list = self.current_list().ok_or_else(|| {
2843 DocumentError::InvalidCursorContext("cursor is not inside a list".into())
2844 })?;
2845 self.set_list_format(list.id(), format)
2846 }
2847
2848 pub fn add_block_to_list(&self, block_id: usize, list_id: usize) -> Result<()> {
2850 let queued = {
2851 let mut inner = self.doc.lock();
2852 let dto = frontend::document_editing::AddBlockToListDto {
2853 block_id: to_i64(block_id),
2854 list_id: to_i64(list_id),
2855 };
2856 document_editing_commands::add_block_to_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2857 inner.modified = true;
2858 inner.queue_event(DocumentEvent::FormatChanged {
2865 position: 0,
2866 length: 0,
2867 kind: crate::flow::FormatChangeKind::List,
2868 });
2869 self.queue_undo_redo_event(&mut inner)
2870 };
2871 crate::inner::dispatch_queued_events(queued);
2872 Ok(())
2873 }
2874
2875 pub fn add_current_block_to_list(&self, list_id: usize) -> Result<()> {
2878 let pos = self.position();
2879 let inner = self.doc.lock();
2880 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2881 drop(inner);
2882 self.add_block_to_list(block_info.block_id as usize, list_id)
2883 }
2884
2885 pub fn remove_block_from_list(&self, block_id: usize) -> Result<()> {
2887 let queued = {
2888 let mut inner = self.doc.lock();
2889 let dto = frontend::document_editing::RemoveBlockFromListDto {
2890 block_id: to_i64(block_id),
2891 };
2892 document_editing_commands::remove_block_from_list(
2893 &inner.ctx,
2894 Some(inner.stack_id),
2895 &dto,
2896 )?;
2897 inner.modified = true;
2898 inner.queue_event(DocumentEvent::FormatChanged {
2901 position: 0,
2902 length: 0,
2903 kind: crate::flow::FormatChangeKind::List,
2904 });
2905 self.queue_undo_redo_event(&mut inner)
2906 };
2907 crate::inner::dispatch_queued_events(queued);
2908 Ok(())
2909 }
2910
2911 pub fn remove_current_block_from_list(&self) -> Result<()> {
2915 let pos = self.position();
2916 let inner = self.doc.lock();
2917 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2918 drop(inner);
2919 self.remove_block_from_list(block_info.block_id as usize)
2920 }
2921
2922 pub fn remove_list_item(&self, list_id: usize, index: usize) -> Result<()> {
2925 let list = crate::text_list::TextList {
2926 doc: self.doc.clone(),
2927 list_id,
2928 };
2929 let block = list.item(index).ok_or_else(|| {
2930 DocumentError::OutOfRange(format!("list item index {index} out of range"))
2931 })?;
2932 self.remove_block_from_list(block.id())
2933 }
2934
2935 pub fn char_format(&self) -> Result<TextFormat> {
2940 let pos = self.position();
2941 let inner = self.doc.lock();
2942
2943 let dto = frontend::document_inspection::GetBlockAtPositionDto {
2945 position: to_i64(pos),
2946 };
2947 let block_info = document_inspection_commands::get_block_at_position(&inner.ctx, &dto)?;
2948 let block_id = block_info.block_id as u64;
2949 let mut block_dto =
2950 frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
2951 .ok_or_else(|| DocumentError::NotFound("block not found at position".into()))?;
2952 let store = inner.ctx.db_context.get_store();
2953 crate::inner::refresh_block_position(&mut block_dto, store);
2954
2955 let local_char = pos.saturating_sub(block_dto.document_position as usize);
2958 let entity: common::entities::Block = block_dto.clone().into();
2959 let plain_owned = common::database::rope_helpers::block_content_via_store(&entity, store);
2960 let plain: &str = &plain_owned;
2961 let byte_offset: u32 = plain
2962 .char_indices()
2963 .nth(local_char)
2964 .map(|(b, _)| b as u32)
2965 .unwrap_or(plain.len() as u32);
2966
2967 let images = store
2970 .block_images
2971 .read()
2972 .get(&block_id)
2973 .cloned()
2974 .unwrap_or_default();
2975 if let Some(img) = images.iter().find(|i| i.byte_offset == byte_offset) {
2976 return Ok(TextFormat::from(&img.format));
2977 }
2978
2979 let runs = store
2981 .format_runs
2982 .read()
2983 .get(&block_id)
2984 .cloned()
2985 .unwrap_or_default();
2986 let fmt = runs
2987 .iter()
2988 .find(|r| r.byte_start <= byte_offset && byte_offset < r.byte_end)
2989 .map(|r| TextFormat::from(&r.format))
2990 .unwrap_or_default();
2991 Ok(fmt)
2992 }
2993
2994 pub fn block_format(&self) -> Result<BlockFormat> {
3001 let pos = self.position();
3002 let inner = self.doc.lock();
3003 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
3004 let block_id = block_info.block_id as u64;
3005 let block = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
3006 .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
3007 Ok(BlockFormat::from(&block))
3008 }
3009
3010 pub fn set_char_format(&self, format: &TextFormat) -> Result<()> {
3014 let (pos, anchor) = self.read_cursor();
3015 let queued = {
3016 let mut inner = self.doc.lock();
3017 let dto = format.to_set_dto(pos, anchor);
3018 document_formatting_commands::set_text_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3019 let start = pos.min(anchor);
3020 let length = pos.max(anchor) - start;
3021 inner.modified = true;
3022 inner.queue_event(DocumentEvent::FormatChanged {
3023 position: start,
3024 length,
3025 kind: crate::flow::FormatChangeKind::Character,
3026 });
3027 self.queue_undo_redo_event(&mut inner)
3028 };
3029 crate::inner::dispatch_queued_events(queued);
3030 Ok(())
3031 }
3032
3033 pub fn link_at_caret(&self) -> Option<LinkExtent> {
3043 let pos = self.position();
3044 let block_id = {
3045 let inner = self.doc.lock();
3046 crate::inner::block_at_caret_dto(&inner.ctx, pos)
3047 .ok()?
3048 .block_id as usize
3049 };
3050 let block = TextBlock {
3051 doc: self.doc.clone(),
3052 block_id,
3053 };
3054 crate::link_extent::link_extent_at(&block, pos)
3055 }
3056
3057 pub fn clear_char_anchor(&self) -> Result<()> {
3069 self.merge_char_format(&TextFormat {
3070 clear_link: true,
3071 ..Default::default()
3072 })
3073 }
3074
3075 pub fn merge_char_format(&self, format: &TextFormat) -> Result<()> {
3077 let (pos, anchor) = self.read_cursor();
3078 let queued = {
3079 let mut inner = self.doc.lock();
3080 let dto = format.to_merge_dto(pos, anchor);
3081 document_formatting_commands::merge_text_format(
3082 &inner.ctx,
3083 Some(inner.stack_id),
3084 &dto,
3085 )?;
3086 let start = pos.min(anchor);
3087 let length = pos.max(anchor) - start;
3088 inner.modified = true;
3089 inner.queue_event(DocumentEvent::FormatChanged {
3090 position: start,
3091 length,
3092 kind: crate::flow::FormatChangeKind::Character,
3093 });
3094 self.queue_undo_redo_event(&mut inner)
3095 };
3096 crate::inner::dispatch_queued_events(queued);
3097 Ok(())
3098 }
3099
3100 pub fn set_block_format(&self, format: &BlockFormat) -> Result<()> {
3107 let (pos, anchor) = self.read_cursor();
3108 let queued = {
3109 let mut inner = self.doc.lock();
3110 let dto = format.to_set_dto(pos, anchor);
3111 document_formatting_commands::set_block_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3112 let start = pos.min(anchor);
3113 let length = pos.max(anchor) - start;
3114 inner.modified = true;
3115 inner.queue_event(DocumentEvent::FormatChanged {
3116 position: start,
3117 length,
3118 kind: crate::flow::FormatChangeKind::Block,
3119 });
3120 self.queue_undo_redo_event(&mut inner)
3121 };
3122 crate::inner::dispatch_queued_events(queued);
3123 Ok(())
3124 }
3125
3126 pub fn set_frame_format(&self, frame_id: usize, format: &FrameFormat) -> Result<()> {
3128 let (pos, anchor) = self.read_cursor();
3129 let queued = {
3130 let mut inner = self.doc.lock();
3131 let dto = format.to_set_dto(pos, anchor, frame_id);
3132 document_formatting_commands::set_frame_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3133 let start = pos.min(anchor);
3134 let length = pos.max(anchor) - start;
3135 inner.modified = true;
3136 inner.queue_event(DocumentEvent::FormatChanged {
3137 position: start,
3138 length,
3139 kind: crate::flow::FormatChangeKind::Block,
3140 });
3141 self.queue_undo_redo_event(&mut inner)
3142 };
3143 crate::inner::dispatch_queued_events(queued);
3144 Ok(())
3145 }
3146
3147 pub fn begin_edit_block(&self) {
3151 let inner = self.doc.lock();
3152 undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
3153 }
3154
3155 pub fn end_edit_block(&self) {
3157 let inner = self.doc.lock();
3158 undo_redo_commands::end_composite(&inner.ctx);
3159 }
3160
3161 pub fn join_previous_edit_block(&self) {
3168 self.begin_edit_block();
3169 }
3170
3171 fn queue_undo_redo_event(&self, inner: &mut TextDocumentInner) -> QueuedEvents {
3175 let can_undo = undo_redo_commands::can_undo(&inner.ctx, Some(inner.stack_id));
3176 let can_redo = undo_redo_commands::can_redo(&inner.ctx, Some(inner.stack_id));
3177 inner.queue_event(DocumentEvent::UndoRedoChanged { can_undo, can_redo });
3178 inner.take_queued_events()
3179 }
3180
3181 fn do_delete(&self, pos: usize, anchor: usize, selection: bool) -> Result<()> {
3182 let queued = {
3183 let mut inner = self.doc.lock();
3184 let (result, removed) = measured_delete(&inner, pos, anchor, selection)?;
3185 let stands_for_the_empty_text = self.finish_delete(
3186 &mut inner,
3187 pos.min(anchor),
3188 removed,
3189 result.new_position,
3190 selection,
3191 );
3192 self.announce_deletion(&mut inner, stands_for_the_empty_text)
3193 };
3194 crate::inner::dispatch_queued_events(queued);
3195 Ok(())
3196 }
3197
3198 fn finish_delete(
3218 &self,
3219 inner: &mut TextDocumentInner,
3220 edit_pos: usize,
3221 removed: usize,
3222 new_position: i64,
3223 selection: bool,
3224 ) -> bool {
3225 let new_pos = to_usize(new_position);
3226 let edit_pos = edit_pos.min(new_pos);
3230 if removed > 0 {
3231 inner.adjust_cursors(edit_pos, removed, 0);
3232 }
3233 let stands_for_the_empty_text =
3234 selection && removed > 0 && new_pos == 0 && main_text_is_empty(inner);
3235 if stands_for_the_empty_text {
3236 inner.emptied_text = crate::inner::EmptiedText::of(inner.ctx.db_context.get_store());
3239 }
3240 {
3241 let mut d = self.data.lock();
3242 d.position = new_pos;
3243 d.anchor = new_pos;
3244 d.whole_text_selected = false;
3245 d.anchor_in_table = None;
3246 }
3247 if removed > 0 {
3248 inner.modified = true;
3249 inner.invalidate_text_cache();
3250 inner.rehighlight_affected(edit_pos);
3251 inner.queue_event(DocumentEvent::ContentsChanged {
3252 position: edit_pos,
3253 chars_removed: removed,
3254 chars_added: 0,
3255 blocks_affected: 1,
3256 });
3257 }
3258 inner.check_block_count_changed();
3259 inner.check_flow_changed();
3260 stands_for_the_empty_text
3261 }
3262
3263 fn announce_deletion(
3268 &self,
3269 inner: &mut TextDocumentInner,
3270 stands_for_the_empty_text: bool,
3271 ) -> QueuedEvents {
3272 let queued = self.queue_undo_redo_event(inner);
3273 self.data.lock().whole_text_selected = stands_for_the_empty_text;
3274 queued
3275 }
3276
3277 fn resolve_move(&self, op: MoveOperation, n: usize) -> usize {
3279 let pos = self.position();
3280 match op {
3281 MoveOperation::NoMove => pos,
3282 MoveOperation::Start => 0,
3283 MoveOperation::End => {
3284 let inner = self.doc.lock();
3285 max_cursor_position_of(&inner).unwrap_or(pos)
3286 }
3287 MoveOperation::NextCharacter | MoveOperation::Right => {
3288 let mut cur = pos;
3289 for _ in 0..n {
3290 let next = self.next_grapheme_boundary(cur);
3291 if next == cur {
3292 break;
3293 }
3294 cur = next;
3295 }
3296 cur
3297 }
3298 MoveOperation::PreviousCharacter | MoveOperation::Left => {
3299 let mut cur = pos;
3300 for _ in 0..n {
3301 let prev = self.prev_grapheme_boundary(cur);
3302 if prev == cur {
3303 break;
3304 }
3305 cur = prev;
3306 }
3307 cur
3308 }
3309 MoveOperation::StartOfBlock | MoveOperation::StartOfLine => {
3310 let inner = self.doc.lock();
3311 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3312 position: to_i64(pos),
3313 };
3314 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3315 .map(|info| to_usize(info.block_start))
3316 .unwrap_or(pos)
3317 }
3318 MoveOperation::EndOfBlock | MoveOperation::EndOfLine => {
3319 let inner = self.doc.lock();
3320 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3321 position: to_i64(pos),
3322 };
3323 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3324 .map(|info| to_usize(info.block_start) + to_usize(info.block_length))
3325 .unwrap_or(pos)
3326 }
3327 MoveOperation::NextBlock => {
3328 let inner = self.doc.lock();
3329 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3330 position: to_i64(pos),
3331 };
3332 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3333 .map(|info| {
3334 to_usize(info.block_start) + to_usize(info.block_length) + 1
3336 })
3337 .unwrap_or(pos)
3338 }
3339 MoveOperation::PreviousBlock => {
3340 let inner = self.doc.lock();
3341 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3342 position: to_i64(pos),
3343 };
3344 let block_start =
3345 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3346 .map(|info| to_usize(info.block_start))
3347 .unwrap_or(pos);
3348 if block_start >= 2 {
3349 let before = common::database::rope_helpers::snap_off_table_anchor(
3353 inner.ctx.db_context.get_store(),
3354 to_i64(block_start - 2),
3355 false,
3356 );
3357 let prev_dto =
3358 frontend::document_inspection::GetBlockAtPositionDto { position: before };
3359 document_inspection_commands::get_block_at_position(&inner.ctx, &prev_dto)
3360 .map(|info| to_usize(info.block_start))
3361 .unwrap_or(0)
3362 } else {
3363 0
3364 }
3365 }
3366 MoveOperation::NextWord | MoveOperation::EndOfWord | MoveOperation::WordRight => {
3367 let (_, end) = self.find_word_boundaries(pos);
3368 if end == pos {
3370 let inner = self.doc.lock();
3372 let max_pos = max_cursor_position_of(&inner).unwrap_or(0);
3373 let scan_len = max_pos.saturating_sub(pos).min(64);
3374 if scan_len == 0 {
3375 return pos;
3376 }
3377 let dto = frontend::document_inspection::GetTextAtPositionDto {
3378 position: to_i64(pos),
3379 length: to_i64(scan_len),
3380 };
3381 if let Ok(r) =
3382 document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3383 {
3384 for (i, ch) in r.text.chars().enumerate() {
3385 if ch.is_alphanumeric() || ch == '_' {
3386 let word_pos = pos + i;
3388 drop(inner);
3389 let (_, word_end) = self.find_word_boundaries(word_pos);
3390 return word_end;
3391 }
3392 }
3393 }
3394 pos + scan_len
3395 } else {
3396 end
3397 }
3398 }
3399 MoveOperation::PreviousWord | MoveOperation::StartOfWord | MoveOperation::WordLeft => {
3400 let (start, _) = self.find_word_boundaries(pos);
3401 if start < pos {
3402 start
3403 } else if pos > 0 {
3404 let mut search = pos - 1;
3407 loop {
3408 search = self.back_off_table_anchor(search);
3412 let (ws, we) = self.find_word_boundaries(search);
3413 if ws < we && ws < pos {
3414 break ws;
3416 }
3417 if search == 0 {
3419 break 0;
3420 }
3421 search -= 1;
3422 }
3423 } else {
3424 0
3425 }
3426 }
3427 MoveOperation::StartOfSentence | MoveOperation::PreviousSentence => {
3428 let mut cur = pos;
3429 for _ in 0..n.max(1) {
3430 let start = match self.find_sentence_boundaries(cur) {
3431 Some((start, _)) => start,
3432 None => break,
3433 };
3434 if start < cur && op == MoveOperation::StartOfSentence {
3437 cur = start;
3438 } else if cur > 0 {
3439 match self.find_sentence_boundaries(self.back_off_table_anchor(cur - 1)) {
3441 Some((prev, _)) if prev < cur => cur = prev,
3442 _ => cur = cur.saturating_sub(1),
3445 }
3446 } else {
3447 break;
3448 }
3449 }
3450 cur
3451 }
3452 MoveOperation::EndOfSentence => {
3453 let mut cur = pos;
3454 for _ in 0..n.max(1) {
3455 let end = match self.find_sentence_boundaries(cur) {
3456 Some((_, end)) => end,
3457 None => break,
3458 };
3459 if end > cur {
3460 cur = end;
3461 } else {
3462 match self.find_sentence_boundaries(cur + 1) {
3463 Some((_, next)) if next > cur => cur = next,
3464 _ => break,
3465 }
3466 }
3467 }
3468 cur
3469 }
3470 MoveOperation::NextSentence => {
3471 let mut cur = pos;
3472 for _ in 0..n.max(1) {
3473 let end = match self.find_sentence_boundaries(cur) {
3476 Some((_, end)) => end,
3477 None => break,
3478 };
3479 match self.find_sentence_boundaries(end + 1) {
3480 Some((start, _)) if start > cur => cur = start,
3481 _ => {
3482 if end > cur {
3483 cur = end;
3484 } else {
3485 break;
3486 }
3487 }
3488 }
3489 }
3490 cur
3491 }
3492 MoveOperation::Up | MoveOperation::Down => {
3493 if matches!(op, MoveOperation::Up) {
3496 self.resolve_move(MoveOperation::PreviousBlock, 1)
3497 } else {
3498 self.resolve_move(MoveOperation::NextBlock, 1)
3499 }
3500 }
3501 }
3502 }
3503
3504 pub(crate) fn snap_position_to_grapheme_boundary(&self) {
3515 let pos = {
3516 let data = self.data.lock();
3517 data.position
3518 };
3519 let snapped = self.forward_grapheme_boundary_at_or_after(pos);
3520 if snapped != pos {
3521 let mut data = self.data.lock();
3522 data.position = snapped;
3523 if data.anchor == pos {
3524 data.anchor = snapped;
3525 }
3526 data.whole_text_selected = false;
3527 }
3528 }
3529
3530 fn forward_grapheme_boundary_at_or_after(&self, pos: usize) -> usize {
3540 let inner = self.doc.lock();
3541 let end = max_cursor_position_of(&inner).unwrap_or(pos);
3542 if pos >= end {
3543 return pos;
3544 }
3545 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3546 position: to_i64(pos),
3547 };
3548 let Ok(block_info) =
3549 document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto)
3550 else {
3551 return pos;
3552 };
3553 let block_start = to_usize(block_info.block_start);
3554 let block_length = to_usize(block_info.block_length);
3555 let offset_in_block = pos.saturating_sub(block_start);
3556 if offset_in_block == 0 || offset_in_block >= block_length {
3558 return pos;
3559 }
3560 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3561 position: to_i64(block_start),
3562 length: to_i64(block_length),
3563 };
3564 let Ok(r) = document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto)
3565 else {
3566 return pos;
3567 };
3568 let text = r.text;
3569 drop(inner);
3570 let mut acc = 0usize;
3573 for g in text.graphemes(true) {
3574 if acc >= offset_in_block {
3575 return block_start + acc;
3576 }
3577 acc += g.chars().count();
3578 }
3579 block_start + acc
3580 }
3581
3582 fn next_grapheme_boundary(&self, pos: usize) -> usize {
3595 let inner = self.doc.lock();
3596 let end = max_cursor_position_of(&inner).unwrap_or(pos);
3597 if pos >= end {
3598 return pos;
3599 }
3600 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3601 position: to_i64(pos),
3602 };
3603 let block_info =
3604 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3605 Ok(info) => info,
3606 Err(_) => return pos + 1,
3607 };
3608 let block_start = to_usize(block_info.block_start);
3609 let block_length = to_usize(block_info.block_length);
3610 let offset_in_block = pos.saturating_sub(block_start);
3611 if offset_in_block >= block_length {
3612 return (pos + 1).min(end);
3615 }
3616 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3617 position: to_i64(pos),
3618 length: to_i64(block_length - offset_in_block),
3619 };
3620 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3621 Ok(r) => r.text,
3622 Err(_) => return pos + 1,
3623 };
3624 drop(inner);
3625 match text.graphemes(true).next() {
3626 Some(g) if !g.is_empty() => (pos + g.chars().count()).min(end),
3627 _ => (pos + 1).min(end),
3628 }
3629 }
3630
3631 fn prev_grapheme_boundary(&self, pos: usize) -> usize {
3635 if pos == 0 {
3636 return 0;
3637 }
3638 let inner = self.doc.lock();
3639 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3640 position: to_i64(pos.saturating_sub(1)),
3641 };
3642 let block_info =
3643 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3644 Ok(info) => info,
3645 Err(_) => return pos - 1,
3646 };
3647 let block_start = to_usize(block_info.block_start);
3648 let block_length = to_usize(block_info.block_length);
3649 let block_end = block_start + block_length;
3650 if pos > block_end {
3654 return pos - 1;
3655 }
3656 if block_length == 0 || pos <= block_start {
3657 return pos.saturating_sub(1);
3658 }
3659 let scan_len = pos - block_start;
3660 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3661 position: to_i64(block_start),
3662 length: to_i64(scan_len),
3663 };
3664 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3665 Ok(r) => r.text,
3666 Err(_) => return pos - 1,
3667 };
3668 drop(inner);
3669 match text.graphemes(true).next_back() {
3670 Some(g) if !g.is_empty() => pos - g.chars().count(),
3671 _ => pos - 1,
3672 }
3673 }
3674
3675 fn find_word_boundaries(&self, pos: usize) -> (usize, usize) {
3681 let inner = self.doc.lock();
3682 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3684 position: to_i64(pos),
3685 };
3686 let block_info =
3687 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3688 Ok(info) => info,
3689 Err(_) => return (pos, pos),
3690 };
3691
3692 let block_start = to_usize(block_info.block_start);
3693 let block_length = to_usize(block_info.block_length);
3694 if block_length == 0 {
3695 return (pos, pos);
3696 }
3697
3698 let dto = frontend::document_inspection::GetTextAtPositionDto {
3699 position: to_i64(block_start),
3700 length: to_i64(block_length),
3701 };
3702 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &dto) {
3703 Ok(r) => r.text,
3704 Err(_) => return (pos, pos),
3705 };
3706
3707 let cursor_offset = pos.saturating_sub(block_start);
3709
3710 let mut last_char_start = 0;
3712 let mut last_char_end = 0;
3713
3714 for (word_byte_start, word) in text.unicode_word_indices() {
3715 let word_char_start = text[..word_byte_start].chars().count();
3717 let word_char_len = word.chars().count();
3718 let word_char_end = word_char_start + word_char_len;
3719
3720 last_char_start = word_char_start;
3721 last_char_end = word_char_end;
3722
3723 if cursor_offset >= word_char_start && cursor_offset < word_char_end {
3724 return (block_start + word_char_start, block_start + word_char_end);
3725 }
3726 }
3727
3728 if cursor_offset == last_char_end && last_char_start < last_char_end {
3730 return (block_start + last_char_start, block_start + last_char_end);
3731 }
3732
3733 (pos, pos)
3734 }
3735
3736 fn find_sentence_boundaries(&self, pos: usize) -> Option<(usize, usize)> {
3742 let locale = self.data.lock().content_locale.clone();
3743
3744 let inner = self.doc.lock();
3745 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3746 position: to_i64(pos),
3747 };
3748 let block_info =
3749 document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto).ok()?;
3750 let block_start = to_usize(block_info.block_start);
3751 let block_length = to_usize(block_info.block_length);
3752 if block_length == 0 {
3753 return None;
3754 }
3755 let dto = frontend::document_inspection::GetTextAtPositionDto {
3756 position: to_i64(block_start),
3757 length: to_i64(block_length),
3758 };
3759 let text = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3760 .ok()?
3761 .text;
3762 drop(inner);
3763
3764 let offset = pos.saturating_sub(block_start);
3765 let (start, end) =
3766 frontend::common::parser_tools::sentence_bounds(&text, offset, locale.as_deref())?;
3767 Some((block_start + start, block_start + end))
3768 }
3769}
3770
3771#[derive(Clone, Copy, PartialEq, Eq)]
3778enum BlockEdge {
3779 First,
3780 Middle,
3781 Last,
3782 OnlyOne,
3783}
3784
3785fn cursor_frame_ref(inner: &TextDocumentInner, block_id: u64) -> Option<FrameRef> {
3789 let parent = crate::text_block::find_parent_frame(inner, block_id)?;
3790 let store = inner.ctx.db_context.get_store();
3791 let frames = store.frames.read();
3792 let frame = frames.get(&parent)?.clone();
3793 frame.parent_frame?;
3794 let is_blockquote = frame.fmt_is_blockquote.unwrap_or(false);
3795
3796 let mut depth = 0;
3797 let mut current = Some(parent);
3798 while let Some(id) = current {
3799 let Some(f) = frames.get(&id) else {
3800 break;
3801 };
3802 if f.parent_frame.is_none() {
3803 break;
3804 }
3805 depth += 1;
3806 current = f.parent_frame;
3807 }
3808
3809 Some(FrameRef {
3810 frame_id: frame.id as usize,
3811 parent_frame_id: frame.parent_frame.map(|id| id as usize),
3812 is_blockquote,
3813 depth,
3814 })
3815}
3816
3817fn innermost_blockquote_frame_id(inner: &TextDocumentInner, block_id: u64) -> Option<usize> {
3821 let mut current = crate::text_block::find_parent_frame(inner, block_id);
3822 let store = inner.ctx.db_context.get_store();
3823 let frames = store.frames.read();
3824 while let Some(id) = current {
3825 let f = frames.get(&id)?;
3826 if f.fmt_is_blockquote == Some(true) {
3827 return Some(f.id as usize);
3828 }
3829 current = f.parent_frame;
3830 }
3831 None
3832}
3833
3834fn blockquote_depth_for_block(inner: &TextDocumentInner, block_id: u64) -> usize {
3837 let mut current = crate::text_block::find_parent_frame(inner, block_id);
3838 let store = inner.ctx.db_context.get_store();
3839 let frames = store.frames.read();
3840 let mut count = 0;
3841 while let Some(id) = current {
3842 let Some(f) = frames.get(&id) else {
3843 break;
3844 };
3845 if f.fmt_is_blockquote == Some(true) {
3846 count += 1;
3847 }
3848 current = f.parent_frame;
3849 }
3850 count
3851}
3852
3853fn block_position_in_current_frame(cursor: &TextCursor) -> Option<BlockEdge> {
3859 let pos = cursor.position();
3860 let inner = cursor.doc.lock();
3861 let block_info = TextCursor::caret_block(&inner, pos)?;
3863 let block_id = block_info.block_id as common::types::EntityId;
3864 let parent_id = crate::text_block::find_parent_frame(&inner, block_info.block_id as u64)?;
3865 let store = inner.ctx.db_context.get_store();
3866 let frames = store.frames.read();
3867 let frame = frames.get(&parent_id)?;
3868 let block_positions: Vec<usize> = frame
3869 .child_order
3870 .iter()
3871 .enumerate()
3872 .filter_map(|(i, &e)| {
3873 if e > 0 {
3874 Some((i, e as common::types::EntityId))
3875 } else {
3876 None
3877 }
3878 })
3879 .filter(|(_, id)| *id == block_id)
3880 .map(|(i, _)| i)
3881 .collect();
3882 let block_idx = *block_positions.first()?;
3883 let positive_entries: Vec<usize> = frame
3884 .child_order
3885 .iter()
3886 .enumerate()
3887 .filter_map(|(i, &e)| if e > 0 { Some(i) } else { None })
3888 .collect();
3889 let first_pos = *positive_entries.first()?;
3890 let last_pos = *positive_entries.last()?;
3891 let is_first = block_idx == first_pos;
3892 let is_last = block_idx == last_pos;
3893 let edge = match (is_first, is_last, positive_entries.len()) {
3894 (_, _, 1) => BlockEdge::OnlyOne,
3895 (true, _, _) => BlockEdge::First,
3896 (_, true, _) => BlockEdge::Last,
3897 _ => BlockEdge::Middle,
3898 };
3899 Some(edge)
3900}