### Clone and Run Example Source: https://github.com/nushell/reedline/blob/main/CONTRIBUTING.md Clone the repository and run the basic example program to get started with reedline development. ```bash git clone https://github.com/nushell/reedline cd reedline # To try our example program cargo run --example basic ``` -------------------------------- ### Search History Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Demonstrates how to create a search query for history items starting with a prefix and then search the history. ```rust use reedline::{SearchQuery, SearchDirection, History}; let query = SearchQuery::last_with_prefix("cd".to_string(), None); let results = history.search(query)?; ``` -------------------------------- ### Create SearchFilter by Command Line Prefix Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Use this example to create a SearchFilter that matches commands starting with a specific prefix. Requires importing SearchFilter and CommandLineSearch. ```rust use reedline::{SearchFilter, CommandLineSearch}; let filter = SearchFilter::from_text_search( CommandLineSearch::Prefix("ls".to_string()), None, ); ``` -------------------------------- ### Configuring Keybindings with EditCommand Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md Example demonstrating how to add custom keybindings for cutting text to the start or end of a line using EditCommand. ```rust use reedline::{EditCommand, ReedlineEvent, Reedline, KeyCode, KeyModifiers}; let mut keybindings = reedline::default_emacs_keybindings(); // Ctrl+U — kill from start of line keybindings.add_binding( KeyModifiers::CONTROL, KeyCode::Char('u'), ReedlineEvent::Edit(vec![EditCommand::CutFromLineStart]), ); // Ctrl+K — kill to end of line keybindings.add_binding( KeyModifiers::CONTROL, KeyCode::Char('k'), ReedlineEvent::Edit(vec![EditCommand::CutToLineEnd]), ); ``` -------------------------------- ### ExampleHighlighter Initialization and Reedline Setup Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Shows how to create an ExampleHighlighter with specific keywords and configure a Reedline editor to use it. ```rust use reedline::{ExampleHighlighter, Reedline}; let keywords = vec!["cd", "ls", "cat", "grep"]; let highlighter = Box::new(ExampleHighlighter::new( keywords.into_iter().map(|s| s.to_string()).collect() )); let editor = Reedline::create().with_highlighter(highlighter); ``` -------------------------------- ### Custom Highlighter Implementation Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Example implementation of the Highlighter trait. This example applies green styling to the entire line and always allows abbreviation expansion. ```rust use reedline::{Highlighter, StyledText}; struct MyHighlighter; impl Highlighter for MyHighlighter { fn highlight(&self, line: &str, _cursor: usize) -> StyledText { // Return line with styling applied StyledText::new(line.to_string(), nu_ansi_term::Color::Green.normal()) } fn should_expand_abbr(&self, _: &str, _: usize, _: reedline::AbbrExpandContext) -> bool { true } } ``` -------------------------------- ### Example: Initialize and Configure ColumnarMenu Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Demonstrates initializing a ColumnarMenu with default settings and then applying custom configurations for name, marker, and column width. ```rust use reedline::ColumnarMenu; let menu = ColumnarMenu::default() .with_name("completion_menu") .with_marker(">>> ") .with_column_width(Some(30)); ``` -------------------------------- ### Create Default ColumnarMenu Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Creates a ColumnarMenu instance with default settings. This is the starting point for further customization. ```rust impl ColumnarMenu { pub fn default() -> Self } ``` -------------------------------- ### Reedline with DefaultPrompt Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Demonstrates how to create a Reedline editor and use the DefaultPrompt to read a line of input from the user. Handles success and other signals. ```rust use reedline::{Reedline, DefaultPrompt, Signal}; let mut editor = Reedline::create(); let prompt = DefaultPrompt::default(); match editor.read_line(&prompt) { Ok(Signal::Success(line)) => println!("Got: {}", line), _ => {} } ``` -------------------------------- ### StyledText Usage Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Demonstrates creating a green-colored styled text and a plain styled text. ```rust use reedline::StyledText; use nu_ansi_term::Color; let highlighted = StyledText::new("hello".to_string(), Color::Green.normal()); let plain = StyledText::plain("world".to_string()); ``` -------------------------------- ### Custom Reedline Implementation Source: https://github.com/nushell/reedline/blob/main/_autodocs/configuration.md Example of creating a complete custom configuration for Reedline, including custom prompt, highlighter, and completer. ```rust use reedline::{ Reedline, Prompt, Highlighter, Completer, Hinter, Validator, ValidationResult, StyledText, Suggestion, Span, DefaultValidator, }; use std::borrow::Cow; struct CustomPrompt; impl Prompt for CustomPrompt { fn render_prompt_left(&self) -> Cow { Cow::Borrowed("custom> ") } fn render_prompt_right(&self) -> Cow { Cow::Borrowed("") } fn render_prompt_indicator(&self, _: reedline::PromptEditMode) -> Cow { Cow::Borrowed("") } } struct CustomHighlighter; impl Highlighter for CustomHighlighter { fn highlight(&self, line: &str, _: usize) -> StyledText { StyledText::plain(line.to_string()) } } struct CustomCompleter; impl Completer for CustomCompleter { fn complete(&mut self, line: &str, pos: usize) -> Vec { vec![Suggestion { value: format!("{}\"{}\", &line[..pos]), span: Span::new(0, pos), ..Default::default() }] } } let editor = Reedline::create() .with_highlighter(Box::new(CustomHighlighter)) .with_completer(Box::new(CustomCompleter)) .with_validator(Box::new(DefaultValidator)); ``` -------------------------------- ### Example: Initialize Reedline with FileBackedHistory Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Demonstrates how to initialize the Reedline editor with a FileBackedHistory instance configured for persistence. Ensure the history file path is correctly specified. ```rust use reedline::{FileBackedHistory, Reedline}; use std::path::PathBuf; let history = Box::new( FileBackedHistory::with_file(500, PathBuf::from("~/.history")) .expect("Failed to create history") ); let editor = Reedline::create().with_history(history); ``` -------------------------------- ### Example Usage of CwdAwareHinter Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Demonstrates creating a CwdAwareHinter with custom styling and integrating it into a Reedline editor. This hinter offers directory-aware history suggestions. ```rust use reedline::{CwdAwareHinter, Reedline}; use nu_ansi_term::{Color, Style}; let hinter = Box::new( CwdAwareHinter::default() .with_style(Style::new().fg(Color::DarkGray)) ); let editor = Reedline::create().with_hinter(hinter); ``` -------------------------------- ### Example Usage of DefaultHinter Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Demonstrates how to create and configure a DefaultHinter with custom styling and history size, then integrate it into a Reedline editor. ```rust use reedline::{DefaultHinter, Reedline}; use nu_ansi_term::{Color, Style}; let hinter = Box::new( DefaultHinter::default() .with_style(Style::new().italic().fg(Color::LightGray)) .with_history_size(100) ); let editor = Reedline::create().with_hinter(hinter); ``` -------------------------------- ### Creating and Configuring a Completion Menu Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Example of how to create a completion menu using ColumnarMenu and integrate it into a Reedline editor instance. This sets up the menu for command completion. ```rust use reedline::{Reedline, ReedlineMenu, ColumnarMenu}; let completion_menu = ReedlineMenu::EngineCompleter( Box::new(ColumnarMenu::default().with_name("completion")) ); let editor = Reedline::create().with_menu(completion_menu); ``` -------------------------------- ### Create a Reedline Editor Source: https://github.com/nushell/reedline/blob/main/_autodocs/README.md Instantiate a new Reedline editor. This is the starting point for most Reedline applications. ```rust let mut editor = Reedline::create(); ``` -------------------------------- ### HistoryNavigationQuery Enum Examples Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Demonstrates how to create HistoryNavigationQuery instances for different browsing modes: normal buffer navigation, prefix search, and substring search. ```rust use reedline::{HistoryNavigationQuery, LineBuffer}; // Bash-style history navigation let query = HistoryNavigationQuery::Normal(LineBuffer::default()); // Fish-style prefix search let query = HistoryNavigationQuery::PrefixSearch("cd".to_string()); // Substring search let query = HistoryNavigationQuery::SubstringSearch("find".to_string()); ``` -------------------------------- ### Mouse Click Event Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Demonstrates how to construct a ReedlineEvent for a mouse click, specifying coordinates and the button pressed. ```rust use reedline::ReedlineEvent; // Mouse click event from keybinding: let event = ReedlineEvent::Mouse { column: 10, row: 5, button: reedline::MouseButton::Left, }; ``` -------------------------------- ### Example MenuTextStyle Creation Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Demonstrates how to create a MenuTextStyle object with custom ANSI styles for different menu elements. This is useful for customizing the appearance of completion menus. ```rust use reedline::MenuTextStyle; use nu_ansi_term::{Color, Style}; let style = MenuTextStyle { selected_text_style: Color::Green.bold().reverse(), text_style: Color::Gray.normal(), description_style: Color::Blue.normal(), selected_match_style: Color::Green.bold().underline(), match_style: Style::default().underline(), }; ``` -------------------------------- ### Create History Session ID Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Demonstrates how to create a history session ID using Reedline. ```rust use reedline::Reedline; let session_id = Reedline::create_history_session_id(); // Returns Some(HistorySessionId) based on current time ``` -------------------------------- ### Reedline Basic Usage Example Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Demonstrates the basic usage of Reedline to read lines from the user, handling success, Ctrl+C, and Ctrl+D signals. ```rust use reedline::{Reedline, DefaultPrompt, Signal}; let mut line_editor = Reedline::create(); let prompt = DefaultPrompt::default(); loop { match line_editor.read_line(&prompt) { Ok(Signal::Success(buffer)) => { println!("User entered: {}", buffer); } Ok(Signal::CtrlC) | Ok(Signal::CtrlD) => { break; } _ => {} } } ``` -------------------------------- ### Complete Reedline Builder Configuration Source: https://github.com/nushell/reedline/blob/main/_autodocs/configuration.md This example shows a comprehensive configuration of the Reedline editor, including history, completer, hinter, highlighter, validator, edit mode, and menu settings. It demonstrates how to apply various customization options using the builder pattern. ```rust use reedline::{ Reedline, DefaultPrompt, FileBackedHistory, DefaultCompleter, DefaultHinter, DefaultValidator, ExampleHighlighter, Emacs, default_emacs_keybindings, ColumnarMenu, ReedlineMenu, MouseClickMode, Signal, CursorConfig, }; use nu_ansi_term::{Color, Style}; use std::path::PathBuf; let mut keybindings = default_emacs_keybindings(); let history = Box::new( FileBackedHistory::with_file(500, PathBuf::from(".history")) .expect("Error configuring history") ); let completer = Box::new(DefaultCompleter::new_with_wordlen( vec!["help".into(), "history".into(), "exit".into()], 2, )); let hinter = Box::new( DefaultHinter::default() .with_style(Style::new().italic().fg(Color::DarkGray)) ); let highlighter = Box::new(ExampleHighlighter::new( vec!["help".into(), "history".into()], )); let validator = Box::new(DefaultValidator); let edit_mode = Box::new(Emacs::new(keybindings)); let menu = ReedlineMenu::EngineCompleter( Box::new(ColumnarMenu::default().with_name("completion_menu")) ); let mut editor = Reedline::create() .with_history(history) .with_completer(completer) .with_hinter(hinter) .with_highlighter(highlighter) .with_validator(validator) .with_edit_mode(edit_mode) .with_menu(menu) .with_ansi_colors(true) .with_quick_completions(false) .with_partial_completions(false) .with_mouse_click(MouseClickMode::EnabledWithOsc133) .use_bracketed_paste(true) .use_kitty_keyboard_enhancement(true) .with_cwd(Some("/home/user".to_string())); let prompt = DefaultPrompt::default(); match editor.read_line(&prompt) { Ok(Signal::Success(line)) => println!("Got: {}", line), _ => {} } ``` -------------------------------- ### Custom Prompt Implementation with PromptEditMode Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Example of implementing the Prompt trait to customize prompt rendering based on the edit mode. Shows how to handle Default, Emacs, and Vi modes. ```rust use reedline::{Prompt, PromptEditMode}; use std::borrow::Cow; struct CustomPrompt; impl Prompt for CustomPrompt { fn render_prompt_left(&self) -> Cow { Cow::Borrowed("$ ") } fn render_prompt_right(&self) -> Cow { Cow::Borrowed("") } fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow { match edit_mode { PromptEditMode::Default => Cow::Borrowed("> "), PromptEditMode::Emacs => Cow::Borrowed("[E] > "), PromptEditMode::Vi(vi_mode) => Cow::Owned(format!("[{}] > ", match vi_mode { reedline::PromptViMode::Insert => "I", reedline::PromptViMode::Normal => "N", } )), } } } ``` -------------------------------- ### Example Completer Implementation Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md An example implementation of the Completer trait. This struct filters a list of commands based on the current input line and position to provide suggestions. ```rust use reedline::{Completer, Suggestion, Span}; struct MyCompleter { commands: Vec, } impl Completer for MyCompleter { fn complete(&mut self, line: &str, pos: usize) -> Vec { let partial = &line[..pos]; self.commands .iter() .filter(|cmd| cmd.starts_with(partial)) .map(|cmd| Suggestion { value: cmd.clone(), span: Span::new(0, pos), ..Default::default() }) .collect() } } ``` -------------------------------- ### Example: Reedline History Session Management Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Demonstrates how to create a history session ID and associate it with a Reedline editor instance. This allows for multi-session history support. ```rust use reedline::Reedline; let session_id = Reedline::create_history_session_id(); let mut editor = Reedline::create(); if let Some(id) = session_id { let _ = editor.set_history_session_id(Some(id)); } ``` -------------------------------- ### ContextAwareHighlighter Implementation Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md An example implementation of the Highlighter trait that uses AbbrExpandContext to make expansion decisions. The BangExpansion variant is conditionally available. ```rust use reedline::{Highlighter, AbbrExpandContext, StyledText}; struct ContextAwareHighlighter; impl Highlighter for ContextAwareHighlighter { fn highlight(&self, line: &str, _cursor: usize) -> StyledText { StyledText::plain(line.to_string()) } fn should_expand_abbr(&self, line: &str, cursor: usize, context: AbbrExpandContext) -> bool { match context { AbbrExpandContext::WordAbbreviation => true, #[cfg(feature = "bashisms")] AbbrExpandContext::BangExpansion => !line.contains("echo"), } } } ``` -------------------------------- ### Initialize FileBackedHistory with HISTORY_SIZE Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Example of initializing FileBackedHistory using the HISTORY_SIZE constant. This sets the maximum number of history items to be kept in memory and specifies the history file path. ```rust use reedline::{FileBackedHistory, HISTORY_SIZE}; use std::path::PathBuf; let history = Box::new( FileBackedHistory::with_file(HISTORY_SIZE, PathBuf::from("~/.history"))? ); ``` -------------------------------- ### Span Example Usage Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Demonstrates how to create Span objects representing byte ranges for replacement. The end byte is exclusive. ```rust use reedline::Span; let span = Span::new(0, 5); // Replace bytes 0-4 (5 bytes total) let span = Span::new(3, 8); // Replace bytes 3-7 ``` -------------------------------- ### SearchQuery Constructor: last_with_prefix Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Creates a SearchQuery to find the most recent history item starting with a specified prefix. Optionally filters by session. ```rust pub fn last_with_prefix(prefix: String, session: Option) -> SearchQuery ``` -------------------------------- ### Highlighter, Validator, and Hinter API Source: https://github.com/nushell/reedline/blob/main/_autodocs/MANIFEST.txt Covers traits for syntax highlighting (`Highlighter`), input validation (`Validator`), and providing hints (`Hinter`), along with their example implementations and related types. ```APIDOC ## api-reference/highlighter-validator-hinter.md ### Description This file documents the components responsible for enhancing the user input experience through syntax highlighting, validation, and contextual hints. ### Components - **`Highlighter` trait**: For applying styles to input text. Includes `StyledText` and example implementations like `ExampleHighlighter` and `SimpleMatchHighlighter`. - **`Validator` trait**: For validating user input. Includes `ValidationResult` and `DefaultValidator` implementation. - **`Hinter` trait**: For providing contextual hints to the user. Includes `DefaultHinter` and `CwdAwareHinter` implementations. - **`Prompt` trait**: For customizing the prompt indicator. Includes `DefaultPrompt`. - **`AbbrExpandContext`**: Context for abbreviation expansion. ``` -------------------------------- ### Reedline with Mouse Click and OSC 133 Markers Configuration Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Example showing how to configure mouse click events and OSC 133 semantic markers when creating a Reedline editor. Painter is internal and configured via the builder. ```rust use reedline::{Reedline, Osc133ClickEventsMarkers}; let mut editor = Reedline::create(); // Painter is internal, typically configured via Reedline builder: let editor = Reedline::create() .with_mouse_click(reedline::MouseClickMode::EnabledWithOsc133); ``` -------------------------------- ### SearchQuery Constructor: last_with_prefix_and_cwd Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Creates a SearchQuery to find the most recent history item starting with a specified prefix and located in a particular working directory. Optionally filters by session. ```rust pub fn last_with_prefix_and_cwd(prefix: String, cwd: String, session: Option) -> SearchQuery ``` -------------------------------- ### ExampleHighlighter Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Initializes an ExampleHighlighter with a list of commands to be highlighted. ```rust impl ExampleHighlighter { pub fn new(commands: Vec) -> Self } ``` -------------------------------- ### ExampleHighlighter::new Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Creates a new ExampleHighlighter that colors specified keywords. ```APIDOC ## ExampleHighlighter::new ### Description Creates a highlighter that colors known commands. It takes a list of keywords to highlight. ### Method Associated function (constructor) ### Signature `pub fn new(commands: Vec) -> Self` ### Parameters #### Parameters - **commands** (`Vec`) - Required - List of keywords to highlight ### Returns - `Self` - An instance of ExampleHighlighter. ``` -------------------------------- ### Span Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Creates a new Span instance from start and end byte positions. Panics if the end position is less than the start position. ```rust impl Span { pub fn new(start: usize, end: usize) -> Span } ``` -------------------------------- ### Handling IOError Source: https://github.com/nushell/reedline/blob/main/_autodocs/errors.md Example of handling I/O errors that occur during file, terminal, or pipe operations. This includes issues like file not found, permission denied, or disk full. The example shows how to inspect the specific IO error kind. ```rust use reedline::{FileBackedHistory, ReedlineError, ReedlineErrorVariants}; use std::path::PathBuf; use std::io; match FileBackedHistory::with_file(100, PathBuf::from(".history")) { Ok(history) => { // Use history } Err(ReedlineError(ReedlineErrorVariants::IOError(io_err))) => { match io_err.kind() { io::ErrorKind::NotFound => { eprintln!("History directory doesn't exist"); } io::ErrorKind::PermissionDenied => { eprintln!("Permission denied accessing history file"); } io::ErrorKind::Other => { eprintln!("I/O error: {}", io_err); } _ => eprintln!("IO error: {}", io_err), } // Fallback to in-memory history } Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Suggestion::display_value Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Gets the string to display to the user, prioritizing display_override over the value. ```APIDOC ## Suggestion::display_value ### Description Get the string to display to user (display_override or value). ### Returns - **&str** ### Request Example ```rust use reedline::Suggestion; use nu_ansi_term::Color; let suggestion = Suggestion { value: "command".to_string(), display_override: Some("command (builtin)".to_string()), description: Some("Do something useful".to_string()), style: Some(Color::Green.normal()), span: reedline::Span::new(0, 3), append_whitespace: true, ..Default::default() }; let display_text = suggestion.display_value(); ``` ``` -------------------------------- ### DescriptionMenu Constructor and Builder Methods Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Provides details on how to create and configure a DescriptionMenu, which displays items with descriptions. ```APIDOC ## DescriptionMenu Menu with description column. ### Constructor ```rust impl DescriptionMenu { pub fn default() -> Self } ``` Creates a menu showing items with descriptions. **Returns:** `DescriptionMenu` instance ### Builder Methods ```rust pub fn with_name(mut self, name: &str) -> Self pub fn with_description_mode(mut self, mode: DescriptionMode) -> Self pub fn with_column_width(mut self, width: Option) -> Self ``` Configure menu. **Returns:** Self for chaining ``` -------------------------------- ### WordEdge Enum Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Specifies which edge of a word a motion should target. Can be either the 'Start' or the 'End' of the word. ```APIDOC ## WordEdge Which edge of a word a motion lands on. **Source:** `src/enums.rs` ```rust pub enum WordEdge { Start, // First character of word End, // Last character of word (inclusive) } ``` | Variant | |---------| | `Start` | | `End` | **Example:** ```rust use reedline::{EditCommand, MotionTarget, WordKind, WordEdge, Direction}; // Go to start of next word let cmd = EditCommand::Move(MotionTarget::Word { kind: WordKind::Small, edge: WordEdge::Start, direction: Direction::Forward, }); // Go to end of current word let cmd = EditCommand::Move(MotionTarget::Word { kind: WordKind::Small, edge: WordEdge::End, direction: Direction::Forward, }); ``` ``` -------------------------------- ### PythonValidator Implementation Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Example implementation of the Validator trait for Python-like syntax. Checks for unclosed parentheses, quotes, and trailing colons. ```rust use reedline::{Validator, ValidationResult}; struct PythonValidator; impl Validator for PythonValidator { fn validate(&self, line: &str) -> ValidationResult { // Check for unclosed parentheses, quotes, colons let unclosed_parens = line.chars().filter(|&c| c == '(').count() > line.chars().filter(|&c| c == ')').count(); let unclosed_quotes = line.chars().filter(|&c| c == '"').count() % 2 != 0; let ends_with_colon = line.trim().ends_with(':'); if unclosed_parens || unclosed_quotes || ends_with_colon { ValidationResult::Incomplete } else { ValidationResult::Complete } } } ``` -------------------------------- ### DescriptionMenu Builder Methods Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Configures a DescriptionMenu instance. Use these methods for chaining configurations like name, description mode, and column width. ```rust pub fn with_name(mut self, name: &str) -> Self ``` ```rust pub fn with_description_mode(mut self, mode: DescriptionMode) -> Self ``` ```rust pub fn with_column_width(mut self, width: Option) -> Self ``` -------------------------------- ### DescriptionMenu Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Creates a new DescriptionMenu instance. This is the default constructor. ```rust impl DescriptionMenu { pub fn default() -> Self } ``` -------------------------------- ### Example Usage of Reedline Result Source: https://github.com/nushell/reedline/blob/main/_autodocs/errors.md Demonstrates how a function returning Reedline's Result type would be declared and used. ```rust use reedline::Result; fn load_history(path: &str) -> Result> { // Returns Result which is Result todo!() } ``` -------------------------------- ### Create Default ListMenu Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Creates a ListMenu instance with default settings for a single-column vertical menu. ```rust impl ListMenu { pub fn default() -> Self } ``` -------------------------------- ### Change Inner Quoted String Command Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Example of creating an EditCommand to change the inner content of a quoted string using TextObject. ```rust use reedline::{EditCommand, TextObject, TextObjectScope, TextObjectType}; // cit — change inner quoted string let cmd = EditCommand::ChangeTextObject { text_object: TextObject { scope: TextObjectScope::Inner, object_type: TextObjectType::Quote, }, }; ``` -------------------------------- ### DefaultPrompt Implementation Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md A simple, built-in prompt implementation that displays 'in > '. Used for basic line editing scenarios. ```rust pub struct DefaultPrompt; ``` -------------------------------- ### Granularity Usage Examples Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Illustrates using the Granularity enum with EditCommand::Cut. 'CharWise' cuts inline, while 'LineWise' cuts the entire line. ```rust use reedline::{EditCommand, MotionTarget, Direction, Granularity}; // Delete to end of line (char-wise) let cmd = EditCommand::Cut { target: MotionTarget::LineEdge(Direction::Forward), granularity: Granularity::CharWise, }; ``` ```rust use reedline::{EditCommand, MotionTarget, Direction, Granularity}; // Delete current line (line-wise) let cmd = EditCommand::Cut { target: MotionTarget::LineEdge(Direction::Forward), granularity: Granularity::LineWise, }; ``` -------------------------------- ### Configure Quick Completions Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Enables auto-selection when only one completion option remains. Accepts a boolean value. ```rust pub fn with_quick_completions(mut self, quick_completions: bool) -> Self ``` -------------------------------- ### Customize Emacs Keybindings Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md This example demonstrates how to add a custom keybinding to the Emacs edit mode. It maps Ctrl+x to the 'complete' edit command. ```rust use reedline::{ default_emacs_keybindings, Emacs, Reedline, ReedlineEvent, EditCommand, KeyCode, KeyModifiers, }; let mut keybindings = default_emacs_keybindings(); keybindings.add_binding( KeyModifiers::CONTROL, KeyCode::Char('x'), ReedlineEvent::Edit(vec![EditCommand::Complete]), ); let editor = Reedline::create() .with_edit_mode(Box::new(Emacs::new(keybindings))); ``` -------------------------------- ### Configure Working Directory Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Sets the logical current working directory for hinting and history. Accepts an Option for the path or None. ```rust pub fn with_cwd(mut self, cwd: Option) -> Self ``` -------------------------------- ### BraceValidator Implementation Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Example implementation of the Validator trait to check for balanced curly braces. Returns Incomplete if open braces exceed close braces. ```rust use reedline::{Validator, ValidationResult}; struct BraceValidator; impl Validator for BraceValidator { fn validate(&self, line: &str) -> ValidationResult { let open_braces = line.chars().filter(|&c| c == '{').count(); let close_braces = line.chars().filter(|&c| c == '}').count(); if open_braces > close_braces { ValidationResult::Incomplete } else { ValidationResult::Complete } } } ``` -------------------------------- ### Reedline Editor with Custom Syntax Highlighter Source: https://github.com/nushell/reedline/blob/main/README.md Creates a Reedline editor instance with a custom syntax highlighter, using ExampleHighlighter with a predefined list of commands. ```rust use reedline::{ExampleHighlighter, Reedline}; let commands = vec![ "test".into(), "hello world".into(), "hello world reedline".into(), "this is the reedline crate".into(), ]; let mut line_editor = Reedline::create().with_highlighter(Box::new(ExampleHighlighter::new(commands))); ``` -------------------------------- ### HistoryItem Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Creates a basic HistoryItem with only the command line text, initializing other fields to None. ```APIDOC ## HistoryItem Constructor ### `new(command_line: String) -> Self` Create a basic history item with just the command. #### Parameters - **command_line** (`String`) - Required - The actual command text. #### Returns - `HistoryItem` - A new `HistoryItem` with other fields set to `None`. ### Example ```rust use reedline::HistoryItem; use std::time::Duration; let mut item = HistoryItem::new("cd /home".to_string()); item.cwd = Some("/tmp".to_string()); item.exit_status = Some(0); item.duration = Some(Duration::from_millis(100)); ``` ``` -------------------------------- ### Define WordEdge Enum Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Defines which edge of a word a motion command targets. Use Start for the first character or End for the last character (inclusive). ```rust pub enum WordEdge { Start, // First character of word End, // Last character of word (inclusive) } ``` -------------------------------- ### Configure Transient Prompt Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Sets a prompt that appears after command submission. Requires a Box implementation. ```rust pub fn with_transient_prompt(mut self, transient_prompt: Box) -> Self ``` -------------------------------- ### Define Span struct Source: https://github.com/nushell/reedline/blob/main/_autodocs/types.md Represents a range within a string, defined by start and end indices. Used to indicate the portion of text a suggestion applies to. ```rust pub struct Span { pub start: usize, pub end: usize, } ``` -------------------------------- ### DefaultCompleter::new Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Creates a new DefaultCompleter with a list of possible completions. ```APIDOC ## DefaultCompleter::new ### Description Creates a completer from a word list. ### Parameters #### Path Parameters - **completions** (Vec) - Required - List of possible completions ### Response #### Success Response (200) - **DefaultCompleter** instance ### Request Example ```rust use reedline::DefaultCompleter; let commands = vec!["cat", "cd", "chmod", "ls", "mkdir"]; let completer = Box::new(DefaultCompleter::new(commands.into_iter().map(|s| s.to_string()).collect())); ``` ``` -------------------------------- ### SimpleMatchHighlighter::new Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Creates a new SimpleMatchHighlighter that highlights text matching a given pattern. ```APIDOC ## SimpleMatchHighlighter::new ### Description Creates a highlighter for pattern matching. ### Method Associated function (constructor) ### Signature `pub fn new(pattern: String) -> Self` ### Parameters #### Path Parameters - **pattern** (`String`) - Yes - Pattern to match ### Returns - `SimpleMatchHighlighter` - The newly created highlighter instance. ``` -------------------------------- ### DefaultHinter Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md A Fish-style history hint provider that suggests commands based on user history. It can be configured with custom styling and history size. ```APIDOC ## DefaultHinter ### Description A Fish-style history hint provider that suggests commands based on user history. It can be configured with custom styling and history size. ### Constructor `pub fn default() -> Self` Creates a hinter suggesting from history. **Returns:** `DefaultHinter` instance ### Builder Methods `pub fn with_style(mut self, style: Style) -> Self` Configures the text style for hints. `pub fn with_history_size(mut self, size: usize) -> Self` Configures the maximum number of history entries to check for suggestions. **Parameters:** - **style** (`nu_ansi_term::Style`): Required - Text style for hints. - **size** (`usize`): Required - Max hints to check. **Returns:** Self for chaining **Example:** ```rust use reedline::{DefaultHinter, Reedline}; use nu_ansi_term::{Color, Style}; let hinter = Box::new( DefaultHinter::default() .with_style(Style::new().italic().fg(Color::LightGray)) .with_history_size(100) ); let editor = Reedline::create().with_hinter(hinter); ``` ``` -------------------------------- ### Handling HistoryDatabaseError Source: https://github.com/nushell/reedline/blob/main/_autodocs/errors.md Example of handling SQLite database errors. This occurs when the SQLite database is locked, corrupted, or a query fails. Requires the 'sqlite' or 'sqlite-dynlib' feature. ```rust use reedline::{Reedline, SqliteBackedHistory, ReedlineError, ReedlineErrorVariants}; use std::path::PathBuf; #[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))] { match SqliteBackedHistory::with_file(PathBuf::from("history.db")) { Ok(history) => { let editor = Reedline::create().with_history(Box::new(history)); // continue } Err(ReedlineError(ReedlineErrorVariants::HistoryDatabaseError(msg))) => { eprintln!("Database error: {}", msg); // Fallback to in-memory history let editor = Reedline::create(); } Err(e) => eprintln!("Other error: {}", e), } } ``` -------------------------------- ### Create Word Motion Commands Targeting Word Edges Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Generates EditCommand instances to move to the start or end of a 'small' word. These are fundamental for text navigation. ```rust use reedline::{EditCommand, MotionTarget, WordKind, WordEdge, Direction}; // Go to start of next word let cmd = EditCommand::Move(MotionTarget::Word { kind: WordKind::Small, edge: WordEdge::Start, direction: Direction::Forward, }); // Go to end of current word let cmd = EditCommand::Move(MotionTarget::Word { kind: WordKind::Small, edge: WordEdge::End, direction: Direction::Forward, }); ``` -------------------------------- ### MenuSettings Builder Methods Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Provides methods for configuring MenuSettings with chaining support. ```rust impl MenuSettings { pub fn with_name(mut self, name: &str) -> Self pub fn with_color(mut self, color: MenuTextStyle) -> Self pub fn with_marker(mut self, marker: String) -> Self pub fn with_only_buffer_difference(mut self, only: bool) -> Self pub fn with_input_mode(mut self, mode: InputMode) -> Self pub fn with_output_mode(mut self, mode: OutputMode) -> Self } ``` -------------------------------- ### Keybindings Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md Creates an empty keybindings map for managing key-to-action mappings. ```APIDOC ## Keybindings Constructor ### Description Creates an empty keybindings map for managing key-to-action mappings. ### Returns `Keybindings` instance ### Example ```rust use reedline::Keybindings; let mut keybindings = Keybindings::new(); ``` ``` -------------------------------- ### Get History Session ID Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Retrieves the currently active history session ID from the Reedline editor instance. Returns None if no session ID has been set. ```rust pub fn get_history_session_id(&self) -> Option ``` -------------------------------- ### FindStop Usage Examples Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Demonstrates how to use the FindStop enum with EditCommand::Move for character finding operations. 'f' finds the character, while 't' stops before it. ```rust use reedline::{EditCommand, MotionTarget, Direction, FindStop}; // f — find char forward let cmd = EditCommand::Move(MotionTarget::Find { ch: 'x', direction: Direction::Forward, stop: FindStop::On, }); ``` ```rust use reedline::{EditCommand, MotionTarget, Direction, FindStop}; // t — till char forward let cmd = EditCommand::Move(MotionTarget::Find { ch: 'x', direction: Direction::Forward, stop: FindStop::Before, }); ``` -------------------------------- ### Create SQLite-Backed History Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Initializes a SqliteBackedHistory instance using a specified file path for storage. Ensure the 'sqlite' or 'sqlite-dynlib' feature is enabled. ```rust #[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))] use reedline::{SqliteBackedHistory, Reedline}; use std::path::PathBuf; #[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))] { let history = Box::new( SqliteBackedHistory::with_file(PathBuf::from("~/.history.db")) .expect("Failed to create history") ); let editor = Reedline::create().with_history(history); } ``` -------------------------------- ### Implement Custom Hinter for Reedline Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Provides a custom Hinter implementation that suggests commands based on history search. It demonstrates how to handle hints, retrieve the full hint text, and extract the next token for incremental completion. ```rust use reedline::{Hinter, History}; struct CustomHinter { last_hint: String, } impl Hinter for CustomHinter { fn handle( &mut self, line: &str, _pos: usize, history: &dyn History, _use_ansi_coloring: bool, _cwd: &str, ) -> String { // Find matching history entry if let Ok(results) = history.search( reedline::SearchQuery::last_with_prefix(line.to_string(), None) ) { if let Some(item) = results.first() { self.last_hint = item.command_line.clone(); return format!("{}", item.command_line[line.len()..].to_string()); } } self.last_hint = String::new(); String::new() } fn complete_hint(&self) -> String { self.last_hint.clone() } fn next_hint_token(&self) -> String { self.last_hint.split_whitespace().next().unwrap_or("").to_string() } } ``` -------------------------------- ### Handling OtherHistoryError Source: https://github.com/nushell/reedline/blob/main/_autodocs/errors.md Example of handling generic history operation failures with a static error message. This can occur due to invalid cursor positions or inconsistent history states. ```rust use reedline::{History, SearchQuery}; match history.search(query) { Ok(results) => println!("Found {} items", results.len()), Err(e) => eprintln!("Search failed: {}", e), } ``` -------------------------------- ### Emacs Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md Creates a new Emacs editor instance with custom keybindings. This allows for GNU Readline-compatible keybindings. ```APIDOC ## Emacs Constructor ### Description Creates a new Emacs editor with custom keybindings. ### Method Signature ```rust Emacs::new(keybindings: Keybindings) -> Self ``` ### Parameters #### Path Parameters - **keybindings** (Keybindings) - Required - Key-to-action mapping ### Request Example ```rust use reedline::{Emacs, default_emacs_keybindings, Reedline}; let keybindings = default_emacs_keybindings(); let editor = Reedline::create() .with_edit_mode(Box::new(Emacs::new(keybindings))); ``` ``` -------------------------------- ### SearchQuery Constructor: everything Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/history.md Creates a SearchQuery to retrieve all history items in a specified direction. Optionally filters by session. ```rust pub fn everything(direction: SearchDirection, session: Option) -> SearchQuery ``` -------------------------------- ### Configure Partial Completions Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Enables filling the buffer with the common prefix of all completions. Accepts a boolean value. ```rust pub fn with_partial_completions(mut self, partial_completions: bool) -> Self ``` -------------------------------- ### with_quick_completions Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Configures whether to auto-select a completion when only one option remains in Reedline. ```APIDOC ## with_quick_completions ### Description Auto-selects when only one completion remains. ### Method ```rust pub fn with_quick_completions(mut self, quick_completions: bool) -> Self ``` ### Parameters #### Path Parameters - **quick_completions** (bool) - Required - Enable quick selection ### Default `false` ``` -------------------------------- ### Delete Until Next Character using MotionTarget Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md Example of using MotionTarget::Find to create an EditCommand::Cut that deletes text from the current cursor position until the next occurrence of a specified character. ```rust use reedline::{ EditCommand, MotionTarget, FindStop, Direction, Granularity, }; // Delete until next 'x' character let cmd = EditCommand::Cut { target: MotionTarget::Find { ch: 'x', direction: Direction::Forward, stop: FindStop::On, }, granularity: Granularity::CharWise, }; ``` -------------------------------- ### Configure CwdAwareHinter Style Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Configures the text styling for hints provided by the CwdAwareHinter. Requires the `sqlite` or `sqlite-dynlib` feature for rich history metadata. ```rust pub fn with_style(mut self, style: Style) -> Self ``` -------------------------------- ### Delete to End of Word using MotionTarget Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md Example of using MotionTarget::Word to create an EditCommand::Cut that deletes text from the current cursor position to the end of the current small word. ```rust use reedline::{ EditCommand, MotionTarget, WordKind, WordEdge, Direction, Granularity, }; // Delete to end of word let cmd = EditCommand::Cut { target: MotionTarget::Word { kind: WordKind::Small, edge: WordEdge::End, direction: Direction::Forward, }, granularity: Granularity::CharWise, }; ``` -------------------------------- ### MenuSettings Builder Methods Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/completion-menu.md Methods for configuring MenuSettings. These methods allow for chaining to set various properties of the menu. ```APIDOC ## MenuSettings Builder Methods ### Description Methods for configuring `MenuSettings`. These methods allow for chaining to set various properties of the menu. ### Methods - `with_name(name: &str) -> Self`: Sets the name of the menu. - `with_color(color: MenuTextStyle) -> Self`: Sets the text style for the menu. - `with_marker(marker: String) -> Self`: Sets the marker for the menu. - `with_only_buffer_difference(only: bool) -> Self`: Configures whether to only show buffer differences. - `with_input_mode(mode: InputMode) -> Self`: Sets the input mode for the menu. - `with_output_mode(mode: OutputMode) -> Self`: Sets the output mode for the menu. ### Returns `Self` for chaining. ``` -------------------------------- ### Handling HistoryFeatureUnsupported Source: https://github.com/nushell/reedline/blob/main/_autodocs/errors.md Example of handling errors when a history feature is not supported by the backend. This is common when using features specific to one history type with another, or when a required feature flag is not enabled. ```rust use reedline::{History, HistorySessionId, ReedlineError, ReedlineErrorVariants}; let session = HistorySessionId::new(12345); match history.session() { Some(_) => println!("Sessions supported"), None => println!("History backend doesn't support sessions"), } // Or check error: match result { Err(ReedlineError(ReedlineErrorVariants::HistoryFeatureUnsupported { history, feature })) => { eprintln!("Feature '{}' not supported by '{}'", feature, history); } _ => {} } ``` -------------------------------- ### Create CwdAwareHinter Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/highlighter-validator-hinter.md Creates a CwdAwareHinter instance, which provides command suggestions from history filtered by the current working directory. This is useful for context-specific suggestions. ```rust impl CwdAwareHinter { pub fn default() -> Self } ``` -------------------------------- ### Reedline EditCommand for Cursor Movement Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/signals-enums.md Illustrates creating EditCommand instances to move the cursor using the Direction enum. Shows examples for moving forward one small word and backward one big WORD. ```rust use reedline::{EditCommand, MotionTarget, WordKind, WordEdge, Direction}; // Move forward one word let cmd = EditCommand::Move(MotionTarget::Word { kind: WordKind::Small, edge: WordEdge::Start, direction: Direction::Forward, }); // Move backward one WORD let cmd = EditCommand::Move(MotionTarget::Word { kind: WordKind::Big, edge: WordEdge::Start, direction: Direction::Backward, }); ``` -------------------------------- ### Vi Constructor Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/edit-mode.md Creates a new Vi editor with separate keybindings for insert and normal modes. This provides Vi-style editing with distinct modes. ```APIDOC ## Vi Constructor ### Description Creates a new Vi editor with separate keybindings for insert and normal modes. ### Method Signature ```rust Vi::new(insert_keybindings: Keybindings, normal_keybindings: Keybindings) -> Self ``` ### Parameters #### Path Parameters - **insert_keybindings** (Keybindings) - Required - Insert mode key mappings - **normal_keybindings** (Keybindings) - Required - Normal mode key mappings ### Request Example ```rust use reedline::{Vi, default_vi_insert_keybindings, default_vi_normal_keybindings, Reedline}; let editor = Reedline::create().with_edit_mode(Box::new(Vi::new( default_vi_insert_keybindings(), default_vi_normal_keybindings(), ))); ``` ``` -------------------------------- ### Configure Mouse Click Handling in Reedline Source: https://github.com/nushell/reedline/blob/main/_autodocs/api-reference/reedline-core.md Example of creating a Reedline editor instance with mouse click events enabled and configured to emit OSC 133 markers. This is useful for applications that need to react to user clicks within the terminal. ```rust use reedline::{Reedline, MouseClickMode}; let editor = Reedline::create() .with_mouse_click(MouseClickMode::EnabledWithOsc133); ```