[GTALUG] Finding current cursor position in the terminal

D. Hugh Redelmeier hugh at mimosa.com
Mon Feb 10 16:18:33 EST 2020


| From: Giles Orr via talk <talk at gtalug.org>

| I'd like to be able to get the current x,y (or row, column) position
| of the cursor in a terminal.  This is for a Bash or ZSH prompt, and my
| intention is to calculate how far across the terminal we've printed
| and then decide if we should wrap the prompt from one to two lines.
| 
| There's a terminal escape sequence to do this:
| 
|     echo -e '\033[6n'

TL;DR: I suspect you need a ? after the ESC [.

Among other things, there is probably clashes of levels of abstraction
here.

This is querying your terminal / terminal emulator.  Every one is free
to support different encodings.  ANSI 3.67 (from my faulty memory) is
the relevant of standard, I would think (it cost money so I never got
a copy).  It looks as if ECMA-48 is similar and available:

<http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-48,%202nd%20Edition,%20August%201979.pdf>

ESC [ is a 7-bit sequence that stands for the eight-bit code CSI
(Control Sequence Introducer).  That's why you see that a lot.

There is a grammar to these commands

A characters is eight bits (or actually, 7 bits).  The "column" of a
character is the most significant hex digit (if 7 bits, the column is
only 3 bits). The row is the least significant hex digit.

control sequence:
  CSI parameters intermediates function

# a parameter is typically empty or a sequence of digits
parameter:
|	parameter digit

# list separated by ;
parameters: parameter
|	parameters ; parameter

intermediate: character from column 2

intermediates:
|	intermediates intermediate

function: character from column 4, 5, 6, or 7, excluding 7/15

If the CSI is followed by ?, I think that is some extension that isn't
part of the standard.  (Anything from column 3 that isn't a digit, :,
or : is an extension).

What you want ought use CPR (CURSOR POSITION REPORT).
This seems to be row 2 column 5 in table 2.  I think that that means
(char) (2 + 5*16) which is R

What you have is function n (column 6 row 15) which should be DAQ
(Define Area Qualification).  With the parameter 6, it means "fill
with ZEROs".  Just what this function does is pretty unclear to me.

SO: maybe you are using an xterm control sequence.
<https://xfree86.org/4.7.0/ctlseqs.html>

CSI ? Ps n, where P is 6, means Report Cursor Position (CPR).
Note the ? (which you didn't have).
This is a DEC extension.  I hope the standard form would work.

Without the ?, it looks like a Set Scrolling Region (a DEC thing).

I have to stop here due to a higher priority interrupt.


More information about the talk mailing list