rubycursestext-cursor

Ruby Curses taking control of the enter key


I'm learning the Curses class and I'm having trouble taking control of the ENTER key. This is my code so far:

require 'curses'


win = Curses::Window.new(0, 0, 0, 0)

Curses.init_screen
Curses.cbreak
Curses.nonl
Curses.stdscr.keypad(true)

loop do
    case Curses.getch
    when 13 # Enter
        Curses.addstr "abc"
    when 8 # Backspace
        Curses.delch
    end
end

win.close

The issue is, when I hit the ENTER key, "abc" is written to the screen (as expected); however, when I hit ENTER a second time, "abc" is just re-written to the same position on the screen. It seems as though hitting the ENTER key first sets the cursor position to (0,0) and then it adds the string. How can I stop it setting the cursor position to (0,0)?

Also, for some reason, the constants don't match up with my keys, so the ENTER key is key 13, yet the Ruby constant for the ENTER key is 400ish. I'm not using a fancy keyboard or anything; standard American one.


Solution

  • Well it seems as though Curses.nonl just means that when ENTER is pressed, "\r" is written rather than "\r\n", so the only way I managed to solve this problem is to disable any output to the screen using Curses.raw and implement all the data writing to the screen myself.

    I don't know why the constants don't much up. Perhaps that's the constant for the other ENTER key on the keyboard (in the bottom right-hand corner). Doesn't really matter though, I can just do puts Curses.getch to find out the number of the key.