Module: Typr

Included in:
Space
Defined in:
lib/terminal.rb,
lib/grid.rb,
lib/line.rb,
lib/text.rb,
lib/space.rb,
lib/stack.rb,
lib/browser.rb

Overview

Terminal control: raw key input, line editing, cursor movement, ANSI colors and terminal geometry. Widgets get the instance helpers via include Typr; class-level helpers (Typr.width, Typr.read_key, ...) drive the whole screen.

Defined Under Namespace

Classes: Browser, Grid, Line, Mouse, Space, Stack, Text

Constant Summary collapse

MIMETYPES =
eval File.read( __dir__ + "/../share/mimetypes" )
INPUT =

Raw /dev/tty used for key input; falls back to $stdin when unavailable.

(IO.new IO.sysopen("/dev/tty", "r")) rescue $stdin
TERMINFO =

KEY_* escapes and keypad sequences are precompiled into share/terminfo by bin/build_terminfo, so the runtime needs no ncurses/infocmp (e.g. Termux).

begin
  eval File.read(File.expand_path("../share/terminfo", __dir__))
rescue StandardError
  {}
end
DEFAULT_KEYS =

Known-good fallback so KEY_* are always defined, even for TERM=dumb.

{ "key_up" => "\eOA", "key_down" => "\eOB", "key_left" => "\eOD",
"key_right" => "\eOC", "key_home" => "\eOH", "key_end" => "\eOF",
"key_backspace" => "\x7f", "key_dc" => "\e[3~", "key_npage" => "\e[6~",
"key_ppage" => "\e[5~", "carriage_return" => "\r",
"keypad_xmit" => "\e[?1h\e=", "keypad_local" => "\e[?1l\e>",
"cursor_invisible" => "\e[?25l", "cursor_normal" => "\e[?25h",
"clear_screen" => "\e[H\e[2J", "user7" => "\e[6n" }
ERASE_LINE =

Common key aliases and the line-erase escape sequence.

"\e[K"
ORIG_COLORS =

Reset foreground/background to the terminal defaults.

"\e[39;49m"
KEY_ESCAPE =
"\e"
KEY_RETURN =
CARRIAGE_RETURN
KEY_TAB =
"\t"
KEY_BACK_TAB =
"\e[Z"
KEY_ALT_BACKSPACE =
"\e\x7f"
KEY_ALT_LEFT =
"\e[1;3D"
KEY_ALT_RIGHT =
"\e[1;3C"
KEY_PAGEDOWN =
KEY_NPAGE
KEY_PAGEUP =
KEY_PPAGE
MOUSE_ON =

Enable/disable mouse reporting. Universal private modes, independent of terminfo: 1000 = button press/release/wheel, 1006 = SGR coordinates.

"\e[?1000h\e[?1006h"
MOUSE_OFF =
"\e[?1000l\e[?1006l"
ALT_SCREEN_ON =
"\e[?1049h"
ALT_SCREEN_OFF =
"\e[?1049l"
MODES =

Text attributes (reset, bold, italic, ...) and named 8/256-color tables.

