Merge commit 'jamessan/master' into dev/use-diffopt
[vcscommand.git] / plugin / vcscommand.vim
blobd647dabf4b254f7662d18b35d3f542c9f13634de
1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of various Version
4 " Control Systems, such as CVS, SVN, SVK, and git.
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 " VCSCommandDisableAll
191 "   This variable, if set, prevents the plugin or any extensions from loading
192 "   at all.  This is useful when a single runtime distribution is used on
193 "   multiple systems with varying versions.
195 " VCSCommandDisableMappings
196 "   This variable, if set to a non-zero value, prevents the default command
197 "   mappings from being set.
199 " VCSCommandDisableExtensionMappings
200 "   This variable, if set to a non-zero value, prevents the default command
201 "   mappings from being set for commands specific to an individual VCS.
203 " VCSCommandEdit
204 "   This variable controls whether to split the current window to display a
205 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
206 "   If not set, it defaults to 'split'.
208 " VCSCommandEnableBufferSetup
209 "   This variable, if set to a non-zero value, activates VCS buffer management
210 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
211 "   the file is VCS-controlled.  This is useful for displaying version
212 "   information in the status bar.  Additional options may be set by
213 "   individual VCS plugins.
215 " VCSCommandMappings
216 "   This variable, if set, overrides the default mappings used for shortcuts.
217 "   It should be a List of 2-element Lists, each containing a shortcut and
218 "   function name pair.
220 " VCSCommandMapPrefix
221 "   This variable, if set, overrides the default mapping prefix ('<Leader>c').
222 "   This allows customization of the mapping space used by the vcscommand
223 "   shortcuts.
225 " VCSCommandResultBufferNameExtension
226 "   This variable, if set to a non-blank value, is appended to the name of the
227 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
228 "   help avoid problems caused by autocommands dependent on file extension.
230 " VCSCommandResultBufferNameFunction
231 "   This variable, if set, specifies a custom function for naming VCS command
232 "   output buffers.  This function will be passed the following arguments:
234 "   command - name of the VCS command being executed (such as 'Log' or
235 "   'Diff').
237 "   originalBuffer - buffer number of the source file.
239 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
241 "   statusText - extra text associated with the VCS action (such as version
242 "   numbers).
244 " VCSCommandSplit
245 "   This variable controls the orientation of the various window splits that
246 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
247 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
248 "   If set to 'horizontal', the resulting windows will be on stacked on top of
249 "   one another.  If set to 'vertical', the resulting windows will be
250 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
251 "   VCSVimDiff windows.
253 " Event documentation {{{2
254 "   For additional customization, VCSCommand.vim uses User event autocommand
255 "   hooks.  Each event is in the VCSCommand group, and different patterns
256 "   match the various hooks.
258 "   For instance, the following could be added to the vimrc to provide a 'q'
259 "   mapping to quit a VCS scratch buffer:
261 "   augroup VCSCommand
262 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr> 
263 "   augroup END
265 "   The following hooks are available:
267 "   VCSBufferCreated           This event is fired just after a VCS command
268 "                              output buffer is created.  It is executed
269 "                              within the context of the new buffer.
271 "   VCSBufferSetup             This event is fired just after VCS buffer setup
272 "                              occurs, if enabled.
274 "   VCSPluginInit              This event is fired when the VCSCommand plugin
275 "                              first loads.
277 "   VCSPluginFinish            This event is fired just after the VCSCommand
278 "                              plugin loads.
280 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
281 "                              command executes to allow customization of,
282 "                              for instance, window placement and focus.
284 " Section: Plugin header {{{1
286 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
287 " completes.  This allows various actions to only be taken by functions after
288 " system initialization.
290 if exists('VCSCommandDisableAll')
291         finish
292 endif
294 if exists('loaded_VCSCommand')
295         finish
296 endif
297 let loaded_VCSCommand = 1
299 if v:version < 700
300         echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
301         finish
302 endif
304 let s:save_cpo=&cpo
305 set cpo&vim
307 " Section: Event group setup {{{1
309 augroup VCSCommand
310 augroup END
312 augroup VCSCommandCommit
313 augroup END
315 " Section: Plugin initialization {{{1
316 silent do VCSCommand User VCSPluginInit
318 " Section: Constants declaration {{{1
320 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
321 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
323 " Section: Script variable initialization {{{1
325 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
326 let s:plugins = {}
328 " temporary values of overridden configuration variables
329 let s:optionOverrides = {}
331 " state flag used to vary behavior of certain automated actions
332 let s:isEditFileRunning = 0
334 " commands needed to restore diff buffers to their original state
335 unlet! s:vimDiffRestoreCmd
337 " original buffer currently reflected in vimdiff windows
338 unlet! s:vimDiffSourceBuffer
341 unlet! s:vimDiffScratchList
343 " Section: Utility functions {{{1
345 " Function: s:ReportError(mapping) {{{2
346 " Displays the given error in a consistent faction.  This is intended to be
347 " invoked from a catch statement.
349 function! s:ReportError(error)
350         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
351 endfunction
354 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
355 " Creates the given mapping by prepending the contents of
356 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
357 " mapping it to the given plugin function.  If a mapping exists for the
358 " specified shortcut + prefix, emit an error but continue.  If a mapping
359 " exists for the specified function, do nothing.
361 function! s:CreateMapping(shortcut, expansion, display)
362         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
363         if !hasmapto(a:expansion)
364                 try
365                         execute 'nmap <silent> <unique>' lhs a:expansion
366                 catch /^Vim(.*):E227:/
367                         if(&verbose != 0)
368                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
369                         endif
370                 endtry
371         endif
372 endfunction
374 " Function: s:ExecuteExtensionMapping(mapping) {{{2
375 " Invokes the appropriate extension mapping depending on the type of the
376 " current buffer.
378 function! s:ExecuteExtensionMapping(mapping)
379         let buffer = bufnr('%')
380         let vcsType = VCSCommandGetVCSType(buffer)
381         if !has_key(s:plugins, vcsType)
382                 throw 'Unknown VCS type:  ' . vcsType
383         endif
384         if !has_key(s:plugins[vcsType][2], a:mapping)
385                 throw 'This extended mapping is not defined for ' . vcsType
386         endif
387         silent execute 'normal' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
388 endfunction
390 " Function: s:ExecuteVCSCommand(command, argList) {{{2
391 " Calls the indicated plugin-specific VCS command on the current buffer.
392 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
393 " occurs.
395 function! s:ExecuteVCSCommand(command, argList)
396         try
397                 let buffer = bufnr('%')
399                 let vcsType = VCSCommandGetVCSType(buffer)
400                 if !has_key(s:plugins, vcsType)
401                         throw 'Unknown VCS type:  ' . vcsType
402                 endif
404                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
405                 let bufferName = bufname(originalBuffer)
407                 " It is already known that the directory is under VCS control.  No further
408                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
409                 " VCS-specific error messages from confusing things.
410                 if !isdirectory(bufferName)
411                         if !filereadable(bufferName)
412                                 throw 'No such file ' . bufferName
413                         endif
414                 endif
416                 let functionMap = s:plugins[vcsType][1]
417                 if !has_key(functionMap, a:command)
418                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
419                 endif
420                 return functionMap[a:command](a:argList)
421         catch
422                 call s:ReportError(v:exception)
423                 return -1
424         endtry
425 endfunction
427 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
428 " Default method of generating the name for VCS result buffers.  This can be
429 " overridden with the VCSResultBufferNameFunction variable.
431 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
432         let fileName = bufname(a:originalBuffer)
433         let bufferName = a:vcsType . ' ' . a:command
434         if strlen(a:statusText) > 0
435                 let bufferName .= ' ' . a:statusText
436         endif
437         let bufferName .= ' ' . fileName
438         let counter = 0
439         let versionedBufferName = bufferName
440         while buflisted(versionedBufferName)
441                 let counter += 1
442                 let versionedBufferName = bufferName . ' (' . counter . ')'
443         endwhile
444         return versionedBufferName
445 endfunction
447 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
448 " Method of generating the name for VCS result buffers that uses the original
449 " file name with the VCS type and command appended as extensions.
451 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
452         let fileName = bufname(a:originalBuffer)
453         let bufferName = a:vcsType . ' ' . a:command
454         if strlen(a:statusText) > 0
455                 let bufferName .= ' ' . a:statusText
456         endif
457         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
458         let counter = 0
459         let versionedBufferName = bufferName
460         while buflisted(versionedBufferName)
461                 let counter += 1
462                 let versionedBufferName = '(' . counter . ') ' . bufferName
463         endwhile
464         return versionedBufferName
465 endfunction
467 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
468 " Creates a new buffer of the given name and associates it with the given
469 " original buffer.
471 function! s:EditFile(command, originalBuffer, statusText)
472         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
474         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
475         if nameExtension == ''
476                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
477         else
478                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
479         endif
481         let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
483         " Protect against useless buffer set-up
484         let s:isEditFileRunning += 1
485         try
486                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
487                 if editCommand == 'split'
488                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
489                                 rightbelow split
490                         else
491                                 vert rightbelow split
492                         endif
493                 endif
495                 enew
497                 let b:VCSCommandCommand = a:command
498                 let b:VCSCommandOriginalBuffer = a:originalBuffer
499                 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
500                 let b:VCSCommandVCSType = vcsType
502                 setlocal buftype=nofile
503                 setlocal noswapfile
504                 let &filetype = vcsType . a:command
506                 if a:statusText != ''
507                         let b:VCSCommandStatusText = a:statusText
508                 endif
510                 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
511                         setlocal bufhidden=delete
512                 endif
513                 silent noautocmd file `=resultBufferName`
514         finally
515                 let s:isEditFileRunning -= 1
516         endtry
517 endfunction
519 " Function: s:SetupBuffer() {{{2
520 " Attempts to set the b:VCSCommandBufferInfo variable
522 function! s:SetupBuffer()
523         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
524                 " This buffer is already set up.
525                 return
526         endif
528         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
529                 " No special status for special buffers other than directory buffers.
530                 return
531         endif
533         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
534                 unlet! b:VCSCommandBufferSetup
535                 return
536         endif
538         try
539                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
540                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
541                 silent do VCSCommand User VCSBufferSetup
542         catch /No suitable plugin/
543                 " This is not a VCS-controlled file.
544                 let b:VCSCommandBufferInfo = []
545         endtry
547         let b:VCSCommandBufferSetup = 1
548 endfunction
550 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
551 " Resets the buffer setup state of the original buffer for a given VCS scratch
552 " buffer.
553 " Returns:  The VCS buffer number in a passthrough mode.
555 function! s:MarkOrigBufferForSetup(buffer)
556         checktime
557         if a:buffer > 0 
558                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
559                 " This should never not work, but I'm paranoid
560                 if origBuffer != a:buffer
561                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
562                 endif
563         endif
564         return a:buffer
565 endfunction
567 " Function: s:OverrideOption(option, [value]) {{{2
568 " Provides a temporary override for the given VCS option.  If no value is
569 " passed, the override is disabled.
571 function! s:OverrideOption(option, ...)
572         if a:0 == 0
573                 call remove(s:optionOverrides[a:option], -1)
574         else
575                 if !has_key(s:optionOverrides, a:option)
576                         let s:optionOverrides[a:option] = []
577                 endif
578                 call add(s:optionOverrides[a:option], a:1)
579         endif
580 endfunction
582 " Function: s:WipeoutCommandBuffers() {{{2
583 " Clears all current VCS output buffers of the specified type for a given source.
585 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
586         let buffer = 1
587         while buffer <= bufnr('$')
588                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
589                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
590                                 execute 'bw' buffer
591                         endif
592                 endif
593                 let buffer = buffer + 1
594         endwhile
595 endfunction
597 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
598 " Checks whether the given buffer is one whose deletion should trigger
599 " restoration of an original buffer after it was diffed.  If so, it executes
600 " the appropriate setting command stored with that original buffer.
602 function! s:VimDiffRestore(vimDiffBuff)
603         let s:isEditFileRunning += 1
604         try
605                 if exists('s:vimDiffSourceBuffer')
606                         if a:vimDiffBuff == s:vimDiffSourceBuffer
607                                 " Original file is being removed.
608                                 unlet! s:vimDiffSourceBuffer
609                                 unlet! s:vimDiffRestoreCmd
610                                 unlet! s:vimDiffScratchList
611                         else
612                                 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
613                                 if index >= 0
614                                         call remove(s:vimDiffScratchList, index)
615                                         if len(s:vimDiffScratchList) == 0
616                                                 if exists('s:vimDiffRestoreCmd')
617                                                         " All scratch buffers are gone, reset the original.
618                                                         " Only restore if the source buffer is still in Diff mode
620                                                         let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
621                                                         if sourceWinNR != -1
622                                                                 " The buffer is visible in at least one window
623                                                                 let currentWinNR = winnr()
624                                                                 while winbufnr(sourceWinNR) != -1
625                                                                         if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
626                                                                                 execute sourceWinNR . 'wincmd w'
627                                                                                 if getwinvar(0, '&diff')
628                                                                                         execute s:vimDiffRestoreCmd
629                                                                                 endif
630                                                                         endif
631                                                                         let sourceWinNR = sourceWinNR + 1
632                                                                 endwhile
633                                                                 execute currentWinNR . 'wincmd w'
634                                                         else
635                                                                 " The buffer is hidden.  It must be visible in order to set the
636                                                                 " diff option.
637                                                                 let currentBufNR = bufnr('')
638                                                                 execute 'hide buffer' s:vimDiffSourceBuffer
639                                                                 if getwinvar(0, '&diff')
640                                                                         execute s:vimDiffRestoreCmd
641                                                                 endif
642                                                                 execute 'hide buffer' currentBufNR
643                                                         endif
645                                                         unlet s:vimDiffRestoreCmd
646                                                 endif 
647                                                 " All buffers are gone.
648                                                 unlet s:vimDiffSourceBuffer
649                                                 unlet s:vimDiffScratchList
650                                         endif
651                                 endif
652                         endif
653                 endif
654         finally
655                 let s:isEditFileRunning -= 1
656         endtry
657 endfunction
659 " Section: Generic VCS command functions {{{1
661 " Function: s:VCSCommit() {{{2
662 function! s:VCSCommit(bang, message)
663         try
664                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
665                 if !has_key(s:plugins, vcsType)
666                         throw 'Unknown VCS type:  ' . vcsType
667                 endif
669                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
671                 " Handle the commit message being specified.  If a message is supplied, it
672                 " is used; if bang is supplied, an empty message is used; otherwise, the
673                 " user is provided a buffer from which to edit the commit message.
675                 if strlen(a:message) > 0 || a:bang == '!'
676                         return s:VCSFinishCommit([a:message], originalBuffer)
677                 endif
679                 call s:EditFile('commitlog', originalBuffer, '')
680                 setlocal ft=vcscommit
682                 " Create a commit mapping.
684                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
686                 silent 0put ='VCS: ----------------------------------------------------------------------'
687                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
688                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
690                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
691                         setlocal buftype=acwrite
692                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
693                         silent put ='VCS: or write this buffer'
694                 endif
696                 silent put ='VCS: ----------------------------------------------------------------------'
697                 $
698                 setlocal nomodified
699         catch
700                 call s:ReportError(v:exception)
701                 return -1
702         endtry
703 endfunction
705 " Function: s:VCSFinishCommitWithBuffer() {{{2
706 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
707 " which removes all lines starting with 'VCS:'.
709 function! s:VCSFinishCommitWithBuffer()
710         setlocal nomodified
711         let currentBuffer = bufnr('%') 
712         let logMessageList = getbufline('%', 1, '$')
713         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
714         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
715         if resultBuffer >= 0
716                 execute 'bw' currentBuffer
717         endif
718         return resultBuffer
719 endfunction
721 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
722 function! s:VCSFinishCommit(logMessageList, originalBuffer)
723         let shellSlashBak = &shellslash
724         try
725                 set shellslash
726                 let messageFileName = tempname()
727                 call writefile(a:logMessageList, messageFileName)
728                 try
729                         let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
730                         if resultBuffer < 0
731                                 return resultBuffer
732                         endif
733                         return s:MarkOrigBufferForSetup(resultBuffer)
734                 finally
735                         call delete(messageFileName)
736                 endtry
737         finally
738                 let &shellslash = shellSlashBak
739         endtry
740 endfunction
742 " Function: s:VCSGotoOriginal(bang) {{{2
743 function! s:VCSGotoOriginal(bang)
744         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
745         if originalBuffer > 0
746                 let origWinNR = bufwinnr(originalBuffer)
747                 if origWinNR == -1
748                         execute 'buffer' originalBuffer
749                 else
750                         execute origWinNR . 'wincmd w'
751                 endif
752                 if a:bang == '!'
753                         let buffnr = 1
754                         let buffmaxnr = bufnr('$')
755                         while buffnr <= buffmaxnr
756                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
757                                         execute 'bw' buffnr
758                                 endif
759                                 let buffnr = buffnr + 1
760                         endwhile
761                 endif
762         endif
763 endfunction
765 " Function: s:VCSVimDiff(...) {{{2
766 function! s:VCSVimDiff(...)
767         try
768                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
769                 if !has_key(s:plugins, vcsType)
770                         throw 'Unknown VCS type:  ' . vcsType
771                 endif
772                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
773                 let s:isEditFileRunning = s:isEditFileRunning + 1
774                 try
775                         " If there's already a VimDiff'ed window, restore it.
776                         " There may only be one VCSVimDiff original window at a time.
778                         if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
779                                 " Clear the existing vimdiff setup by removing the result buffers.
780                                 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
781                         endif
783                         let orientation = substitute(&diffopt, '.*\(horizontal\|vertical\).*', '\1', '')
784                         if !orientation
785                                 let orientation = 'vertical'
786                         endif
787                         " Split and diff
788                         if(a:0 == 2)
789                                 " Reset the vimdiff system, as 2 explicit versions were provided.
790                                 if exists('s:vimDiffSourceBuffer')
791                                         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
792                                 endif
793                                 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
794                                 if resultBuffer < 0
795                                         echomsg 'Can''t open revision ' . a:1
796                                         return resultBuffer
797                                 endif
798                                 let b:VCSCommandCommand = 'vimdiff'
799                                 diffthis
800                                 let s:vimDiffScratchList = [resultBuffer]
801                                 " If no split method is defined, cheat, and set it to vertical.
802                                 try
803                                         call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', orientation)))
804                                         let resultBuffer = s:plugins[vcsType][1].Review([a:2])
805                                 finally
806                                         call s:OverrideOption('VCSCommandSplit')
807                                 endtry
808                                 if resultBuffer < 0
809                                         echomsg 'Can''t open revision ' . a:1
810                                         return resultBuffer
811                                 endif
812                                 let b:VCSCommandCommand = 'vimdiff'
813                                 diffthis
814                                 let s:vimDiffScratchList += [resultBuffer]
815                         else
816                                 " Add new buffer
817                                 call s:OverrideOption('VCSCommandEdit', 'split')
818                                 try
819                                         " Force splitting behavior, otherwise why use vimdiff?
820                                         call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', orientation)))
821                                         try
822                                                 if(a:0 == 0)
823                                                         let resultBuffer = s:plugins[vcsType][1].Review([])
824                                                 else
825                                                         let resultBuffer = s:plugins[vcsType][1].Review([a:1])
826                                                 endif
827                                         finally
828                                                 call s:OverrideOption('VCSCommandSplit')
829                                         endtry
830                                 finally
831                                         call s:OverrideOption('VCSCommandEdit')
832                                 endtry
833                                 if resultBuffer < 0
834                                         echomsg 'Can''t open current revision'
835                                         return resultBuffer
836                                 endif
837                                 let b:VCSCommandCommand = 'vimdiff'
838                                 diffthis
840                                 if !exists('s:vimDiffSourceBuffer')
841                                         " New instance of vimdiff.
842                                         let s:vimDiffScratchList = [resultBuffer]
844                                         " This could have been invoked on a VCS result buffer, not the
845                                         " original buffer.
846                                         wincmd W
847                                         execute 'buffer' originalBuffer
848                                         " Store info for later original buffer restore
849                                         let s:vimDiffRestoreCmd = 
850                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
851                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
852                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
853                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
854                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
855                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
856                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
857                                                                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
858                                         diffthis
859                                         wincmd w
860                                 else
861                                         " Adding a window to an existing vimdiff
862                                         let s:vimDiffScratchList += [resultBuffer]
863                                 endif
864                         endif
866                         let s:vimDiffSourceBuffer = originalBuffer
868                         " Avoid executing the modeline in the current buffer after the autocommand.
870                         let currentBuffer = bufnr('%')
871                         let saveModeline = getbufvar(currentBuffer, '&modeline')
872                         try
873                                 call setbufvar(currentBuffer, '&modeline', 0)
874                                 silent do VCSCommand User VCSVimDiffFinish
875                         finally
876                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
877                         endtry
878                         return resultBuffer
879                 finally
880                         let s:isEditFileRunning = s:isEditFileRunning - 1
881                 endtry
882         catch
883                 call s:ReportError(v:exception)
884                 return -1
885         endtry
886 endfunction
888 " Section: Public functions {{{1
890 " Function: VCSCommandGetVCSType() {{{2
891 " Sets the b:VCSCommandVCSType variable in the given buffer to the
892 " appropriate source control system name.
894 " This uses the Identify extension function to test the buffer.  If the
895 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
896 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
897 " match is considered inexact, and is only applied if no exact match is found.
898 " Multiple inexact matches is currently considered an error.
900 function! VCSCommandGetVCSType(buffer)
901         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
902         if strlen(vcsType) > 0
903                 return vcsType
904         endif
905         let matches = []
906         for vcsType in keys(s:plugins)
907                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
908                 if identified
909                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
910                                 let matches = [vcsType]
911                                 break
912                         else
913                                 let matches += [vcsType]
914                         endif
915                 endif
916         endfor
917         if len(matches) == 1
918                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
919                 return matches[0]
920         elseif len(matches) == 0
921                 throw 'No suitable plugin'
922         else
923                 throw 'Too many matching VCS:  ' . join(matches)
924         endif
925 endfunction
927 " Function: VCSCommandChdir(directory) {{{2
928 " Changes the current directory, respecting :lcd changes.
930 function! VCSCommandChdir(directory)
931         let command = 'cd'
932         if exists("*haslocaldir") && haslocaldir()
933                 let command = 'lcd'
934         endif
935         execute command escape(a:directory, ' ')
936 endfunction
938 " Function: VCSCommandChangeToCurrentFileDir() {{{2
939 " Go to the directory in which the given file is located.
941 function! VCSCommandChangeToCurrentFileDir(fileName)
942         let oldCwd = getcwd()
943         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
944         if strlen(newCwd) > 0
945                 call VCSCommandChdir(newCwd)
946         endif
947         return oldCwd
948 endfunction
950 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
951 " Attempts to locate the original file to which VCS operations were applied
952 " for a given buffer.
954 function! VCSCommandGetOriginalBuffer(vcsBuffer)
955         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
956         if origBuffer
957                 if bufexists(origBuffer)
958                         return origBuffer
959                 else
960                         " Original buffer no longer exists.
961                         throw 'Original buffer for this VCS buffer no longer exists.'
962                 endif
963         else
964                 " No original buffer
965                 return a:vcsBuffer
966         endif
967 endfunction
969 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
970 " Allows VCS modules to register themselves.
972 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
973         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
974         if !empty(a:mappingMap)
975                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
976                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
977                 for shortcut in keys(a:mappingMap)
978                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
979                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
980                 endfor
981         endif
982 endfunction
984 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
985 " General skeleton for VCS function execution.  The given command is executed
986 " after appending the current buffer name (or substituting it for
987 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
988 " new buffer.
990 " The optional 'options' Dictionary may contain the following options:
991 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
992 "               non-zero exit status, the command is still considered
993 "               successfuly.  This defaults to zero.
994 " Returns: name of the new command buffer containing the command results
996 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
997         let allowNonZeroExit = 0
998         if has_key(a:options, 'allowNonZeroExit')
999                 let allowNonZeroExit = a:options.allowNonZeroExit
1000         endif
1002         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1003         if originalBuffer == -1 
1004                 throw 'Original buffer no longer exists, aborting.'
1005         endif
1007         let path = resolve(bufname(originalBuffer))
1009         " Work with netrw or other systems where a directory listing is displayed in
1010         " a buffer.
1012         if isdirectory(path)
1013                 let fileName = '.'
1014         else
1015                 let fileName = fnamemodify(path, ':t')
1016         endif
1018         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1019                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1020         else
1021                 let fullCmd = a:cmd . ' "' . fileName . '"'
1022         endif
1024         " Change to the directory of the current buffer.  This is done for CVS, but
1025         " is left in for other systems as it does not affect them negatively.
1027         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1028         try
1029                 let output = system(fullCmd)
1030         finally
1031                 call VCSCommandChdir(oldCwd)
1032         endtry
1034         " HACK:  if line endings in the repository have been corrupted, the output
1035         " of the command will be confused.
1036         let output = substitute(output, "\r", '', 'g')
1038         if v:shell_error && !allowNonZeroExit
1039                 if strlen(output) == 0
1040                         throw 'Version control command failed'
1041                 else
1042                         let output = substitute(output, '\n', '  ', 'g')
1043                         throw 'Version control command failed:  ' . output
1044                 endif
1045         endif
1047         if strlen(output) == 0
1048                 " Handle case of no output.  In this case, it is important to check the
1049                 " file status, especially since cvs edit/unedit may change the attributes
1050                 " of the file with no visible output.
1052                 checktime
1053                 return 0
1054         endif
1056         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1058         silent 0put=output
1060         " The last command left a blank line at the end of the buffer.  If the
1061         " last line is folded (a side effect of the 'put') then the attempt to
1062         " remove the blank line will kill the last fold.
1063         "
1064         " This could be fixed by explicitly detecting whether the last line is
1065         " within a fold, but I prefer to simply unfold the result buffer altogether.
1067         if has('folding')
1068                 normal zR
1069         endif
1071         $d
1072         1
1074         " Define the environment and execute user-defined hooks.
1076         silent do VCSCommand User VCSBufferCreated
1077         return bufnr('%')
1078 endfunction
1080 " Function: VCSCommandGetOption(name, default) {{{2
1081 " Grab a user-specified option to override the default provided.  Options are
1082 " searched in the window, buffer, then global spaces.
1084 function! VCSCommandGetOption(name, default)
1085         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1086                 return s:optionOverrides[a:name][-1]
1087         elseif exists('w:' . a:name)
1088                 return w:{a:name}
1089         elseif exists('b:' . a:name)
1090                 return b:{a:name}
1091         elseif exists('g:' . a:name)
1092                 return g:{a:name}
1093         else
1094                 return a:default
1095         endif
1096 endfunction
1098 " Function: VCSCommandDisableBufferSetup() {{{2
1099 " Global function for deactivating the buffer autovariables.
1101 function! VCSCommandDisableBufferSetup()
1102         let g:VCSCommandEnableBufferSetup = 0
1103         silent! augroup! VCSCommandPlugin
1104 endfunction
1106 " Function: VCSCommandEnableBufferSetup() {{{2
1107 " Global function for activating the buffer autovariables.
1109 function! VCSCommandEnableBufferSetup()
1110         let g:VCSCommandEnableBufferSetup = 1
1111         augroup VCSCommandPlugin
1112                 au!
1113                 au BufEnter * call s:SetupBuffer()
1114         augroup END
1116         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1117         " chance to run.
1118         if g:loaded_VCSCommand == 2
1119                 call s:SetupBuffer()
1120         endif
1121 endfunction
1123 " Function: VCSCommandGetStatusLine() {{{2
1124 " Default (sample) status line entry for VCS-controlled files.  This is only
1125 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1126 " variable for how to do this).
1128 function! VCSCommandGetStatusLine()
1129         if exists('b:VCSCommandCommand')
1130                 " This is a result buffer.  Return nothing because the buffer name
1131                 " contains information already.
1132                 return ''
1133         endif
1135         if exists('b:VCSCommandVCSType')
1136                                 \ && exists('g:VCSCommandEnableBufferSetup')
1137                                 \ && g:VCSCommandEnableBufferSetup
1138                                 \ && exists('b:VCSCommandBufferInfo')
1139                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1140         else
1141                 return ''
1142         endif
1143 endfunction
1145 " Section: Command definitions {{{1
1146 " Section: Primary commands {{{2
1147 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1148 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1149 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1150 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1151 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1152 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1153 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1154 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1155 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1156 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1157 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1158 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1159 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1160 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1161 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1162 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1163 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1165 " Section: VCS buffer management commands {{{2
1166 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1167 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1169 " Allow reloading VCSCommand.vim
1170 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
1172 " Section: Plugin command mappings {{{1
1173 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1174 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1175 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1176 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1177 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1178 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1179 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1180 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1181 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1182 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1183 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1184 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1185 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1186 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1187 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1188 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1190 " Section: Default mappings {{{1
1192 let s:defaultMappings = [
1193                         \['a', 'VCSAdd'],
1194                         \['c', 'VCSCommit'],
1195                         \['D', 'VCSDelete'],
1196                         \['d', 'VCSDiff'],
1197                         \['G', 'VCSClearAndGotoOriginal'],
1198                         \['g', 'VCSGotoOriginal'],
1199                         \['i', 'VCSInfo'],
1200                         \['L', 'VCSLock'],
1201                         \['l', 'VCSLog'],
1202                         \['n', 'VCSAnnotate'],
1203                         \['q', 'VCSRevert'],
1204                         \['r', 'VCSReview'],
1205                         \['s', 'VCSStatus'],
1206                         \['U', 'VCSUnlock'],
1207                         \['u', 'VCSUpdate'],
1208                         \['v', 'VCSVimDiff'],
1209                         \]
1211 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1212         for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1213                 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1214         endfor
1215 endif
1217 " Section: Menu items {{{1
1218 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1219 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1220 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1221 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1222 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1223 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1224 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1225 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1226 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1227 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1228 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1229 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1231 " Section: Autocommands to restore vimdiff state {{{1
1232 augroup VimDiffRestore
1233         au!
1234         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1235 augroup END
1237 " Section: Optional activation of buffer management {{{1
1239 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1240         call VCSCommandEnableBufferSetup()
1241 endif
1243 " Section: VIM shutdown hook {{{1
1245 " Close all result buffers when VIM exits, to prevent them from being restored
1246 " via viminfo.
1248 " Function: s:CloseAllResultBuffers() {{{2
1249 " Closes all vcscommand result buffers.
1250 function! s:CloseAllResultBuffers()
1251         " This avoids using bufdo as that may load buffers already loaded in another
1252         " vim process, resulting in an error.
1253         let buffnr = 1
1254         let buffmaxnr = bufnr('$')
1255         while buffnr <= buffmaxnr
1256                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != "" 
1257                         execute 'bw' buffnr
1258                 endif
1259                 let buffnr = buffnr + 1
1260         endwhile
1261 endfunction
1263 augroup VCSCommandVIMShutdown
1264         au!
1265         au VimLeavePre * call s:CloseAllResultBuffers()
1266 augroup END
1268 " Section: Plugin completion {{{1
1270 let loaded_VCSCommand = 2
1272 silent do VCSCommand User VCSPluginFinish
1274 let &cpo = s:save_cpo