Class: TTY::Reader
- Inherits:
-
Object
- Object
- TTY::Reader
- Includes:
- Wisper::Publisher
- Defined in:
- lib/tty/reader.rb,
lib/tty/reader/keys.rb,
lib/tty/reader/line.rb,
lib/tty/reader/mode.rb,
lib/tty/reader/console.rb,
lib/tty/reader/history.rb,
lib/tty/reader/version.rb,
lib/tty/reader/win_api.rb,
lib/tty/reader/key_event.rb,
lib/tty/reader/win_console.rb
Overview
A class responsible for reading character input from STDIN
Used internally to provide key and line reading functionality
Defined Under Namespace
Modules: Keys, WinAPI Classes: Console, History, Key, KeyEvent, Line, Mode, WinConsole
Constant Summary collapse
- InputInterrupt =
Raised when the user hits the interrupt key(Control-C)
Class.new(StandardError)
- CARRIAGE_RETURN =
Key codes
13- NEWLINE =
10- BACKSPACE =
8- DELETE =
127- VERSION =
'0.3.0'.freeze
Instance Attribute Summary collapse
- #console ⇒ Object readonly
- #cursor ⇒ Object readonly
- #env ⇒ Object readonly
- #input ⇒ Object readonly
- #output ⇒ Object readonly
- #track_history ⇒ Object (also: #track_history?) readonly
Class Method Summary collapse
-
.windows? ⇒ Boolean
Check if Windowz mode.
Instance Method Summary collapse
- #add_to_history(line) ⇒ Object
-
#clear_display(line, screen_width) ⇒ Object
private
Clear display for the current line input.
-
#count_screen_lines(line_or_size, screen_width = TTY::Screen.width) ⇒ Integer
Count the number of screen lines given line takes up in terminal.
-
#get_codes(options = {}, codes = []) ⇒ Array[Integer]
private
Get input code points.
- #history_next ⇒ Object
- #history_next? ⇒ Boolean
- #history_previous ⇒ Object
- #history_previous? ⇒ Boolean
-
#initialize(**options) ⇒ Reader
constructor
Initialize a Reader.
-
#inspect ⇒ String
Inspect class name and public attributes.
-
#keyctrl_d ⇒ Object
(also: #keyctrl_z)
private
Capture Ctrl+d and Ctrl+z key events.
- #old_subcribe ⇒ Object
-
#read_keypress(options = {}) ⇒ String
(also: #read_char)
Read a keypress including invisible multibyte codes and return a character as a string.
-
#read_line(prompt = '', **options) ⇒ String
Get a single line from STDIN.
-
#read_multiline(*args) {|String| ... } ⇒ Array[String]
(also: #read_lines)
Read multiple lines and return them in an array.
-
#select_console(input) ⇒ Object
private
Select appropriate console.
-
#subscribe(listener, options = {}) ⇒ self|yield
Subscribe to receive key events.
-
#trigger(event, *args) ⇒ Object
Expose event broadcasting.
-
#unbufferred(&block) ⇒ Object
Get input in unbuffered mode.
-
#unsubscribe(listener) ⇒ void
Unsubscribe from receiving key events.
Constructor Details
#initialize(**options) ⇒ Reader
Initialize a Reader
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/tty/reader.rb', line 70 def initialize(**) @input = .fetch(:input) { $stdin } @output = .fetch(:output) { $stdout } @interrupt = .fetch(:interrupt) { :error } @env = .fetch(:env) { ENV } @track_history = .fetch(:track_history) { true } @history_cycle = .fetch(:history_cycle) { false } exclude_proc = ->(line) { line.strip == '' } @history_exclude = .fetch(:history_exclude) { exclude_proc } @history_duplicates = .fetch(:history_duplicates) { false } @console = select_console(input) @history = History.new do |h| h.cycle = @history_cycle h.duplicates = @history_duplicates h.exclude = @history_exclude end @stop = false # gathering input @cursor = TTY::Cursor subscribe(self) end |
Instance Attribute Details
#console ⇒ Object (readonly)
47 48 49 |
# File 'lib/tty/reader.rb', line 47 def console @console end |
#cursor ⇒ Object (readonly)
49 50 51 |
# File 'lib/tty/reader.rb', line 49 def cursor @cursor end |
#env ⇒ Object (readonly)
42 43 44 |
# File 'lib/tty/reader.rb', line 42 def env @env end |
#input ⇒ Object (readonly)
38 39 40 |
# File 'lib/tty/reader.rb', line 38 def input @input end |
#output ⇒ Object (readonly)
40 41 42 |
# File 'lib/tty/reader.rb', line 40 def output @output end |
#track_history ⇒ Object (readonly) Also known as: track_history?
44 45 46 |
# File 'lib/tty/reader.rb', line 44 def track_history @track_history end |
Class Method Details
.windows? ⇒ Boolean
Check if Windowz mode
34 35 36 |
# File 'lib/tty/reader.rb', line 34 def self.windows? ::File::ALT_SEPARATOR == '\\' end |
Instance Method Details
#add_to_history(line) ⇒ Object
383 384 385 |
# File 'lib/tty/reader.rb', line 383 def add_to_history(line) @history.push(line) end |
#clear_display(line, screen_width) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Clear display for the current line input
Handles clearing input that is longer than the current terminal width which allows copy & pasting long strings.
308 309 310 311 312 313 314 315 |
# File 'lib/tty/reader.rb', line 308 def clear_display(line, screen_width) total_lines = count_screen_lines(line.size, screen_width) current_line = count_screen_lines(line.prompt_size + line.cursor, screen_width) lines_down = total_lines - current_line output.print(cursor.down(lines_down)) unless lines_down.zero? output.print(cursor.clear_lines(total_lines)) end |
#count_screen_lines(line_or_size, screen_width = TTY::Screen.width) ⇒ Integer
Count the number of screen lines given line takes up in terminal
327 328 329 330 331 332 333 334 335 336 |
# File 'lib/tty/reader.rb', line 327 def count_screen_lines(line_or_size, screen_width = TTY::Screen.width) line_size = if line_or_size.is_a?(Integer) line_or_size else Line.sanitize(line_or_size).size end # new character + we don't want to add new line on screen_width new_chars = self.class.windows? ? -1 : 1 1 + [0, (line_size - new_chars) / screen_width].max end |
#get_codes(options = {}, codes = []) ⇒ Array[Integer]
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Get input code points
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
# File 'lib/tty/reader.rb', line 191 def get_codes( = {}, codes = []) opts = { echo: true, raw: false }.merge() char = console.get_char(opts) handle_interrupt if console.keys[char] == :ctrl_c return if char.nil? codes << char.ord condition = proc { |escape| (codes - escape).empty? || (escape - codes).empty? && !(64..126).cover?(codes.last) } while console.escape_codes.any?(&condition) get_codes(, codes) end codes end |
#history_next ⇒ Object
391 392 393 394 |
# File 'lib/tty/reader.rb', line 391 def history_next @history.next @history.get end |
#history_next? ⇒ Boolean
387 388 389 |
# File 'lib/tty/reader.rb', line 387 def history_next? @history.next? end |
#history_previous ⇒ Object
400 401 402 403 404 |
# File 'lib/tty/reader.rb', line 400 def history_previous line = @history.get @history.previous line end |
#history_previous? ⇒ Boolean
396 397 398 |
# File 'lib/tty/reader.rb', line 396 def history_previous? @history.previous? end |
#inspect ⇒ String
Inspect class name and public attributes
410 411 412 |
# File 'lib/tty/reader.rb', line 410 def inspect "#<#{self.class}: @input=#{input}, @output=#{output}>" end |
#keyctrl_d ⇒ Object Also known as: keyctrl_z
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Capture Ctrl+d and Ctrl+z key events
378 379 380 |
# File 'lib/tty/reader.rb', line 378 def keyctrl_d(*) @stop = true end |
#old_subcribe ⇒ Object
94 |
# File 'lib/tty/reader.rb', line 94 alias old_subcribe subscribe |
#read_keypress(options = {}) ⇒ String Also known as: read_char
Read a keypress including invisible multibyte codes and return a character as a string. Nothing is echoed to the console. This call will block for a single keypress, but will not wait for Enter to be pressed.
173 174 175 176 177 178 179 180 |
# File 'lib/tty/reader.rb', line 173 def read_keypress( = {}) opts = { echo: false, raw: true }.merge() codes = unbufferred { get_codes(opts) } char = codes ? codes.pack('U*') : nil trigger_key_event(char) if char char end |
#read_line(prompt = '', **options) ⇒ String
Get a single line from STDIN. Each key pressed is echoed back to the shell. The input terminates when enter or return key is pressed.
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/tty/reader.rb', line 223 def read_line(prompt = '', **) opts = { echo: true, raw: true }.merge() line = Line.new(prompt, '') screen_width = TTY::Screen.width output.print(line.prompt) while (codes = get_codes(opts)) && (code = codes[0]) char = codes.pack('U*') trigger_key_event(char) break if [:ctrl_d, :ctrl_z].include?(console.keys[char]) if opts[:raw] && opts[:echo] clear_display(line, screen_width) end if console.keys[char] == :backspace || BACKSPACE == code if !line.start? line.left line.delete end elsif console.keys[char] == :delete || DELETE == code line.delete elsif console.keys[char].to_s =~ /ctrl_/ # skip elsif console.keys[char] == :up line.replace(history_previous) if history_previous? elsif console.keys[char] == :down line.replace(history_next? ? history_next : '') elsif console.keys[char] == :left line.left elsif console.keys[char] == :right line.right elsif console.keys[char] == :home line.move_to_start elsif console.keys[char] == :end line.move_to_end else if opts[:raw] && code == CARRIAGE_RETURN char = "\n" line.move_to_end end line.insert(char) end if (console.keys[char] == :backspace || BACKSPACE == code) && opts[:echo] if opts[:raw] output.print("\e[1X") unless line.start? else output.print(?\s + (line.start? ? '' : ?\b)) end end if opts[:raw] && opts[:echo] output.print(line.to_s) if char == "\n" line.move_to_start elsif !line.end? # readjust cursor position output.print(cursor.backward(line.text_size - line.cursor)) end end if [CARRIAGE_RETURN, NEWLINE].include?(code) output.puts unless opts[:echo] break end end if track_history? && opts[:echo] add_to_history(line.text.rstrip) end line.text end |
#read_multiline(*args) {|String| ... } ⇒ Array[String] Also known as: read_lines
Read multiple lines and return them in an array. Skip empty lines in the returned lines array. The input gathering is terminated by Ctrl+d or Ctrl+z.
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
# File 'lib/tty/reader.rb', line 350 def read_multiline(*args) @stop = false lines = [] loop do line = read_line(*args) break if !line || line == '' next if line !~ /\S/ && !@stop if block_given? yield(line) unless line.to_s.empty? else lines << line unless line.to_s.empty? end break if @stop end lines end |
#select_console(input) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Select appropriate console
134 135 136 137 138 139 140 |
# File 'lib/tty/reader.rb', line 134 def select_console(input) if self.class.windows? && !env['TTY_TEST'] WinConsole.new(input) else Console.new(input) end end |
#subscribe(listener, options = {}) ⇒ self|yield
Subscribe to receive key events
104 105 106 107 108 109 110 111 112 |
# File 'lib/tty/reader.rb', line 104 def subscribe(listener, = {}) old_subcribe(listener, ) object = self if block_given? object = yield unsubscribe(listener) end object end |
#trigger(event, *args) ⇒ Object
Expose event broadcasting
371 372 373 |
# File 'lib/tty/reader.rb', line 371 def trigger(event, *args) publish(event, *args) end |
#unbufferred(&block) ⇒ Object
Get input in unbuffered mode.
150 151 152 153 154 155 156 157 |
# File 'lib/tty/reader.rb', line 150 def unbufferred(&block) bufferring = output.sync # Immediately flush output output.sync = true block[] if block_given? ensure output.sync = bufferring end |
#unsubscribe(listener) ⇒ void
This method returns an undefined value.
Unsubscribe from receiving key events
122 123 124 125 126 127 128 129 |
# File 'lib/tty/reader.rb', line 122 def unsubscribe(listener) registry = send(:local_registrations) registry.each do |object| if object.listener.equal?(listener) registry.delete(object) end end end |