Struct Document

Source
pub struct Document<'a> { /* private fields */ }

Implementations§

Source§

impl<'a> Document<'a>

Source

pub fn new() -> Self

Creates an empty ‘Document’.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello\n world!");
let mut lines = doc.lines();
let empty_rope = Document::new();
assert_eq!(empty_rope.len_lines(), 2);
assert_eq!(empty_rope.len_chars(), 0);
assert_eq!(empty_rope.len_bytes(), 0);
assert!(empty_rope.is_empty());
Source

pub fn from_str(text: &str) -> Self

Creates a ‘Document’ from a string slice.

This is a convience constructor.

Source

pub fn from_reader<R: Read>(reader: R) -> Result<Self>

Creates a new Document from a reader.

§Errors
  • If the reader returns an error, from_reader stops and returns that error.
  • If non-utf8 data is encountered, an IO error with kind InvalidData is returned.
  • If the PathBuf can’t be identified as a file, an IO error with with kind ‘NotFound’ is returned.
Source

pub fn write_file<T: Write>(&self, writer: T) -> Result<()>

Writes the contents of the underlying Rope to a writer.

When more precise control over IO behavior, buffering, etc. is desired, you should handle IO yourself and use the Chunks iterator to iterate through the Rope’s contents.

Runs in O(N) time.

§Errors
  • If the writer returns an error, write_file stops and returns that error.

Note: some data may have been written even if an error is returned.

Source

pub fn len_bytes(&self) -> usize

Total number of bytes in the underlying Rope.

Source

pub fn len_chars(&self) -> usize

Total number of chars in the underlying Rope.

Source

pub fn len_lines(&self) -> usize

Total number of lines in the underlying Rope.

Source

pub fn is_empty(&self) -> bool

Returns true if the rope contains no elements.

§Example
use tui_document::Document;

let doc = Document::default();
assert_eq!(doc.is_empty(), true);
Source

pub fn chars_at<'chr>(&'chr self, pos: usize) -> Chars<'chr>

An iterator over the underlying Rope’s chars starting at a given position.

§Example
use tui_document::Document;

let doc = Document::from_str("hi");
let mut iter = doc.chars_at(0);
assert_eq!(iter.next(), Some('h'));
assert_eq!(iter.next(), Some('i'));
assert_eq!(iter.next(), None);
Source

pub fn lines_at<'lines>(&'lines self, row: usize) -> Lines<'lines>

An iterator over a Rope’s lines at a given position.

See ‘lines’ for more details.

Runs in O(log N) time.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello\n world!");
let mut lines = doc.lines_at(1);
assert_eq!(lines.next().unwrap().as_str(), Some(" world!"));
assert_eq!(lines.next(), None);
Source

pub fn lines<'lines>(&'lines self) -> Lines<'lines>

An iterator over a Rope’s lines.

The returned lines include the line break at the end, if any.

A rope will always start with a signle line, even if a line break is not present.

The last line is returned even if blank, in which case it is returned as an empty slice.

Runs in O(log N) time.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello\n world!");
let mut lines = doc.lines();

assert_eq!(lines.next().unwrap().as_str(), Some("Hello\n"));
assert_eq!(lines.next().unwrap().as_str(), Some(" world!"));
assert_eq!(lines.next(), None);
Source

pub fn chunks<'chunks>(&'chunks self) -> Chunks<'chunks>

An iterator over a Rope’s contiguous str chunks.

Internally, each Rope stores text as a segemented collection of utf8 strings. This iterator iterates over those segments, returning a &str slice for each one. It is useful for situations such as:

  • Writing a rope’s utf8 text data to disk (but see write_to() for a convenience function that does this for casual use-cases).
  • Streaming a rope’s text data somewhere.
  • Saving a rope to a non-utf8 encoding, doing the encoding conversion incrementally as you go.
  • Writing custom iterators over a rope’s text data.

There are precisely two guarantees about the yielded chunks:

  • All non-empty chunks are yielded, and they are yielded in order.
  • CRLF pairs are never split across chunks.

There are no guarantees about the size of yielded chunks, and except for CRLF pairs and being valid str slices there are no guarantees about where the chunks are split. For example, they may be zero-sized, they don’t necessarily align with line breaks, etc.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello world!");
let mut chunk = doc.chunks();

assert_eq!(chunk.next(), Some("Hello world!"));
assert_eq!(chunk.next(), None);
Source

pub fn visible_slice(&self) -> Option<RopeSlice<'_>>

Gets an immutable slice of the underlying Rope, using char indices.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello\nworld!");
let expected = doc.visible_slice().unwrap().as_str();
assert_eq!(expected, Some("Hello\nworld!"));
Source

pub fn slice<R>(&self, char_range: R) -> Option<RopeSlice<'_>>
where R: RangeBounds<usize>,

Gets an immutable slice of the underlying Rope, based on the visible range of the document.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello\nworld!");
let expected = doc.slice(..6).unwrap().as_str();
assert_eq!(expected, Some("Hello\n"));
Source

pub fn cursor_to_char(&self, row: usize, col: usize) -> usize

Convert cursor position to a character position in the rope.

§Example
use tui_document::Document;

let doc = Document::from_str("Hello \nworld!");

assert_eq!(doc.cursor_to_char(0, 1), 1);
assert_eq!(doc.cursor_to_char(1, 1), 8);
Source

