Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get position of cursor in terminal?

I know I may save position using tput sc, but how can I read it's position to the variable? I need the number of row. I don't want to use curses/ncurses.

like image 958
ciembor Avatar asked Dec 01 '11 14:12

ciembor


1 Answers

At ANSI compatible terminals, printing the sequence ESC[6n will report the cursor position to the application as (as though typed at the keyboard) ESC[n;mR, where n is the row and m is the column.

Example:

~$ echo -e "\033[6n"

EDITED:

You should make sure you are reading the keyboard input. The terminal will "type" just the ESC[n;mR sequence (no ENTER key). In bash you can use something like:

echo -ne "\033[6n"            # ask the terminal for the position
read -s -d\[ garbage          # discard the first part of the response
read -s -d R foo              # store the position in bash variable 'foo'
echo -n "Current position: "
echo "$foo"                   # print the position

Explanation: the -d R (delimiter) argument will make read stop at the char R instead of the default record delimiter (ENTER). This will store ESC[n;m in $foo. The cut is using [ as delimiter and picking the second field, letting n;m (row;column).

I don't know about other shells. Your best shot is some oneliner in Perl, Python or something. In Perl you can start with the following (untested) snippet:

~$ perl -e '$/ = "R";' -e 'print "\033[6n";my $x=<STDIN>;my($n, $m)=$x=~m/(\d+)\;(\d+)/;print "Current position: $m, $n\n";'

For example, if you enter:

~$ echo -e "z033[6n"; cat > foo.txt

Press [ENTER] a couple times and then [CRTL]+[D]. Then try:

~$ cat -v foo.txt
^[[47;1R

The n and m values are 47 and 1. Check the wikipedia article on ANSI escape codes for more information.

Before the Internet, in the golden days of the BBS, old farts like me had a lot of fun with these codes.

like image 174
Paulo Scardine Avatar answered Oct 05 '22 05:10

Paulo Scardine