Decorated string in C

Have you ever seen beautiful text in your terminal decorated with color, bold face, etc... ? Have you ever wondered how it's done ? I did, and that's ridiculously simple ! Let me introduce you quickly how to do it in this article.

The ANSI defines a list of escape sequences to control color, font styling, etc... on video text terminals. If you're using a modern decent terminal it should support these sequences, and if not they should be ignored. An escape sequence is one or several bytes which is interpreted by the terminal to modify the following character until it encounters the corresponding closing escape sequence. It's not even a functionality of a language, so you can use it everywhere.

For example, to print a text in bold, the opening escape sequence is \033[1m and the closing escape sequence is \033[0m. Then, if you want to print This is bold text in bold, all you have to do is to print instead \033[1mThis is bold text\033[0m. The list of options available is given in the Wikipedia page I've linked above. Check for it by yourself, there is a ton to have fun with. I'll just give another example, coloring. It can be done with the sequence "\033[38;2;" + r + ";" + g + ";" + b + "m" + str + "\033[39m" where r,g,b are the color values (in [0, 255]) and str is the string to be colored.

No excuses anymore for depressing CLI, welcome to rainbow interfaces, roguelikes and textual display of images !

2021-09-24
in All, C programming,
103 views
Copyright 2021-2024 Baillehache Pascal