Debugging Erlang programs in Emacs
In this post, I’m going to describe how to debug Erlang code within Emacs. We had installed and configured all the tools necessary, and have written our first Erlang “Hello world” program. Since the code-compile-debug is an important cycle, sooner or later, you will need to step into your code to debug it. Therefore, you might as well learn to debug right from the beginning.
Let’s write a small
test module as follows:
case t_compare(X,Y) of
‘X is smaller than Y’;
‘X is greater than Y’;
‘X is equal to Y’
X < Y ->
X > Y ->
This module has two functions, one to compare two numbers, another to print the comparison result. We are going to use this as sample, set break points, and step through the code.
- From the menu, select Erlang -> Shell -> Start New Shell. Or use the key sequence
C-c C-zto start the new shell. This will split your Emacs window into two parts, the upper part showing your code (the source buffer), the lower part showing the shell (the Erlang shell buffer).
- In the source buffer, tell Distel to connect to the Erlang node that has just been started. Use the key sequence
C-c C-d n, then enter the node name (my node name is default to renzhi, as per our
.emacsconfiguration described in the previous post).
- Now you need to compile your source code. In the Erlang shell buffer, and issue the command
to compile the code with debug information.
- In the source buffer, reload the module with key sequence
C-c C-d L.
- Now, we need to do this step to get around a Distel bug. In the source buffer, pop up the debugger process monitor with the key sequence
C-c C-d m. When the monitor buffer shows up, press
kto kill it.
- In the source bugger, toggle the module into debug interpreting, with the key sequence
C-c C-d i.
- Now, you can set break points in your source code anywhere you want the debugger to stop. In the source buffer, bring the cursor to the line where you want to set break point, then issue the key sequence
- In the Erlang shell buffer, let’s run a function in the module:
- The debugger’s process list comes up, place your cursor on your module’s name, then press ENTER to select it for debugging.
- The debugger window shows up, showing source level debugging, as in the following screenshot:
The arrow on the left indicates the line that is currently executing.
You can use the following commands in the debugger buffer:
- Space : Step into an expression
- n : Step over an expression
- b : Toggle break point on the current line
- c : Continue (until next break point)
- h : Pop up the help text of available commands
That’s it. You can step through your source code to debug it. Distel has a bug, so in the preparation stage, you have to bring up the debugger process monitor, then kill it. This is just a work-around of the bug. Otherwise, you won’t be able to set break points, it will always complain the module is not being interpreted.