ANSI Escape Sequences

ANSI escape codes are used to control formatting, colour, cursor position, and other output options on terminal emulators. The ncurses library is a convenient method to change these options, but Unicode characters and 256 colours are not supported by the Fortran ncurses interface. Instead, it is often easier to implement the desired output with ANSI escape sequences only.

Some of the sequences are listed in the following table:

Sequence Description
Esc[Line;ColumnH
Esc[Line;Columnf
Moves the cursor position. If not position is specified, the cursor moves to the the upper-left corner (line 0, column 0).
Esc[ValueA Moves the cursor up by the specified number of lines. The sequence is ignored if the cursor is already on the top line.
Esc[ValueB Moves the cursor down by the specified number of lines. The sequence is ignored if the cursor is already on the bottom line.
Esc[ValueC Moves the cursor forward by the specified number of columns. The sequence is ignored if the cursor is already on the rightmost column.
Esc[ValueD Moves the cursor backward by the specified number of columns. The sequence is ignored if the cursor is already on the leftmost column.
Esc[2J Erases display and moves cursor to the upper-left corner.
Esc[K Erases line by clearing all characters from the cursor position to the end of the line.

The intrinsic Fortran routine achar() is used to output the escape character. The example below just moves the cursor and colourises some text.

! ansi.f90
program main
    implicit none
    character(len=*), parameter :: ESC = achar(27)

    write (*, '(a)', advance='no') ESC // '[2J' ! Move cursor to top left.
    write (*, '(a)', advance='no') ESC // '[44;1m' // ESC // '[38;5;200mThis text is colourised.'
    write (*, '(a)')               ESC // '[0m' ! Reset colours.
end program main

Compile the program with:

$ gfortran9 -o ansi ansi.f90

Instead of achar(), we can also use UCS-4 to escape and embed ANSI escape sequences into strings.

References