I have a program in C where I want to draw colors and move cursors, etc. in the terminal. Currently, I am just using ANSI escape codes to do this. Is ANSI the most modern and most popular/used standard? Is it portable? Will more or fewer terminals support ANSI in the future?
-
if a terminal supports colorized text then yes, it's a good bet it does so via ascii escape codes.– bolovCommented Dec 24, 2022 at 1:41
-
For better portability, you might want to use a library like ncurses to handle the platform-specific parts.– kotatsuyakiCommented Dec 24, 2022 at 1:42
-
@bolov Er, that’s not quite correct. There are bazillions of legacy terminals which do not support so-called ANSI escape codes. Modern terminal emulators, however, tend toward a common set.– DúthomhasCommented Dec 24, 2022 at 1:42
-
Make sure to test on Windows. I don't know the current state, but they used to not work there.– HolyBlackCatCommented Dec 24, 2022 at 5:51
3 Answers
Modern terminal emulators (just about anything normal people will encounter these days) all tend to use stuff you can find documented in two places:
Microsoft’s “Console Virtual Terminal Sequences”
Thomas Dickey’s “XTerm Control Sequences”
It doesn’t get more authoritative than that.
I'd say that ANSI is going to be pretty reliably portable for some time to come.
However, it's possibly more productive and more protected from changes in underlying standards (e.g. a resurgence of PC3270) to use a library. There's an enormous list of them here, under the Libraries section. Ncurses
seems to be something of a staple, and notcurses
has a lot of merit too.
Legacy terminals exist, but try getting by on one these days. I own several of them. Inevitably you end up running screen
or some other program that turns it into an ANSI-compatible terminal from the running program's perspective.
Yes, it is safe to assume in 2023 that all terminals are somewhat reasonably ANSI compliant. If you're writing something like a text editor where you are really driving the terminal hard you might have trouble with the subtle differences between implementations, and in that case something like ncurses might help, but if you just want to use bold and italic and color and clear the screen and things like that, then go for it -- just use the ANSI codes directly.