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.

An overview of the sequences is given by The unicode encoding of the escape character is \u001b. The example below just moves the cursor and colourises some text.

! ansi.f90
program main
    use, intrinsic :: iso_fortran_env
    implicit none
    integer, parameter :: u = selected_char_kind('ISO_10646')

    open(unit=output_unit, encoding='utf-8')

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

Compile the program with:

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