Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using backspace with ncurses

Tags:

c

ncurses

I have a simple ncurses program set up that reads characters one at a time with getch() and copies them into a buffer. The issue I am having is detecting a press of the backspace key. Here is the relevant code:

while((buffer[i] = c = getch()) != EOF) {
    ++i;
    if (c == '\n') {
        break;
    }
    else if (c == KEY_BACKSPACE || c == KEY_DC || c == 127) {
        i--;
        delch();
        buffer[i] = 0;
    }
    refresh();
}

But when attempting to run this code, this is what appears on the screen after trying to delete characters from the line "this is a test":

this is a test^?^?^?

and the contents of buffer are:

this is a test

With gdb I know that the if statement checking for a delete/backspace is being called, so what else should I be doing so that I can delete characters?

like image 781
Jumhyn Avatar asked Jul 08 '12 23:07

Jumhyn


2 Answers

It looks like ^? is what's echoed to the screen when you enter a DEL character.

You could probably call delch() twice, but then you'd have to figure out which characters echo as two-character (or more) sequences.

Your best bet is probably to call noecho() and explicitly print the characters yourself.

like image 57
Keith Thompson Avatar answered Oct 05 '22 05:10

Keith Thompson


There's actually a simpler way of doing it by using the forms library alongside ncurses. If you change your code to this:

while((buffer[i] = c = getch()) != EOF) {
    ++i;
    if (c == '\n') {
        break;
    }
    else if (c == KEY_BACKSPACE || c == KEY_DC || c == 127) {
        form_driver(Form, REQ_DEL_PREV);
    }
    refresh();
}

It will backspace without a problem. You can find some (Albeit limited) documentation for the REQ_DEL_PREV command here.

like image 27
Shades Avatar answered Oct 05 '22 05:10

Shades