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 no 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.
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;200m' // 'Hello, World!'
    write (*, '(a)')               ESC // '[0m' ! Reset colours.
end program main

Compile and run the program with:

$ gfortran10 -o ansi ansi.f90
$ ./ansi

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

M_escape

The M_escape module abstracts the output formatting through parameters and routines for ANSI terminal control. Either use GNU make or the Fortran Package Manager to build the library:

$ git clone https://github.com/urbanjost/M_escape
$ cd M_escape/
$ fpm build

The static library libM_escape.a along the module files m_escape.mod and m_list2.mod will be written to directory build/gfortran/M_escape/ afterwards.

example output
Fig. 1: Output with foreground and background colour set through ANSI escape sequences

The example has to import module M_escape first.

! example.f90
program main
    use :: m_escape
    implicit none

    print '(a)', color('Hello, World!', fg=FG_RED, bg=BG_YELLOW, style=BOLD)
end program main

The example program just has to be linked against the M_escape library:

$ gfortran10 -o example example.f90 libM_escape.a

Fig. 1 shows the output of the example.

Fortran Libraries

References