August 25, 2021
In our magik-development-journeys we often have to look at lots of logging. It would help if this data can be shown in a different way to make it easier to instantly classify what we are looking at; i.e., debug messages might be less important than info messages. One possibility to instantly categorize output is using colors. To facilitate this, I have written sw5_color_terminal, to easily use colors in your Smallworld-terminal.
Colors are very helpful to quickly categorize and identify things. For example, when you’re using a logging framework there often are extensions to colorize log messages dependent on the level. A Python package which does this is colorlog, though there are several others. Colors can be used for other means as well, usually to direct the attention to something important.
ANSI escape codes
Coloring text is actually just a small subset of what can be done using ANSI escape codes. These are commands (codes) a program can output and the terminal acts upon these commands. One example is changing the appearance of text such as colors or bold (Rendition of text), another example is moving the cursor to a different location. Usually used for interactive applications which provides menus and “windows” in a text-based terminal.
Smallworld, when running under Windows uses a “Windows Console”. This Windows Console does not support these ANSI escape codes. Fortunately, there is a tool called ANSICON which enables support for ANSI escape codes in the used console. Much like
ansi.sys in the early MS-DOS days. The
sw5_color_terminal module does exactly that, load ANSICON.
sw5_color_terminal provides an exemplar called
color_terminal. This exemplar is to be used as global
!output!. Also, this exemplar is smart enough to know whether the terminal supports colors (i.e., the current terminal is the color terminal) and provides utility methods to easily color your text using ANSI codes, or does nothing when the terminal does not support colors. I.e., when the output is replaced by the job server when running a job.
Magik> write( color_terminal.safe_fg_red, "Message ", color_terminal.safe_fg_green, "in ", color_terminal.safe_fg_blue, "color", color_terminal.safe_reset)
When using Linux, your terminal most likely already supports colors. ANSICON is not loaded in this case (even impossible to do so), but the exemplar still does provide these utility methods. Thus, you can still easily use colors in your logging or other output.
Note that emacs does not use the Windows Console and this module most likely does not work properly with emacs. Untested, your milage may vary.
sw5_color_terminal provides an easy means to activate ANSI color support in your environment, when needed and possible, and provides an easy means to safely use colors from your code.