How can I get position of cursor in terminal?

a 夏天 提交于 2019-12-17 18:29:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8343250/how-can-i-get-position-of-cursor-in-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!