ANSI Escape Sequences

ANSI escape codes are used to control formatting, colour, cursor position, and other output options on terminal emulators. We can use UCS-4 to escape and embed these sequences into strings. A similar output can be achieved with the ncurses library, but Unicode characters and 256 colours are not supported by the Fortran ncurses interface.

Some 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

    print '(a)', achar(27) // '[2J'  ! Move cursor to top left.
    print '(a)', achar(27) // '[44;1m' // achar(27) // '[38;5;200mThis text is colourised.'
    print '(a)', achar(27) // '[0m'  ! Reset colour.
end program main

Compile the program with:

$ gfortran7 -Wl,-rpath=/usr/local/lib/gcc7/ -o ansi ansi.f90

References