View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           https://www.swi-prolog.org
    6    Copyright (c)  2010-2026, VU University Amsterdam
    7                              CWI, Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(ansi_term,
   38          [ ansi_format/3,              % +Attr, +Format, +Args
   39            ansi_format/4,              % +Stream, +Attr, +Format, +Args
   40            ansi_sgr/2,                 % +Attr, -Sequence
   41            ansi_get_color/2,           % +Which, -rgb(R,G,B)
   42            ansi_hyperlink/2,           % +Stream,+Location
   43            ansi_hyperlink/3            % +Stream,+URL,+Label
   44          ]).   45:- autoload(library(error), [domain_error/2, must_be/2, instantiation_error/1]).   46:- autoload(library(lists), [append/3, selectchk/3]).   47:- autoload(library(utf8), [utf8_codes/3]).   48:- autoload(library(apply), [maplist/2]).

Print decorated text to ANSI consoles

This library allows for exploiting the color and attribute facilities of most modern terminals using ANSI escape sequences. This library provides the following:

The behavior of this library is controlled by two Prolog flags:

[99, 111, 108, 111, 114, 95, 116, 101, 114, 109]
When true, activate the color output for this library. Otherwise simply call format/3.
[104, 121, 112, 101, 114, 108, 105, 110, 107, 95, 116, 101, 114, 109]
Emit terminal hyperlinks for url(Location) and url(URL, Label) elements of Prolog messages.
See also
- http://en.wikipedia.org/wiki/ANSI_escape_code
   73:- multifile
   74    prolog:console_color/2,                     % +Term, -AnsiAttrs
   75    supports_get_color/0,
   76    hyperlink/2,                                % +Stream, +Spec
   77    tty_url_hook/2.                             % +For, -URL
   78
   79color_term_flag_default(true) :-
   80    stream_property(user_input, tty(true)),
   81    stream_property(user_error, tty(true)),
   82    stream_property(user_output, tty(true)),
   83    \+ getenv('TERM', dumb),
   84    !.
   85color_term_flag_default(false).
   86
   87init_color_term_flag :-
   88    color_term_flag_default(Default),
   89    create_prolog_flag(color_term, Default,
   90                       [ type(boolean),
   91                         keep(true)
   92                       ]),
   93    create_prolog_flag(hyperlink_term, false,
   94                       [ type(boolean),
   95                         keep(true)
   96                       ]).
   97
   98:- initialization
   99    init_color_term_flag.  100
  101:- multifile
  102    user:message_property/2.
 ansi_format(+ClassOrAttributes, +Format, +Args) is det
 ansi_format(+Stream, +ClassOrAttributes, +Format, +Args) is det
Format text with ANSI attributes. This predicate behaves as format/2 using Format and Args, but if the current_output is a terminal, it adds ANSI escape sequences according to Attributes. For example, to print a text in bold cyan, do
?- ansi_format([bold,fg(cyan)], 'Hello ~w', [world]).

Attributes is either a single attribute, a list thereof or a term that is mapped to concrete attributes based on the current theme (see prolog:console_color/2). The attribute names are derived from the ANSI specification. See the source for sgr_code/2 for details. Some commonly used attributes are:

bold
underline
fg(Color),bg(Color),hfg(Color),hbg(Color)
For fg(Color) and bg(Color), the colour name can be '#RGB' or '#RRGGBB'
fg8(Spec),bg8(Spec)
8-bit color specification. Spec is a colour name, h(Color) or an integer 0..255.
fg(R,G,B),bg(R,G,B)
24-bit (direct color) specification. The components are integers in the range 0..255.
href(URL)
Wrap the output as a link using ansi_hyperlink/3.

Defined color constants are below. default can be used to access the default color of the terminal.

