Sheharyar Naseer

Cancel Commands in IEx

When typing out long or multi-line commands in IEx, I sometimes make a typo or another mistake. And more often than not, it’s easier typing it from scratch than fixing it. Unfortunately, unlike the Ruby or Node.js REPLs, hitting Ctrl+C in IEx doesn’t cancel the command. Instead, it opens up the BREAK menu.

Hitting Ctrl-C again exits IEx, and if you try to “continue” by pressing c, you still find yourself in the middle of the command you were trying to cancel. A quick Google search reveals that the answer is entering #iex:break in the middle of the command. When received by IEx, it immediately interrupts the current command:

iex(1)> "this is a
...(1)> multiline
...(1)> command
...(1)> #iex:break
** (TokenMissingError) iex:1: incomplete expression

But that is still a lot to remember and type just to get out of a command. But if you’re using iTerm2, you can create a custom map that does it for you!

iTerm2 cancel IEx command

To create a custom keyboard shortcut:

  • Open iTerm preferences (⌘,)
  • Go to the “Keys” section
  • Click on + to create a new map
  • Click on the “Keyboard Shortcut” box, and type the command. It’s a good idea to avoid Ctrl + key combinations, so you can use something like Alt + c or Alt + x
  • Under “Action”, select “Send Text”
  • In the new textbox that appears below, enter &\n#iex:break\n
  • Save, and voila! You can now cancel IEx commands with a simple keyboard shortcut

Note that in the keymap above, you could’ve also just sent #iex:break\n but that would’ve only worked for multi-line commands and on new lines without any text. Prefixing #iex:break with & stops it from executing the current line as well.

If you’re interested in finding out why we can’t just use Ctrl+C to cancel commands, check out this Github Issue on the official Elixir repo (Spoiler: It’s the Erlang VM’s fault).

Here’s the custom shortcut in action:

Cancel multi-line commands IEx