i[ reset bold italic underline slow fast invert ]
COLORS =
i[ black red green yellow blue magenta cyan white ]
COLOR_MAP =
{
  brown: 130, orange: 208, lime: 118, pink: 218,
  maroon: 52, navy: 18, teal: 30, olive: 100,
  coral: 203, tan: 180,
  dark_red: 88, dark_green: 22, dark_yellow: 58,
  dark_blue: 18, dark_magenta: 89, dark_cyan: 30
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.clear(mode = :screen) ⇒ Object

Clear the whole screen (:screen) or just the current line (:line).



252
253
254
# File 'lib/terminal.rb', line 252

def self.clear mode=:screen
  $>.print( { screen: CLEAR_SCREEN, line: ERASE_LINE }[mode]  )
end

.columnObject



461
# File 'lib/terminal.rb', line 461

def self.column; position.last end

.decode_mouse(raw) ⇒ Object

Decode a raw input string into a Mouse event, or nil when raw is not a mouse report. Handles both SGR (CSI < b ; x ; y M/m) and the legacy X10 (CSI M + three bytes) encodings.



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/terminal.rb', line 286

def self.decode_mouse raw
  if (m = raw.match(/\A\e\[<(\d+);(\d+);(\d+)([Mm])\z/))
    code, x, y, final = m[1].to_i, m[2].to_i, m[3].to_i, m[4]
  elsif raw.start_with?("\e[M")
    code, x, y = raw.getbyte(3) - 32, raw.getbyte(4) - 32, raw.getbyte(5) - 32
    final = code == 3 ? ?m : ?M
  else
    return nil
  end
  modifiers = code & 28
  base = code & ~28
  motion = (base & 32) != 0
  wheel = base >= 64
  button = wheel ? base - 64 + 4 : base & 3
  action = if motion then :motion
    elsif wheel then final == ?m ? :release : :press
    else ( final == ?m or code == 3 ) ? :release : :press end
  Mouse.new button, x, y, action, modifiers
end

.exitObject

Restore the terminal: show the cursor, reset keypad/colors, disable mouse reporting and clear.



480
481
482
483
484
485
486
487
488
# File 'lib/terminal.rb', line 480

def self.exit;
extend self
  if $stdin.tty?
    $>.print CURSOR_NORMAL;
    $>.print KEYPAD_LOCAL if defined?(KEYPAD_LOCAL)
    $>.print MOUSE_OFF
    $>.print ORIG_COLORS; color; clear
  end
end

.heightObject



457
# File 'lib/terminal.rb', line 457

def self.height; size.first - 1 end

.init(default = [ :white, :black ]) ⇒ Object

Enter interactive mode: seed the default colors, hide the cursor, enable key-mode (application) escapes and mouse reporting when stdin is a tty.



469
470
471
472
473
474
475
476
477
# File 'lib/terminal.rb', line 469

def self.init default=[ :white, :black  ]
  $default = default.dup
  $color = $default.dup
  if $stdin.tty?
    print CURSOR_INVISIBLE
    print KEYPAD_XMIT if defined?(KEYPAD_XMIT)
    print MOUSE_ON
  end
end

.on_resize(&block) ⇒ Object

Call block whenever the terminal is resized (SIGWINCH).



464
465
466
# File 'lib/terminal.rb', line 464

def self.on_resize &block
  trap(:WINCH, &block)
end

.positionObject

Query the terminal for the current [row, column] via DSR; [0, 0] when stdin is not a tty.



440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/terminal.rb', line 440

def self.position
  return [0, 0] unless $stdin.tty?
  result = ''
  $stdin.raw do |stdin|
    $stdout << USER7
    $stdout.flush
    until (char = stdin.getc) == 'R'
      result << char if char
    end
  end
  result[/[\d;]+/].split(?;).map &:to_i
end

.read_keyObject

Reads a single keypress in raw mode.

Returns the key sequence as a String (e.g. "a" or "\e[A" for up-arrow), or a Typr::Mouse for a mouse report, or nil when stdin is not a tty or input is unavailable.



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/terminal.rb', line 262

def self.read_key
  read = ->(tty) do
    str = tty.sysread 6
    if str.start_with?("\e[M") and str.size < 6
      str << tty.sysread(6 - str.size) # X10 mouse reports
    elsif str.start_with?("\e[")
      # CSI sequences (arrows, SGR mouse, ...) end with a byte >= 0x40.
      str << tty.sysread(1) until str[-1].ord >= 0x40
    elsif str.start_with?("\eO") and str.size < 3
      str << tty.sysread(3 - str.size) # SS3 (application) cursor keys
    elsif str == "\e" and IO.select([tty], nil, nil, 0.03)
      str << tty.read_nonblock(6) rescue nil # alt+key continuation
    end
    str
  end
  raw = (INPUT.raw{ |tty| read.call tty } rescue nil)
  return unless raw
  decode_mouse(raw) || raw
end

.read_line(prompt = '', left: 0, top: 0, initial: '', completions: nil, redraw: nil, &block) ⇒ Object

Interactive line editor used for string prompts (search, %str, ...).

Renders prompt and the query at (left, top) and edits it with arrow keys, ctrl-arrow word jumps, home/end, delete and backspace. Returns the query on enter, nil on escape. A block may inspect each keypress after it is applied; a non-nil return short-circuits the editor and becomes its return value. When stdin is not a tty, the query is read from a single line of piped input instead.

Typr.read_line "/" do |key, query, cursor|
filter query
nil
end


320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/terminal.rb', line 320

def self.read_line prompt='', left: 0, top: 0, initial: '', completions: nil, redraw: nil, &block
  return $stdin.gets&.chomp unless $stdin.tty?
  query, cursor = initial.dup, initial.length
  $>.print CURSOR_NORMAL
  begin
    loop do
      $>.print "\e[%i;%if" % [ top + 1, left + 1 ]
      $>.print ERASE_LINE
      before = text_width( prompt + query[0...cursor] )
      offset = [ left + before - Typr.width, 0 ].max
      $>.print slice_width( prompt + query, offset, Typr.width - left + 1 )
      $>.print "\e[%i;%if" % [ top + 1, left + 1 + before - offset ]
      key = read_key
      return nil if key.nil? or key == KEY_ESCAPE
      return query if key == KEY_RETURN or key == "\n"
      case key
        when KEY_LEFT, "\e[D";    cursor -= 1 if cursor > 0
        when KEY_RIGHT, "\e[C";   cursor += 1 if cursor < query.length
        when KEY_ALT_LEFT, "\eD";    cursor = word_prev query, cursor
        when KEY_ALT_RIGHT, "\eC";   cursor = word_next query, cursor
        when KEY_HOME;            cursor = 0
        when KEY_END;             cursor = query.length
        when KEY_DC, "\e[3~";     query.slice!(cursor, 1) if cursor < query.length
        when KEY_ALT_BACKSPACE
          old = cursor
          cursor = word_prev query, cursor
          query.slice!(cursor, old - cursor)
        when KEY_BACKSPACE, "\b"
          if cursor > 0
            query.slice!(cursor - 1, 1)
            cursor -= 1
          end
        else
          if key.is_a?(String) and key.each_char.all?{ |char| char.ord.between?(32, 126) }
            query.insert(cursor, key)
            cursor += key.length
          end
      end
      cursor = 0 if cursor < 0
      cursor = query.length if cursor > query.length
      result = block.call( key, query, cursor ) if block
      return result unless result.nil?
      if completions and key == KEY_TAB
        raw = query[0...cursor]
        cmd = raw[/\w+/]
        if cmd
          items = IO.popen([{ 'COMP_LINE' => raw, 'COMP_POINT' => raw.bytesize.to_s },
            'bash', '-c', "            _init_completion(){ cur=${COMP_WORDS[COMP_CWORD]}; prev=${COMP_WORDS[COMP_CWORD-1]}; }\n            source /usr/share/bash-completion/completions/\#{cmd} 2>/dev/null || exit\n            COMP_WORDS=($COMP_LINE) COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 ))\n            Fn=$(complete -p \#{cmd} 2>/dev/null | awk '{print $(NF-1)}')\n            eval \"$Fn\" 2>/dev/null && printf '%s\\\\n' \"${COMPREPLY[@]}\"\n          SH\n          items = items.split(\"\\n\").reject(&:empty?).uniq\n          if items.any?\n            grid = Grid.new(left: left, top: [top - items.size - 3, 0].max,\n              input: items.map{ |s| [s] }, border: :light,\n              colors: { columns: [[:blue, :default]] })\n            picked = grid.pick(:row, column: 0)\n            redraw&.call\n            $>.print CURSOR_NORMAL\n            if picked.is_a?(Integer)\n              word_start = cursor\n              word_start -= 1 while word_start > 0 and query[word_start - 1] != ' '\n              query[word_start...cursor] = items[picked]\n              cursor = word_start + items[picked].length\n            end\n          end\n        end\n      end\n    end\n  ensure\n    $>.print CURSOR_INVISIBLE\n  end\nend\n"], err: '/dev/null', &:read)

.rowObject

Current cursor row/column (see position).



460
# File 'lib/terminal.rb', line 460

def self.row; position.first end

.sizeObject

Terminal [rows, cols] (defaults to 24x80 when undetectable); width/height return the usable last column/row.



455
# File 'lib/terminal.rb', line 455

def self.size; IO.console&.winsize || [24, 80] end

.slice_width(str, offset, width) ⇒ Object

Visible substring of str starting at display-width offset, at most width cells wide. ANSI escapes are zero-width and carried through so color state applies inside the window.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/terminal.rb', line 405

def self.slice_width str, offset, width
  vis = 0
  slice = +""
  i = 0
  while i < str.length
    if str[i] == "\e"
      seq = str[i..][/\A\e(\[[0-9;?]*[ -\/]*[@-~]|\][^\a\e]*(?:\a|\e\\)|[()=>0-9])/]
      slice << seq if seq
      i += seq ? seq.length : 1
      next
    end
    cell = Unicode::DisplayWidth.of(str[i])
    vis += cell
    slice << str[i] if vis > offset and vis <= offset + width
    i += 1
  end
  slice
end

.text_width(str) ⇒ Object

Display width of str after stripping ANSI escapes.



398
399
400
# File 'lib/terminal.rb', line 398

def self.text_width str
  Unicode::DisplayWidth.of( str.gsub(/\x1b\[[^m]+m/, '') )
end

.widthObject



456
# File 'lib/terminal.rb', line 456

def self.width; size.last-1 end

.word_next(str, cursor) ⇒ Object

Move the cursor forward to the start of the next word in str.



432
433
434
435
436
# File 'lib/terminal.rb', line 432

def self.word_next str, cursor
  cursor += 1 while cursor < str.length and str[cursor] == ' '
  cursor += 1 while cursor < str.length and str[cursor] != ' '
  cursor
end

.word_prev(str, cursor) ⇒ Object

Move the cursor back to the start of the previous word in str.



425
426
427
428
429
# File 'lib/terminal.rb', line 425

def self.word_prev str, cursor
  cursor -= 1 while cursor > 0 and str[cursor - 1] == ' '
  cursor -= 1 while cursor > 0 and str[cursor - 1] != ' '
  cursor
end

Instance Method Details

#background(c = ) ⇒ Object



241
# File 'lib/terminal.rb', line 241

def background c=$default[1]; $color[1]=c; draw color_code(c,true) end

#clip(str, max, side) ⇒ Object

Truncate str to at most max cells, keeping ANSI color tokens intact and clipping from side (:left/:right).



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/terminal.rb', line 124

def clip str, max, side
  tokens = str.scan(/(\e\[[0-9;]*m)|([^\e]+)/).flatten.compact
  tokens.reverse! if side == :left
  kept, used = [], 0
  tokens.each do |token|
    if token[0] == ?\e
      if side == :left
        kept << token unless kept.empty?
        break if used >= max
      else
        kept << token if used < max
      end
      next
    end
    break if used >= max
    size = Unicode::DisplayWidth.of token
    if used + size <= max
      kept << token
      used += size
    elsif used < max
      need = max - used
      chars = token.chars
      chars.reverse! if side == :left
      width = 0
      out = ""
      chars.each do |char|
        width += Unicode::DisplayWidth.of char
        break if width > need
        out << char
      end
      out.reverse! if side == :left
      kept << out
      used = max
    end
  end
  kept.reverse!.join if side == :left
  kept.join
end

#coerce_type(value) ⇒ Object

Coerce a string into Integer, Float, or Boolean when it matches those forms (yes/no, true/false); otherwise return it unchanged.



189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/terminal.rb', line 189

def coerce_type value
  s = value.to_s
  return nil if s.empty? or /\A(?:nil|NULL)\z/i.match(s)
  case value
     when /^-?[\d]+$/ then s.to_i
     when /^-?\d*[\.\,]\d+$/ then s.to_f
     when /\byes\z/i then true
     when /\bno(ot)?\z/i then false
     when /true\z/i then true
     when /false\z/i then false
     else value
  end
end

#color(c = $default) ⇒ Object



242
243
244
245
246
# File 'lib/terminal.rb', line 242

def color c=$default
  c = [c] unless c.is_a? Array and c.count == 2
  foreground c[0] if c[0]
  background c[1] if c[1]
end

#color_code(color, bg = false) ⇒ Object

Build the ANSI code for color (a Symbol name, greyN, Integer palette id, or [r,g,b] / [fg,bg] Array), optionally as a background; when false the color is emitted as a foreground.



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/terminal.rb', line 216

def color_code color, bg=false
  color = color.to_sym if color.is_a? String
  case color
    when Symbol;
      if id = COLORS.index(color); "\e[#{ id + (bg ? 40 : 30) }m"
      elsif color[/^gr[ae]y\d{,2}$/]
        "\e[%i;5;%im" % [bg ? 48 : 38, 232 + (color[/\d+/].to_f/100*23).to_i]
      elsif id = COLOR_MAP[color]
        "\e[%i;5;%im" % [bg ? 48 : 38, id]
      end
    when Integer; "\e[%i;5;%im" % [ bg ? 48 : 38, color]
    when Array; case color.count
      when 3; "\e[%i;2;%i;%i;%im" % [ bg ? 48 : 38, *color ]
      when 2; color_code( color[0] ) +  color_code( color[1], true )
    end
  end
end

#draw(str) ⇒ Object

Write raw str to stdout.



249
# File 'lib/terminal.rb', line 249

def draw str; $>.print str end

#fade(str, side = :left, num = 3) ⇒ Object

Blend the first (or last) num characters of str into greys to hint at clipping; side selects which end fades.



165
166
167
168
169
170
171
172
173
174
# File 'lib/terminal.rb', line 165

def fade str, side=:left, num=3
  isleft = side == :left
  chars = str[ isleft ? 0..num : -num..-1 ]
  chars = chars.chars.map.with_index do |char,id|
    id = chars.size-id unless isleft
    color_code( "grey#{(80/chars.size)*id+10}".to_sym ) + char
  end.join
  return ( isleft ? chars + color_code($color[0]) + str[num+1..-1] :
    str[0..-num-1] + chars )
end

#foreground(c = ) ⇒ Object

Set and apply the foreground/background color; color sets both from a [fg, bg] pair, a single color, or the module default.



240
# File 'lib/terminal.rb', line 240

def foreground c=$default[0]; $color[0]=c; draw color_code(c) end

#get_backgroundObject

Read the current background/foreground color pair.



235
# File 'lib/terminal.rb', line 235

def get_background; $color[1] end

#get_foregroundObject



236
# File 'lib/terminal.rb', line 236

def get_foreground; $color[0] end

#mode(name) ⇒ Object

Apply a text attribute (+mode+); mode_code returns the escape sequence without writing it.



210
# File 'lib/terminal.rb', line 210

def mode name; draw mode_code(name) end

#mode_code(name) ⇒ Object



211
# File 'lib/terminal.rb', line 211

def mode_code name; if id = MODES.index(name.to_s) then "\e[#{ id }m" end end

#move(x = 0, y = 0) ⇒ Object

Move the cursor to column x, row y (0-based); move_code returns the escape sequence without writing it.



205
# File 'lib/terminal.rb', line 205

def move x=0,y=0; draw move_code( x, y ) end

#move_code(x = 0, y = 0) ⇒ Object



206
# File 'lib/terminal.rb', line 206

def move_code x=0,y=0; "\e[%i;%if" % [ y+1, x+1 ] end

#prepare(str, max, align = :left, side = :right, fade = false) ⇒ Object

Pad or clip str to exactly max cells, honoring align (:left/:right), trimming from side, with an optional trailing fade.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/terminal.rb', line 97

def prepare str, max, align=:left, side=:right, fade=false
  stop = width = real_size( str )
  unless str.ascii_only? and width == str.size
    stop = width = 0
    str.each_char do |c|
      if c == ?\e
        width -= str[stop..-1][/^\x1b\[[^m]+m|/].size-1
        stop += 1
      elsif (cwidth = (c.ascii_only? ? 1 : Unicode::DisplayWidth.of(c))) +
        width > max
        break
      else width += cwidth; stop += 1 end
    end
  end
  if ( space = ( max - width ) ) > 0
    str = [ str[0..stop-1], " " * space ]
    str.reverse! if align == :right
    str.join
  else
    str = clip str, max, side
    str = fade str, side, fade if fade
    return str
  end
end

#real_size(str) ⇒ Object

Display width of str after stripping ANSI escapes and control chars.



185
# File 'lib/terminal.rb', line 185

def real_size str; Unicode::DisplayWidth.of( sanitize(str) ) end

#sanitize(str) ⇒ Object

Strip ANSI escape sequences and control characters (except \n, \t) from shell-generated text, leaving only printable content.



178
179
180
181
182
# File 'lib/terminal.rb', line 178

def sanitize str
  str.scrub
     .gsub(/\e(?:\[[0-9;?]*[ -\/]*[@-~]|\][^\a\e]*(?:\a|\e\\)|[()=><0A])/, '')
     .gsub(/[\x00-\x08\x0b-\x1f\x7f]/, '')
end