Changing colors with IO.ANSI?

I’m looking over the docs for IO.ANSI and so far I’ve been unable to modify my output colors or background.

I have my commands in a foo.exs file which I’m running via mix run foo.exs. I’ve tried variations of things like the following in my foo.exs:

IO.ANSI.yellow()
IO.puts("Hello?")

but nothing seems to actually change the output color. What am I missing?

Thanks!

1 Like

Those functions do not have a side effect, their return value has to be in the string.

IO.puts("#{IO.ANSI.yellow()}Hello?")
3 Likes

Thanks! I’m gonna submit a PR on those docs.

1 Like
4 Likes

Thanks for sending the PR (and the other doc improvements you’ve worked on!)

This is my favorite blog post about IO.ANSI, and I think that you may find it helpful/interesting (by @dnsbty):

4 Likes

Thanks for sharing! I’m glad it’s been helpful for you! I’m happy to answer any other questions anyone might have

1 Like

You could even use IO.ANSI.format/1 to make it clearer:

IO.puts IO.ANSI.red() <> "hello"

Is (almost) the same as:

IO.puts IO.ANSI.format([:red, "hello])

With the difference that IO.ANSI.format/1 will automatically check if current shell supports the ANSI escape codes, so:

elixir script.exs | cat

Will result with non-coloured text.

3 Likes