pub fn insert_char( &mut self, input: char, row: usize, col: usize, ) -> RopeyResult<()>

Insert a single character at the current cursor position.

Does not panic.

§Example
use tui_document::Document;

let mut doc = Document::from_str("ab");
doc.insert_char('c', 0, 2);
let mut iter = doc.chars_at(2);
assert_eq!(iter.next(), Some('c'));
Source

pub fn insert<RefStr: AsRef<str>>( &mut self, row: usize, col: usize, input: RefStr, ) -> RopeyResult<()>

Insert a string at the current cursor position.

Does not panic.

§Example
use tui_document::Document;

let mut doc = Document::from_str("Hello beautiful world!");
doc.insert(0, 22, "\nGoodbye cruel world!");

let expected = doc.slice(22..).unwrap().as_str();
assert_eq!(expected, Some("Goodbye cruel world!"));
Source

pub fn remove<R>(&mut self, char_range: R) -> RopeyResult<()>
where R: RangeBounds<usize>,

Removes the text in the given char index range.

Uses range syntax, e.g. 2..7, 2.., etc. The range is in char indices.

Runs in O(M + log N) time, where N is the length of the Rope and M is the length of the range being removed.

§Example
use tui_document::Document;
let mut doc = Document::from_str( "Hello world!");
doc.remove(5..);
let expected = doc.slice(..).unwrap().as_str();

assert_eq!(expected, Some("Hello"));
Source

pub fn block(self, block: Block<'a>) -> Self

Surrounds the Document widget with a Block.

§Example
use ratatui::widgets::{Block, Paragraph};
use tui_document::Document;

let doc = Document::from_str("Hello, world!").block(Block::bordered().title("Document"));
Source

pub const fn wrap(self, wrap: Wrap) -> Self

Sets the wrapping configuration for the widget.

See Wrap for more information on the different options.

§Example
use ratatui::widgets::{Paragraph, Wrap};
use tui_document::Document;

let doc = Document::from_str("Hello, world!").wrap(Wrap { trim: true });
Source

pub const fn alignment(self, alignment: Alignment) -> Self

Set the text alignment for the given widget.

The alignment is a variant of the Ratatui Alignment enum which can be one of Left, Right, or Center. If no alignment is specified, the text in a paragraph will be left-aligned.

§Example
use ratatui::{layout::Alignment, widgets::Paragraph};

let paragraph = Paragraph::new("Hello World").alignment(Alignment::Center);
Source

pub fn set_style<S: Into<Style>>(self, style: S) -> Self

Sets the style of the entire widget.

style accepts any type that is convertible to Style (e.g. Style, Color , or your own type that implements Into<Style>).

This applies to the entire widget, including the block if one is present. Any style set on the block or text will be added to this style.

§Example
use ratatui::style::{Style, Stylize};
use tui_document::Document;

let doc = Document::from_str("Hello, world!").set_style(Style::new().red().on_white());
Source

pub fn name<S: AsRef<str>>(&mut self, path: S)

Set the name of the document.

Use rename to replace the name of the document.

§Example
use tui_document::Document;

let mut doc = Document::from_str("Hello, world!");
doc.name("example.txt");
Source

pub fn rename<S: AsRef<str>>(&mut self, path: S)

Rename the document.

§Example
use tui_document::Document;

let mut doc = Document::from_str("Hello, world!");
doc.rename("rename_example.txt");

Trait Implementations§

Source§

impl<'a> Clone for Document<'_>

Source§

fn clone(&self) -> Self

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<'a> Debug for Document<'a>

Source§

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

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

impl<'a> Default for Document<'_>

Source§

fn default() -> Self

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

impl<'a, Iter, S> From<Iter> for Document<'_>
where Iter: Iterator<Item = S>, S: ToString,

Source§

fn from(value: Iter) -> Self

use tui_document::Document;

let vec_str = vec!["test1", "test2",];
let char_arr = ['a', 'b', 'c'];
let str_arr = ["apple", "banana", "mango"];
let rope = ropey::Rope::from_str("apple\nbanana");

let from_rope = Document::from(rope.chunks());
let from_str_arr = Document::from(str_arr.iter());
let from_char_arr = Document::from(char_arr.iter());
let from_vec = Document::from(vec_str.iter());
let from_string = Document::from(String::from("hello").chars());
let from_str = Document::from("hello".chars());
Source§

impl<'a> Ord for Document<'_>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'a> PartialEq for Document<'a>

Source§

fn eq(&self, other: &Document<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> PartialOrd for Document<'a>

Source§

fn partial_cmp(&self, other: &Document<'_>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a> Widget for &Document<'_>

Source§

fn render(self, area: Rect, buf: &mut Buffer)

Draws the current state of the widget in the given buffer. That is the only method required to implement a custom widget.
Source§

impl<'a> Widget for Document<'_>

Source§

fn render(self, area: Rect, buf: &mut Buffer)

Draws the current state of the widget in the given buffer. That is the only method required to implement a custom widget.
Source§

impl<'a> Eq for Document<'a>

Source§

impl<'a> StructuralPartialEq for Document<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Document<'a>

§

impl<'a> RefUnwindSafe for Document<'a>

§

impl<'a> Send for Document<'a>

§

impl<'a> Sync for Document<'a>

§

impl<'a> Unpin for Document<'a>

§

impl<'a> UnwindSafe for Document<'a>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> ToOwned for T
where T: Clone,

Source§

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>,

Source§

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>,

Source§

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.