Save and restore 'foldlevel' with VCSVimDiff.
[vcscommand.git] / plugin / vcscommand.vim
blob9303bbbb08e26df268ab1ebd30e0702aaeb19707
1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
5 " Version:       Beta 19
6 " Maintainer:    Bob Hiestand <bob.hiestand@gmail.com>
7 " License:
8 " Copyright (c) 2007 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 " VCSRevert        Replaces the modified version of the current file with the
101 "                  most recent version from the repository.
103 " VCSReview        Displays a particular version of the current file in a new
104 "                  scratch buffer.  If no argument is given, the most recent
105 "                  version of the file on the current branch is retrieved.
107 " VCSStatus        Displays versioning information about the current file in a
108 "                  new scratch buffer.
110 " VCSUnlock        Unlocks the current file in order to allow other users from
111 "                  concurrently modifying it.  The exact semantics of this
112 "                  command depend on the underlying VCS.
114 " VCSUpdate        Updates the current file with any relevant changes from the
115 "                  repository.
117 " VCSVimDiff       Uses vimdiff to display differences between versions of the
118 "                  current file.
120 "                  If no revision is specified, the most recent version of the
121 "                  file on the current branch is used.  With one argument,
122 "                  that argument is used as the revision as above.  With two
123 "                  arguments, the differences between the two revisions is
124 "                  displayed using vimdiff.
126 "                  With either zero or one argument, the original buffer is
127 "                  used to perform the vimdiff.  When the scratch buffer is
128 "                  closed, the original buffer will be returned to normal
129 "                  mode.
131 "                  Once vimdiff mode is started using the above methods,
132 "                  additional vimdiff buffers may be added by passing a single
133 "                  version argument to the command.  There may be up to 4
134 "                  vimdiff buffers total.
136 "                  Using the 2-argument form of the command resets the vimdiff
137 "                  to only those 2 versions.  Additionally, invoking the
138 "                  command on a different file will close the previous vimdiff
139 "                  buffers.
141 " Mapping documentation: {{{2
143 " By default, a mapping is defined for each command.  User-provided mappings
144 " can be used instead by mapping to <Plug>CommandName, for instance:
146 " nmap ,ca <Plug>VCSAdd
148 " The default mappings are as follow:
150 "   <Leader>ca VCSAdd
151 "   <Leader>cn VCSAnnotate
152 "   <Leader>cc VCSCommit
153 "   <Leader>cD VCSDelete
154 "   <Leader>cd VCSDiff
155 "   <Leader>cg VCSGotoOriginal
156 "   <Leader>cG VCSGotoOriginal!
157 "   <Leader>ci VCSInfo
158 "   <Leader>cl VCSLog
159 "   <Leader>cL VCSLock
160 "   <Leader>cr VCSReview
161 "   <Leader>cs VCSStatus
162 "   <Leader>cu VCSUpdate
163 "   <Leader>cU VCSUnlock
164 "   <Leader>cv VCSVimDiff
166 " Options documentation: {{{2
168 " Several variables are checked by the script to determine behavior as follow:
170 " VCSCommandCommitOnWrite
171 "   This variable, if set to a non-zero value, causes the pending commit to
172 "   take place immediately as soon as the log message buffer is written.  If
173 "   set to zero, only the VCSCommit mapping will cause the pending commit to
174 "   occur.  If not set, it defaults to 1.
176 " VCSCommandDeleteOnHide
177 "   This variable, if set to a non-zero value, causes the temporary VCS result
178 "   buffers to automatically delete themselves when hidden.
180 " VCSCommand{VCSType}DiffOpt
181 "   This variable, if set, determines the options passed to the diff command
182 "   of the underlying VCS.  Each VCS plugin defines a default value.
184 " VCSCommandDiffSplit
185 "   This variable overrides the VCSCommandSplit variable, but only for buffers
186 "   created with VCSVimDiff.
188 " VCSCommandDisableMappings
189 "   This variable, if set to a non-zero value, prevents the default command
190 "   mappings from being set.
192 " VCSCommandDisableExtensionMappings
193 "   This variable, if set to a non-zero value, prevents the default command
194 "   mappings from being set for commands specific to an individual VCS.
196 " VCSCommandEdit
197 "   This variable controls whether to split the current window to display a
198 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
199 "   If not set, it defaults to 'split'.
201 " VCSCommandEnableBufferSetup
202 "   This variable, if set to a non-zero value, activates VCS buffer management
203 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
204 "   the file is VCS-controlled.  This is useful for displaying version
205 "   information in the status bar.  Additional options may be set by
206 "   individual VCS plugins.
208 " VCSCommandResultBufferNameExtension
209 "   This variable, if set to a non-blank value, is appended to the name of the
210 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
211 "   help avoid problems caused by autocommands dependent on file extension.
213 " VCSCommandResultBufferNameFunction
214 "   This variable, if set, specifies a custom function for naming VCS command
215 "   output buffers.  This function will be passed the following arguments:
217 "   command - name of the VCS command being executed (such as 'Log' or
218 "   'Diff').
220 "   originalBuffer - buffer number of the source file.
222 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
224 "   statusText - extra text associated with the VCS action (such as version
225 "   numbers).
227 " VCSCommandSplit
228 "   This variable controls the orientation of the various window splits that
229 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
230 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
231 "   If set to 'horizontal', the resulting windows will be on stacked on top of
232 "   one another.  If set to 'vertical', the resulting windows will be
233 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
234 "   VCSVimDiff windows.
236 " Event documentation {{{2
237 "   For additional customization, VCSCommand.vim uses User event autocommand
238 "   hooks.  Each event is in the VCSCommand group, and different patterns
239 "   match the various hooks.
241 "   For instance, the following could be added to the vimrc to provide a 'q'
242 "   mapping to quit a VCS scratch buffer:
244 "   augroup VCSCommand
245 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr> 
246 "   augroup END
248 "   The following hooks are available:
250 "   VCSBufferCreated           This event is fired just after a VCS command
251 "                              output buffer is created.  It is executed
252 "                              within the context of the new buffer.
254 "   VCSBufferSetup             This event is fired just after VCS buffer setup
255 "                              occurs, if enabled.
257 "   VCSPluginInit              This event is fired when the VCSCommand plugin
258 "                              first loads.
260 "   VCSPluginFinish            This event is fired just after the VCSCommand
261 "                              plugin loads.
263 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
264 "                              command executes to allow customization of,
265 "                              for instance, window placement and focus.
267 " Section: Plugin header {{{1
269 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
270 " completes.  This allows various actions to only be taken by functions after
271 " system initialization.
273 if exists('loaded_VCSCommand')
274    finish
275 endif
276 let loaded_VCSCommand = 1
278 if v:version < 700
279   echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
280   finish
281 endif
283 let s:save_cpo=&cpo
284 set cpo&vim
286 " Section: Event group setup {{{1
288 augroup VCSCommand
289 augroup END
291 augroup VCSCommandCommit
292 augroup END
294 " Section: Plugin initialization {{{1
295 silent do VCSCommand User VCSPluginInit
297 " Section: Script variable initialization {{{1
299 let s:plugins = {}
300 let s:pluginFiles = []
301 let s:extendedMappings = {}
302 let s:optionOverrides = {}
303 let s:isEditFileRunning = 0
305 unlet! s:vimDiffRestoreCmd
306 unlet! s:vimDiffSourceBuffer
307 unlet! s:vimDiffScratchList
309 " Section: Utility functions {{{1
311 " Function: s:ReportError(mapping) {{{2
312 " Displays the given error in a consistent faction.  This is intended to be
313 " invoked from a catch statement.
315 function! s:ReportError(error)
316   echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
317 endfunction
319 " Function: s:ExecuteExtensionMapping(mapping) {{{2
320 " Invokes the appropriate extension mapping depending on the type of the
321 " current buffer.
323 function! s:ExecuteExtensionMapping(mapping)
324   let buffer = bufnr('%')
325   let vcsType = VCSCommandGetVCSType(buffer)
326   if !has_key(s:extendedMappings, vcsType)
327     throw 'Unknown VCS type:  ' . vcsType
328   endif
329   if !has_key(s:extendedMappings[vcsType], a:mapping)
330     throw 'This extended mapping is not defined for ' . vcsType
331   endif
332   silent execute 'normal' ':' .  s:extendedMappings[vcsType][a:mapping] . "\<CR>"
333 endfunction
335 " Function: s:ExecuteVCSCommand(command, argList) {{{2
336 " Calls the indicated plugin-specific VCS command on the current buffer.
337 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
338 " occurs.
340 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
341   try
342     let buffer = bufnr('%')
344     let vcsType = VCSCommandGetVCSType(buffer)
345     if !has_key(s:plugins, vcsType)
346       throw 'Unknown VCS type:  ' . vcsType
347     endif
349     let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
350     let bufferName = bufname(originalBuffer)
352     " It is already known that the directory is under VCS control.  No further
353     " checks are needed.  Otherwise, perform some basic sanity checks to avoid
354     " VCS-specific error messages from confusing things.
355     if !isdirectory(bufferName)
356       if !filereadable(bufferName)
357         throw 'No such file ' . bufferName
358       endif
359       if(a:verifyBuffer)
360         if isdirectory(bufferName)
361         endif
362         let revision = VCSCommandGetRevision()
363         if revision == ''
364           throw 'Unable to obtain version information.'
365         elseif revision == 'Unknown'
366           throw 'Item not under source control'
367         elseif revision == 'New'
368           throw 'Operation not available on newly-added item.'
369         endif
370       endif
371     endif
373     let functionMap = s:plugins[vcsType]
374     if !has_key(functionMap, a:command)
375       throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
376     endif
377     return functionMap[a:command](a:argList)
378   catch
379     call s:ReportError(v:exception)
380     return -1
381   endtry
382 endfunction
384 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
385 " Default method of generating the name for VCS result buffers.  This can be
386 " overridden with the VCSResultBufferNameFunction variable.
388 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
389   let fileName = bufname(a:originalBuffer)
390   let bufferName = a:vcsType . ' ' . a:command
391   if strlen(a:statusText) > 0
392     let bufferName .= ' ' . a:statusText
393   endif
394   let bufferName .= ' ' . fileName
395   let counter = 0
396   let versionedBufferName = bufferName
397   while buflisted(versionedBufferName)
398     let counter += 1
399     let versionedBufferName = bufferName . ' (' . counter . ')'
400   endwhile
401   return versionedBufferName
402 endfunction
404 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
405 " Method of generating the name for VCS result buffers that uses the original
406 " file name with the VCS type and command appended as extensions.
408 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
409   let fileName = bufname(a:originalBuffer)
410   let bufferName = a:vcsType . ' ' . a:command
411   if strlen(a:statusText) > 0
412     let bufferName .= ' ' . a:statusText
413   endif
414   let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
415   let counter = 0
416   let versionedBufferName = bufferName
417   while buflisted(versionedBufferName)
418     let counter += 1
419     let versionedBufferName = '(' . counter . ') ' . bufferName
420   endwhile
421   return versionedBufferName
422 endfunction
424 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
425 " Creates a new buffer of the given name and associates it with the given
426 " original buffer.
428 function! s:EditFile(command, originalBuffer, statusText)
429   let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
431   let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
432   if nameExtension == ''
433     let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
434   else
435     let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
436   endif
438   let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
440   " Protect against useless buffer set-up
441   let s:isEditFileRunning += 1
442   try
443     let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
444     if editCommand == 'split'
445       if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
446         rightbelow split
447       else
448         vert rightbelow split
449       endif
450     endif
451     edit `=resultBufferName`
452     let b:VCSCommandCommand = a:command
453     let b:VCSCommandOriginalBuffer = a:originalBuffer
454     let b:VCSCommandSourceFile = bufname(a:originalBuffer)
455     let b:VCSCommandVCSType = vcsType
457     set buftype=nofile
458     set noswapfile
459     let &filetype = vcsType . a:command
461     if a:statusText != ''
462       let b:VCSCommandStatusText = a:statusText
463     endif
465     if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
466       set bufhidden=delete
467     endif
468   finally
469     let s:isEditFileRunning -= 1
470   endtry
472 endfunction
474 " Function: s:SetupBuffer() {{{2
475 " Attempts to set the b:VCSCommandBufferInfo variable
477 function! s:SetupBuffer()
478   if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
479     " This buffer is already set up.
480     return
481   endif
483   if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
484     " No special status for special buffers other than directory buffers.
485     return
486   endif
488   if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
489     unlet! b:VCSCommandBufferSetup
490     return
491   endif
493   try
494     let vcsType = VCSCommandGetVCSType(bufnr('%'))
495     let b:VCSCommandBufferInfo =  s:plugins[vcsType].GetBufferInfo()
496     silent do VCSCommand User VCSBufferSetup
497   catch /No suitable plugin/
498     " This is not a VCS-controlled file.
499     let b:VCSCommandBufferInfo = []
500   endtry
502   let b:VCSCommandBufferSetup = 1
503 endfunction
505 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
506 " Resets the buffer setup state of the original buffer for a given VCS scratch
507 " buffer.
508 " Returns:  The VCS buffer number in a passthrough mode.
510 function! s:MarkOrigBufferForSetup(buffer)
511   checktime
512   if a:buffer > 0 
513     let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
514     " This should never not work, but I'm paranoid
515     if origBuffer != a:buffer
516       call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
517     endif
518   endif
519   return a:buffer
520 endfunction
522 " Function: s:OverrideOption(option, [value]) {{{2
523 " Provides a temporary override for the given VCS option.  If no value is
524 " passed, the override is disabled.
526 function! s:OverrideOption(option, ...)
527   if a:0 == 0
528     call remove(s:optionOverrides[a:option], -1)
529   else
530     if !has_key(s:optionOverrides, a:option)
531       let s:optionOverrides[a:option] = []
532     endif
533     call add(s:optionOverrides[a:option], a:1)
534   endif
535 endfunction
537 " Function: s:WipeoutCommandBuffers() {{{2
538 " Clears all current VCS output buffers of the specified type for a given source.
540 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
541   let buffer = 1
542   while buffer <= bufnr('$')
543     if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
544       if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
545         execute 'bw' buffer
546       endif
547     endif
548     let buffer = buffer + 1
549   endwhile
550 endfunction
552 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
553 " Checks whether the given buffer is one whose deletion should trigger
554 " restoration of an original buffer after it was diffed.  If so, it executes
555 " the appropriate setting command stored with that original buffer.
557 function! s:VimDiffRestore(vimDiffBuff)
558   let s:isEditFileRunning += 1
559   try
560     if exists('s:vimDiffSourceBuffer')
561       if a:vimDiffBuff == s:vimDiffSourceBuffer
562         " Original file is being removed.
563         unlet! s:vimDiffSourceBuffer
564         unlet! s:vimDiffRestoreCmd
565         unlet! s:vimDiffScratchList
566       else
567         let index = index(s:vimDiffScratchList, a:vimDiffBuff)
568         if index >= 0
569           call remove(s:vimDiffScratchList, index)
570           if len(s:vimDiffScratchList) == 0
571             if exists('s:vimDiffRestoreCmd')
572               " All scratch buffers are gone, reset the original.
573               " Only restore if the source buffer is still in Diff mode
575               let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
576               if sourceWinNR != -1
577                 " The buffer is visible in at least one window
578                 let currentWinNR = winnr()
579                 while winbufnr(sourceWinNR) != -1
580                   if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
581                     execute sourceWinNR . 'wincmd w'
582                     if getwinvar(0, '&diff')
583                       execute s:vimDiffRestoreCmd
584                     endif
585                   endif
586                   let sourceWinNR = sourceWinNR + 1
587                 endwhile
588                 execute currentWinNR . 'wincmd w'
589               else
590                 " The buffer is hidden.  It must be visible in order to set the
591                 " diff option.
592                 let currentBufNR = bufnr('')
593                 execute 'hide buffer' s:vimDiffSourceBuffer
594                 if getwinvar(0, '&diff')
595                   execute s:vimDiffRestoreCmd
596                 endif
597                 execute 'hide buffer' currentBufNR
598               endif
600               unlet s:vimDiffRestoreCmd
601             endif 
602             " All buffers are gone.
603             unlet s:vimDiffSourceBuffer
604             unlet s:vimDiffScratchList
605           endif
606         endif
607       endif
608     endif
609   finally
610     let s:isEditFileRunning -= 1
611   endtry
612 endfunction
614 " Section: Generic VCS command functions {{{1
616 " Function: s:VCSCommit() {{{2
617 function! s:VCSCommit(bang, message)
618   try
619     let vcsType = VCSCommandGetVCSType(bufnr('%'))
620     if !has_key(s:plugins, vcsType)
621       throw 'Unknown VCS type:  ' . vcsType
622     endif
624     let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
626     " Handle the commit message being specified.  If a message is supplied, it
627     " is used; if bang is supplied, an empty message is used; otherwise, the
628     " user is provided a buffer from which to edit the commit message.
630     if strlen(a:message) > 0 || a:bang == '!'
631       return s:VCSFinishCommit([a:message], originalBuffer)
632     endif
634     call s:EditFile('commitlog', originalBuffer, '')
635     set ft=vcscommit
637     " Create a commit mapping.
639     nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
641     silent 0put ='VCS: ----------------------------------------------------------------------'
642     silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
643     silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
645     if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
646       set buftype=acwrite
647       au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
648       silent put ='VCS: or write this buffer'
649     endif
651     silent put ='VCS: ----------------------------------------------------------------------'
652     $
653     set nomodified
654   catch
655     call s:ReportError(v:exception)
656     return -1
657   endtry
658 endfunction
660 " Function: s:VCSFinishCommitWithBuffer() {{{2
661 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
662 " which removes all lines starting with 'VCS:'.
664 function! s:VCSFinishCommitWithBuffer()
665   set nomodified
666   let currentBuffer = bufnr('%') 
667   let logMessageList = getbufline('%', 1, '$')
668   call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
669   let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
670   if resultBuffer >= 0
671     execute 'bw' currentBuffer
672   endif
673   return resultBuffer
674 endfunction
676 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
677 function! s:VCSFinishCommit(logMessageList, originalBuffer)
678   let shellSlashBak = &shellslash
679   try
680     set shellslash
681     let messageFileName = tempname()
682     call writefile(a:logMessageList, messageFileName)
683     try
684       let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
685       if resultBuffer < 0
686         return resultBuffer
687       endif
688       return s:MarkOrigBufferForSetup(resultBuffer)
689     finally
690       call delete(messageFileName)
691     endtry
692   finally
693     let &shellslash = shellSlashBak
694   endtry
695 endfunction
697 " Function: s:VCSGotoOriginal(bang) {{{2
698 function! s:VCSGotoOriginal(bang)
699   let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
700   if originalBuffer > 0
701     let origWinNR = bufwinnr(originalBuffer)
702     if origWinNR == -1
703       execute 'buffer' originalBuffer
704     else
705       execute origWinNR . 'wincmd w'
706     endif
707     if a:bang == '!'
708       let buffnr = 1
709       let buffmaxnr = bufnr('$')
710       while buffnr <= buffmaxnr
711         if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
712           execute 'bw' buffnr
713         endif
714         let buffnr = buffnr + 1
715       endwhile
716     endif
717   endif
718 endfunction
720 " Function: s:VCSVimDiff(...) {{{2
721 function! s:VCSVimDiff(...)
722   try
723     let vcsType = VCSCommandGetVCSType(bufnr('%'))
724     if !has_key(s:plugins, vcsType)
725       throw 'Unknown VCS type:  ' . vcsType
726     endif
727     let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
728     let s:isEditFileRunning = s:isEditFileRunning + 1
729     try
730       " If there's already a VimDiff'ed window, restore it.
731       " There may only be one VCSVimDiff original window at a time.
733       if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
734         " Clear the existing vimdiff setup by removing the result buffers.
735         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
736       endif
738       " Split and diff
739       if(a:0 == 2)
740         " Reset the vimdiff system, as 2 explicit versions were provided.
741         if exists('s:vimDiffSourceBuffer')
742           call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
743         endif
744         let resultBuffer = s:plugins[vcsType].Review([a:1])
745         if resultBuffer < 0
746           echomsg 'Can''t open revision ' . a:1
747           return resultBuffer
748         endif
749         let b:VCSCommandCommand = 'vimdiff'
750         diffthis
751         let s:vimDiffScratchList = [resultBuffer]
752         " If no split method is defined, cheat, and set it to vertical.
753         try
754           call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
755           let resultBuffer = s:plugins[vcsType].Review([a:2])
756         finally
757           call s:OverrideOption('VCSCommandSplit')
758         endtry
759         if resultBuffer < 0
760           echomsg 'Can''t open revision ' . a:1
761           return resultBuffer
762         endif
763         let b:VCSCommandCommand = 'vimdiff'
764         diffthis
765         let s:vimDiffScratchList += [resultBuffer]
766       else
767         " Add new buffer
768         call s:OverrideOption('VCSCommandEdit', 'split')
769         try
770           " Force splitting behavior, otherwise why use vimdiff?
771           call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
772           try
773             if(a:0 == 0)
774               let resultBuffer = s:plugins[vcsType].Review([])
775             else
776               let resultBuffer = s:plugins[vcsType].Review([a:1])
777             endif
778           finally
779             call s:OverrideOption('VCSCommandSplit')
780           endtry
781         finally
782           call s:OverrideOption('VCSCommandEdit')
783         endtry
784         if resultBuffer < 0
785           echomsg 'Can''t open current revision'
786           return resultBuffer
787         endif
788         let b:VCSCommandCommand = 'vimdiff'
789         diffthis
791         if !exists('s:vimDiffSourceBuffer')
792           " New instance of vimdiff.
793           let s:vimDiffScratchList = [resultBuffer]
795           " This could have been invoked on a VCS result buffer, not the
796           " original buffer.
797           wincmd W
798           execute 'buffer' originalBuffer
799           " Store info for later original buffer restore
800           let s:vimDiffRestoreCmd = 
801                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
802                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
803                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
804                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
805                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
806                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
807                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
808                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
809           diffthis
810           wincmd w
811         else
812           " Adding a window to an existing vimdiff
813           let s:vimDiffScratchList += [resultBuffer]
814         endif
815       endif
817       let s:vimDiffSourceBuffer = originalBuffer
819       " Avoid executing the modeline in the current buffer after the autocommand.
821       let currentBuffer = bufnr('%')
822       let saveModeline = getbufvar(currentBuffer, '&modeline')
823       try
824         call setbufvar(currentBuffer, '&modeline', 0)
825         silent do VCSCommand User VCSVimDiffFinish
826       finally
827         call setbufvar(currentBuffer, '&modeline', saveModeline)
828       endtry
829       return resultBuffer
830     finally
831       let s:isEditFileRunning = s:isEditFileRunning - 1
832     endtry
833   catch
834     call s:ReportError(v:exception)
835     return -1
836   endtry
837 endfunction
839 " Section: Public functions {{{1
841 " Function: VCSCommandGetVCSType() {{{2
842 " Sets the b:VCSCommandVCSType variable in the given buffer to the
843 " appropriate source control system name.
845 function! VCSCommandGetVCSType(buffer)
846   let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
847   if strlen(vcsType) > 0
848     return vcsType
849   endif
850   for vcsType in keys(s:plugins)
851     if s:plugins[vcsType].Identify(a:buffer)
852       call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
853       return vcsType
854     endif
855   endfor
856   throw 'No suitable plugin'
857 endfunction
859 " Function: VCSCommandChdir(directory) {{{2
860 " Changes the current directory, respecting :lcd changes.
862 function! VCSCommandChdir(directory)
863   let command = 'cd'
864   if exists("*haslocaldir") && haslocaldir()
865     let command = 'lcd'
866   endif
867   execute command escape(a:directory, ' ')
868 endfunction
870 " Function: VCSCommandChangeToCurrentFileDir() {{{2
871 " Go to the directory in which the given file is located.
873 function! VCSCommandChangeToCurrentFileDir(fileName)
874   let oldCwd = getcwd()
875   let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
876   if strlen(newCwd) > 0
877     call VCSCommandChdir(newCwd)
878   endif
879   return oldCwd
880 endfunction
882 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
883 " Attempts to locate the original file to which VCS operations were applied
884 " for a given buffer.
886 function! VCSCommandGetOriginalBuffer(vcsBuffer)
887   let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
888   if origBuffer
889     if bufexists(origBuffer)
890       return origBuffer
891     else
892       " Original buffer no longer exists.
893       throw 'Original buffer for this VCS buffer no longer exists.'
894     endif
895   else
896     " No original buffer
897     return a:vcsBuffer
898   endif
899 endfunction
901 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
902 " Allows VCS modules to register themselves.
904 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
905   let s:plugins[a:name] = a:commandMap
906   call add(s:pluginFiles, a:file)
907   let s:extendedMappings[a:name] = a:mappingMap
908   if !empty(a:mappingMap)
909         \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
910         \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
911     for mapname in keys(a:mappingMap)
912       execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
913     endfor
914   endif
915 endfunction
917 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
918 " General skeleton for VCS function execution.
919 " Returns: name of the new command buffer containing the command results
921 function! VCSCommandDoCommand(cmd, cmdName, statusText)
922   let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
923   if originalBuffer == -1 
924     throw 'Original buffer no longer exists, aborting.'
925   endif
927   let fileName = resolve(bufname(originalBuffer))
929   " Work with netrw or other systems where a directory listing is displayed in
930   " a buffer.
932   if isdirectory(fileName)
933     let realFileName = '.'
934   else
935     let realFileName = fnamemodify(fileName, ':t')
936   endif
938   " Change to the directory of the current buffer.  This is done for CVS, but
939   " is left in for other systems as it does not affect them negatively.
941   let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
942   try
943     let output = system(a:cmd . ' "' . realFileName . '"')
944   finally
945     call VCSCommandChdir(oldCwd)
946   endtry
948   " HACK:  if line endings in the repository have been corrupted, the output
949   " of the command will be confused.
950   let output = substitute(output, "\r", '', 'g')
952   " HACK:  CVS diff command does not return proper error codes
953   if v:shell_error && (a:cmdName != 'diff' || getbufvar(originalBuffer, 'VCSCommandVCSType') != 'CVS')
954     if strlen(output) == 0
955       throw 'Version control command failed'
956     else
957       let output = substitute(output, '\n', '  ', 'g')
958       throw 'Version control command failed:  ' . output
959     endif
960   endif
961   if strlen(output) == 0
962     " Handle case of no output.  In this case, it is important to check the
963     " file status, especially since cvs edit/unedit may change the attributes
964     " of the file with no visible output.
966     checktime
967     return 0
968   endif
970   call s:EditFile(a:cmdName, originalBuffer, a:statusText)
972   silent 0put=output
974   " The last command left a blank line at the end of the buffer.  If the
975   " last line is folded (a side effect of the 'put') then the attempt to
976   " remove the blank line will kill the last fold.
977   "
978   " This could be fixed by explicitly detecting whether the last line is
979   " within a fold, but I prefer to simply unfold the result buffer altogether.
981   if has('folding')
982     normal zR
983   endif
985   $d
986   1
988   " Define the environment and execute user-defined hooks.
990   silent do VCSCommand User VCSBufferCreated
991   return bufnr('%')
992 endfunction
994 " Function: VCSCommandGetOption(name, default) {{{2
995 " Grab a user-specified option to override the default provided.  Options are
996 " searched in the window, buffer, then global spaces.
998 function! VCSCommandGetOption(name, default)
999   if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1000     return s:optionOverrides[a:name][-1]
1001   elseif exists('w:' . a:name)
1002     return w:{a:name}
1003   elseif exists('b:' . a:name)
1004     return b:{a:name}
1005   elseif exists('g:' . a:name)
1006     return g:{a:name}
1007   else
1008     return a:default
1009   endif
1010 endfunction
1012 " Function: VCSCommandGetRevision() {{{2
1013 " Global function for retrieving the current buffer's revision number.
1014 " Returns: Revision number or an empty string if an error occurs.
1016 function! VCSCommandGetRevision()
1017   if !exists('b:VCSCommandBufferInfo')
1018     let b:VCSCommandBufferInfo =  s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1019   endif
1021   if len(b:VCSCommandBufferInfo) > 0
1022     return b:VCSCommandBufferInfo[0]
1023   else
1024     return ''
1025   endif
1026 endfunction
1028 " Function: VCSCommandDisableBufferSetup() {{{2
1029 " Global function for deactivating the buffer autovariables.
1031 function! VCSCommandDisableBufferSetup()
1032   let g:VCSCommandEnableBufferSetup = 0
1033   silent! augroup! VCSCommandPlugin
1034 endfunction
1036 " Function: VCSCommandEnableBufferSetup() {{{2
1037 " Global function for activating the buffer autovariables.
1039 function! VCSCommandEnableBufferSetup()
1040   let g:VCSCommandEnableBufferSetup = 1
1041   augroup VCSCommandPlugin
1042     au!
1043     au BufEnter * call s:SetupBuffer()
1044   augroup END
1046   " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1047   " chance to run.
1048   if g:loaded_VCSCommand == 2
1049     call s:SetupBuffer()
1050   endif
1051 endfunction
1053 " Function: VCSCommandGetStatusLine() {{{2
1054 " Default (sample) status line entry for VCS-controlled files.  This is only
1055 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1056 " variable for how to do this).
1058 function! VCSCommandGetStatusLine()
1059   if exists('b:VCSCommandCommand')
1060     " This is a result buffer.  Return nothing because the buffer name
1061     " contains information already.
1062     return ''
1063   endif
1065   if exists('b:VCSCommandVCSType')
1066         \ && exists('g:VCSCommandEnableBufferSetup')
1067         \ && g:VCSCommandEnableBufferSetup
1068         \ && exists('b:VCSCommandBufferInfo')
1069     return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1070   else
1071     return ''
1072   endif
1073 endfunction
1075 " Section: Command definitions {{{1
1076 " Section: Primary commands {{{2
1077 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1078 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1079 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1080 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1081 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1082 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1083 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1084 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1085 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1086 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1087 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1088 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1089 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1090 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1091 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1092 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1094 " Section: VCS buffer management commands {{{2
1095 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1096 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1098 " Allow reloading VCSCommand.vim
1099 com! VCSReload let savedPluginFiles = s:pluginFiles|aunmenu Plugin.VCS|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for file in savedPluginFiles|execute 'source' file|endfor
1101 " Section: Plugin command mappings {{{1
1102 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1103 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1104 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1105 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1106 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1107 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1108 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1109 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1110 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1111 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1112 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1113 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1114 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1115 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1116 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1117 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1119 " Section: Default mappings {{{1
1121 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1122   if !hasmapto('<Plug>VCSAdd')
1123     nmap <unique> <Leader>ca <Plug>VCSAdd
1124   endif
1125   if !hasmapto('<Plug>VCSAnnotate')
1126     nmap <unique> <Leader>cn <Plug>VCSAnnotate
1127   endif
1128   if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1129     nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1130   endif
1131   if !hasmapto('<Plug>VCSCommit')
1132     nmap <unique> <Leader>cc <Plug>VCSCommit
1133   endif
1134   if !hasmapto('<Plug>VCSDelete')
1135     nmap <unique> <Leader>cD <Plug>VCSDelete
1136   endif
1137   if !hasmapto('<Plug>VCSDiff')
1138     nmap <unique> <Leader>cd <Plug>VCSDiff
1139   endif
1140   if !hasmapto('<Plug>VCSGotoOriginal')
1141     nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1142   endif
1143   if !hasmapto('<Plug>VCSInfo')
1144     nmap <unique> <Leader>ci <Plug>VCSInfo
1145   endif
1146   if !hasmapto('<Plug>VCSLock')
1147     nmap <unique> <Leader>cL <Plug>VCSLock
1148   endif
1149   if !hasmapto('<Plug>VCSLog')
1150     nmap <unique> <Leader>cl <Plug>VCSLog
1151   endif
1152   if !hasmapto('<Plug>VCSRevert')
1153     nmap <unique> <Leader>cq <Plug>VCSRevert
1154   endif
1155   if !hasmapto('<Plug>VCSReview')
1156     nmap <unique> <Leader>cr <Plug>VCSReview
1157   endif
1158   if !hasmapto('<Plug>VCSStatus')
1159     nmap <unique> <Leader>cs <Plug>VCSStatus
1160   endif
1161   if !hasmapto('<Plug>VCSUnlock')
1162     nmap <unique> <Leader>cU <Plug>VCSUnlock
1163   endif
1164   if !hasmapto('<Plug>VCSUpdate')
1165     nmap <unique> <Leader>cu <Plug>VCSUpdate
1166   endif
1167   if !hasmapto('<Plug>VCSVimDiff')
1168     nmap <unique> <Leader>cv <Plug>VCSVimDiff
1169   endif
1170 endif
1172 " Section: Menu items {{{1
1173 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1174 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1175 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1176 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1177 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1178 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1179 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1180 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1181 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1182 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1183 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1184 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1186 " Section: Autocommands to restore vimdiff state {{{1
1187 augroup VimDiffRestore
1188   au!
1189   au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1190 augroup END
1192 " Section: Optional activation of buffer management {{{1
1194 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1195   call VCSCommandEnableBufferSetup()
1196 endif
1198 " Section: VIM shutdown hook {{{1
1200 " Close all result buffers when VIM exits, to prevent them from being restored
1201 " via viminfo.
1203 " Function: s:CloseAllResultBuffers() {{{2
1204 " Closes all vcscommand result buffers.
1205 function! s:CloseAllResultBuffers()
1206   " This avoids using bufdo as that may load buffers already loaded in another
1207   " vim process, resulting in an error.
1208   let buffnr = 1
1209   let buffmaxnr = bufnr('$')
1210   while buffnr <= buffmaxnr
1211     if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != "" 
1212       execute 'bw' buffnr
1213     endif
1214     let buffnr = buffnr + 1
1215   endwhile
1216 endfunction
1218 augroup VCSCommandVIMShutdown
1219   au!
1220   au VimLeavePre * call s:CloseAllResultBuffers()
1221 augroup END
1223 " Section: Plugin completion {{{1
1225 let loaded_VCSCommand = 2
1227 silent do VCSCommand User VCSPluginFinish
1229 let &cpo = s:save_cpo