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_line_break(&self) -> Result<()> {
1130 self.insert_line_break_with_origin(InsertionOrigin::Unspecified)
1131 }
1132
1133 pub fn insert_line_break_with_origin(&self, origin: InsertionOrigin) -> Result<()> {
1136 let mut buffer = [0; 4];
1137 self.insert_text_with_origin(crate::LINE_SEPARATOR.encode_utf8(&mut buffer), origin)
1138 }
1139
1140 pub fn insert_block(&self) -> Result<()> {
1142 let (pos, anchor) = self.read_cursor();
1143 let queued = {
1144 let mut inner = self.doc.lock();
1145
1146 let split_at = |at: usize| -> Result<_> {
1147 let dto = frontend::document_editing::InsertBlockDto {
1148 position: to_i64(at),
1149 anchor: to_i64(at),
1150 };
1151 Ok(document_editing_commands::insert_block(
1152 &inner.ctx,
1153 Some(inner.stack_id),
1154 &dto,
1155 )?)
1156 };
1157 let before = max_cursor_position_of(&inner);
1158 let result = if pos != anchor {
1159 delete_then(&inner, pos, anchor, split_at)?.0
1161 } else {
1162 split_at(pos)?
1163 };
1164
1165 let edit_pos = pos.min(anchor);
1166 let new_pos = to_usize(result.new_position);
1167 let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1169 self.finish_edit(
1170 &mut inner,
1171 edit_pos,
1172 removed,
1173 Insertion::ending_at(new_pos, 1),
1174 new_pos,
1175 2,
1176 )
1177 };
1178 crate::inner::dispatch_queued_events(queued);
1179 Ok(())
1180 }
1181
1182 pub fn insert_html_with_origin(&self, html: &str, origin: InsertionOrigin) -> Result<()> {
1186 let frag = DocumentFragment::from_html(html);
1187 self.insert_fragment_with_origin(&frag, origin)
1188 }
1189
1190 pub fn insert_html(&self, html: &str) -> Result<()> {
1195 let frag = DocumentFragment::from_html(html);
1197 self.insert_fragment(&frag)
1198 }
1199
1200 pub fn insert_markdown_with_origin(
1204 &self,
1205 markdown: &str,
1206 origin: InsertionOrigin,
1207 ) -> Result<()> {
1208 let frag = DocumentFragment::from_markdown(markdown);
1209 self.insert_fragment_with_origin(&frag, origin)
1210 }
1211
1212 pub fn insert_markdown(&self, markdown: &str) -> Result<()> {
1213 let frag = DocumentFragment::from_markdown(markdown);
1214 self.insert_fragment(&frag)
1215 }
1216
1217 pub fn insert_djot_with_origin(&self, djot: &str, origin: InsertionOrigin) -> Result<()> {
1221 let frag = DocumentFragment::from_djot(djot);
1222 self.insert_fragment_with_origin(&frag, origin)
1223 }
1224
1225 pub fn insert_djot(&self, djot: &str) -> Result<()> {
1226 let frag = DocumentFragment::from_djot(djot);
1227 self.insert_fragment(&frag)
1228 }
1229
1230 pub fn insert_footnote_reference(&self, label: &str) -> Result<()> {
1246 self.insert_djot(&format!("[^{label}]"))
1247 }
1248
1249 pub fn insert_fragment(&self, fragment: &DocumentFragment) -> Result<()> {
1293 self.insert_fragment_with_origin(fragment, InsertionOrigin::Unspecified)
1294 }
1295
1296 pub fn insert_fragment_with_origin(
1300 &self,
1301 fragment: &DocumentFragment,
1302 origin: InsertionOrigin,
1303 ) -> Result<()> {
1304 let (pos, anchor) = self.read_cursor();
1305 let queued = {
1306 let mut inner = self.doc.lock();
1307 let replacing_an_empty_text = pos == anchor && self.data.lock().whole_text_selected;
1311 let into_an_emptied_text =
1316 pos == anchor && !replacing_an_empty_text && inner.is_the_emptied_text();
1317
1318 let paste_at = |at: usize, replacing: bool| -> Result<_> {
1328 let store = inner.ctx.db_context.get_store();
1329 let rope_before = store.rope.read().clone();
1330 let before = max_cursor_position_of(&inner);
1331 let fragment_data = if replacing {
1332 frontend::common::parser_tools::fragment_schema::replacing_the_text(
1333 fragment.raw_data(),
1334 )
1335 } else if into_an_emptied_text {
1336 frontend::common::parser_tools::fragment_schema::into_an_emptied_text(
1337 fragment.raw_data(),
1338 )
1339 } else {
1340 fragment.raw_data().into()
1341 };
1342 let dto = frontend::document_editing::InsertFragmentDto {
1343 position: to_i64(at),
1344 anchor: to_i64(at),
1345 fragment_data,
1346 };
1347 let result = document_editing_commands::insert_fragment(
1348 &inner.ctx,
1349 Some(inner.stack_id),
1350 &dto,
1351 )?;
1352 let inserted = if common::database::rope_helpers::rope_positions_match_flow(store) {
1353 let (start, old_end, new_end) = common::database::rope_helpers::changed_span(
1354 &rope_before,
1355 &store.rope.read(),
1356 at,
1357 );
1358 Insertion {
1359 at: start,
1360 removed: old_end - start,
1361 added: new_end - start,
1362 }
1363 } else {
1364 let new_pos = to_usize(result.new_position);
1367 let added = before
1368 .zip(max_cursor_position_of(&inner))
1369 .map_or(new_pos.saturating_sub(at), |(before, after)| {
1370 after.saturating_sub(before)
1371 });
1372 Insertion {
1373 at,
1374 removed: 0,
1375 added,
1376 }
1377 };
1378 Ok((result, inserted))
1379 };
1380 let ((result, inserted), removed, deleted_from) = if pos != anchor {
1381 delete_then(&inner, pos, anchor, |at| paste_at(at, true))?
1382 } else {
1383 (paste_at(pos, replacing_an_empty_text)?, 0, pos)
1384 };
1385
1386 let edit_pos = pos.min(anchor).min(deleted_from);
1389 let new_pos = to_usize(result.new_position);
1390 self.finish_edit_from(
1391 &mut inner,
1392 edit_pos,
1393 removed,
1394 inserted,
1395 new_pos,
1396 to_usize(result.blocks_added),
1397 true,
1398 origin,
1399 )
1400 };
1401 crate::inner::dispatch_queued_events(queued);
1402 Ok(())
1403 }
1404
1405 pub fn selection(&self) -> DocumentFragment {
1416 let (pos, anchor) = self.read_cursor();
1417
1418 let (extract_pos, extract_anchor) = match self.selection_kind() {
1421 SelectionKind::Cells(ref range) => match self.cell_range_positions(range) {
1422 Some((start, end)) => (start, end),
1423 None => return DocumentFragment::new(),
1424 },
1425 SelectionKind::Mixed {
1426 ref cell_range,
1427 text_before,
1428 text_after,
1429 } => {
1430 let (cell_start, cell_end) = match self.cell_range_positions(cell_range) {
1431 Some(p) => p,
1432 None => return DocumentFragment::new(),
1433 };
1434 let table_start = self
1438 .table_anchor_position(cell_range.table_id)
1439 .unwrap_or(cell_start)
1440 .min(cell_start);
1441 let start = if text_before {
1442 pos.min(anchor).min(table_start)
1443 } else {
1444 table_start
1445 };
1446 let end = if text_after {
1447 pos.max(anchor)
1448 } else {
1449 cell_end
1450 };
1451 (start.min(cell_start), end.max(cell_end))
1452 }
1453 SelectionKind::None => return DocumentFragment::new(),
1454 SelectionKind::Text => (pos, anchor),
1455 };
1456
1457 if extract_pos == extract_anchor {
1458 return DocumentFragment::new();
1459 }
1460
1461 let inner = self.doc.lock();
1462 let dto = frontend::document_inspection::ExtractFragmentDto {
1463 position: to_i64(extract_pos),
1464 anchor: to_i64(extract_anchor),
1465 };
1466 match document_inspection_commands::extract_fragment(&inner.ctx, &dto) {
1467 Ok(result) => DocumentFragment::from_raw(result.fragment_data, result.plain_text),
1468 Err(_) => DocumentFragment::new(),
1469 }
1470 }
1471
1472 pub fn insert_image(&self, name: &str, alt: &str, width: u32, height: u32) -> Result<()> {
1481 let (pos, anchor) = self.read_cursor();
1482 let queued = {
1483 let mut inner = self.doc.lock();
1484
1485 let image_at = |at: usize| -> Result<_> {
1486 let dto = frontend::document_editing::InsertImageDto {
1487 position: to_i64(at),
1488 anchor: to_i64(at),
1489 image_name: name.into(),
1490 alt: alt.into(),
1491 width: width as i64,
1492 height: height as i64,
1493 quality: 100,
1494 };
1495 Ok(document_editing_commands::insert_image(
1496 &inner.ctx,
1497 Some(inner.stack_id),
1498 &dto,
1499 )?)
1500 };
1501 let before = max_cursor_position_of(&inner);
1502 let result = if pos != anchor {
1503 delete_then(&inner, pos, anchor, image_at)?.0
1504 } else {
1505 image_at(pos)?
1506 };
1507
1508 let edit_pos = pos.min(anchor);
1509 let new_pos = to_usize(result.new_position);
1510 let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1512 self.finish_edit_ext(
1513 &mut inner,
1514 edit_pos,
1515 removed,
1516 Insertion::ending_at(new_pos, 1),
1517 new_pos,
1518 1,
1519 false,
1520 )
1521 };
1522 crate::inner::dispatch_queued_events(queued);
1523 Ok(())
1524 }
1525
1526 pub fn insert_frame(&self) -> Result<()> {
1528 let (pos, anchor) = self.read_cursor();
1529 let queued = {
1530 let mut inner = self.doc.lock();
1531 let dto = frontend::document_editing::InsertFrameDto {
1532 position: to_i64(pos),
1533 anchor: to_i64(anchor),
1534 };
1535 document_editing_commands::insert_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1536 inner.modified = true;
1539 inner.invalidate_text_cache();
1540 inner.rehighlight_affected(pos.min(anchor));
1541 inner.queue_event(DocumentEvent::ContentsChanged {
1542 position: pos.min(anchor),
1543 chars_removed: 0,
1544 chars_added: 0,
1545 blocks_affected: 1,
1546 });
1547 inner.check_block_count_changed();
1548 inner.check_flow_changed();
1549 self.queue_undo_redo_event(&mut inner)
1550 };
1551 crate::inner::dispatch_queued_events(queued);
1552 Ok(())
1553 }
1554
1555 pub fn insert_table(&self, rows: usize, columns: usize) -> Result<TextTable> {
1561 let (pos, anchor) = self.read_cursor();
1562 let (table_id, queued) = {
1563 let mut inner = self.doc.lock();
1564 let dto = frontend::document_editing::InsertTableDto {
1565 position: to_i64(pos),
1566 anchor: to_i64(anchor),
1567 rows: to_i64(rows),
1568 columns: to_i64(columns),
1569 };
1570 let result =
1571 document_editing_commands::insert_table(&inner.ctx, Some(inner.stack_id), &dto)?;
1572 let new_pos = to_usize(result.new_position);
1573 let table_id = to_usize(result.table_id);
1574 inner.adjust_cursors(pos.min(anchor), 0, new_pos - pos.min(anchor));
1575 {
1576 let mut d = self.data.lock();
1577 d.position = new_pos;
1578 d.anchor = new_pos;
1579 d.whole_text_selected = false;
1580 d.anchor_in_table = None;
1581 }
1582 inner.modified = true;
1583 inner.invalidate_text_cache();
1584 inner.rehighlight_affected(pos.min(anchor));
1585 inner.queue_event(DocumentEvent::ContentsChanged {
1586 position: pos.min(anchor),
1587 chars_removed: 0,
1588 chars_added: new_pos - pos.min(anchor),
1589 blocks_affected: 1,
1590 });
1591 inner.check_block_count_changed();
1592 inner.check_flow_changed();
1593 (table_id, self.queue_undo_redo_event(&mut inner))
1594 };
1595 crate::inner::dispatch_queued_events(queued);
1596 Ok(TextTable {
1597 doc: self.doc.clone(),
1598 table_id,
1599 })
1600 }
1601
1602 pub fn current_table(&self) -> Option<TextTable> {
1607 self.current_table_cell().map(|c| c.table)
1608 }
1609
1610 pub fn current_table_cell(&self) -> Option<TableCellRef> {
1615 let pos = self.position();
1616 let inner = self.doc.lock();
1617 let block_id = crate::inner::block_at_caret_dto(&inner.ctx, pos)
1620 .ok()?
1621 .block_id as usize;
1622
1623 let block = crate::text_block::TextBlock {
1624 doc: self.doc.clone(),
1625 block_id,
1626 };
1627 drop(inner);
1629 block.table_cell()
1630 }
1631
1632 pub fn current_frame(&self) -> Option<FrameRef> {
1639 let pos = self.position();
1640 let inner = self.doc.lock();
1641 let block_info = Self::caret_block(&inner, pos)?;
1642 let block_id = block_info.block_id as u64;
1643 cursor_frame_ref(&inner, block_id)
1644 }
1645
1646 pub fn is_in_blockquote(&self) -> bool {
1650 self.current_blockquote_frame_id().is_some()
1651 }
1652
1653 pub fn current_blockquote_frame_id(&self) -> Option<usize> {
1656 let pos = self.position();
1657 let inner = self.doc.lock();
1658 let block_info = Self::caret_block(&inner, pos)?;
1659 innermost_blockquote_frame_id(&inner, block_info.block_id as u64)
1660 }
1661
1662 pub fn blockquote_depth_at_cursor(&self) -> usize {
1665 let pos = self.position();
1666 let inner = self.doc.lock();
1667 let Some(block_info) = Self::caret_block(&inner, pos) else {
1668 return 0;
1669 };
1670 blockquote_depth_for_block(&inner, block_info.block_id as u64)
1671 }
1672
1673 pub fn is_first_block_in_current_frame(&self) -> bool {
1679 matches!(
1680 block_position_in_current_frame(self),
1681 Some(BlockEdge::First) | Some(BlockEdge::OnlyOne)
1682 )
1683 }
1684
1685 pub fn is_last_block_in_current_frame(&self) -> bool {
1689 matches!(
1690 block_position_in_current_frame(self),
1691 Some(BlockEdge::Last) | Some(BlockEdge::OnlyOne)
1692 )
1693 }
1694
1695 pub fn current_block_is_empty(&self) -> bool {
1698 let pos = self.position();
1699 let inner = self.doc.lock();
1700 let Some(block_info) = Self::caret_block(&inner, pos) else {
1701 return false;
1702 };
1703 let store = inner.ctx.db_context.get_store();
1704 let block_entity = store
1705 .blocks
1706 .read()
1707 .get(&(block_info.block_id as common::types::EntityId))
1708 .cloned();
1709 match block_entity {
1710 Some(b) => {
1711 let len = common::database::rope_helpers::block_char_length(&b, store);
1712 len == 0
1713 }
1714 None => false,
1715 }
1716 }
1717
1718 pub fn selection_spans_multiple_frames(&self) -> bool {
1722 let (pos, anchor) = self.read_cursor();
1723 if pos == anchor {
1724 return false;
1725 }
1726 let inner = self.doc.lock();
1727 let Some((first, last)) = Self::selection_block_ids(&inner, pos, anchor) else {
1730 return false;
1731 };
1732 crate::text_block::find_parent_frame(&inner, first)
1733 != crate::text_block::find_parent_frame(&inner, last)
1734 }
1735
1736 fn selection_block_ids(
1744 inner: &TextDocumentInner,
1745 pos: usize,
1746 anchor: usize,
1747 ) -> Option<(u64, u64)> {
1748 let (lo, hi) = (pos.min(anchor), pos.max(anchor));
1749 let last = Self::caret_block(inner, hi)?.block_id as u64;
1750 if lo == hi {
1751 return Some((last, last));
1752 }
1753 let first = document_inspection_commands::get_block_at_position(
1754 &inner.ctx,
1755 &frontend::document_inspection::GetBlockAtPositionDto {
1756 position: to_i64(lo),
1757 },
1758 )
1759 .ok()?
1760 .block_id as u64;
1761 Some((first, last))
1762 }
1763
1764 pub fn wrap_selection_in_blockquote(&self) -> Result<()> {
1771 if self.selection_spans_multiple_frames() {
1772 return Err(DocumentError::InvalidArgument(
1773 "Cannot wrap selection in blockquote: selection spans multiple frames".into(),
1774 ));
1775 }
1776 let (start_block_id, end_block_id) = self.resolve_selection_block_range()?;
1777 let dto = frontend::document_editing::WrapBlocksInFrameDto {
1778 start_block_id: start_block_id as i64,
1779 end_block_id: end_block_id as i64,
1780 position: Some(frontend::document_editing::FramePosition::InFlow),
1781 top_margin: None,
1782 bottom_margin: None,
1783 left_margin: None,
1784 right_margin: None,
1785 padding: None,
1786 border: None,
1787 is_blockquote: Some(true),
1788 };
1789 let queued = {
1790 let mut inner = self.doc.lock();
1791 let _result = document_editing_commands::wrap_blocks_in_frame(
1792 &inner.ctx,
1793 Some(inner.stack_id),
1794 &dto,
1795 )?;
1796 inner.modified = true;
1797 inner.queue_event(DocumentEvent::FormatChanged {
1805 position: 0,
1806 length: 0,
1807 kind: crate::flow::FormatChangeKind::Block,
1808 });
1809 self.queue_undo_redo_event(&mut inner)
1810 };
1811 crate::inner::dispatch_queued_events(queued);
1812 Ok(())
1813 }
1814
1815 pub fn insert_blockquote(&self) -> Result<()> {
1819 self.wrap_selection_in_blockquote()
1820 }
1821
1822 pub fn toggle_blockquote(&self) -> Result<()> {
1827 if let Some(frame_id) = self.current_blockquote_frame_id() {
1828 self.unwrap_frame_by_id(frame_id)
1829 } else {
1830 self.wrap_selection_in_blockquote()
1831 }
1832 }
1833
1834 pub fn unwrap_current_frame(&self) -> Result<()> {
1838 let frame_ref = self.current_frame().ok_or_else(|| {
1839 DocumentError::InvalidCursorContext("Cursor is not inside any sub-frame".into())
1840 })?;
1841 self.unwrap_frame_by_id(frame_ref.frame_id)
1842 }
1843
1844 pub fn unwrap_current_block_from_blockquote(&self) -> Result<()> {
1848 if self.current_blockquote_frame_id().is_none() {
1849 return Err(DocumentError::InvalidCursorContext(
1850 "Cursor is not inside a blockquote".into(),
1851 ));
1852 }
1853 let block_id = self.current_block_id_for_mutation()?;
1854 let dto = frontend::document_editing::UnwrapBlockFromFrameDto {
1855 block_id: block_id as i64,
1856 };
1857 let queued = {
1858 let mut inner = self.doc.lock();
1859 let _result = document_editing_commands::unwrap_block_from_frame(
1860 &inner.ctx,
1861 Some(inner.stack_id),
1862 &dto,
1863 )?;
1864 inner.modified = true;
1865 inner.queue_event(DocumentEvent::FormatChanged {
1869 position: 0,
1870 length: 0,
1871 kind: crate::flow::FormatChangeKind::Block,
1872 });
1873 self.queue_undo_redo_event(&mut inner)
1874 };
1875 crate::inner::dispatch_queued_events(queued);
1876 Ok(())
1877 }
1878
1879 pub fn increase_blockquote_depth(&self) -> Result<()> {
1883 self.wrap_selection_in_blockquote()
1884 }
1885
1886 pub fn decrease_blockquote_depth(&self) -> Result<()> {
1892 if self.current_blockquote_frame_id().is_none() {
1893 return Err(DocumentError::InvalidCursorContext(
1894 "Cursor is not inside a blockquote to decrease depth".into(),
1895 ));
1896 }
1897 self.unwrap_current_block_from_blockquote()
1898 }
1899
1900 fn unwrap_frame_by_id(&self, frame_id: usize) -> Result<()> {
1901 let dto = frontend::document_editing::UnwrapFrameDto {
1902 frame_id: frame_id as i64,
1903 };
1904 let queued = {
1905 let mut inner = self.doc.lock();
1906 let _result =
1907 document_editing_commands::unwrap_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1908 inner.modified = true;
1909 inner.queue_event(DocumentEvent::FormatChanged {
1913 position: 0,
1914 length: 0,
1915 kind: crate::flow::FormatChangeKind::Block,
1916 });
1917 self.queue_undo_redo_event(&mut inner)
1918 };
1919 crate::inner::dispatch_queued_events(queued);
1920 Ok(())
1921 }
1922
1923 fn current_block_id_for_mutation(&self) -> Result<usize> {
1926 let pos = self.position();
1927 let inner = self.doc.lock();
1928 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
1929 Ok(block_info.block_id as usize)
1930 }
1931
1932 fn resolve_selection_block_range(&self) -> Result<(usize, usize)> {
1936 let (pos, anchor) = self.read_cursor();
1937 let inner = self.doc.lock();
1938 let (first, last) = Self::selection_block_ids(&inner, pos, anchor)
1939 .ok_or_else(|| DocumentError::NotFound("no block at the selection's ends".into()))?;
1940 Ok((first as usize, last as usize))
1941 }
1942
1943 pub fn remove_table(&self, table_id: usize) -> Result<()> {
1947 let queued = {
1948 let mut inner = self.doc.lock();
1949 let before = crate::document::capture_block_state(&inner);
1956 let dto = frontend::document_editing::RemoveTableDto {
1957 table_id: to_i64(table_id),
1958 };
1959 document_editing_commands::remove_table(&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 inner.check_flow_changed();
1966 self.queue_undo_redo_event(&mut inner)
1967 };
1968 crate::inner::dispatch_queued_events(queued);
1969 Ok(())
1970 }
1971
1972 pub fn insert_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
1974 let queued = {
1975 let mut inner = self.doc.lock();
1976 let before = crate::document::capture_block_state(&inner);
1977 let dto = frontend::document_editing::InsertTableRowDto {
1978 table_id: to_i64(table_id),
1979 row_index: to_i64(row_index),
1980 };
1981 document_editing_commands::insert_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
1982 inner.modified = true;
1983 inner.invalidate_text_cache();
1984 inner.rehighlight_all();
1985 crate::document::emit_content_change_events(&mut inner, &before);
1986 inner.check_block_count_changed();
1987 self.queue_undo_redo_event(&mut inner)
1988 };
1989 crate::inner::dispatch_queued_events(queued);
1990 Ok(())
1991 }
1992
1993 pub fn insert_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
1995 let queued = {
1996 let mut inner = self.doc.lock();
1997 let before = crate::document::capture_block_state(&inner);
1998 let dto = frontend::document_editing::InsertTableColumnDto {
1999 table_id: to_i64(table_id),
2000 column_index: to_i64(column_index),
2001 };
2002 document_editing_commands::insert_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
2003 inner.modified = true;
2004 inner.invalidate_text_cache();
2005 inner.rehighlight_all();
2006 crate::document::emit_content_change_events(&mut inner, &before);
2007 inner.check_block_count_changed();
2008 self.queue_undo_redo_event(&mut inner)
2009 };
2010 crate::inner::dispatch_queued_events(queued);
2011 Ok(())
2012 }
2013
2014 pub fn remove_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
2016 let queued = {
2017 let mut inner = self.doc.lock();
2018 let before = crate::document::capture_block_state(&inner);
2019 let dto = frontend::document_editing::RemoveTableRowDto {
2020 table_id: to_i64(table_id),
2021 row_index: to_i64(row_index),
2022 };
2023 document_editing_commands::remove_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
2024 inner.modified = true;
2025 inner.invalidate_text_cache();
2026 inner.rehighlight_all();
2027 crate::document::emit_content_change_events(&mut inner, &before);
2028 inner.check_block_count_changed();
2029 self.queue_undo_redo_event(&mut inner)
2030 };
2031 crate::inner::dispatch_queued_events(queued);
2032 Ok(())
2033 }
2034
2035 pub fn remove_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
2037 let queued = {
2038 let mut inner = self.doc.lock();
2039 let before = crate::document::capture_block_state(&inner);
2040 let dto = frontend::document_editing::RemoveTableColumnDto {
2041 table_id: to_i64(table_id),
2042 column_index: to_i64(column_index),
2043 };
2044 document_editing_commands::remove_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
2045 inner.modified = true;
2046 inner.invalidate_text_cache();
2047 inner.rehighlight_all();
2048 crate::document::emit_content_change_events(&mut inner, &before);
2049 inner.check_block_count_changed();
2050 self.queue_undo_redo_event(&mut inner)
2051 };
2052 crate::inner::dispatch_queued_events(queued);
2053 Ok(())
2054 }
2055
2056 pub fn merge_table_cells(
2058 &self,
2059 table_id: usize,
2060 start_row: usize,
2061 start_column: usize,
2062 end_row: usize,
2063 end_column: usize,
2064 ) -> Result<()> {
2065 let queued = {
2066 let mut inner = self.doc.lock();
2067 let before = crate::document::capture_block_state(&inner);
2068 let dto = frontend::document_editing::MergeTableCellsDto {
2069 table_id: to_i64(table_id),
2070 start_row: to_i64(start_row),
2071 start_column: to_i64(start_column),
2072 end_row: to_i64(end_row),
2073 end_column: to_i64(end_column),
2074 };
2075 document_editing_commands::merge_table_cells(&inner.ctx, Some(inner.stack_id), &dto)?;
2076 inner.modified = true;
2077 inner.invalidate_text_cache();
2078 inner.rehighlight_all();
2079 crate::document::emit_content_change_events(&mut inner, &before);
2080 inner.check_block_count_changed();
2081 self.queue_undo_redo_event(&mut inner)
2082 };
2083 crate::inner::dispatch_queued_events(queued);
2084 Ok(())
2085 }
2086
2087 pub fn split_table_cell(
2089 &self,
2090 cell_id: usize,
2091 split_rows: usize,
2092 split_columns: usize,
2093 ) -> Result<()> {
2094 let queued = {
2095 let mut inner = self.doc.lock();
2096 let before = crate::document::capture_block_state(&inner);
2097 let dto = frontend::document_editing::SplitTableCellDto {
2098 cell_id: to_i64(cell_id),
2099 split_rows: to_i64(split_rows),
2100 split_columns: to_i64(split_columns),
2101 };
2102 document_editing_commands::split_table_cell(&inner.ctx, Some(inner.stack_id), &dto)?;
2103 inner.modified = true;
2104 inner.invalidate_text_cache();
2105 inner.rehighlight_all();
2106 crate::document::emit_content_change_events(&mut inner, &before);
2107 inner.check_block_count_changed();
2108 self.queue_undo_redo_event(&mut inner)
2109 };
2110 crate::inner::dispatch_queued_events(queued);
2111 Ok(())
2112 }
2113
2114 pub fn set_table_format(
2118 &self,
2119 table_id: usize,
2120 format: &crate::flow::TableFormat,
2121 ) -> Result<()> {
2122 let queued = {
2123 let mut inner = self.doc.lock();
2124 let dto = format.to_set_dto(table_id);
2125 document_formatting_commands::set_table_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2126 inner.modified = true;
2127 inner.queue_event(DocumentEvent::FormatChanged {
2128 position: 0,
2129 length: 0,
2130 kind: crate::flow::FormatChangeKind::Block,
2131 });
2132 self.queue_undo_redo_event(&mut inner)
2133 };
2134 crate::inner::dispatch_queued_events(queued);
2135 Ok(())
2136 }
2137
2138 pub fn set_table_cell_format(
2140 &self,
2141 cell_id: usize,
2142 format: &crate::flow::CellFormat,
2143 ) -> Result<()> {
2144 let queued = {
2145 let mut inner = self.doc.lock();
2146 let dto = format.to_set_dto(cell_id);
2147 document_formatting_commands::set_table_cell_format(
2148 &inner.ctx,
2149 Some(inner.stack_id),
2150 &dto,
2151 )?;
2152 inner.modified = true;
2153 inner.queue_event(DocumentEvent::FormatChanged {
2154 position: 0,
2155 length: 0,
2156 kind: crate::flow::FormatChangeKind::Block,
2157 });
2158 self.queue_undo_redo_event(&mut inner)
2159 };
2160 crate::inner::dispatch_queued_events(queued);
2161 Ok(())
2162 }
2163
2164 pub fn remove_current_table(&self) -> Result<()> {
2169 let table = self.current_table().ok_or_else(|| {
2170 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2171 })?;
2172 self.remove_table(table.id())
2173 }
2174
2175 pub fn insert_row_above(&self) -> Result<()> {
2178 let cell_ref = self.current_table_cell().ok_or_else(|| {
2179 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2180 })?;
2181 self.insert_table_row(cell_ref.table.id(), cell_ref.row)
2182 }
2183
2184 pub fn insert_row_below(&self) -> Result<()> {
2187 let cell_ref = self.current_table_cell().ok_or_else(|| {
2188 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2189 })?;
2190 self.insert_table_row(cell_ref.table.id(), cell_ref.row + 1)
2191 }
2192
2193 pub fn insert_column_before(&self) -> Result<()> {
2196 let cell_ref = self.current_table_cell().ok_or_else(|| {
2197 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2198 })?;
2199 self.insert_table_column(cell_ref.table.id(), cell_ref.column)
2200 }
2201
2202 pub fn insert_column_after(&self) -> Result<()> {
2205 let cell_ref = self.current_table_cell().ok_or_else(|| {
2206 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2207 })?;
2208 self.insert_table_column(cell_ref.table.id(), cell_ref.column + 1)
2209 }
2210
2211 pub fn remove_current_row(&self) -> Result<()> {
2214 let cell_ref = self.current_table_cell().ok_or_else(|| {
2215 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2216 })?;
2217 self.remove_table_row(cell_ref.table.id(), cell_ref.row)
2218 }
2219
2220 pub fn remove_current_column(&self) -> Result<()> {
2223 let cell_ref = self.current_table_cell().ok_or_else(|| {
2224 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2225 })?;
2226 self.remove_table_column(cell_ref.table.id(), cell_ref.column)
2227 }
2228
2229 pub fn merge_selected_cells(&self) -> Result<()> {
2236 let pos_cell = self.current_table_cell().ok_or_else(|| {
2237 DocumentError::InvalidCursorContext("cursor position is not inside a table".into())
2238 })?;
2239
2240 let (_pos, anchor) = self.read_cursor();
2245 let anchor_cell = self.table_cell_at(anchor).ok_or_else(|| {
2246 DocumentError::InvalidCursorContext("cursor anchor is not inside a table".into())
2247 })?;
2248
2249 if pos_cell.table.id() != anchor_cell.table.id() {
2250 return Err(DocumentError::InvalidArgument(
2251 "position and anchor are in different tables".into(),
2252 ));
2253 }
2254
2255 let start_row = pos_cell.row.min(anchor_cell.row);
2256 let start_col = pos_cell.column.min(anchor_cell.column);
2257 let end_row = pos_cell.row.max(anchor_cell.row);
2258 let end_col = pos_cell.column.max(anchor_cell.column);
2259
2260 self.merge_table_cells(pos_cell.table.id(), start_row, start_col, end_row, end_col)
2261 }
2262
2263 pub fn split_current_cell(&self, split_rows: usize, split_columns: usize) -> Result<()> {
2266 let cell_ref = self.current_table_cell().ok_or_else(|| {
2267 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2268 })?;
2269 let cell = cell_ref
2271 .table
2272 .cell(cell_ref.row, cell_ref.column)
2273 .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2274 self.split_table_cell(cell.id(), split_rows, split_columns)
2276 }
2277
2278 pub fn set_current_table_format(&self, format: &crate::flow::TableFormat) -> Result<()> {
2281 let table = self.current_table().ok_or_else(|| {
2282 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2283 })?;
2284 self.set_table_format(table.id(), format)
2285 }
2286
2287 pub fn set_current_cell_format(&self, format: &crate::flow::CellFormat) -> Result<()> {
2290 let cell_ref = self.current_table_cell().ok_or_else(|| {
2291 DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2292 })?;
2293 let cell = cell_ref
2294 .table
2295 .cell(cell_ref.row, cell_ref.column)
2296 .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2297 self.set_table_cell_format(cell.id(), format)
2298 }
2299
2300 pub fn selection_kind(&self) -> crate::flow::SelectionKind {
2308 use crate::flow::{CellRange, SelectionKind};
2309
2310 {
2312 let d = self.data.lock();
2313 if let Some(ref range) = d.cell_selection_override {
2314 return SelectionKind::Cells(range.clone());
2315 }
2316 if d.position == d.anchor {
2317 return SelectionKind::None;
2318 }
2319 }
2320
2321 let (pos, anchor) = self.read_cursor();
2322
2323 let pos_cell = self.table_cell_at(pos);
2325 let anchor_cell = self.selection_anchor_cell(anchor, pos_cell.as_ref());
2326
2327 match (&pos_cell, &anchor_cell) {
2328 (None, None) => {
2329 let (start, end) = (pos.min(anchor), pos.max(anchor));
2333 if let Some(t) = self.find_table_between(start, end) {
2334 let table_id = t.id();
2335 let rows = t.rows();
2336 let cols = t.columns();
2337 let range = CellRange {
2338 table_id,
2339 start_row: 0,
2340 start_col: 0,
2341 end_row: if rows > 0 { rows - 1 } else { 0 },
2342 end_col: if cols > 0 { cols - 1 } else { 0 },
2343 };
2344 let spans = self.collect_cell_spans(table_id);
2345 SelectionKind::Mixed {
2346 cell_range: range.expand_for_spans(&spans),
2347 text_before: true,
2348 text_after: true,
2349 }
2350 } else {
2351 SelectionKind::Text
2352 }
2353 }
2354 (Some(pc), Some(ac)) => {
2355 if pc.table.id() != ac.table.id() {
2356 return SelectionKind::Text;
2358 }
2359 if pc.row == ac.row && pc.column == ac.column {
2360 return SelectionKind::Text;
2362 }
2363 let range = CellRange {
2365 table_id: pc.table.id(),
2366 start_row: pc.row.min(ac.row),
2367 start_col: pc.column.min(ac.column),
2368 end_row: pc.row.max(ac.row),
2369 end_col: pc.column.max(ac.column),
2370 };
2371 let spans = self.collect_cell_spans(pc.table.id());
2372 SelectionKind::Cells(range.expand_for_spans(&spans))
2373 }
2374 (Some(tc), None) | (None, Some(tc)) => {
2375 let table_id = tc.table.id();
2379 let rows = tc.table.rows();
2380 let cols = tc.table.columns();
2381
2382 let inside_pos = if pos_cell.is_some() { pos } else { anchor };
2383 let outside_pos = if pos_cell.is_some() { anchor } else { pos };
2384
2385 let text_before = outside_pos < inside_pos;
2386 let text_after = !text_before;
2387
2388 let range = CellRange {
2389 table_id,
2390 start_row: 0,
2391 start_col: 0,
2392 end_row: if rows > 0 { rows - 1 } else { 0 },
2393 end_col: if cols > 0 { cols - 1 } else { 0 },
2394 };
2395 let spans = self.collect_cell_spans(table_id);
2396 SelectionKind::Mixed {
2397 cell_range: range.expand_for_spans(&spans),
2398 text_before,
2399 text_after,
2400 }
2401 }
2402 }
2403 }
2404
2405 pub fn is_cell_selection(&self) -> bool {
2407 matches!(
2408 self.selection_kind(),
2409 crate::flow::SelectionKind::Cells(_) | crate::flow::SelectionKind::Mixed { .. }
2410 )
2411 }
2412
2413 pub fn selected_cell_range(&self) -> Option<crate::flow::CellRange> {
2415 match self.selection_kind() {
2416 crate::flow::SelectionKind::Cells(r) => Some(r),
2417 crate::flow::SelectionKind::Mixed { cell_range, .. } => Some(cell_range),
2418 _ => None,
2419 }
2420 }
2421
2422 pub fn selected_cells(&self) -> Vec<TableCellRef> {
2424 let range = match self.selected_cell_range() {
2425 Some(r) => r,
2426 None => return Vec::new(),
2427 };
2428 let table = TextTable {
2429 doc: self.doc.clone(),
2430 table_id: range.table_id,
2431 };
2432 let mut cells = Vec::new();
2433 for row in range.start_row..=range.end_row {
2434 for col in range.start_col..=range.end_col {
2435 if table.cell(row, col).is_some() {
2436 cells.push(TableCellRef {
2437 table: table.clone(),
2438 row,
2439 column: col,
2440 });
2441 }
2442 }
2443 }
2444 cells
2445 }
2446
2447 pub fn select_table_cell(&self, table_id: usize, row: usize, col: usize) {
2451 let mut d = self.data.lock();
2452 d.cell_selection_override = Some(crate::flow::CellRange {
2453 table_id,
2454 start_row: row,
2455 start_col: col,
2456 end_row: row,
2457 end_col: col,
2458 });
2459 }
2460
2461 pub fn select_cell_range(
2463 &self,
2464 table_id: usize,
2465 start_row: usize,
2466 start_col: usize,
2467 end_row: usize,
2468 end_col: usize,
2469 ) {
2470 let range = crate::flow::CellRange {
2471 table_id,
2472 start_row,
2473 start_col,
2474 end_row,
2475 end_col,
2476 };
2477 let spans = self.collect_cell_spans(table_id);
2478 let mut d = self.data.lock();
2479 d.cell_selection_override = Some(range.expand_for_spans(&spans));
2480 }
2481
2482 pub fn clear_cell_selection(&self) {
2484 let mut d = self.data.lock();
2485 d.cell_selection_override = None;
2486 }
2487
2488 fn cell_range_positions(&self, range: &CellRange) -> Option<(usize, usize)> {
2491 let inner = self.doc.lock();
2492 let main_frame_id = get_main_frame_id(&inner);
2493 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2495 drop(inner);
2496
2497 let table = flow.into_iter().find_map(|e| match e {
2499 FlowElement::Table(t) if t.id() == range.table_id => Some(t),
2500 _ => None,
2501 })?;
2502
2503 let mut min_pos = usize::MAX;
2504 let mut max_pos = 0usize;
2505
2506 for row in range.start_row..=range.end_row {
2507 for col in range.start_col..=range.end_col {
2508 if let Some(cell) = table.cell(row, col) {
2509 for block in cell.blocks() {
2510 let bp = block.position();
2511 let bl = block.length();
2512 min_pos = min_pos.min(bp);
2513 max_pos = max_pos.max(bp + bl);
2514 }
2515 }
2516 }
2517 }
2518
2519 if min_pos == usize::MAX {
2520 return None;
2521 }
2522
2523 Some((min_pos, max_pos + 1))
2525 }
2526
2527 fn table_anchor_position(&self, table_id: usize) -> Option<usize> {
2532 let inner = self.doc.lock();
2533 let store = inner.ctx.db_context.get_store();
2534 common::database::rope_helpers::table_anchor_position(
2535 store,
2536 table_id as common::types::EntityId,
2537 )
2538 .map(to_usize)
2539 }
2540
2541 fn table_cell_at(&self, position: usize) -> Option<TableCellRef> {
2543 let inner = self.doc.lock();
2544 let block_id = crate::inner::block_at_caret_dto(&inner.ctx, position)
2546 .ok()?
2547 .block_id as usize;
2548
2549 let block = crate::text_block::TextBlock {
2550 doc: self.doc.clone(),
2551 block_id,
2552 };
2553 drop(inner);
2554 block.table_cell()
2555 }
2556
2557 fn selection_anchor_cell(
2574 &self,
2575 anchor: usize,
2576 position_cell: Option<&TableCellRef>,
2577 ) -> Option<TableCellRef> {
2578 let cell = self.table_cell_at(anchor)?;
2579 let on_table_anchor = {
2580 let inner = self.doc.lock();
2581 common::database::rope_helpers::snap_off_table_anchor(
2582 inner.ctx.db_context.get_store(),
2583 to_i64(anchor),
2584 true,
2585 ) != to_i64(anchor)
2586 };
2587 let moving_end_in_the_table =
2588 position_cell.is_some_and(|moving| moving.table.id() == cell.table.id());
2589 (!on_table_anchor || moving_end_in_the_table).then_some(cell)
2590 }
2591
2592 fn back_off_table_anchor(&self, position: usize) -> usize {
2598 let inner = self.doc.lock();
2599 to_usize(common::database::rope_helpers::snap_off_table_anchor(
2600 inner.ctx.db_context.get_store(),
2601 to_i64(position),
2602 false,
2603 ))
2604 }
2605
2606 fn find_table_between(&self, start: usize, end: usize) -> Option<TextTable> {
2608 let inner = self.doc.lock();
2609 let main_frame_id = get_main_frame_id(&inner);
2610 let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2612 drop(inner);
2613
2614 for elem in flow {
2615 if let FlowElement::Table(t) = elem {
2616 if let Some(first_cell) = t.cell(0, 0) {
2619 let blocks = first_cell.blocks();
2620 if let Some(fb) = blocks.first() {
2621 let p = fb.position();
2622 if p > start && p < end {
2623 return Some(t);
2624 }
2625 }
2626 }
2627 }
2628 }
2629 None
2630 }
2631
2632 fn collect_cell_spans(&self, table_id: usize) -> Vec<(usize, usize, usize, usize)> {
2634 let inner = self.doc.lock();
2635 let table_dto =
2636 match frontend::commands::table_commands::get_table(&inner.ctx, &(table_id as u64))
2637 .ok()
2638 .flatten()
2639 {
2640 Some(t) => t,
2641 None => return Vec::new(),
2642 };
2643
2644 let mut spans = Vec::with_capacity(table_dto.cells.len());
2645 for &cell_id in &table_dto.cells {
2646 if let Some(cell) =
2647 frontend::commands::table_cell_commands::get_table_cell(&inner.ctx, &cell_id)
2648 .ok()
2649 .flatten()
2650 {
2651 spans.push((
2652 cell.row as usize,
2653 cell.column as usize,
2654 cell.row_span.max(1) as usize,
2655 cell.column_span.max(1) as usize,
2656 ));
2657 }
2658 }
2659 spans
2660 }
2661
2662 pub fn delete_char(&self) -> Result<()> {
2664 let (pos, anchor) = self.read_cursor();
2665 let (del_pos, del_anchor) = if pos != anchor {
2666 (pos, anchor)
2667 } else {
2668 let end = {
2670 let inner = self.doc.lock();
2671 max_cursor_position_of(&inner).unwrap_or(0)
2672 };
2673 if pos >= end {
2674 return Ok(());
2675 }
2676 let to = self.next_grapheme_boundary(pos);
2680 if to == pos {
2681 return Ok(());
2682 }
2683 (pos, to)
2684 };
2685 self.do_delete(del_pos, del_anchor, pos != anchor)
2686 }
2687
2688 pub fn delete_previous_char(&self) -> Result<()> {
2690 let (pos, anchor) = self.read_cursor();
2691 let (del_pos, del_anchor) = if pos != anchor {
2692 (pos, anchor)
2693 } else if pos > 0 {
2694 let from = self.prev_grapheme_boundary(pos);
2695 if from == pos {
2696 return Ok(());
2697 }
2698 (from, pos)
2699 } else {
2700 return Ok(());
2701 };
2702 self.do_delete(del_pos, del_anchor, pos != anchor)
2703 }
2704
2705 pub fn remove_selected_text(&self) -> Result<String> {
2733 let (pos, anchor) = self.read_cursor();
2734 if pos == anchor {
2735 return Ok(String::new());
2736 }
2737 let queued = {
2738 let mut inner = self.doc.lock();
2739 let (result, removed) = measured_delete(&inner, pos, anchor, true)?;
2740 let stands_for_the_empty_text = self.finish_delete(
2741 &mut inner,
2742 pos.min(anchor),
2743 removed,
2744 result.new_position,
2745 true,
2746 );
2747 (
2749 result.deleted_text,
2750 self.announce_deletion(&mut inner, stands_for_the_empty_text),
2751 )
2752 };
2753 crate::inner::dispatch_queued_events(queued.1);
2754 Ok(queued.0)
2755 }
2756
2757 pub fn current_list(&self) -> Option<crate::TextList> {
2768 let pos = self.position();
2769 let inner = self.doc.lock();
2770 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos).ok()?;
2771 let block = crate::text_block::TextBlock {
2772 doc: self.doc.clone(),
2773 block_id: block_info.block_id as usize,
2774 };
2775 drop(inner);
2776 block.list()
2777 }
2778
2779 pub fn create_list(&self, style: ListStyle) -> Result<()> {
2787 let (pos, anchor) = self.read_cursor();
2788 let queued = {
2789 let mut inner = self.doc.lock();
2790 let dto = frontend::document_editing::CreateListDto {
2791 position: to_i64(pos),
2792 anchor: to_i64(anchor),
2793 style: style.clone(),
2794 };
2795 document_editing_commands::create_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2796 inner.modified = true;
2797 inner.rehighlight_affected(pos.min(anchor));
2798 inner.queue_event(DocumentEvent::ContentsChanged {
2799 position: pos.min(anchor),
2800 chars_removed: 0,
2801 chars_added: 0,
2802 blocks_affected: 1,
2803 });
2804 self.queue_undo_redo_event(&mut inner)
2805 };
2806 crate::inner::dispatch_queued_events(queued);
2807 Ok(())
2808 }
2809
2810 pub fn insert_list(&self, style: ListStyle) -> Result<()> {
2812 let (pos, anchor) = self.read_cursor();
2813 let queued = {
2814 let mut inner = self.doc.lock();
2815 let dto = frontend::document_editing::InsertListDto {
2816 position: to_i64(pos),
2817 anchor: to_i64(anchor),
2818 style: style.clone(),
2819 };
2820 let result =
2821 document_editing_commands::insert_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2822 let edit_pos = pos.min(anchor);
2823 let removed = pos.max(anchor) - edit_pos;
2824 let new_pos = to_usize(result.new_position);
2825 self.finish_edit_ext(
2826 &mut inner,
2827 edit_pos,
2828 removed,
2829 Insertion {
2830 at: edit_pos,
2831 removed: 0,
2832 added: new_pos.saturating_sub(edit_pos),
2833 },
2834 new_pos,
2835 1,
2836 false,
2837 )
2838 };
2839 crate::inner::dispatch_queued_events(queued);
2840 Ok(())
2841 }
2842
2843 pub fn set_list_format(&self, list_id: usize, format: &crate::ListFormat) -> Result<()> {
2845 let queued = {
2846 let mut inner = self.doc.lock();
2847 let dto = format.to_set_dto(list_id);
2848 document_formatting_commands::set_list_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2849 inner.modified = true;
2850 inner.queue_event(DocumentEvent::FormatChanged {
2851 position: 0,
2852 length: 0,
2853 kind: crate::flow::FormatChangeKind::List,
2854 });
2855 self.queue_undo_redo_event(&mut inner)
2856 };
2857 crate::inner::dispatch_queued_events(queued);
2858 Ok(())
2859 }
2860
2861 pub fn set_current_list_format(&self, format: &crate::ListFormat) -> Result<()> {
2864 let list = self.current_list().ok_or_else(|| {
2865 DocumentError::InvalidCursorContext("cursor is not inside a list".into())
2866 })?;
2867 self.set_list_format(list.id(), format)
2868 }
2869
2870 pub fn add_block_to_list(&self, block_id: usize, list_id: usize) -> Result<()> {
2872 let queued = {
2873 let mut inner = self.doc.lock();
2874 let dto = frontend::document_editing::AddBlockToListDto {
2875 block_id: to_i64(block_id),
2876 list_id: to_i64(list_id),
2877 };
2878 document_editing_commands::add_block_to_list(&inner.ctx, Some(inner.stack_id), &dto)?;
2879 inner.modified = true;
2880 inner.queue_event(DocumentEvent::FormatChanged {
2887 position: 0,
2888 length: 0,
2889 kind: crate::flow::FormatChangeKind::List,
2890 });
2891 self.queue_undo_redo_event(&mut inner)
2892 };
2893 crate::inner::dispatch_queued_events(queued);
2894 Ok(())
2895 }
2896
2897 pub fn add_current_block_to_list(&self, list_id: usize) -> Result<()> {
2900 let pos = self.position();
2901 let inner = self.doc.lock();
2902 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2903 drop(inner);
2904 self.add_block_to_list(block_info.block_id as usize, list_id)
2905 }
2906
2907 pub fn remove_block_from_list(&self, block_id: usize) -> Result<()> {
2909 let queued = {
2910 let mut inner = self.doc.lock();
2911 let dto = frontend::document_editing::RemoveBlockFromListDto {
2912 block_id: to_i64(block_id),
2913 };
2914 document_editing_commands::remove_block_from_list(
2915 &inner.ctx,
2916 Some(inner.stack_id),
2917 &dto,
2918 )?;
2919 inner.modified = true;
2920 inner.queue_event(DocumentEvent::FormatChanged {
2923 position: 0,
2924 length: 0,
2925 kind: crate::flow::FormatChangeKind::List,
2926 });
2927 self.queue_undo_redo_event(&mut inner)
2928 };
2929 crate::inner::dispatch_queued_events(queued);
2930 Ok(())
2931 }
2932
2933 pub fn remove_current_block_from_list(&self) -> Result<()> {
2937 let pos = self.position();
2938 let inner = self.doc.lock();
2939 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2940 drop(inner);
2941 self.remove_block_from_list(block_info.block_id as usize)
2942 }
2943
2944 pub fn remove_list_item(&self, list_id: usize, index: usize) -> Result<()> {
2947 let list = crate::text_list::TextList {
2948 doc: self.doc.clone(),
2949 list_id,
2950 };
2951 let block = list.item(index).ok_or_else(|| {
2952 DocumentError::OutOfRange(format!("list item index {index} out of range"))
2953 })?;
2954 self.remove_block_from_list(block.id())
2955 }
2956
2957 pub fn char_format(&self) -> Result<TextFormat> {
2962 let pos = self.position();
2963 let inner = self.doc.lock();
2964
2965 let dto = frontend::document_inspection::GetBlockAtPositionDto {
2967 position: to_i64(pos),
2968 };
2969 let block_info = document_inspection_commands::get_block_at_position(&inner.ctx, &dto)?;
2970 let block_id = block_info.block_id as u64;
2971 let mut block_dto =
2972 frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
2973 .ok_or_else(|| DocumentError::NotFound("block not found at position".into()))?;
2974 let store = inner.ctx.db_context.get_store();
2975 crate::inner::refresh_block_position(&mut block_dto, store);
2976
2977 let local_char = pos.saturating_sub(block_dto.document_position as usize);
2980 let entity: common::entities::Block = block_dto.clone().into();
2981 let plain_owned = common::database::rope_helpers::block_content_via_store(&entity, store);
2982 let plain: &str = &plain_owned;
2983 let byte_offset: u32 = plain
2984 .char_indices()
2985 .nth(local_char)
2986 .map(|(b, _)| b as u32)
2987 .unwrap_or(plain.len() as u32);
2988
2989 let images = store
2992 .block_images
2993 .read()
2994 .get(&block_id)
2995 .cloned()
2996 .unwrap_or_default();
2997 if let Some(img) = images.iter().find(|i| i.byte_offset == byte_offset) {
2998 return Ok(TextFormat::from(&img.format));
2999 }
3000
3001 let runs = store
3003 .format_runs
3004 .read()
3005 .get(&block_id)
3006 .cloned()
3007 .unwrap_or_default();
3008 let fmt = runs
3009 .iter()
3010 .find(|r| r.byte_start <= byte_offset && byte_offset < r.byte_end)
3011 .map(|r| TextFormat::from(&r.format))
3012 .unwrap_or_default();
3013 Ok(fmt)
3014 }
3015
3016 pub fn block_format(&self) -> Result<BlockFormat> {
3023 let pos = self.position();
3024 let inner = self.doc.lock();
3025 let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
3026 let block_id = block_info.block_id as u64;
3027 let block = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
3028 .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
3029 Ok(BlockFormat::from(&block))
3030 }
3031
3032 pub fn set_char_format(&self, format: &TextFormat) -> Result<()> {
3036 let (pos, anchor) = self.read_cursor();
3037 let queued = {
3038 let mut inner = self.doc.lock();
3039 let dto = format.to_set_dto(pos, anchor);
3040 document_formatting_commands::set_text_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3041 let start = pos.min(anchor);
3042 let length = pos.max(anchor) - start;
3043 inner.modified = true;
3044 inner.queue_event(DocumentEvent::FormatChanged {
3045 position: start,
3046 length,
3047 kind: crate::flow::FormatChangeKind::Character,
3048 });
3049 self.queue_undo_redo_event(&mut inner)
3050 };
3051 crate::inner::dispatch_queued_events(queued);
3052 Ok(())
3053 }
3054
3055 pub fn link_at_caret(&self) -> Option<LinkExtent> {
3065 let pos = self.position();
3066 let block_id = {
3067 let inner = self.doc.lock();
3068 crate::inner::block_at_caret_dto(&inner.ctx, pos)
3069 .ok()?
3070 .block_id as usize
3071 };
3072 let block = TextBlock {
3073 doc: self.doc.clone(),
3074 block_id,
3075 };
3076 crate::link_extent::link_extent_at(&block, pos)
3077 }
3078
3079 pub fn clear_char_anchor(&self) -> Result<()> {
3091 self.merge_char_format(&TextFormat {
3092 clear_link: true,
3093 ..Default::default()
3094 })
3095 }
3096
3097 pub fn merge_char_format(&self, format: &TextFormat) -> Result<()> {
3099 let (pos, anchor) = self.read_cursor();
3100 let queued = {
3101 let mut inner = self.doc.lock();
3102 let dto = format.to_merge_dto(pos, anchor);
3103 document_formatting_commands::merge_text_format(
3104 &inner.ctx,
3105 Some(inner.stack_id),
3106 &dto,
3107 )?;
3108 let start = pos.min(anchor);
3109 let length = pos.max(anchor) - start;
3110 inner.modified = true;
3111 inner.queue_event(DocumentEvent::FormatChanged {
3112 position: start,
3113 length,
3114 kind: crate::flow::FormatChangeKind::Character,
3115 });
3116 self.queue_undo_redo_event(&mut inner)
3117 };
3118 crate::inner::dispatch_queued_events(queued);
3119 Ok(())
3120 }
3121
3122 pub fn set_block_format(&self, format: &BlockFormat) -> Result<()> {
3129 let (pos, anchor) = self.read_cursor();
3130 let queued = {
3131 let mut inner = self.doc.lock();
3132 let dto = format.to_set_dto(pos, anchor);
3133 document_formatting_commands::set_block_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3134 let start = pos.min(anchor);
3135 let length = pos.max(anchor) - start;
3136 inner.modified = true;
3137 inner.queue_event(DocumentEvent::FormatChanged {
3138 position: start,
3139 length,
3140 kind: crate::flow::FormatChangeKind::Block,
3141 });
3142 self.queue_undo_redo_event(&mut inner)
3143 };
3144 crate::inner::dispatch_queued_events(queued);
3145 Ok(())
3146 }
3147
3148 pub fn set_frame_format(&self, frame_id: usize, format: &FrameFormat) -> Result<()> {
3150 let (pos, anchor) = self.read_cursor();
3151 let queued = {
3152 let mut inner = self.doc.lock();
3153 let dto = format.to_set_dto(pos, anchor, frame_id);
3154 document_formatting_commands::set_frame_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3155 let start = pos.min(anchor);
3156 let length = pos.max(anchor) - start;
3157 inner.modified = true;
3158 inner.queue_event(DocumentEvent::FormatChanged {
3159 position: start,
3160 length,
3161 kind: crate::flow::FormatChangeKind::Block,
3162 });
3163 self.queue_undo_redo_event(&mut inner)
3164 };
3165 crate::inner::dispatch_queued_events(queued);
3166 Ok(())
3167 }
3168
3169 pub fn begin_edit_block(&self) {
3173 let inner = self.doc.lock();
3174 undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
3175 }
3176
3177 pub fn end_edit_block(&self) {
3179 let inner = self.doc.lock();
3180 undo_redo_commands::end_composite(&inner.ctx);
3181 }
3182
3183 pub fn join_previous_edit_block(&self) {
3190 self.begin_edit_block();
3191 }
3192
3193 fn queue_undo_redo_event(&self, inner: &mut TextDocumentInner) -> QueuedEvents {
3197 let can_undo = undo_redo_commands::can_undo(&inner.ctx, Some(inner.stack_id));
3198 let can_redo = undo_redo_commands::can_redo(&inner.ctx, Some(inner.stack_id));
3199 inner.queue_event(DocumentEvent::UndoRedoChanged { can_undo, can_redo });
3200 inner.take_queued_events()
3201 }
3202
3203 fn do_delete(&self, pos: usize, anchor: usize, selection: bool) -> Result<()> {
3204 let queued = {
3205 let mut inner = self.doc.lock();
3206 let (result, removed) = measured_delete(&inner, pos, anchor, selection)?;
3207 let stands_for_the_empty_text = self.finish_delete(
3208 &mut inner,
3209 pos.min(anchor),
3210 removed,
3211 result.new_position,
3212 selection,
3213 );
3214 self.announce_deletion(&mut inner, stands_for_the_empty_text)
3215 };
3216 crate::inner::dispatch_queued_events(queued);
3217 Ok(())
3218 }
3219
3220 fn finish_delete(
3240 &self,
3241 inner: &mut TextDocumentInner,
3242 edit_pos: usize,
3243 removed: usize,
3244 new_position: i64,
3245 selection: bool,
3246 ) -> bool {
3247 let new_pos = to_usize(new_position);
3248 let edit_pos = edit_pos.min(new_pos);
3252 if removed > 0 {
3253 inner.adjust_cursors(edit_pos, removed, 0);
3254 }
3255 let stands_for_the_empty_text =
3256 selection && removed > 0 && new_pos == 0 && main_text_is_empty(inner);
3257 if stands_for_the_empty_text {
3258 inner.emptied_text = crate::inner::EmptiedText::of(inner.ctx.db_context.get_store());
3261 }
3262 {
3263 let mut d = self.data.lock();
3264 d.position = new_pos;
3265 d.anchor = new_pos;
3266 d.whole_text_selected = false;
3267 d.anchor_in_table = None;
3268 }
3269 if removed > 0 {
3270 inner.modified = true;
3271 inner.invalidate_text_cache();
3272 inner.rehighlight_affected(edit_pos);
3273 inner.queue_event(DocumentEvent::ContentsChanged {
3274 position: edit_pos,
3275 chars_removed: removed,
3276 chars_added: 0,
3277 blocks_affected: 1,
3278 });
3279 }
3280 inner.check_block_count_changed();
3281 inner.check_flow_changed();
3282 stands_for_the_empty_text
3283 }
3284
3285 fn announce_deletion(
3290 &self,
3291 inner: &mut TextDocumentInner,
3292 stands_for_the_empty_text: bool,
3293 ) -> QueuedEvents {
3294 let queued = self.queue_undo_redo_event(inner);
3295 self.data.lock().whole_text_selected = stands_for_the_empty_text;
3296 queued
3297 }
3298
3299 fn resolve_move(&self, op: MoveOperation, n: usize) -> usize {
3301 let pos = self.position();
3302 match op {
3303 MoveOperation::NoMove => pos,
3304 MoveOperation::Start => 0,
3305 MoveOperation::End => {
3306 let inner = self.doc.lock();
3307 max_cursor_position_of(&inner).unwrap_or(pos)
3308 }
3309 MoveOperation::NextCharacter | MoveOperation::Right => {
3310 let mut cur = pos;
3311 for _ in 0..n {
3312 let next = self.next_grapheme_boundary(cur);
3313 if next == cur {
3314 break;
3315 }
3316 cur = next;
3317 }
3318 cur
3319 }
3320 MoveOperation::PreviousCharacter | MoveOperation::Left => {
3321 let mut cur = pos;
3322 for _ in 0..n {
3323 let prev = self.prev_grapheme_boundary(cur);
3324 if prev == cur {
3325 break;
3326 }
3327 cur = prev;
3328 }
3329 cur
3330 }
3331 MoveOperation::StartOfBlock | MoveOperation::StartOfLine => {
3332 let inner = self.doc.lock();
3333 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3334 position: to_i64(pos),
3335 };
3336 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3337 .map(|info| to_usize(info.block_start))
3338 .unwrap_or(pos)
3339 }
3340 MoveOperation::EndOfBlock | MoveOperation::EndOfLine => {
3341 let inner = self.doc.lock();
3342 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3343 position: to_i64(pos),
3344 };
3345 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3346 .map(|info| to_usize(info.block_start) + to_usize(info.block_length))
3347 .unwrap_or(pos)
3348 }
3349 MoveOperation::NextBlock => {
3350 let inner = self.doc.lock();
3351 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3352 position: to_i64(pos),
3353 };
3354 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3355 .map(|info| {
3356 to_usize(info.block_start) + to_usize(info.block_length) + 1
3358 })
3359 .unwrap_or(pos)
3360 }
3361 MoveOperation::PreviousBlock => {
3362 let inner = self.doc.lock();
3363 let dto = frontend::document_inspection::GetBlockAtPositionDto {
3364 position: to_i64(pos),
3365 };
3366 let block_start =
3367 document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3368 .map(|info| to_usize(info.block_start))
3369 .unwrap_or(pos);
3370 if block_start >= 2 {
3371 let before = common::database::rope_helpers::snap_off_table_anchor(
3375 inner.ctx.db_context.get_store(),
3376 to_i64(block_start - 2),
3377 false,
3378 );
3379 let prev_dto =
3380 frontend::document_inspection::GetBlockAtPositionDto { position: before };
3381 document_inspection_commands::get_block_at_position(&inner.ctx, &prev_dto)
3382 .map(|info| to_usize(info.block_start))
3383 .unwrap_or(0)
3384 } else {
3385 0
3386 }
3387 }
3388 MoveOperation::NextWord | MoveOperation::EndOfWord | MoveOperation::WordRight => {
3389 let (_, end) = self.find_word_boundaries(pos);
3390 if end == pos {
3392 let inner = self.doc.lock();
3394 let max_pos = max_cursor_position_of(&inner).unwrap_or(0);
3395 let scan_len = max_pos.saturating_sub(pos).min(64);
3396 if scan_len == 0 {
3397 return pos;
3398 }
3399 let dto = frontend::document_inspection::GetTextAtPositionDto {
3400 position: to_i64(pos),
3401 length: to_i64(scan_len),
3402 };
3403 if let Ok(r) =
3404 document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3405 {
3406 for (i, ch) in r.text.chars().enumerate() {
3407 if ch.is_alphanumeric() || ch == '_' {
3408 let word_pos = pos + i;
3410 drop(inner);
3411 let (_, word_end) = self.find_word_boundaries(word_pos);
3412 return word_end;
3413 }
3414 }
3415 }
3416 pos + scan_len
3417 } else {
3418 end
3419 }
3420 }
3421 MoveOperation::PreviousWord | MoveOperation::StartOfWord | MoveOperation::WordLeft => {
3422 let (start, _) = self.find_word_boundaries(pos);
3423 if start < pos {
3424 start
3425 } else if pos > 0 {
3426 let mut search = pos - 1;
3429 loop {
3430 search = self.back_off_table_anchor(search);
3434 let (ws, we) = self.find_word_boundaries(search);
3435 if ws < we && ws < pos {
3436 break ws;
3438 }
3439 if search == 0 {
3441 break 0;
3442 }
3443 search -= 1;
3444 }
3445 } else {
3446 0
3447 }
3448 }
3449 MoveOperation::StartOfSentence | MoveOperation::PreviousSentence => {
3450 let mut cur = pos;
3451 for _ in 0..n.max(1) {
3452 let start = match self.find_sentence_boundaries(cur) {
3453 Some((start, _)) => start,
3454 None => break,
3455 };
3456 if start < cur && op == MoveOperation::StartOfSentence {
3459 cur = start;
3460 } else if cur > 0 {
3461 match self.find_sentence_boundaries(self.back_off_table_anchor(cur - 1)) {
3463 Some((prev, _)) if prev < cur => cur = prev,
3464 _ => cur = cur.saturating_sub(1),
3467 }
3468 } else {
3469 break;
3470 }
3471 }
3472 cur
3473 }
3474 MoveOperation::EndOfSentence => {
3475 let mut cur = pos;
3476 for _ in 0..n.max(1) {
3477 let end = match self.find_sentence_boundaries(cur) {
3478 Some((_, end)) => end,
3479 None => break,
3480 };
3481 if end > cur {
3482 cur = end;
3483 } else {
3484 match self.find_sentence_boundaries(cur + 1) {
3485 Some((_, next)) if next > cur => cur = next,
3486 _ => break,
3487 }
3488 }
3489 }
3490 cur
3491 }
3492 MoveOperation::NextSentence => {
3493 let mut cur = pos;
3494 for _ in 0..n.max(1) {
3495 let end = match self.find_sentence_boundaries(cur) {
3498 Some((_, end)) => end,
3499 None => break,
3500 };
3501 match self.find_sentence_boundaries(end + 1) {
3502 Some((start, _)) if start > cur => cur = start,
3503 _ => {
3504 if end > cur {
3505 cur = end;
3506 } else {
3507 break;
3508 }
3509 }
3510 }
3511 }
3512 cur
3513 }
3514 MoveOperation::Up | MoveOperation::Down => {
3515 if matches!(op, MoveOperation::Up) {
3518 self.resolve_move(MoveOperation::PreviousBlock, 1)
3519 } else {
3520 self.resolve_move(MoveOperation::NextBlock, 1)
3521 }
3522 }
3523 }
3524 }
3525
3526 pub(crate) fn snap_position_to_grapheme_boundary(&self) {
3537 let pos = {
3538 let data = self.data.lock();
3539 data.position
3540 };
3541 let snapped = self.forward_grapheme_boundary_at_or_after(pos);
3542 if snapped != pos {
3543 let mut data = self.data.lock();
3544 data.position = snapped;
3545 if data.anchor == pos {
3546 data.anchor = snapped;
3547 }
3548 data.whole_text_selected = false;
3549 }
3550 }
3551
3552 fn forward_grapheme_boundary_at_or_after(&self, pos: usize) -> usize {
3562 let inner = self.doc.lock();
3563 let end = max_cursor_position_of(&inner).unwrap_or(pos);
3564 if pos >= end {
3565 return pos;
3566 }
3567 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3568 position: to_i64(pos),
3569 };
3570 let Ok(block_info) =
3571 document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto)
3572 else {
3573 return pos;
3574 };
3575 let block_start = to_usize(block_info.block_start);
3576 let block_length = to_usize(block_info.block_length);
3577 let offset_in_block = pos.saturating_sub(block_start);
3578 if offset_in_block == 0 || offset_in_block >= block_length {
3580 return pos;
3581 }
3582 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3583 position: to_i64(block_start),
3584 length: to_i64(block_length),
3585 };
3586 let Ok(r) = document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto)
3587 else {
3588 return pos;
3589 };
3590 let text = r.text;
3591 drop(inner);
3592 let mut acc = 0usize;
3595 for g in text.graphemes(true) {
3596 if acc >= offset_in_block {
3597 return block_start + acc;
3598 }
3599 acc += g.chars().count();
3600 }
3601 block_start + acc
3602 }
3603
3604 fn next_grapheme_boundary(&self, pos: usize) -> usize {
3617 let inner = self.doc.lock();
3618 let end = max_cursor_position_of(&inner).unwrap_or(pos);
3619 if pos >= end {
3620 return pos;
3621 }
3622 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3623 position: to_i64(pos),
3624 };
3625 let block_info =
3626 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3627 Ok(info) => info,
3628 Err(_) => return pos + 1,
3629 };
3630 let block_start = to_usize(block_info.block_start);
3631 let block_length = to_usize(block_info.block_length);
3632 let offset_in_block = pos.saturating_sub(block_start);
3633 if offset_in_block >= block_length {
3634 return (pos + 1).min(end);
3637 }
3638 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3639 position: to_i64(pos),
3640 length: to_i64(block_length - offset_in_block),
3641 };
3642 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3643 Ok(r) => r.text,
3644 Err(_) => return pos + 1,
3645 };
3646 drop(inner);
3647 match text.graphemes(true).next() {
3648 Some(g) if !g.is_empty() => (pos + g.chars().count()).min(end),
3649 _ => (pos + 1).min(end),
3650 }
3651 }
3652
3653 fn prev_grapheme_boundary(&self, pos: usize) -> usize {
3657 if pos == 0 {
3658 return 0;
3659 }
3660 let inner = self.doc.lock();
3661 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3662 position: to_i64(pos.saturating_sub(1)),
3663 };
3664 let block_info =
3665 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3666 Ok(info) => info,
3667 Err(_) => return pos - 1,
3668 };
3669 let block_start = to_usize(block_info.block_start);
3670 let block_length = to_usize(block_info.block_length);
3671 let block_end = block_start + block_length;
3672 if pos > block_end {
3676 return pos - 1;
3677 }
3678 if block_length == 0 || pos <= block_start {
3679 return pos.saturating_sub(1);
3680 }
3681 let scan_len = pos - block_start;
3682 let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3683 position: to_i64(block_start),
3684 length: to_i64(scan_len),
3685 };
3686 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3687 Ok(r) => r.text,
3688 Err(_) => return pos - 1,
3689 };
3690 drop(inner);
3691 match text.graphemes(true).next_back() {
3692 Some(g) if !g.is_empty() => pos - g.chars().count(),
3693 _ => pos - 1,
3694 }
3695 }
3696
3697 fn find_word_boundaries(&self, pos: usize) -> (usize, usize) {
3703 let inner = self.doc.lock();
3704 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3706 position: to_i64(pos),
3707 };
3708 let block_info =
3709 match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3710 Ok(info) => info,
3711 Err(_) => return (pos, pos),
3712 };
3713
3714 let block_start = to_usize(block_info.block_start);
3715 let block_length = to_usize(block_info.block_length);
3716 if block_length == 0 {
3717 return (pos, pos);
3718 }
3719
3720 let dto = frontend::document_inspection::GetTextAtPositionDto {
3721 position: to_i64(block_start),
3722 length: to_i64(block_length),
3723 };
3724 let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &dto) {
3725 Ok(r) => r.text,
3726 Err(_) => return (pos, pos),
3727 };
3728
3729 let cursor_offset = pos.saturating_sub(block_start);
3731
3732 let mut last_char_start = 0;
3734 let mut last_char_end = 0;
3735
3736 for (word_byte_start, word) in text.unicode_word_indices() {
3737 let word_char_start = text[..word_byte_start].chars().count();
3739 let word_char_len = word.chars().count();
3740 let word_char_end = word_char_start + word_char_len;
3741
3742 last_char_start = word_char_start;
3743 last_char_end = word_char_end;
3744
3745 if cursor_offset >= word_char_start && cursor_offset < word_char_end {
3746 return (block_start + word_char_start, block_start + word_char_end);
3747 }
3748 }
3749
3750 if cursor_offset == last_char_end && last_char_start < last_char_end {
3752 return (block_start + last_char_start, block_start + last_char_end);
3753 }
3754
3755 (pos, pos)
3756 }
3757
3758 fn find_sentence_boundaries(&self, pos: usize) -> Option<(usize, usize)> {
3764 let locale = self.data.lock().content_locale.clone();
3765
3766 let inner = self.doc.lock();
3767 let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3768 position: to_i64(pos),
3769 };
3770 let block_info =
3771 document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto).ok()?;
3772 let block_start = to_usize(block_info.block_start);
3773 let block_length = to_usize(block_info.block_length);
3774 if block_length == 0 {
3775 return None;
3776 }
3777 let dto = frontend::document_inspection::GetTextAtPositionDto {
3778 position: to_i64(block_start),
3779 length: to_i64(block_length),
3780 };
3781 let text = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3782 .ok()?
3783 .text;
3784 drop(inner);
3785
3786 let offset = pos.saturating_sub(block_start);
3787 let (start, end) =
3788 frontend::common::parser_tools::sentence_bounds(&text, offset, locale.as_deref())?;
3789 Some((block_start + start, block_start + end))
3790 }
3791}
3792
3793#[derive(Clone, Copy, PartialEq, Eq)]
3800enum BlockEdge {
3801 First,
3802 Middle,
3803 Last,
3804 OnlyOne,
3805}
3806
3807fn cursor_frame_ref(inner: &TextDocumentInner, block_id: u64) -> Option<FrameRef> {
3811 let parent = crate::text_block::find_parent_frame(inner, block_id)?;
3812 let store = inner.ctx.db_context.get_store();
3813 let frames = store.frames.read();
3814 let frame = frames.get(&parent)?.clone();
3815 frame.parent_frame?;
3816 let is_blockquote = frame.fmt_is_blockquote.unwrap_or(false);
3817
3818 let mut depth = 0;
3819 let mut current = Some(parent);
3820 while let Some(id) = current {
3821 let Some(f) = frames.get(&id) else {
3822 break;
3823 };
3824 if f.parent_frame.is_none() {
3825 break;
3826 }
3827 depth += 1;
3828 current = f.parent_frame;
3829 }
3830
3831 Some(FrameRef {
3832 frame_id: frame.id as usize,
3833 parent_frame_id: frame.parent_frame.map(|id| id as usize),
3834 is_blockquote,
3835 depth,
3836 })
3837}
3838
3839fn innermost_blockquote_frame_id(inner: &TextDocumentInner, block_id: u64) -> Option<usize> {
3843 let mut current = crate::text_block::find_parent_frame(inner, block_id);
3844 let store = inner.ctx.db_context.get_store();
3845 let frames = store.frames.read();
3846 while let Some(id) = current {
3847 let f = frames.get(&id)?;
3848 if f.fmt_is_blockquote == Some(true) {
3849 return Some(f.id as usize);
3850 }
3851 current = f.parent_frame;
3852 }
3853 None
3854}
3855
3856fn blockquote_depth_for_block(inner: &TextDocumentInner, block_id: u64) -> usize {
3859 let mut current = crate::text_block::find_parent_frame(inner, block_id);
3860 let store = inner.ctx.db_context.get_store();
3861 let frames = store.frames.read();
3862 let mut count = 0;
3863 while let Some(id) = current {
3864 let Some(f) = frames.get(&id) else {
3865 break;
3866 };
3867 if f.fmt_is_blockquote == Some(true) {
3868 count += 1;
3869 }
3870 current = f.parent_frame;
3871 }
3872 count
3873}
3874
3875fn block_position_in_current_frame(cursor: &TextCursor) -> Option<BlockEdge> {
3881 let pos = cursor.position();
3882 let inner = cursor.doc.lock();
3883 let block_info = TextCursor::caret_block(&inner, pos)?;
3885 let block_id = block_info.block_id as common::types::EntityId;
3886 let parent_id = crate::text_block::find_parent_frame(&inner, block_info.block_id as u64)?;
3887 let store = inner.ctx.db_context.get_store();
3888 let frames = store.frames.read();
3889 let frame = frames.get(&parent_id)?;
3890 let block_positions: Vec<usize> = frame
3891 .child_order
3892 .iter()
3893 .enumerate()
3894 .filter_map(|(i, &e)| {
3895 if e > 0 {
3896 Some((i, e as common::types::EntityId))
3897 } else {
3898 None
3899 }
3900 })
3901 .filter(|(_, id)| *id == block_id)
3902 .map(|(i, _)| i)
3903 .collect();
3904 let block_idx = *block_positions.first()?;
3905 let positive_entries: Vec<usize> = frame
3906 .child_order
3907 .iter()
3908 .enumerate()
3909 .filter_map(|(i, &e)| if e > 0 { Some(i) } else { None })
3910 .collect();
3911 let first_pos = *positive_entries.first()?;
3912 let last_pos = *positive_entries.last()?;
3913 let is_first = block_idx == first_pos;
3914 let is_last = block_idx == last_pos;
3915 let edge = match (is_first, is_last, positive_entries.len()) {
3916 (_, _, 1) => BlockEdge::OnlyOne,
3917 (true, _, _) => BlockEdge::First,
3918 (_, true, _) => BlockEdge::Last,
3919 _ => BlockEdge::Middle,
3920 };
3921 Some(edge)
3922}