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 ascii-table.com. 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 iso_fortran_env
    implicit none
    integer, parameter :: u = selected_char_kind('ISO_10646')

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

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

Compile the programme with:

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