View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2010-2018, VU University Amsterdam
    7                              CWI, Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(ansi_term,
   37          [ ansi_format/3               % +Attr, +Format, +Args
   38          ]).   39:- use_module(library(apply)).   40:- use_module(library(error)).   41
   42/** <module> Print decorated text to ANSI consoles
   43
   44This library allows for exploiting the color and attribute facilities of
   45most modern terminals using ANSI escape sequences. This library provides
   46the following:
   47
   48  - ansi_format/3 allows writing messages to the terminal with ansi
   49    attributes.
   50  - It defines the hook prolog:message_line_element/2, which provides
   51    ansi attributes for print_message/2.
   52
   53@see    http://en.wikipedia.org/wiki/ANSI_escape_code
   54*/
   55
   56:- create_prolog_flag(color_term, true, [type(boolean)]).   57
   58:- meta_predicate
   59    keep_line_pos(+, 0).   60
   61:- multifile
   62    user:message_property/2.   63
   64%!  ansi_format(+Attributes, +Format, +Args) is det.
   65%
   66%   Format text with ANSI  attributes.   This  predicate  behaves as
   67%   format/2 using Format and Args, but if the =current_output= is a
   68%   terminal, it adds ANSI escape sequences according to Attributes.
   69%   For example, to print a text in bold cyan, do
   70%
   71%     ==
   72%     ?- ansi_format([bold,fg(cyan)], 'Hello ~w', [world]).
   73%     ==
   74%
   75%   Attributes is either a single attribute   or a list thereof. The
   76%   attribute names are derived from the ANSI specification. See the
   77%   source for sgr_code/2 for details. Some commonly used attributes
   78%   are:
   79%
   80%     - bold
   81%     - underline
   82%     - fg(Color), bg(Color), hfg(Color), hbg(Color)
   83%
   84%   Defined color constants are below.  =default=   can  be  used to
   85%   access the default color of the terminal.
   86%
   87%     - black, red, green, yellow, blue, magenta, cyan, white
   88%
   89%   ANSI sequences are sent if and only if
   90%
   91%     - The =current_output= has the property tty(true) (see
   92%       stream_property/2).
   93%     - The Prolog flag =color_term= is =true=.
   94
   95ansi_format(Attr, Format, Args) :-
   96    ansi_format(current_output, Attr, Format, Args).
   97
   98ansi_format(Stream, Attr, Format, Args) :-
   99    stream_property(Stream, tty(true)),
  100    current_prolog_flag(color_term, true),
  101    !,
  102    (   is_list(Attr)
  103    ->  maplist(sgr_code_ex, Attr, Codes),
  104        atomic_list_concat(Codes, ;, Code)
  105    ;   sgr_code_ex(Attr, Code)
  106    ),
  107    format(string(Fmt), '\e[~~wm~w\e[0m', [Format]),
  108    format(Stream, Fmt, [Code|Args]),
  109    flush_output.
  110ansi_format(Stream, _Attr, Format, Args) :-
  111    format(Stream, Format, Args).
  112
  113sgr_code_ex(Attr, Code) :-
  114    sgr_code(Attr, Code),
  115    !.
  116sgr_code_ex(Attr, _) :-
  117    domain_error(sgr_code, Attr).
  118
  119%!  sgr_code(+Name, -Code)
  120%
  121%   True when code is the Select   Graphic  Rendition code for Name.
  122%   The defined names are given below. Note that most terminals only
  123%   implement this partially.
  124%
  125%     | reset                       | all attributes off    |
  126%     | bold                        |                       |
  127%     | faint                       |       |
  128%     | italic                      |       |
  129%     | underline                   |       |
  130%     | blink(slow)                 |       |
  131%     | blink(rapid)                |       |
  132%     | negative                    |       |
  133%     | conceal                     |       |
  134%     | crossed_out                 |       |
  135%     | font(primary)               |       |
  136%     | font(N)                     | Alternate font (1..8) |
  137%     | fraktur                     |       |
  138%     | underline(double)           |       |
  139%     | intensity(normal)           |       |
  140%     | fg(Name)                    | Color name    |
  141%     | bg(Name)                    | Color name    |
  142%     | framed                      |       |
  143%     | encircled                   |       |
  144%     | overlined                   |       |
  145%     | ideogram(underline)         |       |
  146%     | right_side_line             |       |
  147%     | ideogram(underline(double)) |       |
  148%     | right_side_line(double)     |       |
  149%     | ideogram(overlined)         |       |
  150%     | left_side_line              |       |
  151%     | ideogram(stress_marking)    |       |
  152%     | -Off                        | Switch attributes off |
  153%     | hfg(Name)                   | Color name    |
  154%     | hbg(Name)                   | Color name    |
  155%
  156%   @see http://en.wikipedia.org/wiki/ANSI_escape_code
  157
  158sgr_code(reset, 0).
  159sgr_code(bold,  1).
  160sgr_code(faint, 2).
  161sgr_code(italic, 3).
  162sgr_code(underline, 4).
  163sgr_code(blink(slow), 5).
  164sgr_code(blink(rapid), 6).
  165sgr_code(negative, 7).
  166sgr_code(conceal, 8).
  167sgr_code(crossed_out, 9).
  168sgr_code(font(primary), 10) :- !.
  169sgr_code(font(N), C) :-
  170    C is 10+N.
  171sgr_code(fraktur, 20).
  172sgr_code(underline(double), 21).
  173sgr_code(intensity(normal), 22).
  174sgr_code(fg(Name), C) :-
  175    ansi_color(Name, N),
  176    C is N+30.
  177sgr_code(bg(Name), C) :-
  178    !,
  179    ansi_color(Name, N),
  180    C is N+40.
  181sgr_code(framed, 51).
  182sgr_code(encircled, 52).
  183sgr_code(overlined, 53).
  184sgr_code(ideogram(underline), 60).
  185sgr_code(right_side_line, 60).
  186sgr_code(ideogram(underline(double)), 61).
  187sgr_code(right_side_line(double), 61).
  188sgr_code(ideogram(overlined), 62).
  189sgr_code(left_side_line, 62).
  190sgr_code(ideogram(stress_marking), 64).
  191sgr_code(-X, Code) :-
  192    off_code(X, Code).
  193sgr_code(hfg(Name), C) :-
  194    ansi_color(Name, N),
  195    C is N+90.
  196sgr_code(hbg(Name), C) :-
  197    !,
  198    ansi_color(Name, N),
  199    C is N+100.
  200
  201off_code(italic_and_franktur, 23).
  202off_code(underline, 24).
  203off_code(blink, 25).
  204off_code(negative, 27).
  205off_code(conceal, 28).
  206off_code(crossed_out, 29).
  207off_code(framed, 54).
  208off_code(overlined, 55).
  209
  210
  211ansi_color(black,   0).
  212ansi_color(red,     1).
  213ansi_color(green,   2).
  214ansi_color(yellow,  3).
  215ansi_color(blue,    4).
  216ansi_color(magenta, 5).
  217ansi_color(cyan,    6).
  218ansi_color(white,   7).
  219ansi_color(default, 9).
  220
  221
  222                 /*******************************
  223                 *             HOOK             *
  224                 *******************************/
  225
  226%!  prolog:message_line_element(+Stream, +Term) is semidet.
  227%
  228%   Hook implementation that deals with  ansi(+Attr, +Fmt, +Args) in
  229%   message specifications.
  230
  231prolog:message_line_element(S, ansi(Attr, Fmt, Args)) :-
  232    ansi_format(S, Attr, Fmt, Args).
  233prolog:message_line_element(S, ansi(Attr, Fmt, Args, Ctx)) :-
  234    ansi_format(S, Attr, Fmt, Args),
  235    (   nonvar(Ctx),
  236        Ctx = ansi(_, RI-RA)
  237    ->  keep_line_pos(S, format(S, RI, RA))
  238    ;   true
  239    ).
  240prolog:message_line_element(S, begin(Level, Ctx)) :-
  241    level_attrs(Level, Attr),
  242    stream_property(S, tty(true)),
  243    current_prolog_flag(color_term, true),
  244    !,
  245    (   is_list(Attr)
  246    ->  maplist(sgr_code, Attr, Codes),
  247        atomic_list_concat(Codes, ;, Code)
  248    ;   sgr_code(Attr, Code)
  249    ),
  250    keep_line_pos(S, format(S, '\e[~wm', [Code])),
  251    Ctx = ansi('\e[0m', '\e[0m\e[~wm'-[Code]).
  252prolog:message_line_element(S, end(Ctx)) :-
  253    nonvar(Ctx),
  254    Ctx = ansi(Reset, _),
  255    keep_line_pos(S, write(S, Reset)).
  256
  257level_attrs(Level,         Attrs) :-
  258    user:message_property(Level, color(Attrs)).
  259level_attrs(informational, fg(green)).
  260level_attrs(information,   fg(green)).
  261level_attrs(debug(_),      fg(blue)).
  262level_attrs(warning,       fg(red)).
  263level_attrs(error,         [fg(red),bold]).
  264
  265keep_line_pos(S, G) :-
  266    stream_property(S, position(Pos)),
  267    !,
  268    stream_position_data(line_position, Pos, LPos),
  269    G,
  270    set_stream(S, line_position(LPos)).
  271keep_line_pos(_, G) :-
  272    G