4

Is there a variable or a function, which can tell me the actual position of the cursor?

#!/usr/bin/env perl
use warnings;
use 5.012;

use Term::ReadKey;
use Term::Cap;
use POSIX;

my( $col, $row ) = GetTerminalSize();

my $termios = new POSIX::Termios;
$termios->getattr;
my $ospeed = $termios->getospeed;

my $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };

# some movement ...

# at which position (x/y) is the cursor now?
sid_com
  • 24,137
  • 26
  • 96
  • 187

4 Answers4

4

You could use curses instead. It has getcurx() and getcurx(). There is a CPAN module for it (and the libcurses-perl package in Debian or Ubuntu).

maxelost
  • 1,517
  • 11
  • 12
3

I don't think you can determine the cursor position using termcap.

The termutils manual says:

If you plan to use the relative cursor motion commands in an application program, you must know what the starting cursor position is. To do this, you must keep track of the cursor position and update the records each time anything is output to the terminal, including graphic characters.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
  • But that's a big "if" - if you *don't* plan to restrict yourself to the relative cursor motion commands (which you might need to do for an old terminal, or a printer), then there are other options available, especially on modern terminals - for instance the [query cursor position](http://www.termsys.demon.co.uk/vtansi.htm) sequence. ("modern" here means "more or less anything produced since about 1980" :-). – psmears Feb 10 '11 at 16:35
  • @psmears Granted. There's ways to *actually* do that. sid_com tagged it as termcap, though. With it, it's just not possible. – Linus Kleen Feb 10 '11 at 17:40
  • Actually (with the `termcap` that's distributed with some versions of Linux, at least - the one maintained by Eric Raymond) the "u7" string is the "query cursor position" sequence, and the "u8" string is a format string that describes the response (see `/etc/termcap` for a description). – psmears Feb 13 '11 at 19:31
1

Some terminals may support querying the position, as CSI 6 n. If supported, the position will be reported as CSI Pl;Pc R. For example

$ echo -e "\e[6n"; xxd

^[[4;1R
0000000: 1b5b 343b 3152 0a                      .[4;1R.

This reports the cursor as being at the 1st column of the 4th line (counting from 1).

However, this probably ought not be relied upon, as not very many terminals actually support this.

LeoNerd
  • 8,344
  • 1
  • 29
  • 36
0

Printing ESC[6n at ANSI compatible terminals will give you the current cursor position as ESC[n;mR, where n is the row and m is the column

So try reading it with terminal escape characters. Something like that:

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