module ANSI

This module contains helpers for various ansi-code operations

Constants

COLORS

ANSI color escape codes set the foreground and background colors. Forground color is a number between 30 and 37. Background color is a number between 40 and 47. The ones place represents the same color for both.

Public Class Methods

clear_screen() click to toggle source
# File lib/ansi.rb, line 11
def self.clear_screen
  $stdout.write "\e[2J"
end
color(text, fg: nil, bg: nil, res: true) click to toggle source
# File lib/ansi.rb, line 34
def self.color(text, fg: nil, bg: nil, res: true)
  fg = COLORS[@private.snake_to_camel(fg)] if fg
  bg = COLORS[@private.snake_to_camel(bg)] if bg
  fg = "\e[38;5;#{fg}m" if fg
  bg = "\e[48;5;#{bg}m" if bg
  "#{fg}#{bg}#{text}#{reset if res}"
end
move_cursor(row, col) click to toggle source
# File lib/ansi.rb, line 23
def self.move_cursor(row, col)
  $stdout.write "\e[#{row + 1};#{col + 1}H"
end
position() click to toggle source
# File lib/ansi.rb, line 50
def self.position
  res = ''
  $stdin.raw do |stdin|
    $stdout << "\e[6n"
    $stdout.flush
    while (c = stdin.getc) != 'R'
      res << c if c
    end
  end
  m = res.match(/(?<row>\d+);(?<column>\d+)/)
  {
    row: m[:row].to_i,
    column: m[:column].to_i
  }
end
print_colors() click to toggle source
reset() click to toggle source
# File lib/ansi.rb, line 42
def self.reset
  "\e[0m"
end
restore_screen() click to toggle source
# File lib/ansi.rb, line 19
def self.restore_screen
  $stdout.write `tput rmcup`
end
save_screen() click to toggle source
# File lib/ansi.rb, line 15
def self.save_screen
  $stdout.write `tput smcup`
end
shift_cursor(rows: 0, cols: 0) click to toggle source
# File lib/ansi.rb, line 27
def self.shift_cursor(rows: 0, cols: 0)
  pos = position
  row = pos[:row] + rows
  col = pos[:column] + cols
  move_cursor(row, col)
end
size() click to toggle source
# File lib/ansi.rb, line 66
def self.size
  win = IO.console.winsize
  {
    height: win[0],
    width: win[1]
  }
end
snake_to_camel(string) click to toggle source
# File lib/ansi.rb, line 93
def self.snake_to_camel(string)
  string.to_s.split('_').map(&:capitalize).join
end
strip(text) click to toggle source
# File lib/ansi.rb, line 46
def self.strip(text)
  text.gsub(/\e\[[0-9,;]+\w/, '')
end