ANSI

De knowledge
Aller à la navigation Aller à la recherche

Les codes d'échappement

Code Abbr Name Effect
CSI n A CUU Cursor Up Moves the cursor n (default 1) cells in the given direction. If the cursor is already at the edge of the screen, this has no effect.
CSI n B CUD Cursor Down
CSI n C CUF Cursor Forward
CSI n D CUB Cursor Back
CSI n E CNL Cursor Next Line Moves cursor to beginning of the line n (default 1) lines down. (not ANSI.SYS)
CSI n F CPL Cursor Previous Line Moves cursor to beginning of the line n (default 1) lines up. (not ANSI.SYS)
CSI n G CHA Cursor Horizontal Absolute Moves the cursor to column n (default 1). (not ANSI.SYS)
CSI n ; m H CUP Cursor Position Moves the cursor to row n, column m. The values are 1-based, and default to 1 (top left corner) if omitted. A sequence such as CSI ;5H is a synonym for CSI 1;5H as well as CSI 17;H is the same as CSI 17H and CSI 17;1H
CSI n J ED Erase in Display Clears part of the screen. If n is 0 (or missing), clear from cursor to end of screen. If n is 1, clear from cursor to beginning of the screen. If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS). If n is 3, clear entire screen and delete all lines saved in the scrollback buffer (this feature was added for xterm and is supported by other terminal applications).
CSI n K EL Erase in Line Erases part of the line. If n is 0 (or missing), clear from cursor to the end of the line. If n is 1, clear from cursor to beginning of the line. If n is 2, clear entire line. Cursor position does not change.
CSI n S SU Scroll Up Scroll whole page up by n (default 1) lines. New lines are added at the bottom. (not ANSI.SYS)
CSI n T SD Scroll Down Scroll whole page down by n (default 1) lines. New lines are added at the top. (not ANSI.SYS)
CSI n ; m f HVP Horizontal Vertical Position Same as CUP, but counts as a format effector function (like CR or LF) rather than an editor function (like CUD or CNL). This can lead to different handling in certain terminal modes.
CSI n m SGR Select Graphic Rendition Sets colors and style of the characters following this code
CSI 5i AUX Port On Enable aux serial port usually for local serial printer
CSI 4i AUX Port Off Disable aux serial port usually for local serial printer
CSI 6n DSR Device Status Report Reports the cursor position (CPR) by transmitting ESC[n;mR, where n is the row and m is the column.

Les styles

Il s'agit de détailler les codes :

CSI n m SGR Select Graphic Rendition Sets colors and style of the characters following this code

Le tableau suivant donne les modes existants:

n Name Note Exemple *
0 Reset or normal All attributes become turned off ANSO0M.png
1 Bold or increased intensity As with faint, the color change is a PC (SCO / CGA) invention.[better source needed] N/A
2 Faint, decreased intensity, or dim May be implemented as a light font weight like bold. N/A
3 Italic Not widely supported. Sometimes treated as inverse or blink. N/A
4 Underline Style extensions exist for Kitty, VTE, mintty and iTerm2. ANSI4M.png
5 Slow blink Sets blinking to less than 150 times per minute Blink.gif
6 Rapid blink MS-DOS ANSI.SYS, 150+ per minute; not widely supported N/A
7 Reverse video or invert Swap foreground and background colors; inconsistent emulation[dubious – discuss] ANSI7m.png
8 Conceal or hide Not widely supported. N/A
9 Crossed-out, or strike Characters legible but marked as if for deletion. Not supported in Terminal.app N/A
10 Primary (default) font N/A
11–19 Alternative font Select alternative font n − 10 N/A
20 Fraktur (Gothic) Rarely supported N/A
21 Doubly underlined; or: not bold Double-underline per ECMA-48, but instead disables bold intensity on several terminals, including in the Linux kernel's console before version 4.17. ANSI4M.png
22 Normal intensity Neither bold nor faint; color changes where intensity is implemented as such. ANSO0M.png
23 Neither italic, nor blackletter
24 Not underlined Neither singly nor doubly underlined ANSO0M.png
25 Not blinking Turn blinking off ANSO0M.png
26 Proportional spacing ITU T.61 and T.416, not known to be used on terminals N/A
27 Not reversed N/A
28 Reveal Not concealed

* Les exemples sont pris sut putty/mobaxterm. N/A c'est que, sur les terminaux caractère standards ce code est sans effet.

Les couleurs

Couleurs de bases

On à 8 couleurs de bases + les mêmes couleurs en surintensité. (à la CGApour ceux qui s'en souviennent)

30–37 Set foreground color ForogroundANSI.png
90-97 Set bright foreground color Ansi9x.png
40–47 Set background color ANSIbackground.png
100-107 Set bright background color 10xansi.png

Couleurs étendues

Là on passe aux écrans EGA, On agrandie la palette:

PaletteANSI.png

Le nombre indique la couleur de fond :

ESC[48:5:⟨n⟩m Select background color

La couleur du texte est soit blanc soit noir pour qu'on puise le voir. Pour changer la couleur du texte on peut, de la même façon,

ESC[38:5:⟨n⟩m Select foreground color

Attention avec putty, cygwin et donc mobaxterm, par défaut, ces subtilités ne sont pas gérées. En revanche le terminal de base linux sur raspberry PI et MINGW64 sous Windows marche tres bien.

#!/usr/bin/perl
my $c=0;
for ($i=16; $i<=231; $i++) {
        printf "\033[48:5:%3sm  ", $i;
        $c++;
        if (($c % 36)==0){
                print ("\n");
        }
}

Nous donne:

Rainbowlut.png

En 24 bits

On passe au VGA. 8 bits par composantes r, g et b. 8x3=24 bits. Ca fait quelque chose comme 17 million de couleurs différentes (16 777 216 exactement).

#!/usr/bin/perl
#
for ($y=0; $y<=255; $y+=4){
        for ($x=0; $x<=255; $x+=2){
                printf ("\033[48;2;%s;%s;%sm ",$x,$y,255-$x);
        }
        print ("\033[0m\n");
}

Nous donne un joli:

RGBANSI.png

Comme quoi dans un terminal en mode caractère on peut faire de jolie dessins!

Utiliser dans du code

L'utilisation des codes ANSI dans un programme peut se faire en incluant simplement les codes d’échappement dans les chaines de caractères écrites à l'écran.

Ainsi pour écrire!

ANSI example.png

On utilisera la chaine :

"Hello \033[7m world \033[0m !"

En shell

Attention en bash ou tout descendant du bourne shell un simple:

 echo "Hello \033[7m world \033[0m !"

Donnera ...

Hello \033[7m world \033[0m !

Il faut préciser l'option -e (enambble escape characters)

 echo -e "Hello \033[7m world \033[0m !"

Ou (seulement en bash) la commande printf dont la syntaxes est celle du C.

 printf "Hello \033[7m world \033[0m !\n"

En C/C++

void main(int argc, char** argv){
    printf ("Hello \033[7m world \033[0m !\n");
}

En perl

On peut faire simplement :

print "Hello \033[7m world \033[0m !\n";

HelloWorld-ANSIPL.png

Mais on peut utiliser la module Term::ANSIColor

Il y a pas mal de façon de l'utiliser. La plus simple :

use Term::ANSIColor qw(:constants);

print "[".GREEN."PASS".RESET."]\n";
print "[".RED."FAIL".RESET."]\n";

PASSFAIL-ANSI-PL.png

Les constantes utilisables:

CLEAR           RESET             BOLD            DARK
FAINT           ITALIC            UNDERLINE       UNDERSCORE
BLINK           REVERSE           CONCEALED

BLACK           RED               GREEN           YELLOW
BLUE            MAGENTA           CYAN            WHITE
BRIGHT_BLACK    BRIGHT_RED        BRIGHT_GREEN    BRIGHT_YELLOW
BRIGHT_BLUE     BRIGHT_MAGENTA    BRIGHT_CYAN     BRIGHT_WHITE

ON_BLACK        ON_RED            ON_GREEN        ON_YELLOW
ON_BLUE         ON_MAGENTA        ON_CYAN         ON_WHITE
ON_BRIGHT_BLACK ON_BRIGHT_RED     ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
ON_BRIGHT_BLUE  ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN  ON_BRIGHT_WHITE

On se limite aux couleurs mais le module permet beaucoup de choses. Une description en français est disponible sur la page du module lui même.

En java

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello \033[7m world \033[0m !"); 
    }
}

Bon au retour à la ligne près (certaint l'incluent par défaut d'autres pas) c'est toujours la même chaine.

Un langage fait le malin pour pas faire comme les autres python

En python

Un simple

print ("Hello \033[7m world \033[0m !")

Affiche:

Python ANSI wrong.png

Il interprète (un peu) les codes ANSI pour les remplacer par... des espaces. Etrange.

Pour utiliser les codes ANSI il faut utiliser une autre syntaxe et, de plus, seul les changements de couleurs (3x pour la couleur du texte et 4x pour le fond) sont acceptés.

print (u"Hello \u001B[47m\u001B[30m World \u001B[0m !")

Nous donne "presque" ce que nous attendons.

Python-Hello-almost-perfect.png

Le "World" est écrit en noir sur fond blanc sale. en Gris quoi.

N'essayez pas de remplacer \001B[47m par \001B[107m ça ne marches pas.

Python a "sa syntaxe":

print (u"\nHello \u001B[47;1m\u001B[30m World \u001B[0m !")

Le ;1 après le \u001B[47 et le m dit que la couleur doit être "vive".

Un nombre limité de fonctions de gestion de curseur sont aussi gérées:


  • Up: \u001b[{n}A moves cursor up by n
  • Down: \u001b[{n}B moves cursor down by n
  • Right: \u001b[{n}C moves cursor right by n
  • Left: \u001b[{n}D moves cursor left by n

  • Next Line: \u001b[{n}E moves cursor to beginning of line n lines down
  • Prev Line: \u001b[{n}F moves cursor to beginning of line n lines down

  • Set Column: \u001b[{n}G moves cursor to column n
  • Set Position: \u001b[{n};{m}H moves cursor to row n column m

  • Clear Screen: \u001b[{n}J clears the screen
    • n=0 clears from cursor until end of screen,
    • n=1 clears from cursor to beginning of screen
    • n=2 clears entire screen
  • Clear Line: \u001b[{n}K clears the current line
    • n=0 clears from cursor to end of line
    • n=1 clears from cursor to start of line
    • n=2 clears entire line

  • Save Position: \u001b[{s} saves the current cursor position
  • Save Position: \u001b[{u} restores the cursor to the last saved position

Ces infos ont été trouvées sur : https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html

En Python ce qui est compliqué devient très simple (numpy par exemple permet de gérer des matrices de réels en deux lignes de code) mais ce qui était simple (écrite en inversion vidéo) devient très compliqué!