How to fix cursor position in Linux terminal using ANSI escape code?

531 views Asked by At

I need to make it so that when I press a key, the cursor remains in its place (column) and just updates the symbol (doesn't move to the next column automatically). Is it possible to do this using ANSI escape code? I want to move the cursor only when I need it (for example, via printf("\e[1C");)

The terminal is in raw mode.

1

There are 1 answers

1
Rachid K. On BEST ANSWER

Put the terminal in non echo mode. Hence, your program controls what you want to display back on the screen.
Here is an example in shell which sets the terminal in raw and non echo mode, displays all the input chars at the same place (moving the cursor 1 step backward with "ESC[1D"), move the cursor 1 step forward if it is a space (with "ESC[1C") and exit if it is "Q":

#!/bin/sh

CSI="\e["

trap restore EXIT

restore() {
  stty sane
}

# Terminal in RAW mode + non echo
stty cooked -echo

while true
do
  read -n1 k >/dev/null 2>&1

  case $k in
    "") # Empty char (content of IFS= space, \n and TAB by default)
        # move the cursor forward
       echo -ne ${CSI}1C;;
    Q) # quit the program
       echo
       exit 0;;
    *) # Any other char is written in place
       echo -ne $k${CSI}1D;;
  esac

done

Doing the same in C is straightforward. Don't forget to call fflush(stdout) after the calls to printf() if they don't display \n