I have an ASCII game board that I am displaying in the Mac OS X Terminal, and it needs to be updated frequently. Is there a convenient way to erase or overwrite previously printed content in the Terminal? Or do I need to clear the screen each time and reprint the board? (Looking for solutions that use either Java or Scala)
-
Java doesn't have a decent 'clear screen' function. I would go for a non-terminal UI, in which you have full control – Stultuske May 26 '14 at 07:01
-
I strongly prefer to use Terminal over creating a GUI. Is there a convenient way to have my application open in its own view like Vim or Emacs so that when the user exits the program he is returned to the original command line? If I can do that, then repeated screen clearing would be ok. – Kvass May 26 '14 at 07:05
-
1This question answers how to get full control over a text terminal in Java: http://stackoverflow.com/questions/1321308/whats-the-best-way-to-get-text-user-interfaces-ncurses-like-functionality-in . – BetaRide May 26 '14 at 07:20
1 Answers
The OS X Terminal program emulates a color xterm (environment variable TERM
shows a default value of xterm-color
), which itself is defined as emulating a DEC VT102/220 which is basically uses/defines the ANSI escape codes.
If you just want to clear the entire display, you'll need to output the escape sequence which corresponds to CUP
(Cursor Update) followed by ED
(Erase Display). On a VT102, you'd specifically want to use:
<ESC>[H<ESC>[J
Where <ESC>
is the escape character (ASCII 27).
To use the Alternate Screen Buffer (as you indicated in vim
or emacs
), you'll need to send the code for beginning the alternate screen buffer when you start:
<ESC>[?1049h
and then change back to the normal screen buffer when you finish:
<ESC>[?1049l
While using the alternate screen buffer, you'll have no scroll back, and you won't affect the scroll back or normal screen contents. Upon resuming the normal screen buffer, you'll get back to the original terminal context, including all existing screen contents and scroll back.

- 17,263
- 6
- 57
- 68