ANSI sequences are sent if and only if

  147ansi_format(Attr, Format, Args) :-
  148    ansi_format(current_output, Attr, Format, Args).
  149
  150ansi_format(Stream, Class, Format, Args) :-
  151    stream_property(Stream, tty(true)),
  152    current_prolog_flag(color_term, true),
  153    class_attrs(Class, Attr),
  154    Attr \== [],
  155    !,
  156    (   selectchk(href(HREF), Attr, Attr1)
  157    ->  true
  158    ;   Attr1 = Attr
  159    ),
  160    sgr_sequence(Attr1, Sequence),
  161    with_output_to(
  162        Stream,
  163        (   write(Sequence),
  164            format_content(Format, Args, HREF),
  165            format('\e[0m')
  166        )
  167    ),
  168    flush_output.
  169ansi_format(Stream, _Attr, Format, Args) :-
  170    format(Stream, Format, Args).
  171
  172format_content(Format, Args, HREF) :-
  173    var(HREF),
  174    !,
  175    format(Format, Args).
  176format_content(Format, Args, HREF) :-
  177    format(string(Label), Format, Args),
  178    ansi_hyperlink(current_output, HREF, Label).
 ansi_sgr(+ClassOrAttributes, -Sequence:string) is det
True when Sequence is the ANSI Select Graphic Rendition sequence that activates the attributes of ClassOrAttributes. Sequence is the empty string if the Prolog flag color_term is false or the class resolves to no attributes.

Unlike ansi_format/4 this does not write to a stream and thus does not require a terminal. It is used to decorate strings that are handed to code that is not aware of colors, notably the toplevel prompt (see the Prolog flag toplevel_prompt). As the caller controls where the sequence ends up, the caller is also responsible for verifying that the destination is a terminal and for emitting the reset sequence `\e[0m`.

See also
- ansi_format/3 for the possible values of ClassOrAttributes.
  197ansi_sgr(Class, Sequence) :-
  198    current_prolog_flag(color_term, true),
  199    class_attrs(Class, Attr),
  200    Attr \== [],
  201    (   selectchk(href(_), Attr, Attr1)
  202    ->  true
  203    ;   Attr1 = Attr
  204    ),
  205    !,
  206    sgr_sequence(Attr1, Sequence).
  207ansi_sgr(_, "").
 sgr_sequence(+ClassOrAttributes, -Sequence:string) is det
Sequence is the SGR escape sequence for Attributes. Note that a single attribute may map to multiple codes, e.g., bg8(Color).
  214sgr_sequence(Attrs, Sequence) :-
  215    phrase(sgr_codes_ex(Attrs), Codes),
  216    codes_sequence(Codes, Sequence).
  217
  218codes_sequence(Codes, Sequence) :-
  219    atomics_to_string(Codes, ;, Code),
  220    format(string(Sequence), '\e[~wm', [Code]).
 sgr_codes(+ClassOrAttributes)// is semidet
As sgr_codes_ex//1, but fails rather than raising an exception if Attributes is not a valid attribute (list). This is used where the decoration is optional and the plain text is a fine alternative.
  228sgr_codes(X) -->
  229    { var(X),
  230      !,
  231      fail
  232    }.
  233sgr_codes([]) -->
  234    !.
  235sgr_codes([H|T]) -->
  236    !,
  237    sgr_codes(H),
  238    sgr_codes(T).
  239sgr_codes(Attr) -->
  240    { sgr_code(Attr, Code) },
  241    (   { is_list(Code) }
  242    ->  list(Code)
  243    ;   [Code]
  244    ).
  245
  246sgr_codes_ex(X) -->
  247    { var(X),
  248      !,
  249      instantiation_error(X)
  250    }.
  251sgr_codes_ex([]) -->
  252    !.
  253sgr_codes_ex([H|T]) -->
  254    !,
  255    sgr_codes_ex(H),
  256    sgr_codes_ex(T).
  257sgr_codes_ex(Attr) -->
  258    (   { sgr_code(Attr, Code) }
  259    ->  (   { is_list(Code) }
  260        ->  list(Code)
  261        ;   [Code]
  262        )
  263    ;   { domain_error(sgr_code, Attr) }
  264    ).
  265
  266list([]) --> [].
  267list([H|T]) --> [H], list(T).
 sgr_code(+Name, -Code)
