Vim: Project Specific Shortcuts

In this post I will show you my setup for project specific shortcuts in vim.

Fair Warning: I’m just a n00b writing this for practice. The intention is more to inspire than to teach. All I do is name the file the same thing in every project and auto source the file using that name whenever I open vim.

I find myself constantly creating vim shortcuts that only pertain to the specific project I’m working on (when I find myself using the same shortcuts across projects, I remake them into something generic). Usually these shortcuts simply point to specific points in files using Vim’s mark system.

For example mark “I” as in Idiot might point to the index page of a website:
" open index page
:e index.html

" set mark I as in idiot
:mark I

" switch back to this file
:b#

Now, if I type 'I from anywhere in my project, it will take me to the index page.

I also may want to load shortcuts specific to the type of project.

For example, if it’s a django project:

:so django/vim_shortcuts.vim

Would load shortcuts that are only for django projects (like running the server).

For organization, I always put these project specific commands in a file called “vim_setup.vim” located at the root of my project directory:
project_folder/vim_setup.vim

By always using the same name for the file, I immediately know what that file is just by reading the name. It also makes it very simple to source the file automatically.

In a file called:
.vim/plugin/auto_source_vim_setup.vim
(note: this is inside of the main vim directory not the project directory)

" on start, source any vim_setup.vim file
autocmd VimEnter * call Source_vim_setup_file()
function! Source_vim_setup_file()
    " check for the file first
    if filereadable("vim_setup.vim")

        " use ':messages' to see if the file was sourced
        echom "sourced: vim_setup.vim"

        " source the file
        so vim_setup.vim
    endif
endfunction

And there you have it. Now if you execute the following in bash:
cd project_directory
vim

Vim will automatically load the mappings and execute the commands for your project.

Thank you for reading this. I welcome all criticism. (you can use the Hacker News thread: https://news.ycombinator.com/item?id=10678445)

Leave a comment