### Install TTY::Reader Gem Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Instructions for installing the TTY::Reader gem using Bundler or as a standalone gem. This is the first step to using the library in a Ruby project. ```ruby gem "tty-reader" ``` ```bash $ bundle ``` ```bash $ gem install tty-reader ``` -------------------------------- ### Read Line Input with TTY::Reader Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Shows how to use TTY::Reader to read a line of input from the user. It includes examples of using a custom prompt, disabling character echoing, and operating in cooked mode instead of raw mode. ```ruby reader.read_line reader.read_line(">>") reader.read_line(raw: false) reader.read_line(echo: false) ``` -------------------------------- ### Initialize TTY::Reader and Listen for Key Events Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Demonstrates how to initialize a TTY::Reader instance and set up event listeners for specific key combinations like Ctrl-X or Escape. This allows for custom actions, such as exiting the application. ```ruby reader = TTY::Reader.new reader.on(:keyctrl_x, :keyescape) do puts "Exiting..." exit end ``` -------------------------------- ### Initialize Reader Source: https://context7.com/piotrmurach/tty-reader/llms.txt Initializes a new TTY::Reader instance, allowing configuration of input/output streams, interrupt handling, and history settings. ```APIDOC ## Initialize Reader ### Description Creates a new TTY::Reader instance with optional configuration for input/output streams, interrupt handling, and history settings. ### Method N/A (Initialization) ### Endpoint N/A (Initialization) ### Parameters #### Parameters - **input** (IO) - Optional - Input stream (default: $stdin) - **output** (IO) - Optional - Output stream (default: $stdout) - **interrupt** (Symbol or Proc) - Optional - Handle Ctrl+C: :signal, :exit, :noop, :error, or Proc - **track_history** (Boolean) - Optional - Enable history tracking (default: true) - **history_cycle** (Boolean) - Optional - Allow cycling through history (default: false) - **history_duplicates** (Boolean) - Optional - Store duplicate lines (default: false) - **history_size** (Integer) - Optional - Maximum history entries (default: 512) - **history_exclude** (Proc) - Optional - Exclude lines from history - **completion_handler** (Proc) - Optional - Handler for autocompletion - **completion_suffix** (String) - Optional - Suffix added after completion ### Request Example ```ruby require "tty-reader" # Basic initialization reader = TTY::Reader.new # Full configuration reader = TTY::Reader.new( input: $stdin, # Input stream (default: $stdin) output: $stdout, # Output stream (default: $stdout) interrupt: :signal, # Handle Ctrl+C: :signal, :exit, :noop, :error, or Proc track_history: true, # Enable history tracking (default: true) history_cycle: true, # Allow cycling through history (default: false) history_duplicates: false, # Store duplicate lines (default: false) history_size: 2048, # Maximum history entries (default: 512) history_exclude: ->(line) { line.strip.empty? }, # Exclude lines from history completion_handler: ->(word) { ["apple", "apricot"].grep(/^#{word}/) }, completion_suffix: " " # Suffix added after completion ) ``` ### Response N/A (Initialization) ``` -------------------------------- ### TTY-Reader Supported Key Events Reference Source: https://context7.com/piotrmurach/tty-reader/llms.txt This section lists the available key events that can be used with the `on`, `subscribe`, and `trigger` methods in the tty-reader gem. This provides a comprehensive reference for all possible input interactions. ```ruby require "tty-reader" reader = TTY::Reader.new ``` -------------------------------- ### Initialize TTY::Reader in Ruby Source: https://context7.com/piotrmurach/tty-reader/llms.txt Initializes a TTY::Reader instance with various configuration options for input/output streams, interrupt handling, and history tracking. Supports custom handlers for completion and exclusion rules. ```ruby require "tty-reader" # Basic initialization reader = TTY::Reader.new # Full configuration reader = TTY::Reader.new( input: $stdin, # Input stream (default: $stdin) output: $stdout, # Output stream (default: $stdout) interrupt: :signal, # Handle Ctrl+C: :signal, :exit, :noop, :error, or Proc track_history: true, # Enable history tracking (default: true) history_cycle: true, # Allow cycling through history (default: false) history_duplicates: false, # Store duplicate lines (default: false) history_size: 2048, # Maximum history entries (default: 512) history_exclude: ->(line) { line.strip.empty? }, # Exclude lines from history completion_handler: ->(word) { ["apple", "apricot"].grep(/^#{word}/) }, completion_suffix: " " # Suffix added after completion ) ``` -------------------------------- ### Listen for Multiple Key Events Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Shows how to listen for multiple key events simultaneously by passing event names as arguments to the `on` method. The provided block will be executed for any of the specified events. ```ruby reader.on(:keyctrl_x, :keyescape) { |event| ... } ``` -------------------------------- ### Implement Word Completion Source: https://context7.com/piotrmurach/tty-reader/llms.txt Enable tab completion for command-line input by providing a `completion_handler` lambda. This handler receives a partial word and should return an array of matching suggestions. A `completion_suffix` can be added after a successful completion. ```ruby require "tty-reader" # Define available completions COMMANDS = %w[help quit exit list show create delete update search] COLORS = %w[red green blue yellow orange purple pink] # Completion handler returns matching suggestions completion_handler = ->(word) { all_words = COMMANDS + COLORS all_words.grep(/^#{Regexp.escape(word)}/i) } reader = TTY::Reader.new( completion_handler: completion_handler, completion_suffix: " " # Add space after completion ) # Listen for completion events reader.on(:complete) do |event| puts "\nCompleted: #{event.completion}" end puts "Type a command and press Tab to complete" puts "Commands: #{COMMANDS.join(', ')}" puts "Colors: #{COLORS.join(', ')}" loop do input = reader.read_line("=> ") break if input.strip == "exit" puts "Executing: #{input}" end # Dynamic completion based on context reader.completion_handler = ->(word) { # Could query database, filesystem, or API Dir.glob("#{word}*").take(10) } ``` -------------------------------- ### Read Multiline Input with a Prefix Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Demonstrates how to provide a line prefix for multiline input by passing a string as the first argument to `read_multiline`. ```ruby reader.read_multiline(">> ") ``` -------------------------------- ### Subscribe an Object to Key Events Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Explains how to subscribe an object to listen for key events using the `subscribe` method. The listener object must implement methods corresponding to the events it wishes to receive (e.g., `keypress(event)`). ```ruby class MyListener def keypress(event) ... end end reader.subscribe(MyListener.new) ``` -------------------------------- ### Read Single Keypress with TTY::Reader Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Illustrates how to read a single keypress from the user using TTY::Reader. It provides methods for both blocking and non-blocking reads. ```ruby reader.read_char reader.read_keypress reader.read_keypress(nonblock: true) ``` -------------------------------- ### Listen for Key Press Events Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Explains how to register a listener for key press events using the `on` method. A block is executed when the specified event occurs, receiving a `KeyEvent` object. ```ruby reader.on(:keypress) { |event| .... } ``` -------------------------------- ### Subscribe to Key Events with `on` Source: https://context7.com/piotrmurach/tty-reader/llms.txt Register callbacks for specific key events like keypress, keyescape, and keyenter. The callback receives a KeyEvent object containing details about the pressed key and the current line content. Multiple events can be handled by a single callback, and handlers can be chained. ```ruby require "tty-reader" reader = TTY::Reader.new # Listen for specific key events reader.on(:keyescape) do |event| puts "\nEscape pressed, exiting..." exit end # Multiple events with one handler reader.on(:keyctrl_x, :keyctrl_c) do |event| puts "\nInterrupt received" exit end # Generic keypress handler with event inspection reader.on(:keypress) do |event| puts "Key: #{event.key.name}" # :alpha, :num, :up, :down, :enter, etc. puts "Value: #{event.value.inspect}" # The actual character pressed puts "Line: #{event.line}" # Current line content puts "Ctrl: #{event.key.ctrl}" # true if Ctrl was held puts "Shift: #{event.key.shift}" # true if Shift was held end # Vim-style navigation example reader.on(:keypress) do |event| case event.value when "j" then reader.trigger(:keydown) when "k" then reader.trigger(:keyup) when "h" then reader.trigger(:keyleft) when "l" then reader.trigger(:keyright) end end # Chain multiple handlers reader .on(:keyenter) { |e| puts "Submitted: #{e.line}" } .on(:keytab) { |e| puts "Tab pressed" } .on(:keyup) { |e| puts "History previous" } .on(:keydown) { |e| puts "History next" } # Start reading input loop do reader.read_line("=> ") end ``` -------------------------------- ### Pre-populate Line Content for Editing Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Demonstrates how to pre-populate the line content for editing using the `:value` option with the `read_line` method. This is useful for providing default text or allowing users to edit existing input. ```ruby reader.read_line("> ", value: "edit me") # > edit me ``` -------------------------------- ### Programmatically Trigger Key Events with `trigger` Source: https://context7.com/piotrmurach/tty-reader/llms.txt Simulate key events programmatically using the `trigger` method. This is useful for creating custom key bindings or for testing. You can trigger standard key events or custom events with associated data. ```ruby require "tty-reader" reader = TTY::Reader.new # Set up event handlers first reader.on(:keydown) { |e| puts "Moving down in history" } reader.on(:keyup) { |e| puts "Moving up in history" } reader.on(:keyhome) { |e| puts "Cursor to start" } reader.on(:keyend) { |e| puts "Cursor to end" } # Custom keybindings: trigger events based on input reader.on(:keypress) do |event| case event.value when "j" then reader.trigger(:keydown) # vim down when "k" then reader.trigger(:keyup) # vim up when "0" then reader.trigger(:keyhome) # vim line start when "$" then reader.trigger(:keyend) # vim line end when "q" puts "Quitting..." exit end end # Trigger with custom event data reader.on(:custom_save) do |data| puts "Saving: #{data}" end reader.trigger(:custom_save, "document.txt") loop do reader.read_line("vim> ") end ``` -------------------------------- ### Subscribe Objects to Key Events Source: https://context7.com/piotrmurach/tty-reader/llms.txt Subscribe objects to receive all key events by implementing methods that match event names (e.g., `keypress`, `keyenter`). Subscriptions can be block-scoped for temporary event handling or manually managed with `subscribe` and `unsubscribe`. ```ruby require "tty-reader" # Define a listener class class InputLogger def keypress(event) puts "[LOG] Key: #{event.value.inspect}" end def keyenter(event) puts "[LOG] Line submitted: #{event.line}" end def keyctrl_c(event) puts "[LOG] Interrupt!" exit end end class CommandHandler def keypress(event) # Handle special commands if event.line.start_with?("/") puts "Command detected: #{event.line}" end end end reader = TTY::Reader.new logger = InputLogger.new handler = CommandHandler.new # Subscribe objects reader.subscribe(logger) reader.subscribe(handler) # Block-scoped subscription (auto-unsubscribes after block) reader.subscribe(InputLogger.new) do reader.read_line("temp> ") # Logger only active during this call end # Manual unsubscription reader.unsubscribe(logger) # Continue with remaining subscribers loop do reader.read_line("=> ") end ``` -------------------------------- ### Trigger Key Events Manually Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Explains how to manually trigger key events using the `trigger` method. This is useful for simulating user input or testing event handling logic. ```ruby reader.trigger(:keydown) reader.trigger(:keyup) ``` -------------------------------- ### Subscribe to Events for Block Duration Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Demonstrates an alternative way to use `subscribe` where an object listens to events only for the duration of a block's execution. This is useful for temporary event handling. ```ruby reader.subscribe(MyListener) do ... end ``` -------------------------------- ### Handle Character Input Events with TTY Reader Source: https://context7.com/piotrmurach/tty-reader/llms.txt This snippet demonstrates how to use the `reader.on` method to capture different types of key presses, including alphanumeric keys, navigation keys, control key combinations, and function keys. It also shows a comprehensive handler for various key events. ```ruby require "tty-reader" reader = TTY::Reader.new # Character input events reader.on(:keypress) { |e| } # Any key press reader.on(:keyenter) { |e| } # Enter/Return key reader.on(:keyreturn) { |e| } # Return key reader.on(:keytab) { |e| } # Tab key reader.on(:keybackspace){ |e| } # Backspace key reader.on(:keyspace) { |e| } # Space key reader.on(:keyescape) { |e| } # Escape key reader.on(:keydelete) { |e| } # Delete key reader.on(:keyalpha) { |e| } # Any letter (a-z, A-Z) reader.on(:keynum) { |e| } # Any number (0-9) # Navigation events reader.on(:keyup) { |e| } # Up arrow reader.on(:keydown) { |e| } # Down arrow reader.on(:keyleft) { |e| } # Left arrow reader.on(:keyright) { |e| } # Right arrow reader.on(:keyhome) { |e| } # Home key reader.on(:keyend) { |e| } # End key reader.on(:keyclear) { |e| } # Clear key # Ctrl key combinations (Ctrl+A through Ctrl+Z) reader.on(:keyctrl_a) { |e| } # Ctrl+A (often: select all / move to start) reader.on(:keyctrl_c) { |e| } # Ctrl+C (interrupt) reader.on(:keyctrl_d) { |e| } # Ctrl+D (EOF) reader.on(:keyctrl_e) { |e| } # Ctrl+E (often: move to end) reader.on(:keyctrl_k) { |e| } # Ctrl+K (often: kill line) reader.on(:keyctrl_l) { |e| } # Ctrl+L (often: clear screen) reader.on(:keyctrl_u) { |e| } # Ctrl+U (often: clear line) reader.on(:keyctrl_w) { |e| } # Ctrl+W (often: delete word) reader.on(:keyctrl_x) { |e| } # Ctrl+X reader.on(:keyctrl_z) { |e| } # Ctrl+Z (suspend/EOF on Windows) # Function keys (F1 through F24) reader.on(:keyf1) { |e| } # F1 reader.on(:keyf2) { |e| } # F2 reader.on(:keyf12) { |e| } # F12 # Example: Comprehensive key handler reader.on(:keypress) do |event| key = event.key case key.name when :alpha modifier = key.shift ? "Shift+" : "" puts "#{modifier}Letter: #{event.value}" when :num puts "Number: #{event.value}" when :up, :down, :left, :right puts "Arrow: #{key.name}" else puts "Other key: #{key.name}" end end loop { reader.read_line("=> ") } ``` -------------------------------- ### Build Interactive Shell with TTY::Reader Source: https://context7.com/piotrmurach/tty-reader/llms.txt This Ruby code defines a `Shell` class that utilizes TTY::Reader to create an interactive command-line interface. It handles user input, command parsing, custom keybindings for screen clearing and interrupt handling, and autocompletion for predefined commands. Dependencies include the 'tty-reader' gem. ```ruby require "tty-reader" class Shell COMMANDS = %w[help list show create delete quit exit clear history] def initialize @reader = TTY::Reader.new( interrupt: :noop, history_cycle: false, history_duplicates: false, completion_handler: method(:complete), completion_suffix: " " ) setup_keybindings end def complete(word) COMMANDS.grep(/^#{Regexp.escape(word)}/i) end def setup_keybindings @reader.on(:keyctrl_c) do puts "\nUse 'quit' or 'exit' to leave" end @reader.on(:keyctrl_l) do print "\e[2J\e[H" # Clear screen end @reader.on(:keyescape) do puts "\nEscape pressed" end end def run puts "Welcome to MyShell v1.0" puts "Type 'help' for commands, Tab for completion" puts "" loop do input = @reader.read_line("myshell> ").strip case input when "" next when "quit", "exit" puts "Goodbye!" break when "help" puts "Available commands: #{COMMANDS.join(', ')}" when "clear" print "\e[2J\e[H" when "history" puts "History feature enabled - use up/down arrows" when /^list/ puts "Listing items..." when /^show (.+)/ puts "Showing: #{$1}" when /^create (.+)/ puts "Creating: #{$1}" when /^delete (.+)/ puts "Deleting: #{$1}" else puts "Unknown command: #{input}" end end end end Shell.new.run ``` -------------------------------- ### Configure Interrupt Key Behavior Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Details the `:interrupt` configuration option for `TTY::Reader.new`. It allows customization of how the interrupt key (Control-C) is handled, with options like `:signal`, `:exit`, `:noop`, or a custom proc. ```ruby reader = TTY::Reader.new(interrupt: :signal) ``` -------------------------------- ### Configure TTY::Reader History Cycle (Ruby) Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Sets the `:history_cycle` option for TTY::Reader to `true`, enabling infinite navigation through the history buffer. This allows users to cycle back to the beginning of the history after reaching the end, and vice-versa. ```ruby reader = TTY::Reader.new(history_cycle: true) ``` -------------------------------- ### Read Multiline Input in Raw Mode Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Shows how to read multiline input using `read_multiline`. In raw mode (default), it functions as a multiline editor with support for control characters and history navigation. Input is terminated by Ctrl+d or Ctrl+z. ```ruby reader.read_multiline # => [ "line1", "line2", ... ] ``` -------------------------------- ### Configure Input History with TTY Reader Source: https://context7.com/piotrmurach/tty-reader/llms.txt This snippet shows how to configure input history tracking in TTY Reader. It covers disabling history, enabling it, and customizing behavior like history cycling, duplicate entries, size limits, and excluding specific lines from history. ```ruby require "tty-reader" # Disable history entirely reader = TTY::Reader.new(track_history: false) # Configure history behavior reader = TTY::Reader.new( track_history: true, # Enable history (default) history_cycle: true, # Wrap around at beginning/end history_duplicates: false, # Don't store duplicate lines history_size: 1000, # Store up to 1000 entries history_exclude: ->(line) { # Exclude empty lines and commands starting with space line.strip.empty? || line.start_with?(" ") } ) # History is shared across read_line calls puts "Enter commands (use up/down arrows for history):" 5.times do |i| input = reader.read_line("[#{i + 1}]> ") puts "Recorded: #{input.strip}" end # History works with multiline too reader.read_multiline(">>") ``` -------------------------------- ### Configure Interrupt Handling with TTY Reader Source: https://context7.com/piotrmurach/tty-reader/llms.txt This snippet illustrates different ways to configure how TTY Reader handles the Ctrl+C interrupt signal. Options include raising an error, sending a signal, exiting the process, doing nothing, or executing a custom handler. ```ruby require "tty-reader" # Default: raises InputInterrupt exception reader = TTY::Reader.new(interrupt: :error) try reader.read_line("=> ") rescue TTY::Reader::InputInterrupt puts "\nInput interrupted!" end # Send SIGINT signal to process reader = TTY::Reader.new(interrupt: :signal) # Exit with status code 130 reader = TTY::Reader.new(interrupt: :exit) # Ignore Ctrl+C entirely reader = TTY::Reader.new(interrupt: :noop) # Custom handler with Proc reader = TTY::Reader.new( interrupt: -> { puts "\nCtrl+C pressed - type 'quit' to exit" } ) loop do input = reader.read_line("=> ") break if input.strip == "quit" end ``` -------------------------------- ### Handle Key Events with KeyEvent Object Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Details the properties of the `KeyEvent` object yielded to event listeners. It provides access to the pressed key (`key`), its value (`value`), and the current line content (`line`). ```ruby reader.on(:keypress) do |event| if event.value == "j" ... end if event.value == "k" ... end end ``` -------------------------------- ### Read Multiline Input in Cooked Mode Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Illustrates how to read multiline input in 'cooked' mode by setting the `:raw` option to `false`. In this mode, keystrokes are interpreted by the terminal, not TTY::Reader. ```ruby reader.read_line(raw: false) ``` -------------------------------- ### Read Multiline Input with TTY::Reader in Ruby Source: https://context7.com/piotrmurach/tty-reader/llms.txt Captures multiple lines of input until an exit key (like Ctrl+D or Ctrl+Z) is pressed, returning an array of lines. Supports custom prompts for each line, pre-populated initial text, and processing lines as they are entered via a block. ```ruby require "tty-reader" reader = TTY::Reader.new # Basic multiline input puts "Enter your message (Ctrl+D to finish):" lines = reader.read_multiline puts "You entered #{lines.length} lines" puts lines.join # With prompt prefix for each line puts "Enter notes (Ctrl+D to finish):" notes = reader.read_multiline(">> ") # >> First line # >> Second line # >> ^D puts "Notes:\n#{notes.join}" # Pre-populated first line lines = reader.read_multiline("> ", value: "Edit this text") # Process lines as they're entered using block form puts "Enter commands (Ctrl+D to finish):" reader.read_multiline("$ ") do |line| puts "Processing: #{line.strip}" end # Custom exit keys lines = reader.read_multiline("| ", exit_keys: [:ctrl_d, :ctrl_z, :escape]) ``` -------------------------------- ### read_keypress / read_char Source: https://context7.com/piotrmurach/tty-reader/llms.txt Reads a single keypress from the terminal. Useful for building interactive menus or capturing hotkeys. ```APIDOC ## read_keypress / read_char ### Description Reads a single keypress without waiting for Enter. Returns the character pressed as a string. Useful for building interactive menus or capturing hotkeys. ### Method Instance Method ### Endpoint reader.read_keypress(echo: boolean, nonblock: boolean) ### Parameters #### Parameters - **echo** (Boolean) - Optional - Whether to echo the character on the screen (default: false) - **nonblock** (Boolean) - Optional - Non-blocking mode (returns nil if no input available) ### Request Example ```ruby require "tty-reader" reader = TTY::Reader.new # Basic keypress reading (blocking, no echo) char = reader.read_keypress puts "You pressed: #{char.inspect}" # => "You pressed: \"a\"" # With echo enabled (shows character on screen) char = reader.read_keypress(echo: true) # Non-blocking mode (returns nil if no input available) char = reader.read_keypress(nonblock: true) if char puts "Key: #{char} (code: #{char.ord})" else puts "No key pressed" end # Example: Wait for specific key puts "Press 'y' to continue or 'n' to cancel" loop do char = reader.read_keypress case char.downcase when 'y' puts "Continuing..." break when 'n' puts "Cancelled" exit end end ``` ### Response #### Success Response (String or nil) - **char** (String or nil) - The character pressed, or nil if nonblock is true and no key is pressed. ``` -------------------------------- ### Read Single Keypress with TTY::Reader in Ruby Source: https://context7.com/piotrmurach/tty-reader/llms.txt Reads a single keypress without requiring Enter, returning the character as a string. Supports options for echoing the character to the screen and non-blocking reads. Useful for hotkeys and interactive menus. ```ruby require "tty-reader" reader = TTY::Reader.new # Basic keypress reading (blocking, no echo) char = reader.read_keypress puts "You pressed: #{char.inspect}" # => "You pressed: \"a\"" # With echo enabled (shows character on screen) char = reader.read_keypress(echo: true) # Non-blocking mode (returns nil if no input available) char = reader.read_keypress(nonblock: true) if char puts "Key: #{char} (code: #{char.ord})" else puts "No key pressed" end # Example: Wait for specific key puts "Press 'y' to continue or 'n' to cancel" loop do char = reader.read_keypress case char.downcase when 'y' puts "Continuing..." break when 'n' puts "Cancelled" exit end end ``` -------------------------------- ### Configure TTY::Reader History Size (Ruby) Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Sets the `:history_size` option for TTY::Reader to `2048`, increasing the maximum number of lines that can be stored in the history buffer. The default size is `512` lines. ```ruby reader = TTY::Reader.new(history_size: 2048) ``` -------------------------------- ### Read Line with Editing and History using TTY::Reader in Ruby Source: https://context7.com/piotrmurach/tty-reader/llms.txt Reads a line of input with full editing capabilities, including cursor navigation and history. Returns the entered text upon pressing Enter. Supports custom prompts, pre-populated values, password input, and custom exit keys. ```ruby require "tty-reader" reader = TTY::Reader.new # Basic line reading input = reader.read_line puts "You entered: #{input}" # With custom prompt name = reader.read_line("Enter your name: ") puts "Hello, #{name.strip}!" # Pre-populated value for editing filename = reader.read_line("File: ", value: "document.txt") # Without echo (for passwords) password = reader.read_line("Password: ", echo: false) # Cooked mode (let terminal handle input) input = reader.read_line("Input: ", raw: false) # With custom exit keys (stop on Tab or Escape) input = reader.read_line("Search: ", exit_keys: [:tab, :escape]) # Example: Simple REPL puts "Simple Calculator (type 'exit' to quit)" loop do input = reader.read_line("calc> ") break if input.strip == "exit" begin result = eval(input) # Note: eval is dangerous in production! puts "=> #{result}" rescue => e puts "Error: #{e.message}" end end ``` -------------------------------- ### Unsubscribe an Object from Key Events Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Shows how to remove an object from the list of event listeners using the `unsubscribe` method. This stops the object from receiving further key event notifications. ```ruby reader.unsubscribe(my_listener) ``` -------------------------------- ### read_multiline Source: https://context7.com/piotrmurach/tty-reader/llms.txt Reads multiple lines of input until a specific exit key is pressed. ```APIDOC ## read_multiline ### Description Read multiple lines of input until Ctrl+D (Unix) or Ctrl+Z (Windows) is pressed. Returns an array of lines. Useful for capturing text blocks or multi-line configurations. ### Method Instance Method ### Endpoint reader.read_multiline(prompt: string, value: string, exit_keys: array of symbols) { |line| ... } ### Parameters #### Parameters - **prompt** (String) - Optional - The prompt to display before each line. - **value** (String) - Optional - Pre-populated first line. - **exit_keys** (Array of Symbols) - Optional - Keys that will terminate input. - **block** (Block) - Optional - A block to process each line as it's entered. ### Request Example ```ruby require "tty-reader" reader = TTY::Reader.new # Basic multiline input puts "Enter your message (Ctrl+D to finish):" lines = reader.read_multiline puts "You entered #{lines.length} lines" puts lines.join # With prompt prefix for each line puts "Enter notes (Ctrl+D to finish):" notes = reader.read_multiline(">> ") # >> First line # >> Second line # >> ^D puts "Notes:\n#{notes.join}" # Pre-populated first line lines = reader.read_multiline("> ", value: "Edit this text") # Process lines as they're entered using block form puts "Enter commands (Ctrl+D to finish):" reader.read_multiline("$ ") do |line| puts "Processing: #{line.strip}" end # Custom exit keys lines = reader.read_multiline("| ", exit_keys: [:ctrl_d, :ctrl_z, :escape]) ``` ### Response #### Success Response (Array of Strings) - **lines** (Array) - An array of strings, each representing a line of input. ``` -------------------------------- ### Disable Input History Tracking Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Shows how to disable the input history buffer for `read_line` and `read_multiline` using the `:track_history` option set to `false`. This prevents the up/down arrow keys from navigating through previous inputs. ```ruby reader = TTY::Reader.new(track_history: false) ``` -------------------------------- ### Configure TTY::Reader History Duplicates (Ruby) Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Sets the `:history_duplicates` option for TTY::Reader to `true`, allowing duplicate lines to be stored in the history buffer. By default, duplicate lines are not stored. ```ruby reader = TTY::Reader.new(history_duplicates: true) ``` -------------------------------- ### Configure TTY::Reader History Exclude (Ruby) Source: https://github.com/piotrmurach/tty-reader/blob/master/README.md Sets the `:history_exclude` option for TTY::Reader using a Proc to define custom logic for excluding lines from history. The Proc receives the line as an argument. By default, empty lines are excluded. ```ruby reader = TTY::Reader.new(history_exclude: ->(line) { ... }) ``` -------------------------------- ### read_line Source: https://context7.com/piotrmurach/tty-reader/llms.txt Reads a single line of input from the terminal, with line editing support. ```APIDOC ## read_line ### Description Read a single line of input with full line editing support including cursor movement, backspace, delete, and history navigation. Returns the entered text when Enter is pressed. ### Method Instance Method ### Endpoint reader.read_line(prompt: string, value: string, echo: boolean, raw: boolean, exit_keys: array of symbols) ### Parameters #### Parameters - **prompt** (String) - Optional - The prompt to display to the user. - **value** (String) - Optional - Pre-populated value for editing. - **echo** (Boolean) - Optional - Whether to echo the input (e.g. for passwords). - **raw** (Boolean) - Optional - Whether to disable terminal processing of input. - **exit_keys** (Array of Symbols) - Optional - Keys that will terminate input. ### Request Example ```ruby require "tty-reader" reader = TTY::Reader.new # Basic line reading input = reader.read_line puts "You entered: #{input}" # With custom prompt name = reader.read_line("Enter your name: ") puts "Hello, #{name.strip}!" # Pre-populated value for editing filename = reader.read_line("File: ", value: "document.txt") # Without echo (for passwords) password = reader.read_line("Password: ", echo: false) # Cooked mode (let terminal handle input) input = reader.read_line("Input: ", raw: false) # With custom exit keys (stop on Tab or Escape) input = reader.read_line("Search: ", exit_keys: [:tab, :escape]) # Example: Simple REPL puts "Simple Calculator (type 'exit' to quit)" loop do input = reader.read_line("calc> ") break if input.strip == "exit" begin result = eval(input) # Note: eval is dangerous in production! puts "=> #{result}" rescue => e puts "Error: #{e.message}" end end ``` ### Response #### Success Response (String) - **input** (String) - The entered text. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.