Simple yet powerful multi-line text editor widget for tui-rs and ratatui

Overview

tui-textarea

crate docs CI

tui-textarea is a simple yet powerful text editor widget like <textarea> in HTML for tui-rs and ratatui. Multi-line text editor can be easily put as part of your TUI application.

Features:

  • Multi-line text editor widget with basic operations (insert/delete characters, auto scrolling, ...)
  • Emacs-like shortcuts (C-n/C-p/C-f/C-b, M-f/M-b, C-a/C-e, C-h/C-d, C-k, M-</M->, ...)
  • Undo/Redo
  • Line number
  • Cursor line highlight
  • Search with regular expressions
  • Mouse scrolling
  • Yank support. Paste text deleted with C-k, C-j, ...
  • Backend agnostic. crossterm, termion, and your own backend are all supported
  • Multiple textarea widgets in the same screen
  • Support both tui-rs (the original) and ratatui (the fork by community)

Documentation

Examples

Running cargo run --example in this repository can demonstrate usage of tui-textarea.

minimal

cargo run --example minimal

Minimal usage with crossterm support.

minimal example

editor

cargo run --example editor --features search file.txt

Simple text editor to edit multiple files.

editor example

single_line

cargo run --example single_line

Single-line input form with float number validation.

single line example

split

cargo run --example split

Two split textareas in a screen and switch them. An example for multiple textarea instances.

multiple textareas example

termion

cargo run --example termion --features=termion

Minimal usage with termion support.

variable

cargo run --example variable

Simple textarea with variable height following the number of lines.

modal

cargo run --example modal

Simple modal text editor like vi.

Examples for ratatui support

All above examples uses tui-rs, but some examples provide ratatui version. Try ratatui_ prefix. In these cases, you need to specify features to use ratatui and --no-default-features flag explicitly.

# ratatui version of `minimal` example
cargo run --example ratatui_minimal --no-default-features --features=ratatui-crossterm

# ratatui version of `editor` example
cargo run --example ratatui_editor --no-default-features --features=ratatui-crossterm,search file.txt

# ratatui version of `termion` example
cargo run --example ratatui_termion --no-default-features --features=ratatui-termion

Installation

Add tui-textarea crate to dependencies in your Cargo.toml. This enables crossterm backend support by default.

[dependencies]
tui = "*"
tui-textarea = "*"

If you need text search with regular expressions, enable search feature. It adds regex crate crate as dependency.

[dependencies]
tui = "*"
tui-textarea = { version = "*", features = ["search"] }

If you're using tui-rs with termion, enable termion feature instead of crossterm feature.

[dependencies]
tui = { version = "*", default-features = false, features = ["termion"] }
tui-textarea = { version = "*", default-features = false, features = ["termion"] }

If you're using ratatui instead of tui-rs, you need to enable features for using ratatui crate. The following table shows feature names corresponding to the dependencies.

crossterm termion Your own backend
tui-rs crossterm (enabled by default) termion your-backend
ratatui ratatui-crossterm ratatui-termion ratatui-your-backend

For example, when you want to use the combination of ratatui and crossterm,

[dependencies]
ratatui = "*"
tui-textarea = { version = "*", features = ["ratatui-crossterm"], default-features=false }

Note that tui-rs support and ratatui support are exclusive. When you use ratatui support, you must disable tui-rs support by default-features=false.

In addition to above dependencies, you also need to install crossterm or termion to initialize your application and to receive key inputs. Note that version of crossterm crate is different between tui-rs and ratatui. Please select the correct version.

Minimal Usage

use tui_textarea::TextArea;
use crossterm::event::{Event, read};

let mut term = tui::Terminal::new(...);

// Create an empty `TextArea` instance which manages the editor state
let mut textarea = TextArea::default();

// Event loop
loop {
    term.draw(|f| {
        // Get `tui::layout::Rect` where the editor should be rendered
        let rect = ...;
        // `TextArea::widget` builds a widget to render the editor with tui
        let widget = textarea.widget();
        // Render the widget in terminal screen
        f.render_widget(widget, rect);
    })?;

    if let Event::Key(key) = read()? {
        // Your own key mapping to break the event loop
        if key.code == KeyCode::Esc {
            break;
        }
        // `TextArea::input` can directly handle key events from backends and update the editor state
        textarea.input(key);
    }
}

// Get text lines as `&[String]`
println!("Lines: {:?}", textarea.lines());

TextArea is an instance to manage the editor state. By default, it disables line numbers and highlights cursor line with underline.

TextArea::widget() builds a widget to render the current state of the editor. Create the widget and render it on each tick of event loop.

TextArea::input() receives inputs from tui backends. The method can take key events from backends such as crossterm::event::KeyEvent or termion::event::Key directly if the features are enabled. The method handles default key mappings as well.

Default key mappings are as follows:

