Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you edit existing text (and move the cursor around) in the terminal?

I saw this demo once that printed out a paragraph of text (like you'd get when typing some-command --help), and it then jumped back up to a couple keywords in the text and changed the text color, after it was already printed out in the terminal.

That seems crazy to me. How did they do that?

Starting to think about it, I guess stdout and stdin are technically an "IO stream", so maybe that's a persistent variable that keeps track of the position of a cursor? I remember doing something like that when building a language parser.

The goal would be this: say you type the following into the console, and it outputs a blank array because in Node.js, it's all async and we don't want to write the async function everytime in the console:

$ node app.js > App.User.all() => [] 

Then when the async callback executes, you go back and edit the => [] to include the result:

$ node app.js > App.User.all() => [#<User id:1>, #<User id:2>...] 

That would be awesome to at least know how to implement, even if there are a lot of other issues to work through (unrelated to this question. And I know you can define a global callback and do something like App.User.all(_c)).

How do you edit the terminal output after it's already been printed?

like image 303
Lance Avatar asked May 14 '12 14:05

Lance


People also ask

How do I move around in terminal?

What I usually do is Ctrl - A to get to the beginning and then repeatedly Alt - F to move forward, word by word (or Ctrl - E to go the end and Alt - B to then go backward).

How do I move the cursor in Linux terminal?

Move Cursor on The Command LineCtrl+A or Home – moves the cursor to the start of a line. Ctrl+E or End – moves the cursor to the end of the line. Ctrl+B or Left Arrow – moves the cursor back one character at a time. Ctrl+F or Right Arrow – moves the cursor forward one character at a time.


1 Answers

Finally found that "demo":

  • https://github.com/asyncly/cdir/blob/223fe0039fade4fad2bb08c2f7affac3bdcf2f89/cdir.js#L24
  • http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html
  • http://ascii-table.com/ansi-escape-sequences-vt-100.php

  • Position the Cursor: \033[<L>;<C>H or \033[<L>;<C>f (puts the cursor at line L and column C)

  • Move the cursor up N lines: \033[<N>A
  • Move the cursor down N lines: \033[<N>B
  • Move the cursor forward N columns: \033[<N>C
  • Move the cursor backward N columns: \033[<N>D
  • Clear the screen, move to (0,0): \033[2J
  • Erase to end of line: \033[K
  • Save cursor position: \033[s
  • Restore cursor position: \033[u
like image 122
Lance Avatar answered Sep 29 '22 16:09

Lance