How to colorize Elixir iex prompt?
Asked Answered
F

1

12

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)?

Frisky answered 19/6, 2016 at 21:24 Comment(0)
F
29

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.]

Frisky answered 19/6, 2016 at 21:24 Comment(6)
IEx.configure colors: [ eval_result: [ :green, :bright ] ] # I wonder why green shows as yellow?Inexorable
@Inexorable ANSI color names map to indexes in a color table defined elsewhere (e.g., in a terminal program.) Many terminal programs support color schemes (e.g., github.com/lysyi3m/osx-terminal-themes)Frisky
on Windows 10 the location of the config file is %USERPROFILE%\.iex.exsPalm
What comes in place of %USERPROFILE%??Macadam
just in case, one uses multiple windows terminals, e.g. ConEmu/Cmder and plain cmd/VSCode, which cannot do ANSI, the config can be made conditional, e.g. if System.get_env("ConEmuANSI") == "ON" do ... endPalm
The "\e[G" seems incompatible with Elixir 1.15.6 - it causes (FunctionClauseError) no function clause matching in :prim_tty.cols/2Ingenuous

© 2022 - 2024 — McMap. All rights reserved.