Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I output Elixir terms with colour?

Tags:

elixir

In iex, terms are coloured nicely. Can I take advantage of this in my own programs? Is there something like IO.color_inspect?

like image 719
Roger Lipscombe Avatar asked Dec 08 '22 15:12

Roger Lipscombe


2 Answers

Both IO.inspect and inspect allow you to pass syntax_colors option where you can specify the color you want for each type of term as documented here. Unfortunately, it looks like the configuration used by IEx is not exposed so you'll have to copy paste or make your own.

iex(1)> syntax_colors = [number: :yellow, atom: :cyan, string: :green, boolean: :magenta, nil: :magenta]
[number: :yellow, atom: :cyan, string: :green, boolean: :magenta, nil: :magenta]
iex(2)> IO.inspect [1, :a, "b", nil], syntax_colors: syntax_colors; :ok
[1, :a, "b", nil]
:ok

iex

like image 69
Dogbert Avatar answered Dec 18 '22 07:12

Dogbert


See the IO.ANSI library for rendering ANSI escape sequences to control formatting, colour, etc.

ExUnit's CLI formatter has some good usage examples.

Using it can be as simple as concatenating or interpolating ANSI characters for foreground or background colours and resets. For example

IO.ANSI example using foreground colours

like image 40
Dennis Avatar answered Dec 18 '22 08:12

Dennis