I’m using Elixir more and more lately and I love it!
Elixir is a functional language and as such it’s very common to feed a function with the return of another one like so:
It can quickly become are to read so Elixir provides a syntactic sugar to pipe a function return to another one:
line |> String.split() |> length()
Easier on the eyes isn’t it?
First of all we need a function that will describe what we want to do:
(defun bounga/insert-elixir-pipe-operator () "Insert a newline and the |> operator" (interactive) (end-of-line) (newline-and-indent) (insert "|> "))
We defined the function
- acts interactively
- goes to the end of the current line
- adds a newline and indents the cursor
- inserts the pipe operator followed by a white space
If you try it by calling
M-x bounga/insert-elixir-pipe-operator in a
buffer, you’ll see it does what we want.
Bind the function to a key chord
To use this new function effectively you should bind it to a key chord (a keyboard shortcut).
We’ll bind the function to
M-RET (Alt + Enter on most keyboards).
Depending on the way you handle your packages there’s two ways of setting it up.
(define-key elixir-mode-map (kbd "M-RET") 'bounga/insert-elixir-pipe-operator)
(use-package elixir-mode :bind (:map elixir-mode-map ("M-RET" . bounga/insert-elixir-pipe-operator)))
Now you’re good to go!
If you’re in an Elixir buffer then
M-RET will insert a new line and
add the pipe operator whether you’re at the end of the line, at the
beginning or in the middle of it.
Let’s see it in action:
Have fun with Emacs and Elixir!