jazmit
jazmit

Reputation: 5410

What is the best way to switch between projects in 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?

Upvotes: 6

Views: 2448

Answers (4)

Andy Stewart
Andy Stewart

Reputation: 5498

Try vim-rooter: when you enter a buffer it automatically changes directory to the buffer's "root" (e.g. git repo root) directory.

Upvotes: 2

Peter Rincker
Peter Rincker

Reputation: 45147

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

Upvotes: 4

Yong Wu nerd
Yong Wu nerd

Reputation: 46

Just put two project in a new directory, and open Vim in this directory, then you can use ctrlP to open file in both projects.

If you don't want to move the project, create soft link and put them in one directory.

Upvotes: 1

And R
And R

Reputation: 512

This tip suggests using uppercase marks as 'file bookmarks'.

For example, open your .vimrc, press mV, and close Vim. The next time you want to edit your .vimrc, just press 'V to open it.

Upvotes: 1

Related Questions