Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby curses colors

Tags:

ruby

curses

How can I get colors with Ruby's default Curses library?

So something like:

puts "\e[0m\e[30;47mtest\e[0m"

works great. Gives a nice black on light gray background. But this:

#!/usr/bin/env ruby

require 'curses'

Curses.noecho # do not show typed keys
Curses.init_screen
Curses.stdscr.keypad(true) # enable arrow keys (for pageup/down)
Curses.stdscr.nodelay = 1

Curses.clear
Curses.setpos(0,0)
Curses.addstr "Hello!"
Curses.addstr "\e[0m\e[30;47mHello!\e[0m"

Displays:

Hello!

^[[0m^[[30;47mHello!^[[0m

Ultimately, I need colors for this:

How to capture a key press in Ruby?

require 'curses'

Curses.noecho # do not show typed keys
Curses.init_screen
Curses.stdscr.keypad(true) # enable arrow keys (required for pageup/down)

loop do
  case Curses.getch
  when Curses::Key::PPAGE
    Curses.setpos(0,0)
    Curses.addstr("Page Up")
  when Curses::Key::NPAGE
    Curses.setpos(0,0)
    Curses.addstr("Page Dn")
  end
end
like image 278
Aleksandr Levchuk Avatar asked Sep 07 '11 02:09

Aleksandr Levchuk


1 Answers

There are examples of curses usage in the ruby source code, see, e.g. here.

Your code could be something like:

require 'curses'
include Curses

Curses.noecho # do not show typed keys
Curses.init_screen
Curses.stdscr.keypad(true) # enable arrow keys (required for pageup/down)
Curses.start_color
# Determines the colors in the 'attron' below
Curses.init_pair(COLOR_BLUE,COLOR_BLUE,COLOR_BLACK) 
Curses.init_pair(COLOR_RED,COLOR_RED,COLOR_BLACK)

loop do

  case Curses.getch

  when Curses::Key::PPAGE
    Curses.clear
    Curses.setpos(0,0)
    # Use colors defined color_init
    Curses.attron(color_pair(COLOR_RED)|A_NORMAL){
      Curses.addstr("Page Up")
    }
  when Curses::Key::NPAGE
    Curses.clear
    Curses.setpos(0,0)
    Curses.attron(color_pair(COLOR_BLUE)|A_NORMAL){
      Curses.addstr("Page Down")
    }
  end
end
like image 146
Tatu Lahtela Avatar answered Oct 22 '22 18:10

Tatu Lahtela