Quick Tip: Drupal Hook Commenting Using Vim

According to the Drupal Coding Standards for Documenting Hook Implementations, its considered a good practice to quickly chuck a comment before any function which implements a Drupal hook (eg, hook_menu). This helps someone reading your code quickly see that the function is actually linked with a hook in Drupal and isn't just a function in your module to be called directly.

But… Well… The thing is… Does anyone else get bored of writing the following over and over again? I know do…


/**
 * Implements hook_menu().
 */

Wouldn't it be nice if you could just type in "menu" and Vim could just fill it our for you? Here follows a little Vim script for inserting a "hook implements" comment at the current cursor position.


function! DrupalImplementsComment(hook)
  set paste

  exe "normal! i/**\"
  \          . " * Implements hook_" . a:hook . "()\"
  \          . " */\"

  set nopaste
endfunction

map  :call DrupalImplementsComment(input("Enter Hook name:"))

Wherever your cursor is, press Ctrl+C 3 times, you then get prompted to enter the hook name. When you press enter, a comment gets inserted. Hopefully this will save someone some time - its already saving me time!

To install the script, I just have it in a file called DrupalCommenting.vim inside my ~/.vim/ folder. Then, inside my ~/.vimrc file, I have a line which imports the source file, eg: so ~/.vim/DrupalCommenting.vim.

Any improvements very welcome!