Mappings Description
Ctrl+H, Backspace Delete one character before cursor
Ctrl+D, Delete Delete one character next to cursor
Ctrl+M, Enter Insert newline
Ctrl+K Delete from cursor until the end of line
Ctrl+J Delete from cursor until the head of line
Ctrl+W, Alt+H, Alt+Backspace Delete one word before cursor
Alt+D, Alt+Delete Delete one word next to cursor
Ctrl+U Undo
Ctrl+R Redo
Ctrl+Y Paste yanked text
Ctrl+F, Move cursor forward by one character
Ctrl+B, Move cursor backward by one character
Ctrl+P, Move cursor up by one line
Ctrl+N, Move cursor down by one line
Alt+F, Ctrl+→ Move cursor forward by word
Atl+B, Ctrl+← Move cursor backward by word
Alt+], Alt+P, Ctrl+↑ Move cursor up by paragraph
Alt+[, Alt+N, Ctrl+↓ Move cursor down by paragraph
Ctrl+E, End, Ctrl+Alt+F, Ctrl+Alt+→ Move cursor to the end of line
Ctrl+A, Home, Ctrl+Alt+B, Ctrl+Alt+← Move cursor to the head of line
Alt+<, Ctrl+Alt+P, Ctrl+Alt+↑ Move cursor to top of lines
Alt+>, Ctrl+Alt+N, Ctrl+Alt+↓ Move cursor to bottom of lines
Ctrl+V, PageDown Scroll down by page
Alt+V, PageUp Scroll up by page

Deleting multiple characters at once saves the deleted text to yank buffer. It can be pasted with Ctrl+Y later.

If you don't want to use default key mappings, see the 'Advanced Usage' section.

Basic Usage

Create TextArea instance with text

TextArea implements Default trait to create an editor instance with an empty text.

let mut textarea = TextArea::default();

TextArea::new() creates an editor instance with text lines passed as Vec<String>.

let mut lines: Vec<String> = ...;
let mut textarea = TextArea::new(lines);

TextArea implements From<impl Iterator<Item=impl Into<String>>>. TextArea::from() can create an editor instance from any iterators whose elements can be converted to String.

// Create `TextArea` from from `[&str]`
let mut textarea = TextArea::from([
    "this is first line",
    "this is second line",
    "this is third line",
]);

// Create `TextArea` from `String`
let mut text: String = ...;
let mut textarea = TextARea::from(text.lines());

TextArea also implements FromIterator<impl Into<String>>. Iterator::collect() can collect strings as an editor instance. This allows to create TextArea reading lines from file efficiently using io::BufReader.

let file = fs::File::open(path)?;
let mut textarea: TextArea = io::BufReader::new(file).lines().collect::<io::Result<_>>()?;

Get text contents from TextArea

TextArea::lines() returns text lines as &[String]. It borrows text contents temporarily.

let text: String = textarea.lines().join("\n");

TextArea::into_lines() moves TextArea instance into text lines as Vec<String>. This can retrieve the text contents without any copy.

let lines: Vec<String> = textarea.into_lines();

Note that TextArea always contains at least one line. For example, an empty text means one empty line. This is because any text file must end with newline.

let textarea = TextArea::default();
assert_eq!(textarea.into_lines(), [""]);

Show line number

By default, TextArea does now show line numbers. To enable, set a style for rendering line numbers by TextArea::set_line_number_style(). For example, the following renders line numbers in dark gray background color.

use tui::style::{Style, Color};

let style = Style::default().bg(Color::DarkGray);
textarea.set_line_number_style(style);

Configure cursor line style

By default, TextArea renders the line at cursor with underline so that users can easily notice where the current line is. To change the style of cursor line, use TextArea::set_cursor_line_style(). For example, the following styles the cursor line with bold text.

use tui::style::{Style, Modifier};

let style = Style::default().add_modifier(Modifier::BOLD);
textarea.set_line_number_style(style);

To disable cursor line style, set the default style as follows:

use tui::style::{Style, Modifier};

textarea.set_line_number_style(Style::default());

Configure tab width

The default tab width is 4. To change it, use TextArea::set_tab_length() method. The following sets 2 to tab width. Typing tab key inserts 2 spaces.

textarea.set_tab_length(2);

Configure max history size

By default, past 50 modifications are stored as edit history. The history is used for undo/redo. To change how many past edits are remembered, use TextArea::set_max_histories() method. The following remembers past 1000 changes.

textarea.set_max_histories(1000);

Setting 0 disables undo/redo.

textarea.set_max_histories(0);

Text search with regular expressions

To search text in textarea, set a regular expression pattern with TextArea::set_search_pattern() and move cursor with TextArea::search_forward() for forward search or TextArea::search_back() backward search. The regular expression is handled by regex crate.

Text search wraps around the textarea. When searching forward and no match found until the end of textarea, it searches the pattern from start of the file.

Matches are highlighted in textarea. The text style to highlight matches can be changed with TextArea::set_search_style(). Setting an empty string to TextArea::set_search_pattern() stops the text search.

// Start text search matching to "hello" or "hi". This highlights matches in textarea but does not move cursor.
// `regex::Error` is returned on invalid pattern.
textarea.set_search_pattern("(hello|hi)").unwrap();

textarea.search_forward(false); // Move cursor to the next match
textarea.search_back(false);    // Move cursor to the previous match

// Setting empty string stops the search
textarea.set_search_pattern("").unwrap();

No UI is provided for text search. You need to provide your own UI to input search query. It is recommended to use another TextArea for search form. To build a single-line input form, see 'Single-line input like <input> in HTML' in 'Advanced Usage' section below.

editor example implements a text search with search form built on TextArea. See the implementation for working example.

To use text search, search feature needs to be enabled in your Cargo.toml. It is disabled by default to avoid depending on regex crate until it is necessary.

tui-textarea = { version = "*", features = ["search"] }

Advanced Usage

Single-line input like <input> in HTML

To use TextArea for single-line input widget like <input> in HTML, ignore all key mappings which inserts newline.

use crossterm::event::{Event, read};
use tui_textarea::{Input, Key};

let default_text: &str = ...;
let default_text = default_text.replace(&['\n', '\r'], " "); // Ensure no new line is contained
let mut textarea = TextArea::new(vec![default_text]);

// Event loop
loop {
    // ...

    // Using `Input` is not mandatory, but it's useful for pattern match
    // Ignore Ctrl+m and Enter. Otherwise handle keys as usual
    match read()?.into() {
        Input { key: Key::Char('m'), ctrl: true, alt: false }
        | Input { key: Key::Enter, .. } => continue,
        input => {
            textarea.input(key);
        }
    }
}

let text = textarea.into_lines().remove(0); // Get input text

See single_line example for working example.

Define your own key mappings

All editor operations are defined as public methods of TextArea. To move cursor, use tui_textarea::CursorMove to notify how to move the cursor.

Method Operation
textarea.delete_char() Delete one character before cursor
textarea.delete_next_char() Delete one character next to cursor
textarea.insert_newline() Insert newline
textarea.delete_line_by_end() Delete from cursor until the end of line
textarea.delete_line_by_head() Delete from cursor until the head of line
textarea.delete_word() Delete one word before cursor
textarea.delete_next_word() Delete one word next to cursor
textarea.undo() Undo
textarea.redo() Redo
textarea.paste() Paste yanked text
textarea.move_cursor(CursorMove::Forward) Move cursor forward by one character
textarea.move_cursor(CursorMove::Back) Move cursor backward by one character
textarea.move_cursor(CursorMove::Up) Move cursor up by one line
textarea.move_cursor(CursorMove::Down) Move cursor down by one line
textarea.move_cursor(CursorMove::WordForward) Move cursor forward by word
textarea.move_cursor(CursorMove::WordBack) Move cursor backward by word
textarea.move_cursor(CursorMove::ParagraphForward) Move cursor up by paragraph
textarea.move_cursor(CursorMove::ParagraphBack) Move cursor down by paragraph
textarea.move_cursor(CursorMove::End) Move cursor to the end of line
textarea.move_cursor(CursorMove::Head) Move cursor to the head of line
textarea.move_cursor(CursorMove::Top) Move cursor to top of lines
textarea.move_cursor(CursorMove::Bottom) Move cursor to bottom of lines
textarea.move_cursor(CursorMove::Jump(row, col)) Move cursor to (row, col) position
textarea.move_cursor(CursorMove::InViewport) Move cursor to stay in the viewport
textarea.set_search_pattern(pattern) Set a pattern for text search
textarea.search_forward(match_cursor) Move cursor to next match of text search
textarea.search_back(match_cursor) Move cursor to previous match of text search
textarea.scroll(Scrolling::PageDown) Scroll down the viewport by page
textarea.scroll(Scrolling::PageUp) Scroll up the viewport by page
textarea.scroll(Scrolling::HalfPageDown) Scroll down the viewport by half-page
textarea.scroll(Scrolling::HalfPageUp) Scroll up the viewport by half-page
textarea.scroll((row, col)) Scroll down the viewport to (row, col) position

To define your own key mappings, simply call the above methods in your code instead of TextArea::input() method. The following example defines modal key mappings like Vim.

use crossterm::event::{Event, read};
use tui_textarea::{Input, Key, CursorMove, Scrolling};

let mut textarea = ...;

enum Mode {
    Normal,
    Insert,
}

let mut mode = Mode::Normal;

// Event loop
loop {
    // ...

    match mode {
        Mode::Normal => match read()?.into() {
            Input { key: Key::Char('h'), .. } => textarea.move_cursor(CursorMove::Back),
            Input { key: Key::Char('j'), .. } => textarea.move_cursor(CursorMove::Down),
            Input { key: Key::Char('k'), .. } => textarea.move_cursor(CursorMove::Up),
            Input { key: Key::Char('l'), .. } => textarea.move_cursor(CursorMove::Forward),
            Input { key: Key::Char('i'), .. } => mode = Mode::Insert, // Enter insert mode
            // ...Add more mappings
            _ => {},
        },
        Mode::Insert => match read()?.into() {
            Input { key: Key::Esc, .. } => {
                mode = Mode::Normal; // Back to normal mode with Esc or Ctrl+C
            }
            input => {
                textarea.input(input); // Use default key mappings in insert mode
            }
        },
    }
}

See modal example for working example. It implements more Vim-like key mappings.

If you don't want to use default key mappings, TextArea::input_without_shortcuts() method can be used instead of TextArea::input(). The method only handles very basic operations such as inserting/deleting single characters, tabs, newlines.

match read()?.into() {
    // Handle your own key mappings here
    // ...
    input => textarea.input_without_shortcuts(input),
}

Use your own backend

tui-rs allows to make your own backend by implementing tui::backend::Backend trait. tui-textarea also supports it. In this case, please use your-backend feature for tui-rs or ratatui-your-backend feature for ratatui. They avoid adding backend crates (crossterm and termion) since you're using your own backend.

[dependencies]
tui = { version = "*", default-features = false }
tui-textarea = { version = "*", default-features = false, features = ["your-backend"] }

tui_textarea::Input is a type for backend-agnostic key input. What you need to do is converting key event in your own backend into the tui_textarea::Input instance. Then TextArea::input() method can handle the input as other backend.

In the following example, let's say your_backend::KeyDown is a key event type for your backend and your_backend::read_next_key() returns the next key event.

// In your backend implementation

pub enum KeyDown {
    Char(char),
    BS,
    Del,
    Esc,
    // ...
}

// Return tuple of (key, ctrlkey, altkey)
pub fn read_next_key() -> (KeyDown, bool, bool) {
    // ...
}

Then you can implement the logic to convert your_backend::KeyDown value into tui_textarea::Input value.

use tui_textarea::{Input, Key};
use your_backend::KeyDown;

fn keydown_to_input(key: KeyDown, ctrl: bool, alt: bool) -> Input {
    match key {
        KeyDown::Char(c) => Input { key: Key::Char(c), ctrl, alt },
        KeyDown::BS => Input { key: Key::Backspace, ctrl, alt },
        KeyDown::Del => Input { key: Key::Delete, ctrl, alt },
        KeyDown::Esc => Input { key: Key::Esc, ctrl, alt },
        // ...
        _ => Input::default(),
    }
}

For the keys which are not handled by tui-textarea, tui_textarea::Input::default() is available. It returns 'null' key. An editor will do nothing with the key.

Finally, convert your own backend's key input type into tui_textarea::Input and pass it to TextArea::input().

let mut textarea = ...;

// Event loop
loop {
    // ...

    let (key, ctrl, alt) = your_backend::read_next_key();
    if key == your_backend::KeyDown::Esc {
        break; // For example, quit your app on pressing Esc
    }
    textarea.input(keydown_to_input(key, ctrl, alt));
}

Put multiple TextArea instances in screen

You don't need to do anything special. Create multiple TextArea instances and render widgets built from each instances.

The following is an example to put two textarea widgets in application and manage the focus.

use tui_textarea::{TextArea, Input, Key};
use crossterm::event::{Event, read};

let editors = &mut [
    TextArea::default(),
    TextArea::default(),
];

let mut focused = 0;

loop {
    term.draw(|f| {
        let rects = ...;

        for (editor, rect) in editors.iter_mut().zip(rects.into_iter()) {
            let widget = editor.widget();
            f.render_widget(widget, rect);
        }
    })?;

    match read()?.into() {
        // Switch focused textarea by Ctrl+S
        Input { key: Key::Char('s'), ctrl: true, .. } => focused = (focused + 1) % 2;
        // Handle input by the focused editor
        input => editors[focused].input(input),
    }
}

See split example and editor example for working example.

Minimum Supported Rust Version

MSRV of this crate is depending on tui crate. Currently MSRV is 1.56.1.

Versioning

This crate is not reaching v1.0.0 yet. There is no plan to bump the major version for now. Current versioning policy is as follows:

  • Major: Fixed to 0
  • Minor: Bump on breaking change
  • Patch: Bump on new feature or bug fix

Contributing to tui-textarea

This project is developed on GitHub.

For feature requests or bug reports, please create an issue. For submitting patches, please create a pull request.

Please see CONTRIBUTING.md before making a PR.

License

tui-textarea is distributed under The MIT License.

Comments
  • ratatui-minimal has strange behavior

    ratatui-minimal has strange behavior

    • sometimes when started there is an extra blank line and the cursor is positioned on the second line
    • if I type a single character it is repeated in the widget

    image

    Here I simply ran it and typed hello world

    It only fails on windows, works on linux (WSL unbuntu 20)

    BTW - minimal (with tui) works fine

    opened by pm100 8
  • Ratatui support

    Ratatui support

    With the release of ratatui, it would be nice to have a feature flag or release of this crate that supports it!

    https://github.com/tui-rs-revival/ratatui/releases

    enhancement 
    opened by dzfrias 5
  • fix windows double character

    fix windows double character

    fix for https://github.com/rhysd/tui-textarea/issues/14

    a change in crossterm 0.26 (https://github.com/crossterm-rs/crossterm/pull/745) causes key release event to be generated on windows. The input handler of textarea was treating those as additional keystrokes. The same bug was apparent in all the samples

    Note I also added some logging. I did not remove it as the plumbing is useful to have (I think)

    opened by pm100 4
  • Change cursor shape

    Change cursor shape

    I've been trying to change the cursor style to a blinking bar for an editor program, but it seems like there isn't a way to do this beyond changing cursor color and blink rate.

    I've tried doing so through crossterm but it seems like this is ignored in the rendering of the textarea.

    //main.rs
    ...
    use crossterm::cursor::SetCursorStyle;
    use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
    use crossterm::terminal::{
        disable_raw_mode, enable_raw_mode, is_raw_mode_enabled, EnterAlternateScreen,
        LeaveAlternateScreen,
    };
    ...
        crossterm::execute!(term.backend_mut(), SetCursorStyle::SteadyBar).unwrap();
    
        // Main render loop
        let mutex = Mutex::new(());
        while running.load(Ordering::SeqCst) {
            term.draw(|f| {
                let buffer = buffer.lock().unwrap();
                let buffer_widget = buffer.textarea.widget();
                let rectangle = Rect::new(0, 0, f.size().width, f.size().height);
                f.render_widget(buffer_widget, rectangle);
            })
            .unwrap();
    
            // TUI refresh rate
            let guard = mutex.lock().unwrap();
            _ = condvar.wait_timeout(guard, Duration::from_millis(50));
        }
    ...
    

    And my implementation of Buffer which creates the TextArea

    ...
    impl Buffer {
        pub fn new(config: &Config) -> io::Result<Self> {
            // TODO: Generate path
            let path = config.output_name.clone();
    
            let file_already_existed = path.exists();
            let mut textarea = if let Ok(md) = path.metadata() {
                if md.is_file() {
                    let contents = fs::read_to_string(path.clone())?;
                    TextArea::from(contents.lines())
                } else {
                    // Path exists but is not a file
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        format!("{:?} exists but is not a file", path),
                    ));
                }
            } else {
                TextArea::default() // File does not exist
            };
            textarea.set_hard_tab_indent(config.use_hard_indent);
            // Remove default underline style from active line
            textarea.set_cursor_line_style(Style::default());
            Ok(Self {
                textarea,
                path,
                modified: false,
                file_already_existed,
            })
        }
        ...
    

    I've tried calling textarea.set_cursor_style from here (https://docs.rs/tui-textarea/latest/tui_textarea/struct.TextArea.html#method.set_cursor_style), but the Style struct from the tui crate just doesn't seem to support a way to change the cursor shape.

    Is this a limitation of the tui crate? Is there a way I can change my cursor shape?

    opened by brooksvb 2
  • the trait `From<KeyEvent>` is not implemented for `tui_textarea::Input`

    the trait `From` is not implemented for `tui_textarea::Input`

    Hi, after update the crossterm crate to version 0.26.0, I started getting this error message at text_area.input():

    the trait `From<KeyEvent>` is not implemented for `tui_textarea::Input`
    

    My code:

      pub fn handle(&mut self, key_event: KeyEvent) {
            match key_event {
                KeyEvent {
                    code: KeyCode::Esc | KeyCode::Enter | KeyCode::Down | KeyCode::Up,
                    ..
                } => self.on_focus = false,
                input => {
                    self.text_area.input(input);
                    self.buffer = self.text_area.lines()[0].clone()
                }
            }
        }
    

    the KeyEvent is from crossterm::event::KeyEvent It Cargo.toml:

    [dependencies]
    # another non-TUI related deps
    tui = "0.19.0" # uses crossterm as default
    crossterm = "0.26.0"
    tui-textarea = { version = "0.2.0", features = ["crossterm"] }
    # another non-TUI related deps
    

    It's like the code can't read the impl From<KeyEvent> for Input int the input.rs class

    opened by rvigo 2
  • Feature request: Changing cursor shape

    Feature request: Changing cursor shape

    First let me tell, this crate is amazing! It completely suits me as it is for now, but in the future it might be helpful to be able to change cursor shape (i want to make a vim-like text area in my project at some point, and changing cursor shape between normal mode (block) and insert mode (line) would make it way more user friendly)

    Thanks again for making this crate!

    enhancement 
    opened by JayJaySea 2
  • Compiler error: Can't read a crossterm event and pass into input function

    Compiler error: Can't read a crossterm event and pass into input function

    image

    tui = { version = "*", features = ["crossterm"] }
    tui-textarea = { version = "*", features = ["crossterm"] }
    
    opened by Gnarus-G 1
  • Panic when max history is set to 0

    Panic when max history is set to 0

    If set the maximum amount of history to 0, then according to the documentation, undo / redo should be disabled. Actually there is a panic at change of the text in TextArea. This is because the value in history.rs:115 is out of range. I consider it necessary to add an additional condition for checking compliance with the boundaries

    bug 
    opened by Volkalex28 1
  • placeholder text support

    placeholder text support

    in order to cleanly integrate tui-textarea into another tool (gitui https://github.com/extrawurst/gitui) I need this feature.

    It is like the html input tag placeholder feature, text is displayed dimmed in the input box as a hint of what to enter. Once text is entered the hint is removed

    placeholder

    I had to slightly modify how the text and its surrounding block are displayed. it is very tricky to get precise control. over the text style of the paragraph and its containing block otherwise. I placed a link to the discussion about this topic with ratatui team. https://github.com/tui-rs-revival/ratatui/issues/144

    I added 2 samples of a popup dialog with the new feature. I also added it to the single_line sample as that seemed a good fit

    opened by pm100 0
  • Hard tabs are not rendered

    Hard tabs are not rendered

    Repro

    Save the following code as foo.go.

    package main
    
    func main() {
    	println("hello")
    	if true {
    		println("true")
    	}
    }
    

    Then run cargo run --example editor foo.go

    Expected behavior

    Hard tabs are rendered as tabs.

    package main
    
    func main() {
        println("hello")
        if true {
            println("true")
        }
    }
    

    Actual behavior

    Hard tabs are not rendered.

    package main
    
    func main() {
    println("hello")
    if true {
    println("true")
    }
    }
    

    Environment

    • iTerm2
    • tui-textarea: v0.1.0
    • tui: v0.18.0
    • Backend: crossterm
    • Rust: 1.60.0
    bug 
    opened by rhysd 0
  • Derive debug for Textarea

    Derive debug for Textarea

    Hello. I think it will be awesome if you can derive the debug trait. It makes it impossible to embed the textarea in any structure that has the debug trait, which is not nice for debugging purposes. Regards

    opened by danielo515 0
  • 'placeholder' feature request

    'placeholder' feature request

    Can I ask you to look at this PR. I want to plug this library into gitui, but I am blocked waiting for this

    It adds support for hint text when the text box is empty - like placeholder in the html textbox widget

    opened by pm100 0
  • Widget not implemented?

    Widget not implemented?

    Anyone have any idea how to fix this?

    error[E0277]: the trait bound `impl ratatui::widgets::Widget + '_: Widget` is not satisfied
      --> src\components\text_entry.rs:43:21
       |
    43 |     f.render_widget(tw, rect);
       |       ------------- ^^ the trait `Widget` is not implemented for `impl ratatui::widgets::Widget + '_`
       |       |
       |       required by a bound introduced by this call
       |
       = help: the following other types implement trait `Widget`:
                 BarChart<'a>
                 Canvas<'a, F>
                 Chart<'a>
                 Gauge<'a>
                 LineGauge<'a>
                 List<'a>
                 Paragraph<'a>
                 Sparkline<'a>
               and 7 others
    note: required by a bound in `ratatui::Frame::<'a, B>::render_widget`
      --> C:\Users\haydu\.cargo\registry\src\github.com-1ecc6299db9ec823\ratatui-0.21.0\src\terminal.rs:88:12
       |
    86 |     pub fn render_widget<W>(&mut self, widget: W, area: Rect)
       |            ------------- required by a bound in this associated function
    87 |     where
    88 |         W: Widget,
       |            ^^^^^^ required by this bound in `Frame::<'a, B>::render_widget`
    
    For more information about this error, try `rustc --explain E0277`.
    error: could not compile `wd` (lib) due to previous error
    
    
    opened by haydenflinner 2
  • New minor version for ratatui dependencies

    New minor version for ratatui dependencies

    Hi, at first I want to thank you on this great library. I used it in my app tui-journal and it was a charm!

    I came across an issue while trying updating my app to use ratatui instead of tui-rs.

    The problem is that cargo didn't recognize the new features for ratatui since they are in save version as before, and it seems that cargo cache this info somewhere in my machine. I've tried to clear my caches but this didn't solve the problem.

    I believe the version should be updated to 0.2.1 since there are new features has been added.

    Here is the error message I got when I try to add the features with cargo cli

    $ cargo add tui-textarea --no-default-features -F ratatui-crossterm
    
        Updating crates.io index
          Adding tui-textarea v0.2.0 to dependencies.
    error: unrecognized feature for crate tui-textarea: ratatui-crossterm
    disabled features:
        arbitrary, crossterm, search, termion
    
    

    And here is the error message when I try to add inside cargo.toml

    [dependencies]
    crossterm = "0.26.1"
    ratatui = "*"
    tui-textarea = { version = "*", features = ["ratatui-crossterm"], default-features=false }
    
    error: failed to select a version for `tui-textarea`.
    versions that meet the requirements `*` (locked to 0.2.0) are: 0.2.0
    
    the package `test_ratatui` depends on `tui-textarea`, with features: `ratatui-crossterm` but `tui-textarea` does not have these features.
    
    failed to select a version for `tui-textarea` which could resolve this conflict
    
    opened by AmmarAbouZor 5
  • placeholder feature

    placeholder feature

    in order to cleanly integrate tui-textarea into another tool (gitui https://github.com/extrawurst/gitui) I need this feature.

    It is like the html input tag placeholder feature, text is displayed dimmed in the input box as a hint of what to enter. Once text is entered the hint is removed

    placeholder

    I had to slightly modify how the text and its surrounding block are displayed. it is very tricky to get precise control. over the text style of the paragraph and its containing block otherwise. I placed a link to the discussion about this topic with ratatui team. https://github.com/tui-rs-revival/ratatui/issues/144

    I added 2 samples of a popup dialog with the new feature. I also added it to the single_line sample as that seemed a good fit

    opened by pm100 1
Releases(v0.2.0)
  • v0.2.0(Oct 18, 2022)

    • Add Scrolling enum to provide more flexible scrolling via TextArea::scroll method. It has the following enum variants.
      • BREAKING Scrolling::Delta scrolls the textarea by given rows and cols. This variant can be converted from (i16, i16) so migrating from v0.1.6 is very easy.
        let rows: i16 = ...;
        let cols: i16 = ...;
        
        // Until v0.1.6
        textarea.scroll(rows, cols);
        
        // Since v0.2.0
        textarea.scroll((rows, cols));
        
      • Scrolling::PageDown and Scrolling::PageUp scroll the textarea by page.
      • Scrolling::HalfPageDown and Scrolling::HalfPageUp scroll the textarea by half-page.
    • Update default key mappings handled by TextArea::input method.
      • BREAKING Change PageDown and PageUp keys to scroll down/up the textarea by page since v0.2.0. Until v0.1.6, it moved the cursor down/up by one paragraph.
      • Add Ctrl+V and Alt+V keys to scroll down/up the textarea by page as Emacs-like key mappings.
      • Add Alt+] and Alt+[ keys to move the cursor down/up by one paragraph as Emacs-like key mappings.
    • BREAKING Add #[non_exhaustive] attribute to CursorMove enum. This is because more cursor move variations may be added in the future.
    • Fix panic when the max history size is zero (which means the edit history is disabled). (#4)
    Source code(tar.gz)
    Source code(zip)
  • v0.1.6(Sep 28, 2022)

    • Support mouse scroll. (#2)
      • Handle mouse events for both crossterm and termion backends.
      • TextArea::scroll method was added.
      • Key::MouseScrollUp and Key::MouseScrollDown virtual keys are added to Key enum so that custom backends can support mouse scrolling.
      • CursorMove::InViewport variant was added to CursorMove enum, which ensures the cursor to be within the viewport.
    • Add TextArea::alignment and TextArea::set_alignment to set the text alignment of textarea. Note that right and center alignments don't work well with line number so calling TextArea::set_alignment with them automatically disables it. (#3, thanks @Volkalex28)
    • Set rust-version to 1.56.1 in Cargo.toml to show MSRV explicitly.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.5(Jul 18, 2022)

    • Improve performance to render a textarea widget. When number of lines increases, now rendering lines is about 2~8x faster according to our benchmark suites. See the commit for more details of the benchmark results. This was archived by managing a vertical scroll position by ourselves instead of scroll handling by Paragraph. Previously, a cost of rendering lines was O(n) where n was number of all lines. Now the cost is O(1).
    • Implement Clone for TextArea so that textarea instances can be copied easily. It is useful when you create multiple textarea instances with the same configuration. Create a first TextArea instance with configuring blocks and styles, then simply clone it.
    • Add arbitrary feature which is disabled by default. By enabling it, Input, Key and CursorMove can be randomly generated via arbitrary crate. This feature aims to be used by fuzzing tests.
    • Add many benchmark suites to track performance; insert/delete lines/characters, text search, moving a cursor.
    • Improve fuzzing tests to include rendering a textarea to a dummy terminal backend and moving a cursor randomly.
    • Refactor TextArea implementation. The implementation of text search was separated to src/search.rs. The implementation of highlighting was separated to src/highlight.rs. And the implementation of widget rendered by tui-rs was separated to src/widget.rs. These refactorings changed no public API.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.4(Jul 10, 2022)

    • Fix the cursor line style was not applied when a cursor is at the end of line.
    • Fix the cursor position after undoing the modification by 'delete until head of line' (^J by default).
    Source code(tar.gz)
    Source code(zip)
  • v0.1.3(Jul 8, 2022)

    • Text search was implemented. Text search is gated behind search feature flag to avoid depending on regex crate until it is necessary. See the usage document, the API document, and the working example for more details.
      • TextArea::set_search_pattern sets a search pattern in regular expression. This updates highlights at matches in textarea, but does not move the cursor.
      • TextArea::search_forward moves cursor to the next match of the text search based on current cursor position.
      • TextArea::search_back moves cursor to the previous match of the text search based on current cursor position.
      • TextArea::set_search_style sets the text style for highlighting matches of text search.
      search in editor example
    Source code(tar.gz)
    Source code(zip)
  • v0.1.2(Jun 25, 2022)

    • Indent with hard tab is now supported. TextArea::set_hard_tab_indent method enables indentation with a hard tab on hitting a tab key.
      let mut textarea = TextArea::default();
      
      textarea.set_hard_tab_indent(true);
      textarea.insert_tab();
      assert_eq!(textarea.lines(), ["\t"]);
      

      Demo with cargo run --example editor: screencast

    • Add TextArea::indent method to get an indent string of textarea.
      let mut textarea = TextArea::default();
      
      assert_eq!(textarea.indent(), "    ");
      textarea.set_tab_length(2);
      assert_eq!(textarea.indent(), "  ");
      textarea.set_hard_tab_indent(true);
      assert_eq!(textarea.indent(), "\t");
      
    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Jun 21, 2022)

    • Add TextArea::yank_text and TextArea::set_yank_text to set/get yanked text of the textarea.
      let mut textarea = TextArea::default();
      textarea.set_yank_text("hello, world");
      assert_eq!(textarea.yank_text(), "hello, world");
      textarea.paste();
      assert_eq!(textarea.lines(), ["hello, world"]);
      
    • Add CursorMove::Jump(row, col) variant to move cursor to arbitrary (row, col) position with TextArea::move_cursor.
      let mut textarea = TextArea::from(["aaaa", "bbbb"]);
      textarea.move_cursor(CursorMove::Jump(1, 2));
      assert_eq!(textarea.cursor(), (1, 2));
      
    • Fix hard tabs are not rendered (#1)
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jun 19, 2022)

    First release :tada:

    • GitHub repository: https://github.com/rhysd/tui-textarea
    • crates.io: https://crates.io/crates/tui-textarea
    • docs.rs: https://docs.rs/tui-textarea/latest/tui_textarea/
    Source code(tar.gz)
    Source code(zip)
Owner
Linda_pp
A dog enjoying software development (with bugs)
Linda_pp
A TUI for exploring crates.io using Ratatui

crates-tui crates-tui is a simple terminal user interface explorer for crates.io based on Ratatui. crates-tui.mov It supports features like: copy carg

Ratatui 28 Mar 11, 2024
A rust crate for rendering large text to the terminal using font8x8 and ratatui.

tui-big-text tui-big-text is a rust crate that renders large pixel text as a ratatui widget using the glyphs from the font8x8 crate. Installation carg

Josh McKinney 7 Sep 7, 2023
A menu widget for tui-rs ecosystem

tui-menu A menu widget for tui-rs ecosystem. Features Sub menu groups. Intuitive movement. Item's data is generic as long as it Cloneable. Try cargo r

shuo 3 Nov 30, 2022
A simple and efficient terminal UI implementation with ratatui.rs for getting quick insights from csv files right on the terminal

CSV-GREP csv-grep is an intuitive TUI application writting with ratatui.rs for reading, viewing and quickly analysing csv files right on the terminal.

Anthony Ezeabasili 16 Mar 10, 2024
A simple library fot creating file explorer for the ratatui crate.

ratatui-explorer ratatui-explorer is a simple library for creating file explorers for ratatui. Features: File explorer functionality. Input handling (

null 5 Feb 29, 2024
Pure Rust multi-line text handling

COSMIC Text Pure Rust multi-line text handling. COSMIC Text provides advanced text shaping, layout, and rendering wrapped up into a simple abstraction

Pop!_OS 1k Apr 26, 2023
A template for bootstrapping a Rust TUI application with tui-rs & crossterm

rust-tui-template A template for bootstrapping a Rust TUI application with tui-rs & crossterm. tui-rs The library is based on the principle of immedia

Orhun Parmaksız 72 Dec 31, 2022
nvim-oxi provides safe and idiomatic Rust bindings to the rich API exposed by the Neovim text editor.

?? nvim-oxi nvim-oxi provides safe and idiomatic Rust bindings to the rich API exposed by the Neovim text editor. The project is mostly intended for p

Riccardo Mazzarini 655 Jul 13, 2023
Slippy map (openstreetmap) widget for egui

Slippy maps widget for egui. Limitations There are couple of limitations when using this library. Some of them will might probably be lifted at some p

Piotr 13 Jun 14, 2023
Hotkey widget for egui!

egui-keybind, a hotkey library for egui crates.io | docs.rs | examples | changelogs This library provides a simple egui widget for keybindings (hotkey

null 4 Dec 19, 2023
A widget library built on top of bevy_ui.

Sickle UI A widget library built on top of bevy's internal bevy_ui. Example If you clone the repository, you can simply build and run the main example

UmbraLuminosa 226 Jul 26, 2024
Amp: A text editor for your terminal.

Amp: A text editor for your terminal. Heavily inspired by Vi/Vim. Amp aims to take the core interaction model of Vim, simplify it, and bundle in the e

Jordan MacDonald 3.3k Jan 3, 2023
A basic text editor, written in Rust (hence the name).

rut A basic text editor, written in Rust (hence the name). Why, though? I just wanted a basic TUI text editor (like Nano) that could: Be used with all

Lowell Thoerner 4 Feb 3, 2023
Yet another command-line chat GPT frontend written in Rust.

gpterm Yet another command-line chat GPT frontend written in Rust. Features Stream output with typing effect Store chat messages/history Context aware

Makis Christou 22 May 4, 2023
An implementation of Piet's text interface using cosmic-text

piet-cosmic-text Implements piet's Text interface using the cosmic-text crate. License piet-cosmic-text is free software: you can redistribute it and/

John Nunley 7 Mar 12, 2023
Need a powerful and simple library to work with arithmetic progressions in Rust? You should definitively try out ariprog!

Ariprog I had a test (03/2024) on arithmetic progressions, so I decided to create a library to study math. Taking advantage of the fact that I was stu

Kauê Fraga Rodrigues 4 Mar 19, 2024
Yet Another Texture Packer - a small and simple CLI application to pack multiple textures/sprites into a texture atlas/sprite sheet

YATP (Yet Another Texture Packer) A small and simple CLI application to pack multiple textures/sprites into a texture atlas/sprite sheet. Installation

Petar Petrov 2 Sep 11, 2022
A structure editor for a simple functional programming language, with Vim-like shortcuts and commands.

dilim A structure editor for a simple functional programming language, with Vim-like shortcuts and commands. Written in Rust, using the Yew framework,

Joomy Korkut 6 Nov 18, 2022