Quick add debugger code in different languages

When working with Ruby, I often need to insert binding.pry to trouble-shoot a problem. I got tired of typing this all the time so some time back I created a mapping in my .vimrc to handle this:

nnoremap <Leader>,upry Obinding.pry<ESC>
nnoremap <Leader>,dpry obinding.pry<ESC>

Now inserting the code was a simple ,,upry or ,,dpry (my <Leader> is a comma)

Then I started working more with Javascript and wanted the same functionality but didn’t want to code yet another shortcut to remember, since by now my fingers really knew this sequence. So I generalized it to insert whatever was appropriate for the language (i.e., filetype).

Here’s the code, hoping it’s useful to someone else.

First, determine the debugging statement required, based on the filetype setting: I also realized that our Cucmber step Then I pry could also use the same treatment.

function! SetPry()
  if &ft == 'cucumber'
    let pry_command = 'And I pry'
  elseif &ft == 'ruby'
    let pry_command = 'binding.pry'
  elseif &ft == 'javascript'
    let pry_command = 'debugger;'
  else
    echo "Pry command unknown for this filetype: " &ft
    return
  end
  return pry_command
endfunction

Then define the new mapping

nnoremap <Leader>,upry :execute "normal " . "O" . SetPry()<ESC>
nnoremap <Leader>,dpry :execute "normal " . "o" . SetPry()<ESC>

Now I can use the same command, regardless of the language, and vim is smart enough to just do the right thing.

Hey, thanks for the tip.
I used to use abbreviation for it as in iaabrev bp binding.pry and aslo noticed that I need the second one for javscript. Since I used to use it in insert mode initially and I don’t use cucmber I modified yours to be

inoremap <Leader>bp <ESC>:execute "normal " . "O" . SetPry()<ESC>

function! SetPry()
  if &ft == 'ruby'
    let pry_command = 'binding.pry'
  elseif &ft == 'javascript'
    let pry_command = 'debugger;'
  else
    echo "Pry command unknown for this filetype: " &ft
    return
  end
  return pry_command
endfunction

Cool, Andrei – glad it was useful for you!