Struct loro::LoroText

source ·
pub struct LoroText { /* private fields */ }
Expand description

LoroText container. It’s used to model plaintext/richtext.

Implementations§

source§

impl LoroText

source

pub fn new() -> Self

Create a new container that is detached from the document.

The edits on a detached container will not be persisted. To attach the container to the document, please insert it into an attached container.

source

pub fn is_attached(&self) -> bool

Whether the container is attached to a document

The edits on a detached container will not be persisted. To attach the container to the document, please insert it into an attached container.

source

pub fn id(&self) -> ContainerID

Get the ContainerID of the text container.

source

pub fn insert(&self, pos: usize, s: &str) -> LoroResult<()>

Insert a string at the given unicode position.

source

pub fn delete(&self, pos: usize, len: usize) -> LoroResult<()>

Delete a range of text at the given unicode position with unicode length.

source

pub fn is_empty(&self) -> bool

Whether the text container is empty.

source

pub fn len_utf8(&self) -> usize

Get the length of the text container in UTF-8.

source

pub fn len_unicode(&self) -> usize

Get the length of the text container in Unicode.

source

pub fn len_utf16(&self) -> usize

Get the length of the text container in UTF-16.

source

pub fn apply_delta(&self, delta: &[TextDelta]) -> LoroResult<()>

Apply a delta to the text container.

source

pub fn mark( &self, range: Range<usize>, key: &str, value: impl Into<LoroValue> ) -> LoroResult<()>

Mark a range of text with a key-value pair.

You can use it to create a highlight, make a range of text bold, or add a link to a range of text.

You can specify the expand option to set the behavior when inserting text at the boundary of the range.

  • after(default): when inserting text right after the given range, the mark will be expanded to include the inserted text
  • before: when inserting text right before the given range, the mark will be expanded to include the inserted text
  • none: the mark will not be expanded to include the inserted text at the boundaries
  • both: when inserting text either right before or right after the given range, the mark will be expanded to include the inserted text

You should make sure that a key is always associated with the same expand type.

Note: this is not suitable for unmergeable annotations like comments.

source

pub fn unmark(&self, range: Range<usize>, key: &str) -> LoroResult<()>

Unmark a range of text with a key and a value.

You can use it to remove highlights, bolds or links

You can specify the expand option to set the behavior when inserting text at the boundary of the range.

Note: You should specify the same expand type as when you mark the text.

  • after(default): when inserting text right after the given range, the mark will be expanded to include the inserted text
  • before: when inserting text right before the given range, the mark will be expanded to include the inserted text
  • none: the mark will not be expanded to include the inserted text at the boundaries
  • both: when inserting text either right before or right after the given range, the mark will be expanded to include the inserted text

You should make sure that a key is always associated with the same expand type.

Note: you cannot delete unmergeable annotations like comments by this method.

source

pub fn to_delta(&self) -> LoroValue

Get the text in Delta format.

§Example

let doc = LoroDoc::new();
let text = doc.get_text("text");
text.insert(0, "Hello world!").unwrap();
text.mark(0..5, "bold", true).unwrap();
assert_eq!(
    text.to_delta().to_json_value(),
    json!([
        { "insert": "Hello", "attributes": {"bold": true} },
        { "insert": " world!" },
    ])
);
text.unmark(3..5, "bold").unwrap();
assert_eq!(
    text.to_delta().to_json_value(),
    json!([
        { "insert": "Hel", "attributes": {"bold": true} },
        { "insert": "lo world!" },
   ])
);
source

pub fn to_string(&self) -> String

Get the text content of the text container.

source

pub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor>

Get the cursor at the given position.

Using “index” to denote cursor positions can be unstable, as positions may shift with document edits. To reliably represent a position or range within a document, it is more effective to leverage the unique ID of each item/character in a List CRDT or Text CRDT.

Loro optimizes State metadata by not storing the IDs of deleted elements. This approach complicates tracking cursors since they rely on these IDs. The solution recalculates position by replaying relevant history to update stable positions accurately. To minimize the performance impact of history replay, the system updates cursor info to reference only the IDs of currently present elements, thereby reducing the need for replay.

§Example
let doc = LoroDoc::new();
let text = &doc.get_text("text");
text.insert(0, "01234").unwrap();
let pos = text.get_cursor(5, Default::default()).unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 5);
text.insert(0, "01234").unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 10);
text.delete(0, 10).unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 0);
text.insert(0, "01234").unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 5);

Trait Implementations§

source§

impl Clone for LoroText

source§

fn clone(&self) -> LoroText

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl ContainerTrait for LoroText

§

type Handler = TextHandler

The handler of the container.
source§

fn to_container(&self) -> Container

Convert the container to a Container.
source§

fn to_handler(&self) -> Self::Handler

Convert the container to a handler.
source§

fn from_handler(handler: Self::Handler) -> Self

Convert the handler to a container.
source§

fn is_attached(&self) -> bool

Whether the container is attached to a document.
source§

fn get_attached(&self) -> Option<Self>

If a detached container is attached, this method will return its corresponding attached handler.
source§

fn try_from_container(container: Container) -> Option<Self>

Try to convert the container to the handler.
source§

impl Debug for LoroText

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for LoroText

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> ZeroElement for T
where T: Default,