I’ve got a little keybinding in my .vimrc file which inserts a debug statement into a file, and then saves it;

map <Leader>db Odebugger; 1<CR><ESC>:w<CR>

So, if I’m editing foo.rb with my cursor on line 2;

1 def hello
2   puts "Hello, world!"
3 end

Then if I hit ,db the file will look like this;

1 def hello
2   debugger; 1
3   puts "Hello, world!"
4 end

Saving the file triggers any test runner process that might be watching the file for changes.

FYI the ; 1 is there in case I want to insert a debug statement at the end of a block – in that case, it gives the debugger something to stop on.

This is great for ruby and javascript, but for other languages like elixir, I need to insert a different statement.

In the past, I’ve done this by creating a custom .vimrc file for each project, in which I remap that key combination to whatever is appropriate. But, that gets pretty tedious when you have a lot of projects.

I want to define my editor config once, but have it insert whatever statement is appropriate, according to the language of the file I’m editing.

Here’s how I’ve done it.

Create a file ~/.vim/scripts/debug.vim

function InsertDebugStatement()
  let debug = "debugger; 1"  | " default because it works for ruby & javascript

  if (&filetype == "elixir")
    let debug = "TestHelper.enable_debug_logging"

  exec ":normal O" . debug
  exec ":write"


map <Leader>db :call InsertDebugStatement()<CR>

Then, in my .vimrc;

source ~/.vim/scripts/debug.vim

That’s it. The key sequence calls the InsertDebugStatement function, which uses the current value of filetype to insert whatever debug statement is required, and then save the file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s