Vim Tips Wiki
Tip 176 Printable Monobook Previous Next

created December 8, 2001 · complexity intermediate · author Steven Grady · version 6.0

The following code automatically checks out files from perforce when the user modifies them. It first confirms the check-out with the user.

(Perforce is a commercial version control system. I imagine this could be modified for RCS, CVS, etc., but I don't use those.)

I'm a Vim newbie -- I've used vi since 1984, but just started with Vim a couple days ago. Color me impressed! Please excuse any stupidity in the code..

Note that this function needs the "P4HOME" environment variable to be set. I could extract it by invoking "p4 client", but I don't want to invoke p4 every time I start Vim. So I assume the user sets it in the environment.

" Set a buffer-local variable to the perforce path, if this file is under the perforce root.
function IsUnderPerforce()
  if exists("$P4HOME")
    if expand("%:p") =~ ("^" . $P4HOME)
      let b:p4path = substitute(expand("%:p"), $P4HOME, "//depot", "")

" Confirm with the user, then checkout a file from perforce.
function P4Checkout()
  if exists("b:p4path")
    if (confirm("Checkout from Perforce?", "&Yes\n&No", 1) == 1)
      call system("p4 edit " . b:p4path . " > /dev/null")
      if v:shell_error == 0
        set noreadonly

if !exists("au_p4_cmd")
  let au_p4_cmd=1
  au BufEnter * call IsUnderPerforce()
  au FileChangedRO * call P4Checkout()


I think it only works if you've checked out the entire depot. I only have one branch checked out (//depot/main/...) and it doesn't work because the substitution just puts in //depot and not //depot/main. I just fixed that in my version of the code and it works now, but I think in addition to $P4HOME one needs a $P4ROOT or some such for the root of what you checked out. Of course you could get both of these from p4client, but it sounds like in the original tip this was undesirable...just something to be aware of for other users of this excellent tip.

Check out this plugin for superset of functionality (it also automagically checks files out from perforce) script#240