
ansi_term.pl -- 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:
- ansi_format/3 allows writing messages to the terminal with ansi attributes.
- It defines the hook prolog:message_line_element/2, which provides ansi attributes and hyperlinks for print_message/2.
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)andurl(URL, Label)elements of Prolog messages. The default istrueif the environment identifies a terminal known to support OSC 8 hyperlinks.
hyperlink_term_flag_default(-Bool) is det[private]- True when Bool tells whether the terminal is known to support OSC 8 hyperlinks. There is no escape sequence to ask whether a terminal supports them, so we recognise the terminal from the environment variables it sets. A multiplexer (tmux, screen) hides the terminal it runs in and only passes hyperlinks on if configured to do so, so we do not enable them inside one.
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_outputis 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/3). 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)andbg(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.
defaultcan be used to access the default color of the terminal.- black, red, green, yellow, blue, magenta, cyan, white
ANSI sequences are sent if and only if
- The
current_outputhas the propertytty(true)(see stream_property/2). - The Prolog flag
color_termistrue.
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_termisfalseor 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`.
sgr_sequence(+ClassOrAttributes, -Sequence:string) is det[private]- Sequence is the SGR escape sequence for Attributes. Note that a
single attribute may map to multiple codes, e.g.,
bg8(Color).
sgr_codes(+ClassOrAttributes)// is semidet[private]- 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.
sgr_code(+Name, -Code)[private]- 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.
reset all 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)-Off Switch attributes off hfg(Name)Color name hbg(Name)Color name - prolog:console_color(+Theme, +Term, -AnsiAttributes) is semidet[multifile]
- 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. Theme is the
current theme: the value of the Prolog flag
themeor, if no theme is selected, the theme of a loaded theme file. Defaults are defined in the fileboot/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
oddorevenand 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.andfalse.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)andport(Port):- goal(Port, Parity)
- The goal of a frame reported for Port. Parity is
oddorevenand 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,inputoranswer(_)is painted up to the right margin using `\e[K`. A background ongoal(_,_)is not: the debugger writes its?prompt on the same line.If Theme does not define Term, the theme it is based on is used (see prolog:theme_base/2).
- prolog:console_color(+Term, -AnsiAttributes) is semidet[multifile]
- As prolog:console_color/3, but for any theme. This allows the user to define colours in the init file that apply to all themes.
- prolog:theme_base(?Theme, ?Base) is nondet[multifile]
- Hook that makes Theme a variation of the theme Base. If Theme does
not define the colours of a class (prolog:console_color/3), those
of Base are used, and so on. The same applies to the styles of the
online help and the theme colours of the development tools. The
theme file of Theme must load the theme file of Base, e.g.
:- module(prolog_theme_my_dark, []). :- use_module(library(theme/dark)). :- multifile prolog:theme/1, prolog:theme_base/2. prolog:theme(my_dark). prolog:theme_base(my_dark, dark).
prolog:message_line_element(+Stream, +Term) is semidet[multifile]- 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_termflag isfalseor 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.
reinstall_message_attrs(+Stream, +Ctx) is det[private]- 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.
link_label(+Label, -Class, -Format, -Args, -Ctx) is semidet[private]- Decompose a decorated label of an url/2 message element. Fails if Label is plain text, which is written using ansi_hyperlink/3.
ansi_sgr_for(+Stream, +Class, -Sequence) is semidet[private]- 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.
erase_eol(+Attrs, -EOL) is det[private]- 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.
ansi_hyperlink(+Stream, +Location) is det
ansi_hyperlink(+Stream, +Location, +Label) is det- Create a hyperlink for a terminal emulator using the
OSC 8escape sequence. Location is one of- An absolute URL
- An atom (interpreted as a file name)
- A term
File:Line - A term
File:Line:Column
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 capitalLbefore the line, as used by GitHub, is accepted by Epilog as well.The sequence is emitted if and only if the Prolog flag
hyperlink_termistrueand Stream has the propertytty(true). ansi_format/4 is guarded the same way forcolor_term, so that a message captured using with_output_to/2 is plain text.
hyperlink_stream(+Stream) is semidet[private]- True when Stream may carry OSC 8 hyperlinks. Compare ansi_sgr_for/3, which decides the same question for SGR sequences.
is_url(@URL) is semidet[private]- True if URL is an absolute URL. This means it has a scheme and is not a (Windows) absolute file name as in `c:...`
location_url(+Location, -URL) is det[private]- 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.
tty_url_hook(+Location, -URL)[multifile]- Hook for location_url/2.
url_file_name(-URL, +File) is semidet[private]- Same as uri_file_name/2 in mode (-,+), but as a core library we do
not wish to depend on the
clibpackage and its foreign support.
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
foregroundandbackground. This predicate sends a request to the console (user_output) and reads the reply. This assumes anxtermcompatible terminal.
exchange_color(+Which, -RGB) is semidet[private]- Ask the terminal for colour Which and read its reply.
read_osc_reply(+In, +Param:codes, -Body:codes) is semidet[private]- 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.
color_reply(-RGB)// is semidet[private]- 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.
hex_value(+Digits, -Fraction) is det[private]- 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.
Re-exported predicates
The following predicates are exported from this file while their implementation is defined in imported modules or non-module files loaded by this module.
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_outputis 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/3). 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)andbg(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.
defaultcan be used to access the default color of the terminal.- black, red, green, yellow, blue, magenta, cyan, white
ANSI sequences are sent if and only if
- The
current_outputhas the propertytty(true)(see stream_property/2). - The Prolog flag
color_termistrue.
ansi_hyperlink(+Stream, +Location) is det
ansi_hyperlink(+Stream, +Location, +Label) is det- Create a hyperlink for a terminal emulator using the
OSC 8escape sequence. Location is one of- An absolute URL
- An atom (interpreted as a file name)
- A term
File:Line - A term
File:Line:Column
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 capitalLbefore the line, as used by GitHub, is accepted by Epilog as well.The sequence is emitted if and only if the Prolog flag
hyperlink_termistrueand Stream has the propertytty(true). ansi_format/4 is guarded the same way forcolor_term, so that a message captured using with_output_to/2 is plain text.