pub struct LoroText { /* private fields */ }Expand description
LoroText container. It’s used to model plaintext/richtext.
Indexing and lengths:
- Rust APIs default to Unicode scalar positions for
insert/deleteandslice. - For byte-based integration, use
insert_utf8/delete_utf8. - For UTF-16 code unit offsets (e.g., integrating with JavaScript), use
insert_utf16/delete_utf16/slice_utf16and related helpers. - You can inspect
len_unicode,len_utf8, andlen_utf16depending on your needs.
§Example (emoji)
use loro::LoroDoc;
let doc = LoroDoc::new();
let text = doc.get_text("text");
text.insert(0, "Hello 😀 World").unwrap();
assert_eq!(text.len_unicode(), 13); // visible characters
assert!(text.len_utf16() >= text.len_unicode()); // emoji may count as 2 in UTF-16
// Delete the emoji safely by Unicode indices
let start = 6; // after "Hello "
text.delete(start, 1).unwrap();
assert_eq!(text.to_string(), "Hello World");Implementations§
Source§impl LoroText
impl LoroText
Sourcepub fn new() -> Self
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.
Sourcepub fn is_attached(&self) -> bool
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.
Sourcepub fn iter(&self, callback: impl FnMut(&str) -> bool)
pub fn iter(&self, callback: impl FnMut(&str) -> bool)
Iterate over contiguous text chunks.
The callback function will be called for each contiguous text segment (internal span),
not necessarily a single character. If you need per-character iteration, iterate the
returned &str within the callback.
If the callback returns false, the iteration will stop.
Limitation: you cannot access or alter the doc state when iterating.
If you need to access or alter the doc state, please use to_string instead.
Sourcepub fn insert(&self, pos: usize, s: &str) -> LoroResult<()>
pub fn insert(&self, pos: usize, s: &str) -> LoroResult<()>
Insert a string at the given unicode position.
Sourcepub fn insert_utf8(&self, pos: usize, s: &str) -> LoroResult<()>
pub fn insert_utf8(&self, pos: usize, s: &str) -> LoroResult<()>
Insert a string at the given utf-8 position.
Sourcepub fn insert_utf16(&self, pos: usize, s: &str) -> LoroResult<()>
pub fn insert_utf16(&self, pos: usize, s: &str) -> LoroResult<()>
Insert a string at the given UTF-16 code unit position.
This is useful when working with JavaScript or other UTF-16-based index systems.
Sourcepub fn delete(&self, pos: usize, len: usize) -> LoroResult<()>
pub fn delete(&self, pos: usize, len: usize) -> LoroResult<()>
Delete a range of text at the given unicode position with unicode length.
Sourcepub fn delete_utf8(&self, pos: usize, len: usize) -> LoroResult<()>
pub fn delete_utf8(&self, pos: usize, len: usize) -> LoroResult<()>
Delete a range of text at the given utf-8 position with utf-8 length.
Sourcepub fn delete_utf16(&self, pos: usize, len: usize) -> LoroResult<()>
pub fn delete_utf16(&self, pos: usize, len: usize) -> LoroResult<()>
Delete a range of text at the given UTF-16 code unit position with UTF-16 length.
Sourcepub fn slice(&self, start_index: usize, end_index: usize) -> LoroResult<String>
pub fn slice(&self, start_index: usize, end_index: usize) -> LoroResult<String>
Get a string slice at the given Unicode range
Sourcepub fn slice_utf16(
&self,
start_index: usize,
end_index: usize,
) -> LoroResult<String>
pub fn slice_utf16( &self, start_index: usize, end_index: usize, ) -> LoroResult<String>
Get a string slice using UTF-16 code unit offsets.
Sourcepub fn slice_delta(
&self,
start: usize,
end: usize,
pos_type: PosType,
) -> LoroResult<Vec<TextDelta>>
pub fn slice_delta( &self, start: usize, end: usize, pos_type: PosType, ) -> LoroResult<Vec<TextDelta>>
Get the rich-text delta within a range.
The range is expressed in the coordinate system selected by pos_type:
Unicode scalar indices (PosType::Unicode), UTF-8 bytes, UTF-16 units, etc.
The returned TextDelta segments contain only inserts and preserve the
attributes active inside the slice.
§Errors
Returns LoroError::OutOfBound when the range
exceeds the current text length in the chosen coordinate system, or
LoroError::EndIndexLessThanStartIndex
if end < start.
§Examples
use loro::{LoroDoc, TextDelta};
use loro::cursor::PosType;
let doc = LoroDoc::new();
let text = doc.get_text("text");
text.insert(0, "A😀BC").unwrap();
text.mark(0..2, "bold", true).unwrap(); // A and 😀
let delta = text.slice_delta(1, 3, PosType::Unicode).unwrap();
assert_eq!(delta.len(), 2);
if let TextDelta::Insert { insert, attributes } = &delta[0] {
assert_eq!(insert, "😀");
assert_eq!(attributes.as_ref().unwrap().get("bold").unwrap(), &true.into());
} else {
unreachable!();
}
if let TextDelta::Insert { insert, attributes } = &delta[1] {
assert_eq!(insert, "B");
assert!(attributes.is_none());
} else {
unreachable!();
}Sourcepub fn char_at(&self, pos: usize) -> LoroResult<char>
pub fn char_at(&self, pos: usize) -> LoroResult<char>
Get the characters at given unicode position.
Sourcepub fn splice(&self, pos: usize, len: usize, s: &str) -> LoroResult<String>
pub fn splice(&self, pos: usize, len: usize, s: &str) -> LoroResult<String>
Delete specified character and insert string at the same position at given unicode position.
Sourcepub fn splice_utf16(&self, pos: usize, len: usize, s: &str) -> LoroResult<()>
pub fn splice_utf16(&self, pos: usize, len: usize, s: &str) -> LoroResult<()>
Delete specified range and insert a string at the same UTF-16 position.
Sourcepub fn len_unicode(&self) -> usize
pub fn len_unicode(&self) -> usize
Get the length of the text container in Unicode.
Sourcepub fn update(
&self,
text: &str,
options: UpdateOptions,
) -> Result<(), UpdateTimeoutError>
pub fn update( &self, text: &str, options: UpdateOptions, ) -> Result<(), UpdateTimeoutError>
Update the current text based on the provided text.
It will calculate the minimal difference and apply it to the current text. It uses Myers’ diff algorithm to compute the optimal difference.
This could take a long time for large texts (e.g. > 50_000 characters).
In that case, you should use updateByLine instead.
§Example
use loro::LoroDoc;
let doc = LoroDoc::new();
let text = doc.get_text("text");
text.insert(0, "Hello").unwrap();
text.update("Hello World", Default::default()).unwrap();
assert_eq!(text.to_string(), "Hello World");Sourcepub fn update_by_line(
&self,
text: &str,
options: UpdateOptions,
) -> Result<(), UpdateTimeoutError>
pub fn update_by_line( &self, text: &str, options: UpdateOptions, ) -> Result<(), UpdateTimeoutError>
Update the current text based on the provided text.
This update calculation is line-based, which will be more efficient but less precise.
Sourcepub fn apply_delta(&self, delta: &[TextDelta]) -> LoroResult<()>
pub fn apply_delta(&self, delta: &[TextDelta]) -> LoroResult<()>
Apply a delta to the text container.
Sourcepub fn mark(
&self,
range: Range<usize>,
key: &str,
value: impl Into<LoroValue>,
) -> LoroResult<()>
pub fn mark( &self, range: Range<usize>, key: &str, value: impl Into<LoroValue>, ) -> LoroResult<()>
Mark a range of text with a key-value pair.
The range uses Unicode scalar indices; use [mark_utf8] for UTF-8 byte offsets.
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 textbefore: when inserting text right before the given range, the mark will be expanded to include the inserted textnone: the mark will not be expanded to include the inserted text at the boundariesboth: 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.
Sourcepub fn mark_utf8(
&self,
range: Range<usize>,
key: &str,
value: impl Into<LoroValue>,
) -> LoroResult<()>
pub fn mark_utf8( &self, range: Range<usize>, key: &str, value: impl Into<LoroValue>, ) -> LoroResult<()>
Mark a range of text with a key-value pair using UTF-8 byte offsets.
Sourcepub fn mark_utf16(
&self,
range: Range<usize>,
key: &str,
value: impl Into<LoroValue>,
) -> LoroResult<()>
pub fn mark_utf16( &self, range: Range<usize>, key: &str, value: impl Into<LoroValue>, ) -> LoroResult<()>
Mark a range of text with a key-value pair using UTF-16 code unit offsets.
Sourcepub fn unmark(&self, range: Range<usize>, key: &str) -> LoroResult<()>
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 textbefore: when inserting text right before the given range, the mark will be expanded to include the inserted textnone: the mark will not be expanded to include the inserted text at the boundariesboth: 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.
Sourcepub fn unmark_utf16(&self, range: Range<usize>, key: &str) -> LoroResult<()>
pub fn unmark_utf16(&self, range: Range<usize>, key: &str) -> LoroResult<()>
Unmark a range of text with a key and a value using UTF-16 code unit offsets.
Sourcepub fn to_delta(&self) -> Vec<TextDelta>
pub fn to_delta(&self) -> Vec<TextDelta>
Get the text in Delta format.
§Example
use loro::{LoroDoc, ToJson, ExpandType, TextDelta};
use serde_json::json;
use rustc_hash::FxHashMap;
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(),
vec![
TextDelta::Insert {
insert: "Hello".to_string(),
attributes: Some(FxHashMap::from_iter([("bold".to_string(), true.into())])),
},
TextDelta::Insert {
insert: " world!".to_string(),
attributes: None,
},
]
);
text.unmark(3..5, "bold").unwrap();
assert_eq!(
text.to_delta(),
vec![
TextDelta::Insert {
insert: "Hel".to_string(),
attributes: Some(FxHashMap::from_iter([("bold".to_string(), true.into())])),
},
TextDelta::Insert {
insert: "lo world!".to_string(),
attributes: None,
},
]
);Sourcepub fn get_richtext_value(&self) -> LoroValue
pub fn get_richtext_value(&self) -> LoroValue
Get the rich text value 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.get_richtext_value().to_json_value(),
json!([
{ "insert": "Hello", "attributes": {"bold": true} },
{ "insert": " world!" },
])
);
text.unmark(3..5, "bold").unwrap();
assert_eq!(
text.get_richtext_value().to_json_value(),
json!([
{ "insert": "Hel", "attributes": {"bold": true} },
{ "insert": "lo world!" },
])
);Sourcepub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor>
pub fn get_cursor(&self, pos: usize, side: Side) -> Option<Cursor>
Get the cursor at the given position in the given Unicode 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);Sourcepub fn is_deleted(&self) -> bool
pub fn is_deleted(&self) -> bool
Whether the text container is deleted.
Sourcepub fn convert_pos(
&self,
index: usize,
from: PosType,
to: PosType,
) -> Option<usize>
pub fn convert_pos( &self, index: usize, from: PosType, to: PosType, ) -> Option<usize>
Convert a position between coordinate systems (Unicode, UTF-16, UTF-8 bytes, Event).
Returns None when the position is out of bounds or the conversion isn’t supported.
Sourcepub fn push_str(&self, s: &str) -> LoroResult<()>
pub fn push_str(&self, s: &str) -> LoroResult<()>
Push a string to the end of the text container.
Sourcepub fn get_editor_at_unicode_pos(&self, pos: usize) -> Option<PeerID>
pub fn get_editor_at_unicode_pos(&self, pos: usize) -> Option<PeerID>
Get the editor of the text at the given position.
Returns None if the position is out of bounds or attribution is unavailable.
§Example
use loro::LoroDoc;
let doc = LoroDoc::new();
let t = doc.get_text("t");
t.insert(0, "hi").unwrap();
let who = t.get_editor_at_unicode_pos(0);
assert!(who.is_some());Trait Implementations§
Source§impl ContainerTrait for LoroText
impl ContainerTrait for LoroText
Source§type Handler = TextHandler
type Handler = TextHandler
Source§fn id(&self) -> ContainerID
fn id(&self) -> ContainerID
Source§fn to_container(&self) -> Container
fn to_container(&self) -> Container
Source§fn to_handler(&self) -> Self::Handler
fn to_handler(&self) -> Self::Handler
Source§fn from_handler(handler: Self::Handler) -> Self
fn from_handler(handler: Self::Handler) -> Self
Source§fn is_attached(&self) -> bool
fn is_attached(&self) -> bool
Source§fn get_attached(&self) -> Option<Self>
fn get_attached(&self) -> Option<Self>
Source§fn try_from_container(container: Container) -> Option<Self>
fn try_from_container(container: Container) -> Option<Self>
Source§fn is_deleted(&self) -> bool
fn is_deleted(&self) -> bool
Source§fn subscribe(&self, callback: Subscriber) -> Option<Subscription>
fn subscribe(&self, callback: Subscriber) -> Option<Subscription>
Auto Trait Implementations§
impl Freeze for LoroText
impl RefUnwindSafe for LoroText
impl Send for LoroText
impl Sync for LoroText
impl Unpin for LoroText
impl UnwindSafe for LoroText
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moreSource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);