Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to colorize Elixir iex prompt?

Is it possible to add color and other effects to the iex prompt? Does iex have a resource file (like .irbrc for Ruby's irb)? Is there a customization API that allows prompt customization (like Ruby's IRB.conf)?

like image 835
jwfearn Avatar asked Jun 19 '16 21:06

jwfearn


Video Answer


1 Answers

Yes, yes, and yes!

To customize your prompt, you'll need several things:

  • An .iex.exs file in your home directory. Create this file if it doesn't exist. It will be executed when iex launches.
  • [optional] A call to Application.put_env to enable ANSI. You may need this if iex on your platform (e.g., Windows 10) does not detect ANSI support.
  • A call to IEx.configure to enable color and set the prompt.
  • ANSI escape codes to correct the cursor position. Without this, using up/down arrows to cycle through command history moves the cursor ever farther to the right. IO.ANSI does not currently expose all the cursor movement codes, but raw codes will work for terminals that support them.
  • IO.ANSI formatting functions.
  • Prompt text.
  • IO.ANSI.reset to turn off any remaining formatting.
  • Convert to a string with IO.chardata_to_string.

Here's what works for me with iex 1.3.0 in Terminal and iTerm2 3.0.3 on OS X 10.11.5 and in Console, GitBash, and ConEmu on Windows 10:

# ~/.iex.exs
Application.put_env(:elixir, :ansi_enabled, true)
IEx.configure(
  colors: [enabled: true],
  default_prompt: [
    "\e[G",    # ANSI CHA, move cursor to column 1
    :magenta,
    "%prefix", # IEx prompt variable
    ">",       # plain string
    :reset
  ] |> IO.ANSI.format |> IO.chardata_to_string
)

This code works pretty well, but my prompt only takes effect after the first interaction: when iex first launches, it shows its builtin prompt. If I hit return, then my prompt goes into effect. If anyone knows how to fix that, please share.

[UPDATED: modified to work better on Windows.]

like image 143
jwfearn Avatar answered Sep 28 '22 07:09

jwfearn