Search code examples
cncursescurses

stopping addCh() from overwriting frollowing chars (ncurses, c)


I working on a basic ncurses program and ran across this issue.

I am trying to call addch() without overwritten the following characters.

Basically, I want to be able to type out something like

"elp!"

Use the left cursor to move to the first position, and then type h in front of the current text to get

"help!"

Right now that behavior would result in

"hlp"

With the h overwriting the first character.

My code showing this issue:

setlocale(LC_ALL, "");
initscr();
cbreak();
noecho();
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);
clear();

short currentCh;
int x, y;

while (currentCh = getch()) {
  bool modeChange = false;
  getyx(stdscr, y, x);

  if (currentCh == KEY_LEFT) {
    if (x != 0)
      move(y, x - 1);
  } else {
    addch(currentCh);
  }
}

My best idea so far seems to be to save all characters typed in a string, then modify that string with the correct new characters, then clear the screen and call addstr() each time a char is typed (In other words you are printing the contents of a string, instead of character by character).

This requires you to clear the screen after each ch, and rewriting everything.

This is obviously janky, and not ideal, so I was wondering if there is a better way.


Solution

  • Rather than addch for that special case, you can insert a character using insch:

    These routines insert the character ch before the character under the cursor. All characters to the right of the cursor are moved one space to the right, with the possibility of the rightmost character on the line being lost. The insertion operation does not change the cursor position.

    For instance, you could decide to use that when the current cell contains something other than a blank. You can read that character using inch (similar spelling, different meaning):

    These routines return the character, of type chtype, at the current position in the named window. If any attributes are set for that position, their values are OR'ed into the value returned. Constants defined in <curses.h> can be used with the & (logical AND) operator to extract the character or attributes alone.

    (as noted in the manual page, AND the return value with A_CHARTEXT to get just the character).