True when code is the Select Graphic Rendition code for Name. The defined names are given below. Note that most terminals only implement this partially.
resetall attributes off
bold
faint
italic
underline
blink(slow)
blink(rapid)
negative
conceal
crossed_out
font(primary)
font(N)Alternate font (1..8)
fraktur
underline(double)
intensity(normal)
fg(Name)Color name
bg(Name)Color name
framed
encircled
overlined
ideogram(underline)
right_side_line
ideogram(underline(double))
right_side_line(double)
ideogram(overlined)
left_side_line
ideogram(stress_marking)
-OffSwitch attributes off
hfg(Name)Color name
hbg(Name)Color name
See also
- http://en.wikipedia.org/wiki/ANSI_escape_code
  309sgr_code(reset, 0).
  310sgr_code(bold,  1).
  311sgr_code(faint, 2).
  312sgr_code(italic, 3).
  313sgr_code(underline, 4).
  314sgr_code(blink(slow), 5).
  315sgr_code(blink(rapid), 6).
  316sgr_code(negative, 7).
  317sgr_code(conceal, 8).
  318sgr_code(crossed_out, 9).
  319sgr_code(font(primary), 10) :- !.
  320sgr_code(font(N), C) :-
  321    C is 10+N.
  322sgr_code(fraktur, 20).
  323sgr_code(underline(double), 21).
  324sgr_code(intensity(normal), 22).
  325sgr_code(fg(Name), C) :-
  326    (   ansi_color(Name, N)
  327    ->  C is N+30
  328    ;   rgb(Name, R, G, B)
  329    ->  sgr_code(fg(R,G,B), C)
  330    ).
  331sgr_code(bg(Name), C) :-
  332    !,
  333    (   ansi_color(Name, N)
  334    ->  C is N+40
  335    ;   rgb(Name, R, G, B)
  336    ->  sgr_code(bg(R,G,B), C)
  337    ).
  338sgr_code(framed, 51).
  339sgr_code(encircled, 52).
  340sgr_code(overlined, 53).
  341sgr_code(ideogram(underline), 60).
  342sgr_code(right_side_line, 60).
  343sgr_code(ideogram(underline(double)), 61).
  344sgr_code(right_side_line(double), 61).
  345sgr_code(ideogram(overlined), 62).
  346sgr_code(left_side_line, 62).
  347sgr_code(ideogram(stress_marking), 64).
  348sgr_code(-X, Code) :-
  349    off_code(X, Code).
  350sgr_code(hfg(Name), C) :-
  351    ansi_color(Name, N),
  352    C is N+90.
  353sgr_code(hbg(Name), C) :-
  354    !,
  355    ansi_color(Name, N),
  356    C is N+100.
  357sgr_code(fg8(Name), [38,5,N]) :-
  358    ansi_color8(Name, N).
  359sgr_code(bg8(Name), [48,5,N]) :-
  360    ansi_color8(Name, N).
  361sgr_code(fg(R,G,B), [38,2,R,G,B]) :-
  362    between(0, 255, R),
  363    between(0, 255, G),
  364    between(0, 255, B).
  365sgr_code(bg(R,G,B), [48,2,R,G,B]) :-
  366    between(0, 255, R),
  367    between(0, 255, G),
  368    between(0, 255, B).
  369
  370off_code(italic_and_franktur, 23).
  371off_code(underline, 24).
  372off_code(blink, 25).
  373off_code(negative, 27).
  374off_code(conceal, 28).
  375off_code(crossed_out, 29).
  376off_code(framed, 54).
  377off_code(overlined, 55).
  378
  379ansi_color8(h(Name), N) :-
  380    !,
  381    ansi_color(Name, N0),
  382    N is N0+8.
  383ansi_color8(Name, N) :-
  384    atom(Name),
  385    !,
  386    ansi_color(Name, N).
  387ansi_color8(N, N) :-
  388    between(0, 255, N).
  389
  390ansi_color(black,   0).
  391ansi_color(red,     1).
  392ansi_color(green,   2).
  393ansi_color(yellow,  3).
  394ansi_color(blue,    4).
  395ansi_color(magenta, 5).
  396ansi_color(cyan,    6).
  397ansi_color(white,   7).
  398ansi_color(default, 9).
  399
  400rgb(Name, R, G, B) :-
  401    atom_codes(Name, [0'#,R1,R2,G1,G2,B1,B2]),
  402    hex_color(R1,R2,R),
  403    hex_color(G1,G2,G),
  404    hex_color(B1,B2,B).
  405rgb(Name, R, G, B) :-
  406    atom_codes(Name, [0'#,R1,G1,B1]),
  407    hex_color(R1,R),
  408    hex_color(G1,G),
  409    hex_color(B1,B).
  410
  411hex_color(D1,D2,V) :-
  412    code_type(D1, xdigit(V1)),
  413    code_type(D2, xdigit(V2)),
  414    V is 16*V1+V2.
  415
  416hex_color(D1,V) :-
  417    code_type(D1, xdigit(V1)),
  418    V is 16*V1+V1.
 prolog:console_color(+Term, -AnsiAttributes) is semidet
Hook that allows for mapping abstract terms to concrete ANSI attributes. This hook is used by theme files to adjust the rendering based on user preferences and context. Defaults are defined in the file boot/messages.pl, default_theme/2.

Besides the classes used for messages (code, comment, var, warning, error, truth(Truth), port(Port), message(Kind), ...), the interactive toplevel uses these:

prompt
The ?- prompt and its `| ` continuation.
input
The text typed by the user at the prompt.
answer(Parity)
An answer written by the toplevel. Parity is odd or even and alternates over the answers of a single query, which allows for striping the answers using a background color. Only an answer that shows bindings, residual goals or delays uses this class: true. and false. are not answers to stripe, and neither is the empty line that separates the answer from the next query.
binding(name)
The variable name in a binding such as X = 1.

The debugger uses, besides frame(level) and port(Port):

goal(Port, Parity)
The goal of a frame reported for Port. Parity is odd or even and alternates over the steps of a trace, which allows for striping the goals using a background color. Match on Port to color the goal by port instead of (or in addition to) striping.

Note that a background color on prompt, input or answer(_) is painted up to the right margin using `\e[K`. A background on goal(_,_) is not: the debugger writes its ? prompt on the same line.

See also
- library(theme/dark) for an example implementation and the Term values used by the system messages.
  463                 /*******************************
  464                 *             HOOK             *
  465                 *******************************/
 prolog:message_line_element(+Stream, +Term) is semidet
Hook implementation that colours the message elements produced by print_message_lines/3. Handled elements are:
ansi(Class, Fmt, Args)
ansi(Class, Fmt, Args, Ctx)
Write Fmt/Args using the attributes of Class. As the element ends with a full reset, the 4th argument version re-installs the decoration of the message as a whole afterwards.
url(Location)
url(URL, Label)
Write a hyperlink. See ansi_hyperlink/2,3. Label is an atom or string, a Format-Args pair or an ansi/3 or ansi/4 term. The latter combines a hyperlink with a style class.
begin(Class, Ctx)
end(Ctx)
Decorate the message as a whole. See below.
nl(Ctx),flush(Ctx)
End a line. If the message has a background colour, the remainder of the line is painted using `\e[K` (Erase in Line) such that the coloured block extends to the right margin.
eol(Ctx)
As above, but also reset the attributes: this ends the decorated part of the line. A message uses this for its last line if that line is not ended using nl. Resetting matters because a terminal that scrolls while a background colour is in effect paints the newly exposed line with it.

Ctx is the message context. It is created by the handler for begin/2 as a term

ansi(Reset, ReInstall, EraseEol)

where Reset is the sequence written by end/1, ReInstall is a Format-Args pair that re-installs the attributes of the message and EraseEol is the sequence that paints the remainder of the line or the empty atom. Callers must treat Ctx as opaque. It is left unbound if Stream is not a terminal, if the color_term flag is false or if the message has no attributes. All handlers that use Ctx therefore fail if it is unbound, which makes print_message_lines/3 fall back to writing plain text.

  510prolog:message_line_element(S, ansi(Class, Fmt, Args)) :-
  511    class_attrs(Class, Attr),
  512    ansi_format(S, Attr, Fmt, Args).
  513prolog:message_line_element(S, ansi(Class, Fmt, Args, Ctx)) :-
  514    class_attrs(Class, Attr),
  515    ansi_format(S, Attr, Fmt, Args),
  516    reinstall_message_attrs(S, Ctx).
  517prolog:message_line_element(S, nl(Ctx)) :-
  518    nonvar(Ctx),
  519    Ctx = ansi(_, _, EOL),
  520    write(S, EOL),
  521    nl(S).
  522prolog:message_line_element(S, flush(Ctx)) :-
  523    nonvar(Ctx),
  524    Ctx = ansi(_, _, EOL),
  525    write(S, EOL),
  526    flush_output(S).
  527prolog:message_line_element(S, eol(Ctx)) :-
  528    nonvar(Ctx),
  529    Ctx = ansi(Reset, _, EOL),
  530    write(S, EOL),
  531    write(S, Reset).
  532prolog:message_line_element(S, url(Location)) :-
  533    ansi_hyperlink(S, Location).
  534prolog:message_line_element(S, url(URL, Label)) :-
  535    link_label(Label, Class, Fmt, Args, Ctx),
  536    !,
  537    format(string(Text), Fmt, Args),
  538    (   ansi_sgr_for(S, Class, Sequence)
  539    ->  write(S, Sequence),
  540        ansi_hyperlink(S, URL, Text),
  541        write(S, '\e[0m'),
  542        reinstall_message_attrs(S, Ctx)
  543    ;   ansi_hyperlink(S, URL, Text)
  544    ).
  545prolog:message_line_element(S, url(URL, Label)) :-
  546    ansi_hyperlink(S, URL, Label).
  547prolog:message_line_element(S, begin(Level, Ctx)) :-
  548    level_attrs(Level, Attr),
  549    Attr \== [],
  550    stream_property(S, tty(true)),
  551    current_prolog_flag(color_term, true),
  552    phrase(sgr_codes(Attr), Codes),     % fails on a kind without a theme
  553    !,
  554    codes_sequence(Codes, Sequence),
  555    write(S, Sequence),
  556    erase_eol(Attr, EOL),
  557    Ctx = ansi('\e[0m', '\e[0m~w'-[Sequence], EOL).
  558prolog:message_line_element(S, end(Ctx)) :-
  559    nonvar(Ctx),
  560    Ctx = ansi(Reset, _, _),
  561    write(S, Reset).
 reinstall_message_attrs(+Stream, +Ctx) is det
Re-install the attributes of the message as a whole after an element that ended with a full reset. See prolog:message_line_element/2.
  568reinstall_message_attrs(S, Ctx) :-
  569    (   nonvar(Ctx),
  570        Ctx = ansi(_, RI-RA, _)
  571    ->  format(S, RI, RA)
  572    ;   true
  573    ).
 link_label(+Label, -Class, -Format, -Args, -Ctx) is semidet
Decompose a decorated label of an url/2 message element. Fails if Label is plain text, which is written using ansi_hyperlink/3.
  580link_label(Fmt-Args, -, Fmt, Args, _) :-
  581    atom(Fmt),
  582    is_list(Args),
  583    !.
  584link_label(ansi(Class, Fmt, Args), Class, Fmt, Args, _).
  585link_label(ansi(Class, Fmt, Args, Ctx), Class, Fmt, Args, Ctx).
 ansi_sgr_for(+Stream, +Class, -Sequence) is semidet
Sequence activates the attributes of Class on Stream. Fails if the Stream is not a terminal, if colour output is disabled or if Class has no attributes.
  593ansi_sgr_for(S, Class, Sequence) :-
  594    Class \== (-),
  595    stream_property(S, tty(true)),
  596    ansi_sgr(Class, Sequence),
  597    Sequence \== "".
 erase_eol(+Attrs, -EOL) is det
If Attrs sets a background color we must paint the remainder of the line to make the colored block extend to the right margin. `\e[K` (Erase in Line) does so on terminals that implement background color erase and does not move the cursor.
  606erase_eol(Attrs, EOL) :-
  607    (   is_list(Attrs),
  608        has_background(Attrs)
  609    ->  EOL = '\e[K'
  610    ;   EOL = ''
  611    ).
  612
  613has_background([H|T]) :-
  614    (   background(H)
  615    ->  true
  616    ;   has_background(T)
  617    ).
  618
  619background(bg(_)).
  620background(bg(_,_,_)).
  621background(bg8(_)).
  622background(hbg(_)).
  623
  624level_attrs(Level,         Attrs) :-
  625    user:message_property(Level, color(Attrs)),
  626    !.
  627level_attrs(Level,         Attrs) :-
  628    class_attrs(message(Level), Attrs).
  629
  630class_attrs(Class, Attrs) :-
  631    user:message_property(Class, color(Attrs)),
  632    !.
  633class_attrs(Class, Attrs) :-
  634    prolog:console_color(Class, Attrs),
  635    !.
  636class_attrs(Class, Attrs) :-
  637    '$messages':default_theme(Class, Attrs),
  638    !.
  639class_attrs(Attrs, Attrs).
 ansi_hyperlink(+Stream, +Location) is det
 ansi_hyperlink(+Stream, +Location, +Label) is det
Create a hyperlink for a terminal emulator using the OSC 8 escape sequence. Location is one of

There is no official standard for encoding the Line and Column. We emit

``file://AbsFileName[#Line[:Column]]``

Both Line and Column count from 1, as in the messages we print and as used by e.g., rg --hyperlink-format=.... Note that a capital L before the line, as used by GitHub, is accepted by Epilog as well.

The sequence is emitted if and only if the Prolog flag hyperlink_term is true and Stream has the property tty(true). ansi_format/4 is guarded the same way for color_term, so that a message captured using with_output_to/2 is plain text.

See also
- https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
  669ansi_hyperlink(Stream, Location) :-
  670    hyperlink(Stream, url(Location)),
  671    !.
  672ansi_hyperlink(Stream, Location) :-
  673    location_label(Location, Label),
  674    ansi_hyperlink(Stream, Location, Label).
  675
  676location_label(File:Line:Column, Label) =>
  677    format(string(Label), '~w:~w:~w', [File,Line,Column]).
  678location_label(File:Line, Label) =>
  679    format(string(Label), '~w:~w', [File,Line]).
  680location_label(File, Label) =>
  681    format(string(Label), '~w', [File]).
  682
  683ansi_hyperlink(Stream, Location, Label),
  684    hyperlink(Stream, url(Location, Label)) =>
  685    true.
  686ansi_hyperlink(Stream, Location, Label) =>
  687    (   hyperlink_stream(Stream),
  688        location_url(Location, URL)
  689    ->  format(Stream, '\e]8;;~w\e\\', [URL]),
  690        format(Stream, '~w', [Label]),
  691        format(Stream, '\e]8;;\e\\', [])
  692    ;   format(Stream, '~w', [Label])
  693    ).
 hyperlink_stream(+Stream) is semidet
True when Stream may carry OSC 8 hyperlinks. Compare ansi_sgr_for/3, which decides the same question for SGR sequences.
  700hyperlink_stream(Stream) :-
  701    current_prolog_flag(hyperlink_term, true),
  702    stream_property(Stream, tty(true)).
 is_url(@URL) is semidet
True if URL is an absolute URL. This means it has a scheme and is not a (Windows) absolute file name as in `c:...`
  709is_url(URL) :-
  710    (   atom(URL)
  711    ->  true
  712    ;   string(URL)
  713    ),
  714    sub_string(URL, Before, _, _, :),
  715    !,
  716    Before > 0,
  717    sub_string(URL, 0, Before, _, Scheme),
  718    atom_codes(Scheme, Codes),
  719    maplist(between(0'a, 0'z), Codes),
  720    not_drive_scheme(Scheme).
  721
  722:- if(current_prolog_flag(windows, true)).  723not_drive_scheme(Scheme) :-
  724    \+ string_length(Scheme, 1).
  725:- else.  726not_drive_scheme(_).
  727:- endif.
 location_url(+Location, -URL) is det
Translate Location into a (file) URL. This predicate is hooked by tty_url_hook/2 with the same signature to allow for actions, location specifiers or URL schemes.
  735location_url(Location, URL),
  736    tty_url_hook(Location, URL0) =>
  737    URL = URL0.
  738location_url(File:Line:Column, URL) =>
  739    url_file_name(FileURL, File),
  740    format(string(URL), '~w#~d:~d', [FileURL, Line, Column]).
  741location_url(File:Line, URL) =>
  742    url_file_name(FileURL, File),
  743    format(string(URL), '~w#~w', [FileURL, Line]).
  744location_url(File, URL) =>
  745    url_file_name(URL, File).
 tty_url_hook(+Location, -URL)
Hook for location_url/2.
 url_file_name(-URL, +File) is semidet
Same as uri_file_name/2 in mode (-,+), but as a core library we do not wish to depend on the clib package and its foreign support.
  757url_file_name(URL, File) :-
  758    is_url(File), !,
  759    URL = File.
  760url_file_name(URL, File) :-
  761    absolute_file_name(File, AbsFile),
  762    ensure_leading_slash(AbsFile, AbsFile1),
  763    url_encode_path(AbsFile1, Encoded),
  764    format(string(URL), 'file://~s', [Encoded]).
  765
  766ensure_leading_slash(Path, SlashPath) :-
  767    (   sub_atom(Path, 0, _, _, /)
  768    ->  SlashPath = Path
  769    ;   atom_concat(/, Path, SlashPath)
  770    ).
  771
  772url_encode_path(Name, Encoded) :-
  773    atom_codes(Name, Codes),
  774    phrase(utf8_codes(Codes), UTF8),
  775    phrase(encode(UTF8), Encoded).
  776
  777encode([]) --> [].
  778encode([H|T]) --> encode1(H), encode(T).
  779
  780encode1(C) -->
  781    { reserved(C),
  782      !,
  783      format(codes([C1,C2]), '~`0t~16r~2|', [C])
  784    },
  785    "%", [C1,C2].
  786encode1(C) -->
  787    [C].
  788
  789reserved(C) :- C =< 0'\s.
  790reserved(C) :- C >= 127.
  791reserved(0'#).
 ansi_get_color(+Which, -RGB) is semidet
Obtain the RGB color for an ANSI color parameter. Which is either a color alias or an integer ANSI color id. Defined aliases are foreground and background. This predicate sends a request to the console (user_output) and reads the reply. This assumes an xterm compatible terminal.
Arguments:
RGB- is a term rgb(Red,Green,Blue). The color components are floats in the range 0.0..1.0. They are sRGB encoded, as that is what the terminal reports; linearise them before doing colour arithmetic that assumes light intensities.
Compatibility
- Up to version 10.1.13 the components were integers in the range 0..65535. The terminal reports one to four hexadecimal digits per component, so that range suggested a precision the reply does not have, and it clashed with the rgb/3 term of win_window_color/2, whose components are in the range 0..255.
  811ansi_get_color(Which0, RGB) :-
  812    \+ current_prolog_flag(console_menu, true),
  813    stream_property(user_input, tty(true)),
  814    stream_property(user_output, tty(true)),
  815    stream_property(user_error, tty(true)),
  816    supports_get_color,
  817    (   color_alias(Which0, Which)
  818    ->  true
  819    ;   must_be(between(0,15),Which0)
  820    ->  Which = Which0
  821    ),
  822    catch(ansi_get_color_(Which, RGB),
  823          error(timeout_error(_,_), _),
  824          no_xterm).
  825
  826supports_get_color :-
  827    \+ current_prolog_flag(windows, true),
  828    getenv('TERM', Term),
  829    sub_atom(Term, 0, _, _, xterm),
  830    \+ getenv('TERM_PROGRAM', 'Apple_Terminal').
  831
  832color_alias(foreground, 10).
  833color_alias(background, 11).
  834
  835ansi_get_color_(Which, RGB) :-
  836    stream_property(user_input, timeout(Old)),
  837    setup_call_cleanup(
  838        set_stream(user_input, timeout(0.05)),
  839        with_tty_raw(exchange_color(Which, RGB)),
  840        set_stream(user_input, timeout(Old))),
  841    !.
  842
  843no_xterm :-
  844    print_message(warning, ansi(no_xterm_get_colour)),
  845    fail.
 exchange_color(+Which, -RGB) is semidet
Ask the terminal for colour Which and read its reply.
  851exchange_color(Which, RGB) :-
  852    format(user_output, '\e]~w;?\a', [Which]),
  853    flush_output(user_output),
  854    format(codes(Id), '~w', [Which]),
  855    read_osc_reply(user_input, Id, Codes),
  856    phrase(color_reply(RGB), Codes).
 read_osc_reply(+In, +Param:codes, -Body:codes) is semidet
Read the body of the OSC reply to our query, i.e., the text between ESC ] Param ; and the string terminator. Terminals reply with either BEL or ST (ESC \), so we accept both.

Anything that is not our reply is echoed: it was typed by the user while we were waiting rather than sent by the terminal.

  867read_osc_reply(In, Param, Body) :-
  868    get_code(In, C),
  869    C \== -1,
  870    (   C == 0'\e,
  871        osc_reply(In, Param, Body0)
  872    ->  Body = Body0
  873    ;   put_code(user_output, C),
  874        read_osc_reply(In, Param, Body)
  875    ).
  876
  877osc_reply(In, Param, Body) :-
  878    get_code(In, 0']),
  879    read_osc_param(In, Param),
  880    read_osc_string(In, Body).
  881
  882read_osc_param(In, Param) :-
  883    read_osc_param_(In, Codes),
  884    Codes == Param.
  885
  886read_osc_param_(In, Codes) :-
  887    get_code(In, C),
  888    C \== -1,
  889    (   C == 0';
  890    ->  Codes = []
  891    ;   Codes = [C|T],
  892        read_osc_param_(In, T)
  893    ).
  894
  895read_osc_string(In, Codes) :-
  896    get_code(In, C),
  897    C \== -1,
  898    (   C == 0'\a                       % BEL
  899    ->  Codes = []
  900    ;   C == 0'\e                       % ST: ESC \
  901    ->  get_code(In, 0'\\),
  902        Codes = []
  903    ;   Codes = [C|T],
  904        read_osc_string(In, T)
  905    ).
 color_reply(-RGB)// is semidet
Parse the body of the reply. This is an X11 colour specification as understood by XParseColor(). Terminals differ in the number of digits they use per component: xterm replies with four, others with one, two or three. A component of N digits is expressed as the fraction of its maximum, which is what XParseColor() scaling amounts to and avoids claiming a precision the reply does not have.
  916color_reply(rgb(R,G,B)) -->
  917    "rgb:", !,
  918    hex_component(R), "/", hex_component(G), "/", hex_component(B).
  919color_reply(rgb(R,G,B)) -->                     % #RGB, #RRGGBB, ...
  920    "#",
  921    hex_digits(Ds),
  922    { length(Ds, Len),
  923      N is Len//3,
  924      N > 0, N =< 4,
  925      length(RDs, N), length(GDs, N), length(BDs, N),
  926      append(RDs, Rest, Ds),
  927      append(GDs, BDs, Rest),
  928      hex_value(RDs, R),
  929      hex_value(GDs, G),
  930      hex_value(BDs, B)
  931    }.
  932
  933hex_component(V) -->
  934    hex_digits(Ds),
  935    { Ds \== [],
  936      length(Ds, N),
  937      N =< 4,
  938      hex_value(Ds, V)
  939    }.
  940
  941hex_digits([H|T]) -->
  942    [H],
  943    { code_type(H, xdigit(_)) },
  944    !,
  945    hex_digits(T).
  946hex_digits([]) -->
  947    [].
 hex_value(+Digits, -Fraction) is det
Fraction is a float in 0.0..1.0. Note that we must not rely on (/)/2 to produce a float: that depends on the Prolog flag prefer_rationals.
  955hex_value(Ds, V) :-
  956    hex_value(Ds, 0, V0),
  957    length(Ds, N),
  958    Max is 16^N - 1,
  959    V is float(V0)/Max.
  960
  961hex_value([], V, V).
  962hex_value([D|T], V0, V) :-
  963    code_type(D, xdigit(DV)),
  964    V1 is V0*16+DV,
  965    hex_value(T, V1, V).
  966
  967:- multifile prolog:message//1.  968
  969prolog:message(ansi(no_xterm_get_colour)) -->
  970    [ 'Terminal claims to be xterm compatible,'-[], nl,
  971      'but does not report colour info'-[]
  972    ]