简体   繁体   中英

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

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 (eg, 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.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM