O'Reilly logo

Mastering Vim by Ruslan Osipov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The basics

Let's start simple: let's get our plugin to add a key binding that comments out the current line by prefixing it with a Python-style comment (#).

Let's start in ~/.vim/pack/plugins/start/vim-commenter/plugin/commenter.vim:

" Comment out the current line in Python.function! g:commenter#Comment()  let l:line = getline('.')  call setline('.', '# ' . l:line)endfunctionnnoremap gc :call g:commenter#Comment()<cr>

In the previous example, we've created a function that inserts # in front of the current line (.) and maps it to gc. As you might remember, g, while having some mappings assigned to it (see :help g), is effectively a free namespace for the user to fill, and c stands for "comment".

Another popular prefix for custom mappings is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required