2

Using ANSI escape sequences, I would like to find the current location of the cursor in the terminal/screen/window.

To move the cursor to the 5th row, 3rd column of the screen/terminal/window, I could use this statement:

print!("\x1B[{};{}H", 5, 3);

(followed by a flush if needed -- io::stdout().flush().unwrap();. I could use println!(), but that'll move the cursor.)

If I want to know where the cursor is currently located, I could use this statement:

print!("\x1B[6n"];

which will print to the terminal/screen a result like this:

^[[5;3R

How can I capture that output into a variable (for further processing into an eventual x=3, Y=5 result)?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • 1
    I think that's you need to use a text user interface like ncurses see [lists](https://crates.io/keywords/ncurses) – Zeppi Sep 27 '22 at 12:59
  • Read it as input. – KamilCuk Sep 27 '22 at 13:05
  • Does this answer your question? [How can I append a formatted string to an existing String?](https://stackoverflow.com/questions/28333612/how-can-i-append-a-formatted-string-to-an-existing-string) – BallpointBen Sep 27 '22 at 13:35
  • @Zeppi, ncurses works, but I'm trying to do this without resorting to a TUI library, just using ANSI escape sequences. – Debian_Fanatic Sep 27 '22 at 13:59
  • @BallpointBen, no, that just adds to an existing string; I'm trying to scrape into a variable the contents of what's placed onto the screen, in effect, redirecting stdout to a variable, I think. – Debian_Fanatic Sep 27 '22 at 14:02
  • @KamilCuk, could you provide more specifics, or better, an example? Thanks! – Debian_Fanatic Sep 27 '22 at 14:03
  • 1
    First set the controlling terminal to RAW, disable ECHO. Here's a C example: https://stackoverflow.com/questions/50884685/how-to-get-cursor-position-in-c-using-ansi-code – KamilCuk Sep 27 '22 at 14:10
  • @Debian_Fanatic If you had a String containing `^[[5;3R` you could parse it (with regex, say) to get `(3, 5)`? – BallpointBen Sep 27 '22 at 17:32
  • 2
    @BallpointBen, yes, if I had that string. Parsing it is easy; getting the string is what I haven't been able to do. The `print!("\x1B[6n"];` command will print the string I need, to stdout, but I need that string in a variable, not on the screen (stdout). – Debian_Fanatic Sep 27 '22 at 21:15

0 Answers0