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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With