Bumped release version to 'Beta 24'.
[vcscommand.git] / plugin / vcscommand.vim
blobbe4eb563e7ab904e6d9a6c50b22c4af0d0fe269c
1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
5 " Version:       Beta 24
6 " Maintainer:    Bob Hiestand <bob.hiestand@gmail.com>
7 " License:
8 " Copyright (c) 2008 Bob Hiestand
10 " Permission is hereby granted, free of charge, to any person obtaining a copy
11 " of this software and associated documentation files (the "Software"), to
12 " deal in the Software without restriction, including without limitation the
13 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
14 " sell copies of the Software, and to permit persons to whom the Software is
15 " furnished to do so, subject to the following conditions:
17 " The above copyright notice and this permission notice shall be included in
18 " all copies or substantial portions of the Software.
20 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
26 " IN THE SOFTWARE.
28 " Section: Documentation {{{1
30 " Provides functions to invoke various source control commands on the current
31 " file (either the current buffer, or, in the case of an directory buffer, the
32 " directory and all subdirectories associated with the current buffer).  The
33 " output of the commands is captured in a new scratch window.
35 " This plugin needs additional extension plugins, each  specific to a source
36 " control system, to function.  Those plugins should be placed in a
37 " subdirectory of the standard plugin directory named 'vcscommand'.  Several
38 " options include the name of the version control system in the option name.
39 " Such options use the placeholder text '{VCSType}', which would be replaced
40 " in actual usage with 'CVS' or 'SVN', for instance.
42 " Command documentation {{{2
44 " VCSAdd           Adds the current file to source control.
46 " VCSAnnotate      Displays the current file with each line annotated with the
47 "                  version in which it was most recently changed.  If an
48 "                  argument is given, the argument is used as a revision
49 "                  number to display.  If not given an argument, it uses the
50 "                  most recent version of the file on the current branch.
51 "                  Additionally, if the current buffer is a VCSAnnotate buffer
52 "                  already, the version number on the current line is used.
54 " VCSBlame         Alias for 'VCSAnnotate'.
56 " VCSCommit[!]     Commits changes to the current file to source control.
58 "                  If called with arguments, the arguments are the log message.
60 "                  If '!' is used, an empty log message is committed.
62 "                  If called with no arguments, this is a two-step command.
63 "                  The first step opens a buffer to accept a log message.
64 "                  When that buffer is written, it is automatically closed and
65 "                  the file is committed using the information from that log
66 "                  message.  The commit can be abandoned if the log message
67 "                  buffer is deleted or wiped before being written.
69 " VCSDelete        Deletes the current file and removes it from source control.
71 " VCSDiff          With no arguments, this displays the differences between
72 "                  the current file and its parent version under source
73 "                  control in a new scratch buffer.
75 "                  With one argument, the diff is performed on the
76 "                  current file against the specified revision.
78 "                  With two arguments, the diff is performed between the
79 "                  specified revisions of the current file.
81 "                  This command uses the 'VCSCommand{VCSType}DiffOpt' variable
82 "                  to specify diff options.  If that variable does not exist,
83 "                  a plugin-specific default is used.  If you wish to have no
84 "                  options, then set it to the empty string.
86 " VCSGotoOriginal  Jumps to the source buffer if the current buffer is a VCS
87 "                  scratch buffer.  If VCSGotoOriginal[!] is used, remove all
88 "                  VCS scratch buffers associated with the original file.
90 " VCSInfo          Displays extended information about the current file in a
91 "                  new scratch buffer. 
93 " VCSLock          Locks the current file in order to prevent other users from
94 "                  concurrently modifying it.  The exact semantics of this
95 "                  command depend on the underlying VCS.
97 " VCSLog           Displays the version history of the current file in a new
98 "                  scratch buffer.
100 " VCSRemove        Alias for 'VCSDelete'.
102 " VCSRevert        Replaces the modified version of the current file with the
103 "                  most recent version from the repository.
105 " VCSReview        Displays a particular version of the current file in a new
106 "                  scratch buffer.  If no argument is given, the most recent
107 "                  version of the file on the current branch is retrieved.
109 " VCSStatus        Displays versioning information about the current file in a
110 "                  new scratch buffer.
112 " VCSUnlock        Unlocks the current file in order to allow other users from
113 "                  concurrently modifying it.  The exact semantics of this
114 "                  command depend on the underlying VCS.
116 " VCSUpdate        Updates the current file with any relevant changes from the
117 "                  repository.
119 " VCSVimDiff       Uses vimdiff to display differences between versions of the
120 "                  current file.
122 "                  If no revision is specified, the most recent version of the
123 "                  file on the current branch is used.  With one argument,
124 "                  that argument is used as the revision as above.  With two
125 "                  arguments, the differences between the two revisions is
126 "                  displayed using vimdiff.
128 "                  With either zero or one argument, the original buffer is
129 "                  used to perform the vimdiff.  When the scratch buffer is
130 "                  closed, the original buffer will be returned to normal
131 "                  mode.
133 "                  Once vimdiff mode is started using the above methods,
134 "                  additional vimdiff buffers may be added by passing a single
135 "                  version argument to the command.  There may be up to 4
136 "                  vimdiff buffers total.
138 "                  Using the 2-argument form of the command resets the vimdiff
139 "                  to only those 2 versions.  Additionally, invoking the
140 "                  command on a different file will close the previous vimdiff
141 "                  buffers.
143 " Mapping documentation: {{{2
145 " By default, a mapping is defined for each command.  User-provided mappings
146 " can be used instead by mapping to <Plug>CommandName, for instance:
148 " nmap ,ca <Plug>VCSAdd
150 " The default mappings are as follow:
152 "   <Leader>ca VCSAdd
153 "   <Leader>cn VCSAnnotate
154 "   <Leader>cc VCSCommit
155 "   <Leader>cD VCSDelete
156 "   <Leader>cd VCSDiff
157 "   <Leader>cg VCSGotoOriginal
158 "   <Leader>cG VCSGotoOriginal!
159 "   <Leader>ci VCSInfo
160 "   <Leader>cl VCSLog
161 "   <Leader>cL VCSLock
162 "   <Leader>cr VCSReview
163 "   <Leader>cs VCSStatus
164 "   <Leader>cu VCSUpdate
165 "   <Leader>cU VCSUnlock
166 "   <Leader>cv VCSVimDiff
168 " Options documentation: {{{2
170 " Several variables are checked by the script to determine behavior as follow:
172 " VCSCommandCommitOnWrite
173 "   This variable, if set to a non-zero value, causes the pending commit to
174 "   take place immediately as soon as the log message buffer is written.  If
175 "   set to zero, only the VCSCommit mapping will cause the pending commit to
176 "   occur.  If not set, it defaults to 1.
178 " VCSCommandDeleteOnHide
179 "   This variable, if set to a non-zero value, causes the temporary VCS result
180 "   buffers to automatically delete themselves when hidden.
182 " VCSCommand{VCSType}DiffOpt
183 "   This variable, if set, determines the options passed to the diff command
184 "   of the underlying VCS.  Each VCS plugin defines a default value.
186 " VCSCommandDiffSplit
187 "   This variable overrides the VCSCommandSplit variable, but only for buffers
188 "   created with VCSVimDiff.
190 " VCSCommandDisableMappings
191 "   This variable, if set to a non-zero value, prevents the default command
192 "   mappings from being set.
194 " VCSCommandDisableExtensionMappings
195 "   This variable, if set to a non-zero value, prevents the default command
196 "   mappings from being set for commands specific to an individual VCS.
198 " VCSCommandEdit
199 "   This variable controls whether to split the current window to display a
200 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
201 "   If not set, it defaults to 'split'.
203 " VCSCommandEnableBufferSetup
204 "   This variable, if set to a non-zero value, activates VCS buffer management
205 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
206 "   the file is VCS-controlled.  This is useful for displaying version
207 "   information in the status bar.  Additional options may be set by
208 "   individual VCS plugins.
210 " VCSCommandResultBufferNameExtension
211 "   This variable, if set to a non-blank value, is appended to the name of the
212 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
213 "   help avoid problems caused by autocommands dependent on file extension.
215 " VCSCommandResultBufferNameFunction
216 "   This variable, if set, specifies a custom function for naming VCS command
217 "   output buffers.  This function will be passed the following arguments:
219 "   command - name of the VCS command being executed (such as 'Log' or
220 "   'Diff').
222 "   originalBuffer - buffer number of the source file.
224 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
226 "   statusText - extra text associated with the VCS action (such as version
227 "   numbers).
229 " VCSCommandSplit
230 "   This variable controls the orientation of the various window splits that
231 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
232 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
233 "   If set to 'horizontal', the resulting windows will be on stacked on top of
234 "   one another.  If set to 'vertical', the resulting windows will be
235 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
236 "   VCSVimDiff windows.
238 " Event documentation {{{2
239 "   For additional customization, VCSCommand.vim uses User event autocommand
240 "   hooks.  Each event is in the VCSCommand group, and different patterns
241 "   match the various hooks.
243 "   For instance, the following could be added to the vimrc to provide a 'q'
244 "   mapping to quit a VCS scratch buffer:
246 "   augroup VCSCommand
247 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr> 
248 "   augroup END
250 "   The following hooks are available:
252 "   VCSBufferCreated           This event is fired just after a VCS command
253 "                              output buffer is created.  It is executed
254 "                              within the context of the new buffer.
256 "   VCSBufferSetup             This event is fired just after VCS buffer setup
257 "                              occurs, if enabled.
259 "   VCSPluginInit              This event is fired when the VCSCommand plugin
260 "                              first loads.
262 "   VCSPluginFinish            This event is fired just after the VCSCommand
263 "                              plugin loads.
265 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
266 "                              command executes to allow customization of,
267 "                              for instance, window placement and focus.
269 " Section: Plugin header {{{1
271 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
272 " completes.  This allows various actions to only be taken by functions after
273 " system initialization.
275 if exists('loaded_VCSCommand')
276         finish
277 endif
278 let loaded_VCSCommand = 1
280 if v:version < 700
281         echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
282         finish
283 endif
285 let s:save_cpo=&cpo
286 set cpo&vim
288 " Section: Event group setup {{{1
290 augroup VCSCommand
291 augroup END
293 augroup VCSCommandCommit
294 augroup END
296 " Section: Plugin initialization {{{1
297 silent do VCSCommand User VCSPluginInit
299 " Section: Constants declaration {{{1
301 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
302 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
304 " Section: Script variable initialization {{{1
306 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
307 let s:plugins = {}
309 " temporary values of overridden configuration variables
310 let s:optionOverrides = {}
312 " state flag used to vary behavior of certain automated actions
313 let s:isEditFileRunning = 0
315 " commands needed to restore diff buffers to their original state
316 unlet! s:vimDiffRestoreCmd
318 " original buffer currently reflected in vimdiff windows
319 unlet! s:vimDiffSourceBuffer
322 unlet! s:vimDiffScratchList
324 " Section: Utility functions {{{1
326 " Function: s:ReportError(mapping) {{{2
327 " Displays the given error in a consistent faction.  This is intended to be
328 " invoked from a catch statement.
330 function! s:ReportError(error)
331         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
332 endfunction
334 " Function: s:ExecuteExtensionMapping(mapping) {{{2
335 " Invokes the appropriate extension mapping depending on the type of the
336 " current buffer.
338 function! s:ExecuteExtensionMapping(mapping)
339         let buffer = bufnr('%')
340         let vcsType = VCSCommandGetVCSType(buffer)
341         if !has_key(s:plugins, vcsType)
342                 throw 'Unknown VCS type:  ' . vcsType
343         endif
344         if !has_key(s:plugins[vcsType][2], a:mapping)
345                 throw 'This extended mapping is not defined for ' . vcsType
346         endif
347         silent execute 'normal' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
348 endfunction
350 " Function: s:ExecuteVCSCommand(command, argList) {{{2
351 " Calls the indicated plugin-specific VCS command on the current buffer.
352 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
353 " occurs.
355 function! s:ExecuteVCSCommand(command, argList)
356         try
357                 let buffer = bufnr('%')
359                 let vcsType = VCSCommandGetVCSType(buffer)
360                 if !has_key(s:plugins, vcsType)
361                         throw 'Unknown VCS type:  ' . vcsType
362                 endif
364                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
365                 let bufferName = bufname(originalBuffer)
367                 " It is already known that the directory is under VCS control.  No further
368                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
369                 " VCS-specific error messages from confusing things.
370                 if !isdirectory(bufferName)
371                         if !filereadable(bufferName)
372                                 throw 'No such file ' . bufferName
373                         endif
374                 endif
376                 let functionMap = s:plugins[vcsType][1]
377                 if !has_key(functionMap, a:command)
378                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
379                 endif
380                 return functionMap[a:command](a:argList)
381         catch
382                 call s:ReportError(v:exception)
383                 return -1
384         endtry
385 endfunction
387 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
388 " Default method of generating the name for VCS result buffers.  This can be
389 " overridden with the VCSResultBufferNameFunction variable.
391 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
392         let fileName = bufname(a:originalBuffer)
393         let bufferName = a:vcsType . ' ' . a:command
394         if strlen(a:statusText) > 0
395                 let bufferName .= ' ' . a:statusText
396         endif
397         let bufferName .= ' ' . fileName
398         let counter = 0
399         let versionedBufferName = bufferName
400         while buflisted(versionedBufferName)
401                 let counter += 1
402                 let versionedBufferName = bufferName . ' (' . counter . ')'
403         endwhile
404         return versionedBufferName
405 endfunction
407 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
408 " Method of generating the name for VCS result buffers that uses the original
409 " file name with the VCS type and command appended as extensions.
411 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
412         let fileName = bufname(a:originalBuffer)
413         let bufferName = a:vcsType . ' ' . a:command
414         if strlen(a:statusText) > 0
415                 let bufferName .= ' ' . a:statusText
416         endif
417         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
418         let counter = 0
419         let versionedBufferName = bufferName
420         while buflisted(versionedBufferName)
421                 let counter += 1
422                 let versionedBufferName = '(' . counter . ') ' . bufferName
423         endwhile
424         return versionedBufferName
425 endfunction
427 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
428 " Creates a new buffer of the given name and associates it with the given
429 " original buffer.
431 function! s:EditFile(command, originalBuffer, statusText)
432         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
434         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
435         if nameExtension == ''
436                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
437         else
438                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
439         endif
441         let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
443         " Protect against useless buffer set-up
444         let s:isEditFileRunning += 1
445         try
446                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
447                 if editCommand == 'split'
448                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
449                                 rightbelow split
450                         else
451                                 vert rightbelow split
452                         endif
453                 endif
455                 enew
457                 let b:VCSCommandCommand = a:command
458                 let b:VCSCommandOriginalBuffer = a:originalBuffer
459                 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
460                 let b:VCSCommandVCSType = vcsType
462                 setlocal buftype=nofile
463                 setlocal noswapfile
464                 let &filetype = vcsType . a:command
466                 if a:statusText != ''
467                         let b:VCSCommandStatusText = a:statusText
468                 endif
470                 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
471                         setlocal bufhidden=delete
472                 endif
473                 silent noautocmd file `=resultBufferName`
474         finally
475                 let s:isEditFileRunning -= 1
476         endtry
477 endfunction
479 " Function: s:SetupBuffer() {{{2
480 " Attempts to set the b:VCSCommandBufferInfo variable
482 function! s:SetupBuffer()
483         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
484                 " This buffer is already set up.
485                 return
486         endif
488         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
489                 " No special status for special buffers other than directory buffers.
490                 return
491         endif
493         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
494                 unlet! b:VCSCommandBufferSetup
495                 return
496         endif
498         try
499                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
500                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
501                 silent do VCSCommand User VCSBufferSetup
502         catch /No suitable plugin/
503                 " This is not a VCS-controlled file.
504                 let b:VCSCommandBufferInfo = []
505         endtry
507         let b:VCSCommandBufferSetup = 1
508 endfunction
510 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
511 " Resets the buffer setup state of the original buffer for a given VCS scratch
512 " buffer.
513 " Returns:  The VCS buffer number in a passthrough mode.
515 function! s:MarkOrigBufferForSetup(buffer)
516         checktime
517         if a:buffer > 0 
518                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
519                 " This should never not work, but I'm paranoid
520                 if origBuffer != a:buffer
521                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
522                 endif
523         endif
524         return a:buffer
525 endfunction
527 " Function: s:OverrideOption(option, [value]) {{{2
528 " Provides a temporary override for the given VCS option.  If no value is
529 " passed, the override is disabled.
531 function! s:OverrideOption(option, ...)
532         if a:0 == 0
533                 call remove(s:optionOverrides[a:option], -1)
534         else
535                 if !has_key(s:optionOverrides, a:option)
536                         let s:optionOverrides[a:option] = []
537                 endif
538                 call add(s:optionOverrides[a:option], a:1)
539         endif
540 endfunction
542 " Function: s:WipeoutCommandBuffers() {{{2
543 " Clears all current VCS output buffers of the specified type for a given source.
545 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
546         let buffer = 1
547         while buffer <= bufnr('$')
548                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
549                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
550                                 execute 'bw' buffer
551                         endif
552                 endif
553                 let buffer = buffer + 1
554         endwhile
555 endfunction
557 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
558 " Checks whether the given buffer is one whose deletion should trigger
559 " restoration of an original buffer after it was diffed.  If so, it executes
560 " the appropriate setting command stored with that original buffer.
562 function! s:VimDiffRestore(vimDiffBuff)
563         let s:isEditFileRunning += 1
564         try
565                 if exists('s:vimDiffSourceBuffer')
566                         if a:vimDiffBuff == s:vimDiffSourceBuffer
567                                 " Original file is being removed.
568                                 unlet! s:vimDiffSourceBuffer
569                                 unlet! s:vimDiffRestoreCmd
570                                 unlet! s:vimDiffScratchList
571                         else
572                                 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
573                                 if index >= 0
574                                         call remove(s:vimDiffScratchList, index)
575                                         if len(s:vimDiffScratchList) == 0
576                                                 if exists('s:vimDiffRestoreCmd')
577                                                         " All scratch buffers are gone, reset the original.
578                                                         " Only restore if the source buffer is still in Diff mode
580                                                         let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
581                                                         if sourceWinNR != -1
582                                                                 " The buffer is visible in at least one window
583                                                                 let currentWinNR = winnr()
584                                                                 while winbufnr(sourceWinNR) != -1
585                                                                         if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
586                                                                                 execute sourceWinNR . 'wincmd w'
587                                                                                 if getwinvar(0, '&diff')
588                                                                                         execute s:vimDiffRestoreCmd
589                                                                                 endif
590                                                                         endif
591                                                                         let sourceWinNR = sourceWinNR + 1
592                                                                 endwhile
593                                                                 execute currentWinNR . 'wincmd w'
594                                                         else
595                                                                 " The buffer is hidden.  It must be visible in order to set the
596                                                                 " diff option.
597                                                                 let currentBufNR = bufnr('')
598                                                                 execute 'hide buffer' s:vimDiffSourceBuffer
599                                                                 if getwinvar(0, '&diff')
600                                                                         execute s:vimDiffRestoreCmd
601                                                                 endif
602                                                                 execute 'hide buffer' currentBufNR
603                                                         endif
605                                                         unlet s:vimDiffRestoreCmd
606                                                 endif 
607                                                 " All buffers are gone.
608                                                 unlet s:vimDiffSourceBuffer
609                                                 unlet s:vimDiffScratchList
610                                         endif
611                                 endif
612                         endif
613                 endif
614         finally
615                 let s:isEditFileRunning -= 1
616         endtry
617 endfunction
619 " Section: Generic VCS command functions {{{1
621 " Function: s:VCSCommit() {{{2
622 function! s:VCSCommit(bang, message)
623         try
624                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
625                 if !has_key(s:plugins, vcsType)
626                         throw 'Unknown VCS type:  ' . vcsType
627                 endif
629                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
631                 " Handle the commit message being specified.  If a message is supplied, it
632                 " is used; if bang is supplied, an empty message is used; otherwise, the
633                 " user is provided a buffer from which to edit the commit message.
635                 if strlen(a:message) > 0 || a:bang == '!'
636                         return s:VCSFinishCommit([a:message], originalBuffer)
637                 endif
639                 call s:EditFile('commitlog', originalBuffer, '')
640                 setlocal ft=vcscommit
642                 " Create a commit mapping.
644                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
646                 silent 0put ='VCS: ----------------------------------------------------------------------'
647                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
648                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
650                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
651                         setlocal buftype=acwrite
652                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
653                         silent put ='VCS: or write this buffer'
654                 endif
656                 silent put ='VCS: ----------------------------------------------------------------------'
657                 $
658                 setlocal nomodified
659         catch
660                 call s:ReportError(v:exception)
661                 return -1
662         endtry
663 endfunction
665 " Function: s:VCSFinishCommitWithBuffer() {{{2
666 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
667 " which removes all lines starting with 'VCS:'.
669 function! s:VCSFinishCommitWithBuffer()
670         setlocal nomodified
671         let currentBuffer = bufnr('%') 
672         let logMessageList = getbufline('%', 1, '$')
673         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
674         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
675         if resultBuffer >= 0
676                 execute 'bw' currentBuffer
677         endif
678         return resultBuffer
679 endfunction
681 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
682 function! s:VCSFinishCommit(logMessageList, originalBuffer)
683         let shellSlashBak = &shellslash
684         try
685                 set shellslash
686                 let messageFileName = tempname()
687                 call writefile(a:logMessageList, messageFileName)
688                 try
689                         let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
690                         if resultBuffer < 0
691                                 return resultBuffer
692                         endif
693                         return s:MarkOrigBufferForSetup(resultBuffer)
694                 finally
695                         call delete(messageFileName)
696                 endtry
697         finally
698                 let &shellslash = shellSlashBak
699         endtry
700 endfunction
702 " Function: s:VCSGotoOriginal(bang) {{{2
703 function! s:VCSGotoOriginal(bang)
704         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
705         if originalBuffer > 0
706                 let origWinNR = bufwinnr(originalBuffer)
707                 if origWinNR == -1
708                         execute 'buffer' originalBuffer
709                 else
710                         execute origWinNR . 'wincmd w'
711                 endif
712                 if a:bang == '!'
713                         let buffnr = 1
714                         let buffmaxnr = bufnr('$')
715                         while buffnr <= buffmaxnr
716                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
717                                         execute 'bw' buffnr
718                                 endif
719                                 let buffnr = buffnr + 1
720                         endwhile
721                 endif
722         endif
723 endfunction
725 " Function: s:VCSVimDiff(...) {{{2
726 function! s:VCSVimDiff(...)
727         try
728                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
729                 if !has_key(s:plugins, vcsType)
730                         throw 'Unknown VCS type:  ' . vcsType
731                 endif
732                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
733                 let s:isEditFileRunning = s:isEditFileRunning + 1
734                 try
735                         " If there's already a VimDiff'ed window, restore it.
736                         " There may only be one VCSVimDiff original window at a time.
738                         if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
739                                 " Clear the existing vimdiff setup by removing the result buffers.
740                                 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
741                         endif
743                         " Split and diff
744                         if(a:0 == 2)
745                                 " Reset the vimdiff system, as 2 explicit versions were provided.
746                                 if exists('s:vimDiffSourceBuffer')
747                                         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
748                                 endif
749                                 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
750                                 if resultBuffer < 0
751                                         echomsg 'Can''t open revision ' . a:1
752                                         return resultBuffer
753                                 endif
754                                 let b:VCSCommandCommand = 'vimdiff'
755                                 diffthis
756                                 let s:vimDiffScratchList = [resultBuffer]
757                                 " If no split method is defined, cheat, and set it to vertical.
758                                 try
759                                         call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
760                                         let resultBuffer = s:plugins[vcsType][1].Review([a:2])
761                                 finally
762                                         call s:OverrideOption('VCSCommandSplit')
763                                 endtry
764                                 if resultBuffer < 0
765                                         echomsg 'Can''t open revision ' . a:1
766                                         return resultBuffer
767                                 endif
768                                 let b:VCSCommandCommand = 'vimdiff'
769                                 diffthis
770                                 let s:vimDiffScratchList += [resultBuffer]
771                         else
772                                 " Add new buffer
773                                 call s:OverrideOption('VCSCommandEdit', 'split')
774                                 try
775                                         " Force splitting behavior, otherwise why use vimdiff?
776                                         call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
777                                         try
778                                                 if(a:0 == 0)
779                                                         let resultBuffer = s:plugins[vcsType][1].Review([])
780                                                 else
781                                                         let resultBuffer = s:plugins[vcsType][1].Review([a:1])
782                                                 endif
783                                         finally
784                                                 call s:OverrideOption('VCSCommandSplit')
785                                         endtry
786                                 finally
787                                         call s:OverrideOption('VCSCommandEdit')
788                                 endtry
789                                 if resultBuffer < 0
790                                         echomsg 'Can''t open current revision'
791                                         return resultBuffer
792                                 endif
793                                 let b:VCSCommandCommand = 'vimdiff'
794                                 diffthis
796                                 if !exists('s:vimDiffSourceBuffer')
797                                         " New instance of vimdiff.
798                                         let s:vimDiffScratchList = [resultBuffer]
800                                         " This could have been invoked on a VCS result buffer, not the
801                                         " original buffer.
802                                         wincmd W
803                                         execute 'buffer' originalBuffer
804                                         " Store info for later original buffer restore
805                                         let s:vimDiffRestoreCmd = 
806                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
807                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
808                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
809                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
810                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
811                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
812                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
813                                                                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
814                                         diffthis
815                                         wincmd w
816                                 else
817                                         " Adding a window to an existing vimdiff
818                                         let s:vimDiffScratchList += [resultBuffer]
819                                 endif
820                         endif
822                         let s:vimDiffSourceBuffer = originalBuffer
824                         " Avoid executing the modeline in the current buffer after the autocommand.
826                         let currentBuffer = bufnr('%')
827                         let saveModeline = getbufvar(currentBuffer, '&modeline')
828                         try
829                                 call setbufvar(currentBuffer, '&modeline', 0)
830                                 silent do VCSCommand User VCSVimDiffFinish
831                         finally
832                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
833                         endtry
834                         return resultBuffer
835                 finally
836                         let s:isEditFileRunning = s:isEditFileRunning - 1
837                 endtry
838         catch
839                 call s:ReportError(v:exception)
840                 return -1
841         endtry
842 endfunction
844 " Section: Public functions {{{1
846 " Function: VCSCommandGetVCSType() {{{2
847 " Sets the b:VCSCommandVCSType variable in the given buffer to the
848 " appropriate source control system name.
850 " This uses the Identify extension function to test the buffer.  If the
851 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
852 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
853 " match is considered inexact, and is only applied if no exact match is found.
854 " Multiple inexact matches is currently considered an error.
856 function! VCSCommandGetVCSType(buffer)
857         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
858         if strlen(vcsType) > 0
859                 return vcsType
860         endif
861         let matches = []
862         for vcsType in keys(s:plugins)
863                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
864                 if identified
865                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
866                                 let matches = [vcsType]
867                                 break
868                         else
869                                 let matches += [vcsType]
870                         endif
871                 endif
872         endfor
873         if len(matches) == 1
874                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
875                 return matches[0]
876         elseif len(matches) == 0
877                 throw 'No suitable plugin'
878         else
879                 throw 'Too many matching VCS:  ' . join(matches)
880         endif
881 endfunction
883 " Function: VCSCommandChdir(directory) {{{2
884 " Changes the current directory, respecting :lcd changes.
886 function! VCSCommandChdir(directory)
887         let command = 'cd'
888         if exists("*haslocaldir") && haslocaldir()
889                 let command = 'lcd'
890         endif
891         execute command escape(a:directory, ' ')
892 endfunction
894 " Function: VCSCommandChangeToCurrentFileDir() {{{2
895 " Go to the directory in which the given file is located.
897 function! VCSCommandChangeToCurrentFileDir(fileName)
898         let oldCwd = getcwd()
899         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
900         if strlen(newCwd) > 0
901                 call VCSCommandChdir(newCwd)
902         endif
903         return oldCwd
904 endfunction
906 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
907 " Attempts to locate the original file to which VCS operations were applied
908 " for a given buffer.
910 function! VCSCommandGetOriginalBuffer(vcsBuffer)
911         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
912         if origBuffer
913                 if bufexists(origBuffer)
914                         return origBuffer
915                 else
916                         " Original buffer no longer exists.
917                         throw 'Original buffer for this VCS buffer no longer exists.'
918                 endif
919         else
920                 " No original buffer
921                 return a:vcsBuffer
922         endif
923 endfunction
925 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
926 " Allows VCS modules to register themselves.
928 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
929         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
930         if !empty(a:mappingMap)
931                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
932                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
933                 for mapname in keys(a:mappingMap)
934                         execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
935                 endfor
936         endif
937 endfunction
939 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
940 " General skeleton for VCS function execution.  The given command is executed
941 " after appending the current buffer name (or substituting it for
942 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
943 " new buffer.
945 " The optional 'options' Dictionary may contain the following options:
946 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
947 "               non-zero exit status, the command is still considered
948 "               successfuly.  This defaults to zero.
949 " Returns: name of the new command buffer containing the command results
951 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
952         let allowNonZeroExit = 0
953         if has_key(a:options, 'allowNonZeroExit')
954                 let allowNonZeroExit = a:options.allowNonZeroExit
955         endif
957         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
958         if originalBuffer == -1 
959                 throw 'Original buffer no longer exists, aborting.'
960         endif
962         let path = resolve(bufname(originalBuffer))
964         " Work with netrw or other systems where a directory listing is displayed in
965         " a buffer.
967         if isdirectory(path)
968                 let fileName = '.'
969         else
970                 let fileName = fnamemodify(path, ':t')
971         endif
973         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
974                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
975         else
976                 let fullCmd = a:cmd . ' "' . fileName . '"'
977         endif
979         " Change to the directory of the current buffer.  This is done for CVS, but
980         " is left in for other systems as it does not affect them negatively.
982         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
983         try
984                 let output = system(fullCmd)
985         finally
986                 call VCSCommandChdir(oldCwd)
987         endtry
989         " HACK:  if line endings in the repository have been corrupted, the output
990         " of the command will be confused.
991         let output = substitute(output, "\r", '', 'g')
993         if v:shell_error && !allowNonZeroExit
994                 if strlen(output) == 0
995                         throw 'Version control command failed'
996                 else
997                         let output = substitute(output, '\n', '  ', 'g')
998                         throw 'Version control command failed:  ' . output
999                 endif
1000         endif
1002         if strlen(output) == 0
1003                 " Handle case of no output.  In this case, it is important to check the
1004                 " file status, especially since cvs edit/unedit may change the attributes
1005                 " of the file with no visible output.
1007                 checktime
1008                 return 0
1009         endif
1011         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1013         silent 0put=output
1015         " The last command left a blank line at the end of the buffer.  If the
1016         " last line is folded (a side effect of the 'put') then the attempt to
1017         " remove the blank line will kill the last fold.
1018         "
1019         " This could be fixed by explicitly detecting whether the last line is
1020         " within a fold, but I prefer to simply unfold the result buffer altogether.
1022         if has('folding')
1023                 normal zR
1024         endif
1026         $d
1027         1
1029         " Define the environment and execute user-defined hooks.
1031         silent do VCSCommand User VCSBufferCreated
1032         return bufnr('%')
1033 endfunction
1035 " Function: VCSCommandGetOption(name, default) {{{2
1036 " Grab a user-specified option to override the default provided.  Options are
1037 " searched in the window, buffer, then global spaces.
1039 function! VCSCommandGetOption(name, default)
1040         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1041                 return s:optionOverrides[a:name][-1]
1042         elseif exists('w:' . a:name)
1043                 return w:{a:name}
1044         elseif exists('b:' . a:name)
1045                 return b:{a:name}
1046         elseif exists('g:' . a:name)
1047                 return g:{a:name}
1048         else
1049                 return a:default
1050         endif
1051 endfunction
1053 " Function: VCSCommandDisableBufferSetup() {{{2
1054 " Global function for deactivating the buffer autovariables.
1056 function! VCSCommandDisableBufferSetup()
1057         let g:VCSCommandEnableBufferSetup = 0
1058         silent! augroup! VCSCommandPlugin
1059 endfunction
1061 " Function: VCSCommandEnableBufferSetup() {{{2
1062 " Global function for activating the buffer autovariables.
1064 function! VCSCommandEnableBufferSetup()
1065         let g:VCSCommandEnableBufferSetup = 1
1066         augroup VCSCommandPlugin
1067                 au!
1068                 au BufEnter * call s:SetupBuffer()
1069         augroup END
1071         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1072         " chance to run.
1073         if g:loaded_VCSCommand == 2
1074                 call s:SetupBuffer()
1075         endif
1076 endfunction
1078 " Function: VCSCommandGetStatusLine() {{{2
1079 " Default (sample) status line entry for VCS-controlled files.  This is only
1080 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1081 " variable for how to do this).
1083 function! VCSCommandGetStatusLine()
1084         if exists('b:VCSCommandCommand')
1085                 " This is a result buffer.  Return nothing because the buffer name
1086                 " contains information already.
1087                 return ''
1088         endif
1090         if exists('b:VCSCommandVCSType')
1091                                 \ && exists('g:VCSCommandEnableBufferSetup')
1092                                 \ && g:VCSCommandEnableBufferSetup
1093                                 \ && exists('b:VCSCommandBufferInfo')
1094                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1095         else
1096                 return ''
1097         endif
1098 endfunction
1100 " Section: Command definitions {{{1
1101 " Section: Primary commands {{{2
1102 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1103 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1104 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1105 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1106 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1107 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1108 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1109 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1110 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1111 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1112 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1113 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1114 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1115 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1116 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1117 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1118 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1120 " Section: VCS buffer management commands {{{2
1121 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1122 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1124 " Allow reloading VCSCommand.vim
1125 com! VCSReload let savedPlugins = s:plugins|let s:plugins = {}|aunmenu Plugin.VCS|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for plugin in values(savedPlugins)|execute 'source' plugin[0]|endfor|unlet savedPlugins
1127 " Section: Plugin command mappings {{{1
1128 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1129 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1130 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1131 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1132 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1133 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1134 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1135 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1136 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1137 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1138 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1139 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1140 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1141 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1142 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1143 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1145 " Section: Default mappings {{{1
1147 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1148         if !hasmapto('<Plug>VCSAdd')
1149                 nmap <unique> <Leader>ca <Plug>VCSAdd
1150         endif
1151         if !hasmapto('<Plug>VCSAnnotate')
1152                 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1153         endif
1154         if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1155                 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1156         endif
1157         if !hasmapto('<Plug>VCSCommit')
1158                 nmap <unique> <Leader>cc <Plug>VCSCommit
1159         endif
1160         if !hasmapto('<Plug>VCSDelete')
1161                 nmap <unique> <Leader>cD <Plug>VCSDelete
1162         endif
1163         if !hasmapto('<Plug>VCSDiff')
1164                 nmap <unique> <Leader>cd <Plug>VCSDiff
1165         endif
1166         if !hasmapto('<Plug>VCSGotoOriginal')
1167                 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1168         endif
1169         if !hasmapto('<Plug>VCSInfo')
1170                 nmap <unique> <Leader>ci <Plug>VCSInfo
1171         endif
1172         if !hasmapto('<Plug>VCSLock')
1173                 nmap <unique> <Leader>cL <Plug>VCSLock
1174         endif
1175         if !hasmapto('<Plug>VCSLog')
1176                 nmap <unique> <Leader>cl <Plug>VCSLog
1177         endif
1178         if !hasmapto('<Plug>VCSRevert')
1179                 nmap <unique> <Leader>cq <Plug>VCSRevert
1180         endif
1181         if !hasmapto('<Plug>VCSReview')
1182                 nmap <unique> <Leader>cr <Plug>VCSReview
1183         endif
1184         if !hasmapto('<Plug>VCSStatus')
1185                 nmap <unique> <Leader>cs <Plug>VCSStatus
1186         endif
1187         if !hasmapto('<Plug>VCSUnlock')
1188                 nmap <unique> <Leader>cU <Plug>VCSUnlock
1189         endif
1190         if !hasmapto('<Plug>VCSUpdate')
1191                 nmap <unique> <Leader>cu <Plug>VCSUpdate
1192         endif
1193         if !hasmapto('<Plug>VCSVimDiff')
1194                 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1195         endif
1196 endif
1198 " Section: Menu items {{{1
1199 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1200 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1201 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1202 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1203 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1204 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1205 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1206 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1207 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1208 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1209 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1210 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1212 " Section: Autocommands to restore vimdiff state {{{1
1213 augroup VimDiffRestore
1214         au!
1215         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1216 augroup END
1218 " Section: Optional activation of buffer management {{{1
1220 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1221         call VCSCommandEnableBufferSetup()
1222 endif
1224 " Section: VIM shutdown hook {{{1
1226 " Close all result buffers when VIM exits, to prevent them from being restored
1227 " via viminfo.
1229 " Function: s:CloseAllResultBuffers() {{{2
1230 " Closes all vcscommand result buffers.
1231 function! s:CloseAllResultBuffers()
1232         " This avoids using bufdo as that may load buffers already loaded in another
1233         " vim process, resulting in an error.
1234         let buffnr = 1
1235         let buffmaxnr = bufnr('$')
1236         while buffnr <= buffmaxnr
1237                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != "" 
1238                         execute 'bw' buffnr
1239                 endif
1240                 let buffnr = buffnr + 1
1241         endwhile
1242 endfunction
1244 augroup VCSCommandVIMShutdown
1245         au!
1246         au VimLeavePre * call s:CloseAllResultBuffers()
1247 augroup END
1249 " Section: Plugin completion {{{1
1251 let loaded_VCSCommand = 2
1253 silent do VCSCommand User VCSPluginFinish
1255 let &cpo = s:save_cpo