Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to switch between projects in Vim?

Tags:

vim

I use CtrlP to get around files within a project (which can usually be defined as being a git repo root), but often find myself using :cd to switch between different projects which seems unnecessarily time consuming.

I'd like vim to be able to remember different git repo roots I have visited and quickly jump between them. Once there, all the files in the repo will be available to CtrlP and I can get to where I want.

Is there some way to get what I want with an existing plugin?

like image 611
jazmit Avatar asked Feb 02 '15 21:02

jazmit


1 Answers

If you use fugitive.vim then I might have an option for you.

Put the following in your ~/.vimrc file:

set viminfo+=!

if !exists('g:PROJECTS')
  let g:PROJECTS = {}
endif

augroup project_discovery
  autocmd!
  autocmd User Fugitive let g:PROJECTS[fnamemodify(fugitive#repo().dir(), ':h')] = 1
augroup END

command! -complete=customlist,s:project_complete -nargs=1 Project cd <args>

function! s:project_complete(lead, cmdline, _) abort
  let results = keys(get(g:, 'PROJECTS', {}))

  " use projectionist if available
  if exists('*projectionist#completion_filter')
    return projectionist#completion_filter(results, a:lead, '/')
  endif

  " fallback to cheap fuzzy matching
  let regex = substitute(a:lead, '.', '[&].*', 'g')
  return filter(results, 'v:val =~ regex')
endfunction

Overview

The idea is that anytime fugitive activates a buffer the script stores the project directory path inside a g:PROJECTS dictionary. Adding ! to 'viminfo' will store capitalized global variables to the viminfo file thereby making the discovered projects persist. Once fugitive discovers a project the :Project command can be used to :cd to that directory with completion.

Notes and Warnings

  • I have not tested any of this code. Use as-is.
  • Requires Fugitive.vim
  • Optionally uses Projectionist.vim completion if available
  • Feel free to add directory paths to g:PROJECTS by other means
  • Must visit a repository so that it can be discovered
  • There is no clean up for missing project directories
  • Vim has no concept of "project" so there is only so much that can be done
like image 125
Peter Rincker Avatar answered Oct 07 '22 14:10

Peter Rincker