Removed trailing white space in source.
[vcscommand.git] / plugin / vcscommand.vim
blob98973bdca177da5feea213ee1c977347f1e4a309
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 "                  If '!' is used, the view of the annotated buffer is split
55 "                  so that the annotation is in a separate window from the
56 "                  content, and each is highlighted separately.
58 " VCSBlame         Alias for 'VCSAnnotate'.
60 " VCSCommit[!]     Commits changes to the current file to source control.
62 "                  If called with arguments, the arguments are the log message.
64 "                  If '!' is used, an empty log message is committed.
66 "                  If called with no arguments, this is a two-step command.
67 "                  The first step opens a buffer to accept a log message.
68 "                  When that buffer is written, it is automatically closed and
69 "                  the file is committed using the information from that log
70 "                  message.  The commit can be abandoned if the log message
71 "                  buffer is deleted or wiped before being written.
73 " VCSDelete        Deletes the current file and removes it from source control.
75 " VCSDiff          With no arguments, this displays the differences between
76 "                  the current file and its parent version under source
77 "                  control in a new scratch buffer.
79 "                  With one argument, the diff is performed on the
80 "                  current file against the specified revision.
82 "                  With two arguments, the diff is performed between the
83 "                  specified revisions of the current file.
85 "                  This command uses the 'VCSCommand{VCSType}DiffOpt' variable
86 "                  to specify diff options.  If that variable does not exist,
87 "                  a plugin-specific default is used.  If you wish to have no
88 "                  options, then set it to the empty string.
90 " VCSGotoOriginal  Jumps to the source buffer if the current buffer is a VCS
91 "                  scratch buffer.  If VCSGotoOriginal[!] is used, remove all
92 "                  VCS scratch buffers associated with the original file.
94 " VCSInfo          Displays extended information about the current file in a
95 "                  new scratch buffer.
97 " VCSLock          Locks the current file in order to prevent other users from
98 "                  concurrently modifying it.  The exact semantics of this
99 "                  command depend on the underlying VCS.
101 " VCSLog           Displays the version history of the current file in a new
102 "                  scratch buffer.
104 " VCSRemove        Alias for 'VCSDelete'.
106 " VCSRevert        Replaces the modified version of the current file with the
107 "                  most recent version from the repository.
109 " VCSReview        Displays a particular version of the current file in a new
110 "                  scratch buffer.  If no argument is given, the most recent
111 "                  version of the file on the current branch is retrieved.
113 " VCSStatus        Displays versioning information about the current file in a
114 "                  new scratch buffer.
116 " VCSUnlock        Unlocks the current file in order to allow other users from
117 "                  concurrently modifying it.  The exact semantics of this
118 "                  command depend on the underlying VCS.
120 " VCSUpdate        Updates the current file with any relevant changes from the
121 "                  repository.
123 " VCSVimDiff       Uses vimdiff to display differences between versions of the
124 "                  current file.
126 "                  If no revision is specified, the most recent version of the
127 "                  file on the current branch is used.  With one argument,
128 "                  that argument is used as the revision as above.  With two
129 "                  arguments, the differences between the two revisions is
130 "                  displayed using vimdiff.
132 "                  With either zero or one argument, the original buffer is
133 "                  used to perform the vimdiff.  When the scratch buffer is
134 "                  closed, the original buffer will be returned to normal
135 "                  mode.
137 "                  Once vimdiff mode is started using the above methods,
138 "                  additional vimdiff buffers may be added by passing a single
139 "                  version argument to the command.  There may be up to 4
140 "                  vimdiff buffers total.
142 "                  Using the 2-argument form of the command resets the vimdiff
143 "                  to only those 2 versions.  Additionally, invoking the
144 "                  command on a different file will close the previous vimdiff
145 "                  buffers.
147 " Mapping documentation: {{{2
149 " By default, a mapping is defined for each command.  User-provided mappings
150 " can be used instead by mapping to <Plug>CommandName, for instance:
152 " nmap ,ca <Plug>VCSAdd
154 " The default mappings are as follow:
156 "   <Leader>ca VCSAdd
157 "   <Leader>cn VCSAnnotate
158 "   <Leader>cN VCSAnnotate!
159 "   <Leader>cc VCSCommit
160 "   <Leader>cD VCSDelete
161 "   <Leader>cd VCSDiff
162 "   <Leader>cg VCSGotoOriginal
163 "   <Leader>cG VCSGotoOriginal!
164 "   <Leader>ci VCSInfo
165 "   <Leader>cl VCSLog
166 "   <Leader>cL VCSLock
167 "   <Leader>cr VCSReview
168 "   <Leader>cs VCSStatus
169 "   <Leader>cu VCSUpdate
170 "   <Leader>cU VCSUnlock
171 "   <Leader>cv VCSVimDiff
173 " Options documentation: {{{2
175 " Several variables are checked by the script to determine behavior as follow:
177 " VCSCommandCommitOnWrite
178 "   This variable, if set to a non-zero value, causes the pending commit to
179 "   take place immediately as soon as the log message buffer is written.  If
180 "   set to zero, only the VCSCommit mapping will cause the pending commit to
181 "   occur.  If not set, it defaults to 1.
183 " VCSCommandDeleteOnHide
184 "   This variable, if set to a non-zero value, causes the temporary VCS result
185 "   buffers to automatically delete themselves when hidden.
187 " VCSCommand{VCSType}DiffOpt
188 "   This variable, if set, determines the options passed to the diff command
189 "   of the underlying VCS.  Each VCS plugin defines a default value.
191 " VCSCommandDiffSplit
192 "   This variable overrides the VCSCommandSplit variable, but only for buffers
193 "   created with VCSVimDiff.
195 " VCSCommandDisableAll
196 "   This variable, if set, prevents the plugin or any extensions from loading
197 "   at all.  This is useful when a single runtime distribution is used on
198 "   multiple systems with varying versions.
200 " VCSCommandDisableMappings
201 "   This variable, if set to a non-zero value, prevents the default command
202 "   mappings from being set.
204 " VCSCommandDisableExtensionMappings
205 "   This variable, if set to a non-zero value, prevents the default command
206 "   mappings from being set for commands specific to an individual VCS.
208 " VCSCommandEdit
209 "   This variable controls whether to split the current window to display a
210 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
211 "   If not set, it defaults to 'split'.
213 " VCSCommandEnableBufferSetup
214 "   This variable, if set to a non-zero value, activates VCS buffer management
215 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
216 "   the file is VCS-controlled.  This is useful for displaying version
217 "   information in the status bar.  Additional options may be set by
218 "   individual VCS plugins.
220 " VCSCommandMappings
221 "   This variable, if set, overrides the default mappings used for shortcuts.
222 "   It should be a List of 2-element Lists, each containing a shortcut and
223 "   function name pair.
225 " VCSCommandMapPrefix
226 "   This variable, if set, overrides the default mapping prefix ('<Leader>c').
227 "   This allows customization of the mapping space used by the vcscommand
228 "   shortcuts.
230 " VCSCommandResultBufferNameExtension
231 "   This variable, if set to a non-blank value, is appended to the name of the
232 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
233 "   help avoid problems caused by autocommands dependent on file extension.
235 " VCSCommandResultBufferNameFunction
236 "   This variable, if set, specifies a custom function for naming VCS command
237 "   output buffers.  This function will be passed the following arguments:
239 "   command - name of the VCS command being executed (such as 'Log' or
240 "   'Diff').
242 "   originalBuffer - buffer number of the source file.
244 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
246 "   statusText - extra text associated with the VCS action (such as version
247 "   numbers).
249 " VCSCommandSplit
250 "   This variable controls the orientation of the various window splits that
251 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
252 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
253 "   If set to 'horizontal', the resulting windows will be on stacked on top of
254 "   one another.  If set to 'vertical', the resulting windows will be
255 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
256 "   VCSVimDiff windows.
258 " VCSCommandVCSTypeOverride
259 "   This variable allows the VCS type detection to be overridden on a
260 "   path-by-path basis.  The value of this variable is expected to be a List
261 "   of Lists.  Each high-level List item is a List containing two elements.
262 "   The first element is a regular expression that will be matched against the
263 "   full file name of a given buffer.  If it matches, the second element will
264 "   be used as the VCS type.
266 " Event documentation {{{2
267 "   For additional customization, VCSCommand.vim uses User event autocommand
268 "   hooks.  Each event is in the VCSCommand group, and different patterns
269 "   match the various hooks.
271 "   For instance, the following could be added to the vimrc to provide a 'q'
272 "   mapping to quit a VCS scratch buffer:
274 "   augroup VCSCommand
275 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
276 "   augroup END
278 "   The following hooks are available:
280 "   VCSBufferCreated           This event is fired just after a VCS command
281 "                              output buffer is created.  It is executed
282 "                              within the context of the new buffer.
284 "   VCSBufferSetup             This event is fired just after VCS buffer setup
285 "                              occurs, if enabled.
287 "   VCSPluginInit              This event is fired when the VCSCommand plugin
288 "                              first loads.
290 "   VCSPluginFinish            This event is fired just after the VCSCommand
291 "                              plugin loads.
293 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
294 "                              command executes to allow customization of,
295 "                              for instance, window placement and focus.
297 " Section: Plugin header {{{1
299 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
300 " completes.  This allows various actions to only be taken by functions after
301 " system initialization.
303 if exists('VCSCommandDisableAll')
304         finish
305 endif
307 if exists('loaded_VCSCommand')
308         finish
309 endif
310 let loaded_VCSCommand = 1
312 if v:version < 700
313         echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
314         finish
315 endif
317 let s:save_cpo=&cpo
318 set cpo&vim
320 " Section: Event group setup {{{1
322 augroup VCSCommand
323 augroup END
325 augroup VCSCommandCommit
326 augroup END
328 " Section: Plugin initialization {{{1
329 silent do VCSCommand User VCSPluginInit
331 " Section: Constants declaration {{{1
333 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
334 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
336 " Section: Script variable initialization {{{1
338 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
339 let s:plugins = {}
341 " temporary values of overridden configuration variables
342 let s:optionOverrides = {}
344 " state flag used to vary behavior of certain automated actions
345 let s:isEditFileRunning = 0
347 " commands needed to restore diff buffers to their original state
348 unlet! s:vimDiffRestoreCmd
350 " original buffer currently reflected in vimdiff windows
351 unlet! s:vimDiffSourceBuffer
354 unlet! s:vimDiffScratchList
356 " Section: Utility functions {{{1
358 " Function: s:ReportError(mapping) {{{2
359 " Displays the given error in a consistent faction.  This is intended to be
360 " invoked from a catch statement.
362 function! s:ReportError(error)
363         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
364 endfunction
367 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
368 " Creates the given mapping by prepending the contents of
369 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
370 " mapping it to the given plugin function.  If a mapping exists for the
371 " specified shortcut + prefix, emit an error but continue.  If a mapping
372 " exists for the specified function, do nothing.
374 function! s:CreateMapping(shortcut, expansion, display)
375         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
376         if !hasmapto(a:expansion)
377                 try
378                         execute 'nmap <silent> <unique>' lhs a:expansion
379                 catch /^Vim(.*):E227:/
380                         if(&verbose != 0)
381                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
382                         endif
383                 endtry
384         endif
385 endfunction
387 " Function: s:ExecuteExtensionMapping(mapping) {{{2
388 " Invokes the appropriate extension mapping depending on the type of the
389 " current buffer.
391 function! s:ExecuteExtensionMapping(mapping)
392         let buffer = bufnr('%')
393         let vcsType = VCSCommandGetVCSType(buffer)
394         if !has_key(s:plugins, vcsType)
395                 throw 'Unknown VCS type:  ' . vcsType
396         endif
397         if !has_key(s:plugins[vcsType][2], a:mapping)
398                 throw 'This extended mapping is not defined for ' . vcsType
399         endif
400         silent execute 'normal' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
401 endfunction
403 " Function: s:ExecuteVCSCommand(command, argList) {{{2
404 " Calls the indicated plugin-specific VCS command on the current buffer.
405 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
406 " occurs.
408 function! s:ExecuteVCSCommand(command, argList)
409         try
410                 let buffer = bufnr('%')
412                 let vcsType = VCSCommandGetVCSType(buffer)
413                 if !has_key(s:plugins, vcsType)
414                         throw 'Unknown VCS type:  ' . vcsType
415                 endif
417                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
418                 let bufferName = bufname(originalBuffer)
420                 " It is already known that the directory is under VCS control.  No further
421                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
422                 " VCS-specific error messages from confusing things.
423                 if !isdirectory(bufferName)
424                         if !filereadable(bufferName)
425                                 throw 'No such file ' . bufferName
426                         endif
427                 endif
429                 let functionMap = s:plugins[vcsType][1]
430                 if !has_key(functionMap, a:command)
431                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
432                 endif
433                 return functionMap[a:command](a:argList)
434         catch
435                 call s:ReportError(v:exception)
436                 return -1
437         endtry
438 endfunction
440 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
441 " Default method of generating the name for VCS result buffers.  This can be
442 " overridden with the VCSResultBufferNameFunction variable.
444 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
445         let fileName = bufname(a:originalBuffer)
446         let bufferName = a:vcsType . ' ' . a:command
447         if strlen(a:statusText) > 0
448                 let bufferName .= ' ' . a:statusText
449         endif
450         let bufferName .= ' ' . fileName
451         let counter = 0
452         let versionedBufferName = bufferName
453         while buflisted(versionedBufferName)
454                 let counter += 1
455                 let versionedBufferName = bufferName . ' (' . counter . ')'
456         endwhile
457         return versionedBufferName
458 endfunction
460 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
461 " Method of generating the name for VCS result buffers that uses the original
462 " file name with the VCS type and command appended as extensions.
464 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
465         let fileName = bufname(a:originalBuffer)
466         let bufferName = a:vcsType . ' ' . a:command
467         if strlen(a:statusText) > 0
468                 let bufferName .= ' ' . a:statusText
469         endif
470         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
471         let counter = 0
472         let versionedBufferName = bufferName
473         while buflisted(versionedBufferName)
474                 let counter += 1
475                 let versionedBufferName = '(' . counter . ') ' . bufferName
476         endwhile
477         return versionedBufferName
478 endfunction
480 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
481 " Creates a new buffer of the given name and associates it with the given
482 " original buffer.
484 function! s:EditFile(command, originalBuffer, statusText)
485         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
487         " Protect against useless buffer set-up
488         let s:isEditFileRunning += 1
489         try
490                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
491                 if editCommand == 'split'
492                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
493                                 rightbelow split
494                         else
495                                 vert rightbelow split
496                         endif
497                 endif
499                 enew
501                 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
503         finally
504                 let s:isEditFileRunning -= 1
505         endtry
506 endfunction
508 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
509 " Creates convenience buffer variables and the name of a vcscommand result
510 " buffer.
512 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
513         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
514         if nameExtension == ''
515                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
516         else
517                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
518         endif
520         let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
522         let b:VCSCommandCommand = a:command
523         let b:VCSCommandOriginalBuffer = a:originalBuffer
524         let b:VCSCommandSourceFile = bufname(a:originalBuffer)
525         let b:VCSCommandVCSType = a:vcsType
526         if a:statusText != ''
527                 let b:VCSCommandStatusText = a:statusText
528         endif
530         setlocal buftype=nofile
531         setlocal noswapfile
532         let &filetype = a:vcsType . a:command
534         if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
535                 setlocal bufhidden=delete
536         endif
537         silent noautocmd file `=name`
538 endfunction
540 " Function: s:SetupBuffer() {{{2
541 " Attempts to set the b:VCSCommandBufferInfo variable
543 function! s:SetupBuffer()
544         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
545                 " This buffer is already set up.
546                 return
547         endif
549         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
550                 " No special status for special buffers other than directory buffers.
551                 return
552         endif
554         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
555                 unlet! b:VCSCommandBufferSetup
556                 return
557         endif
559         try
560                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
561                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
562                 silent do VCSCommand User VCSBufferSetup
563         catch /No suitable plugin/
564                 " This is not a VCS-controlled file.
565                 let b:VCSCommandBufferInfo = []
566         endtry
568         let b:VCSCommandBufferSetup = 1
569 endfunction
571 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
572 " Resets the buffer setup state of the original buffer for a given VCS scratch
573 " buffer.
574 " Returns:  The VCS buffer number in a passthrough mode.
576 function! s:MarkOrigBufferForSetup(buffer)
577         checktime
578         if a:buffer > 0
579                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
580                 " This should never not work, but I'm paranoid
581                 if origBuffer != a:buffer
582                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
583                 endif
584         endif
585         return a:buffer
586 endfunction
588 " Function: s:OverrideOption(option, [value]) {{{2
589 " Provides a temporary override for the given VCS option.  If no value is
590 " passed, the override is disabled.
592 function! s:OverrideOption(option, ...)
593         if a:0 == 0
594                 call remove(s:optionOverrides[a:option], -1)
595         else
596                 if !has_key(s:optionOverrides, a:option)
597                         let s:optionOverrides[a:option] = []
598                 endif
599                 call add(s:optionOverrides[a:option], a:1)
600         endif
601 endfunction
603 " Function: s:WipeoutCommandBuffers() {{{2
604 " Clears all current VCS output buffers of the specified type for a given source.
606 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
607         let buffer = 1
608         while buffer <= bufnr('$')
609                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
610                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
611                                 execute 'bw' buffer
612                         endif
613                 endif
614                 let buffer = buffer + 1
615         endwhile
616 endfunction
618 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
619 " Checks whether the given buffer is one whose deletion should trigger
620 " restoration of an original buffer after it was diffed.  If so, it executes
621 " the appropriate setting command stored with that original buffer.
623 function! s:VimDiffRestore(vimDiffBuff)
624         let s:isEditFileRunning += 1
625         try
626                 if exists('s:vimDiffSourceBuffer')
627                         if a:vimDiffBuff == s:vimDiffSourceBuffer
628                                 " Original file is being removed.
629                                 unlet! s:vimDiffSourceBuffer
630                                 unlet! s:vimDiffRestoreCmd
631                                 unlet! s:vimDiffScratchList
632                         else
633                                 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
634                                 if index >= 0
635                                         call remove(s:vimDiffScratchList, index)
636                                         if len(s:vimDiffScratchList) == 0
637                                                 if exists('s:vimDiffRestoreCmd')
638                                                         " All scratch buffers are gone, reset the original.
639                                                         " Only restore if the source buffer is still in Diff mode
641                                                         let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
642                                                         if sourceWinNR != -1
643                                                                 " The buffer is visible in at least one window
644                                                                 let currentWinNR = winnr()
645                                                                 while winbufnr(sourceWinNR) != -1
646                                                                         if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
647                                                                                 execute sourceWinNR . 'wincmd w'
648                                                                                 if getwinvar(0, '&diff')
649                                                                                         execute s:vimDiffRestoreCmd
650                                                                                 endif
651                                                                         endif
652                                                                         let sourceWinNR = sourceWinNR + 1
653                                                                 endwhile
654                                                                 execute currentWinNR . 'wincmd w'
655                                                         else
656                                                                 " The buffer is hidden.  It must be visible in order to set the
657                                                                 " diff option.
658                                                                 let currentBufNR = bufnr('')
659                                                                 execute 'hide buffer' s:vimDiffSourceBuffer
660                                                                 if getwinvar(0, '&diff')
661                                                                         execute s:vimDiffRestoreCmd
662                                                                 endif
663                                                                 execute 'hide buffer' currentBufNR
664                                                         endif
666                                                         unlet s:vimDiffRestoreCmd
667                                                 endif
668                                                 " All buffers are gone.
669                                                 unlet s:vimDiffSourceBuffer
670                                                 unlet s:vimDiffScratchList
671                                         endif
672                                 endif
673                         endif
674                 endif
675         finally
676                 let s:isEditFileRunning -= 1
677         endtry
678 endfunction
680 " Section: Generic VCS command functions {{{1
682 " Function: s:VCSAnnotate(...) {{{2
683 function! s:VCSAnnotate(bang, ...)
684         try
685                 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
686                 if annotateBuffer == -1
687                         return -1
688                 endif
689                 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
690                         let vcsType = VCSCommandGetVCSType(annotateBuffer)
691                         let functionMap = s:plugins[vcsType][1]
692                         let splitRegex = ''
693                         if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
694                                 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
695                         endif
696                         let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
697                         if splitRegex == ''
698                                 return annotateBuffer
699                         endif
700                         let originalBuffer = VCSCommandGetOriginalBuffer(annotateBuffer)
701                         let originalFileType = getbufvar(originalBuffer, '&ft')
702                         let annotateFileType = getbufvar(annotateBuffer, '&ft')
703                         execute "normal 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
704                         call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
705                         set scrollbind
706                         leftabove vert new
707                         normal 0P
708                         execute "normal" . col('$') . "\<c-w>|"
709                         call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
710                         wincmd l
711                 endif
712                 return annotateBuffer
713         catch
714                 call s:ReportError(v:exception)
715                 return -1
716         endtry
717 endfunction
719 " Function: s:VCSCommit() {{{2
720 function! s:VCSCommit(bang, message)
721         try
722                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
723                 if !has_key(s:plugins, vcsType)
724                         throw 'Unknown VCS type:  ' . vcsType
725                 endif
727                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
729                 " Handle the commit message being specified.  If a message is supplied, it
730                 " is used; if bang is supplied, an empty message is used; otherwise, the
731                 " user is provided a buffer from which to edit the commit message.
733                 if strlen(a:message) > 0 || a:bang == '!'
734                         return s:VCSFinishCommit([a:message], originalBuffer)
735                 endif
737                 call s:EditFile('commitlog', originalBuffer, '')
738                 setlocal ft=vcscommit
740                 " Create a commit mapping.
742                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
744                 silent 0put ='VCS: ----------------------------------------------------------------------'
745                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
746                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
748                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
749                         setlocal buftype=acwrite
750                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
751                         silent put ='VCS: or write this buffer'
752                 endif
754                 silent put ='VCS: ----------------------------------------------------------------------'
755                 $
756                 setlocal nomodified
757         catch
758                 call s:ReportError(v:exception)
759                 return -1
760         endtry
761 endfunction
763 " Function: s:VCSFinishCommitWithBuffer() {{{2
764 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
765 " which removes all lines starting with 'VCS:'.
767 function! s:VCSFinishCommitWithBuffer()
768         setlocal nomodified
769         let currentBuffer = bufnr('%')
770         let logMessageList = getbufline('%', 1, '$')
771         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
772         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
773         if resultBuffer >= 0
774                 execute 'bw' currentBuffer
775         endif
776         return resultBuffer
777 endfunction
779 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
780 function! s:VCSFinishCommit(logMessageList, originalBuffer)
781         let shellSlashBak = &shellslash
782         try
783                 set shellslash
784                 let messageFileName = tempname()
785                 call writefile(a:logMessageList, messageFileName)
786                 try
787                         let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
788                         if resultBuffer < 0
789                                 return resultBuffer
790                         endif
791                         return s:MarkOrigBufferForSetup(resultBuffer)
792                 finally
793                         call delete(messageFileName)
794                 endtry
795         finally
796                 let &shellslash = shellSlashBak
797         endtry
798 endfunction
800 " Function: s:VCSGotoOriginal(bang) {{{2
801 function! s:VCSGotoOriginal(bang)
802         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
803         if originalBuffer > 0
804                 let origWinNR = bufwinnr(originalBuffer)
805                 if origWinNR == -1
806                         execute 'buffer' originalBuffer
807                 else
808                         execute origWinNR . 'wincmd w'
809                 endif
810                 if a:bang == '!'
811                         let buffnr = 1
812                         let buffmaxnr = bufnr('$')
813                         while buffnr <= buffmaxnr
814                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
815                                         execute 'bw' buffnr
816                                 endif
817                                 let buffnr = buffnr + 1
818                         endwhile
819                 endif
820         endif
821 endfunction
823 " Function: s:VCSVimDiff(...) {{{2
824 function! s:VCSVimDiff(...)
825         try
826                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
827                 if !has_key(s:plugins, vcsType)
828                         throw 'Unknown VCS type:  ' . vcsType
829                 endif
830                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
831                 let s:isEditFileRunning = s:isEditFileRunning + 1
832                 try
833                         " If there's already a VimDiff'ed window, restore it.
834                         " There may only be one VCSVimDiff original window at a time.
836                         if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
837                                 " Clear the existing vimdiff setup by removing the result buffers.
838                                 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
839                         endif
841                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
842                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
843                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
845                         " Split and diff
846                         if(a:0 == 2)
847                                 " Reset the vimdiff system, as 2 explicit versions were provided.
848                                 if exists('s:vimDiffSourceBuffer')
849                                         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
850                                 endif
851                                 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
852                                 if resultBuffer < 0
853                                         echomsg 'Can''t open revision ' . a:1
854                                         return resultBuffer
855                                 endif
856                                 let b:VCSCommandCommand = 'vimdiff'
857                                 diffthis
858                                 let s:vimDiffScratchList = [resultBuffer]
859                                 " If no split method is defined, cheat, and set it to vertical.
860                                 try
861                                         call s:OverrideOption('VCSCommandSplit', orientation)
862                                         let resultBuffer = s:plugins[vcsType][1].Review([a:2])
863                                 finally
864                                         call s:OverrideOption('VCSCommandSplit')
865                                 endtry
866                                 if resultBuffer < 0
867                                         echomsg 'Can''t open revision ' . a:1
868                                         return resultBuffer
869                                 endif
870                                 let b:VCSCommandCommand = 'vimdiff'
871                                 diffthis
872                                 let s:vimDiffScratchList += [resultBuffer]
873                         else
874                                 " Add new buffer
875                                 call s:OverrideOption('VCSCommandEdit', 'split')
876                                 try
877                                         " Force splitting behavior, otherwise why use vimdiff?
878                                         call s:OverrideOption('VCSCommandSplit', orientation)
879                                         try
880                                                 if(a:0 == 0)
881                                                         let resultBuffer = s:plugins[vcsType][1].Review([])
882                                                 else
883                                                         let resultBuffer = s:plugins[vcsType][1].Review([a:1])
884                                                 endif
885                                         finally
886                                                 call s:OverrideOption('VCSCommandSplit')
887                                         endtry
888                                 finally
889                                         call s:OverrideOption('VCSCommandEdit')
890                                 endtry
891                                 if resultBuffer < 0
892                                         echomsg 'Can''t open current revision'
893                                         return resultBuffer
894                                 endif
895                                 let b:VCSCommandCommand = 'vimdiff'
896                                 diffthis
898                                 if !exists('s:vimDiffSourceBuffer')
899                                         " New instance of vimdiff.
900                                         let s:vimDiffScratchList = [resultBuffer]
902                                         " This could have been invoked on a VCS result buffer, not the
903                                         " original buffer.
904                                         wincmd W
905                                         execute 'buffer' originalBuffer
906                                         " Store info for later original buffer restore
907                                         let s:vimDiffRestoreCmd =
908                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
909                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
910                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
911                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
912                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
913                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
914                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
915                                                                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
916                                         diffthis
917                                         wincmd w
918                                 else
919                                         " Adding a window to an existing vimdiff
920                                         let s:vimDiffScratchList += [resultBuffer]
921                                 endif
922                         endif
924                         let s:vimDiffSourceBuffer = originalBuffer
926                         " Avoid executing the modeline in the current buffer after the autocommand.
928                         let currentBuffer = bufnr('%')
929                         let saveModeline = getbufvar(currentBuffer, '&modeline')
930                         try
931                                 call setbufvar(currentBuffer, '&modeline', 0)
932                                 silent do VCSCommand User VCSVimDiffFinish
933                         finally
934                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
935                         endtry
936                         return resultBuffer
937                 finally
938                         let s:isEditFileRunning = s:isEditFileRunning - 1
939                 endtry
940         catch
941                 call s:ReportError(v:exception)
942                 return -1
943         endtry
944 endfunction
946 " Section: Public functions {{{1
948 " Function: VCSCommandGetVCSType() {{{2
949 " Sets the b:VCSCommandVCSType variable in the given buffer to the
950 " appropriate source control system name.
952 " This uses the Identify extension function to test the buffer.  If the
953 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
954 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
955 " match is considered inexact, and is only applied if no exact match is found.
956 " Multiple inexact matches is currently considered an error.
958 function! VCSCommandGetVCSType(buffer)
959         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
960         if strlen(vcsType) > 0
961                 return vcsType
962         endif
963         if exists("g:VCSCommandVCSTypeOverride")
964                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
965                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
966                         if match(fullpath, path) > -1
967                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
968                                 return vcsType
969                         endif
970                 endfor
971         endif
972         let matches = []
973         for vcsType in keys(s:plugins)
974                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
975                 if identified
976                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
977                                 let matches = [vcsType]
978                                 break
979                         else
980                                 let matches += [vcsType]
981                         endif
982                 endif
983         endfor
984         if len(matches) == 1
985                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
986                 return matches[0]
987         elseif len(matches) == 0
988                 throw 'No suitable plugin'
989         else
990                 throw 'Too many matching VCS:  ' . join(matches)
991         endif
992 endfunction
994 " Function: VCSCommandChdir(directory) {{{2
995 " Changes the current directory, respecting :lcd changes.
997 function! VCSCommandChdir(directory)
998         let command = 'cd'
999         if exists("*haslocaldir") && haslocaldir()
1000                 let command = 'lcd'
1001         endif
1002         execute command escape(a:directory, ' ')
1003 endfunction
1005 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1006 " Go to the directory in which the given file is located.
1008 function! VCSCommandChangeToCurrentFileDir(fileName)
1009         let oldCwd = getcwd()
1010         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1011         if strlen(newCwd) > 0
1012                 call VCSCommandChdir(newCwd)
1013         endif
1014         return oldCwd
1015 endfunction
1017 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1018 " Attempts to locate the original file to which VCS operations were applied
1019 " for a given buffer.
1021 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1022         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1023         if origBuffer
1024                 if bufexists(origBuffer)
1025                         return origBuffer
1026                 else
1027                         " Original buffer no longer exists.
1028                         throw 'Original buffer for this VCS buffer no longer exists.'
1029                 endif
1030         else
1031                 " No original buffer
1032                 return a:vcsBuffer
1033         endif
1034 endfunction
1036 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1037 " Allows VCS modules to register themselves.
1039 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1040         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1041         if !empty(a:mappingMap)
1042                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1043                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1044                 for shortcut in keys(a:mappingMap)
1045                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1046                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1047                 endfor
1048         endif
1049 endfunction
1051 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1052 " General skeleton for VCS function execution.  The given command is executed
1053 " after appending the current buffer name (or substituting it for
1054 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1055 " new buffer.
1057 " The optional 'options' Dictionary may contain the following options:
1058 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1059 "               non-zero exit status, the command is still considered
1060 "               successfuly.  This defaults to zero.
1061 " Returns: name of the new command buffer containing the command results
1063 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1064         let allowNonZeroExit = 0
1065         if has_key(a:options, 'allowNonZeroExit')
1066                 let allowNonZeroExit = a:options.allowNonZeroExit
1067         endif
1069         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1070         if originalBuffer == -1
1071                 throw 'Original buffer no longer exists, aborting.'
1072         endif
1074         let path = resolve(bufname(originalBuffer))
1076         " Work with netrw or other systems where a directory listing is displayed in
1077         " a buffer.
1079         if isdirectory(path)
1080                 let fileName = '.'
1081         else
1082                 let fileName = fnamemodify(path, ':t')
1083         endif
1085         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1086                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1087         else
1088                 let fullCmd = a:cmd . ' "' . fileName . '"'
1089         endif
1091         " Change to the directory of the current buffer.  This is done for CVS, but
1092         " is left in for other systems as it does not affect them negatively.
1094         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1095         try
1096                 let output = system(fullCmd)
1097         finally
1098                 call VCSCommandChdir(oldCwd)
1099         endtry
1101         " HACK:  if line endings in the repository have been corrupted, the output
1102         " of the command will be confused.
1103         let output = substitute(output, "\r", '', 'g')
1105         if v:shell_error && !allowNonZeroExit
1106                 if strlen(output) == 0
1107                         throw 'Version control command failed'
1108                 else
1109                         let output = substitute(output, '\n', '  ', 'g')
1110                         throw 'Version control command failed:  ' . output
1111                 endif
1112         endif
1114         if strlen(output) == 0
1115                 " Handle case of no output.  In this case, it is important to check the
1116                 " file status, especially since cvs edit/unedit may change the attributes
1117                 " of the file with no visible output.
1119                 checktime
1120                 return 0
1121         endif
1123         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1125         silent 0put=output
1127         " The last command left a blank line at the end of the buffer.  If the
1128         " last line is folded (a side effect of the 'put') then the attempt to
1129         " remove the blank line will kill the last fold.
1130         "
1131         " This could be fixed by explicitly detecting whether the last line is
1132         " within a fold, but I prefer to simply unfold the result buffer altogether.
1134         if has('folding')
1135                 normal zR
1136         endif
1138         $d
1139         1
1141         " Define the environment and execute user-defined hooks.
1143         silent do VCSCommand User VCSBufferCreated
1144         return bufnr('%')
1145 endfunction
1147 " Function: VCSCommandGetOption(name, default) {{{2
1148 " Grab a user-specified option to override the default provided.  Options are
1149 " searched in the window, buffer, then global spaces.
1151 function! VCSCommandGetOption(name, default)
1152         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1153                 return s:optionOverrides[a:name][-1]
1154         elseif exists('w:' . a:name)
1155                 return w:{a:name}
1156         elseif exists('b:' . a:name)
1157                 return b:{a:name}
1158         elseif exists('g:' . a:name)
1159                 return g:{a:name}
1160         else
1161                 return a:default
1162         endif
1163 endfunction
1165 " Function: VCSCommandDisableBufferSetup() {{{2
1166 " Global function for deactivating the buffer autovariables.
1168 function! VCSCommandDisableBufferSetup()
1169         let g:VCSCommandEnableBufferSetup = 0
1170         silent! augroup! VCSCommandPlugin
1171 endfunction
1173 " Function: VCSCommandEnableBufferSetup() {{{2
1174 " Global function for activating the buffer autovariables.
1176 function! VCSCommandEnableBufferSetup()
1177         let g:VCSCommandEnableBufferSetup = 1
1178         augroup VCSCommandPlugin
1179                 au!
1180                 au BufEnter * call s:SetupBuffer()
1181         augroup END
1183         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1184         " chance to run.
1185         if g:loaded_VCSCommand == 2
1186                 call s:SetupBuffer()
1187         endif
1188 endfunction
1190 " Function: VCSCommandGetStatusLine() {{{2
1191 " Default (sample) status line entry for VCS-controlled files.  This is only
1192 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1193 " variable for how to do this).
1195 function! VCSCommandGetStatusLine()
1196         if exists('b:VCSCommandCommand')
1197                 " This is a result buffer.  Return nothing because the buffer name
1198                 " contains information already.
1199                 return ''
1200         endif
1202         if exists('b:VCSCommandVCSType')
1203                                 \ && exists('g:VCSCommandEnableBufferSetup')
1204                                 \ && g:VCSCommandEnableBufferSetup
1205                                 \ && exists('b:VCSCommandBufferInfo')
1206                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1207         else
1208                 return ''
1209         endif
1210 endfunction
1212 " Section: Command definitions {{{1
1213 " Section: Primary commands {{{2
1214 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1215 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1216 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1217 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1218 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1219 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1220 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1221 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1222 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1223 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1224 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1225 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1226 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1227 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1228 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1229 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1230 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1232 " Section: VCS buffer management commands {{{2
1233 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1234 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1236 " Allow reloading VCSCommand.vim
1237 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
1239 " Section: Plugin command mappings {{{1
1240 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1241 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1242 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1243 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1244 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1245 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1246 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1247 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1248 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1249 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1250 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1251 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1252 nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1253 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1254 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1255 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1256 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1258 " Section: Default mappings {{{1
1260 let s:defaultMappings = [
1261                         \['a', 'VCSAdd'],
1262                         \['c', 'VCSCommit'],
1263                         \['D', 'VCSDelete'],
1264                         \['d', 'VCSDiff'],
1265                         \['G', 'VCSClearAndGotoOriginal'],
1266                         \['g', 'VCSGotoOriginal'],
1267                         \['i', 'VCSInfo'],
1268                         \['L', 'VCSLock'],
1269                         \['l', 'VCSLog'],
1270                         \['N', 'VCSSplitAnnotate'],
1271                         \['n', 'VCSAnnotate'],
1272                         \['q', 'VCSRevert'],
1273                         \['r', 'VCSReview'],
1274                         \['s', 'VCSStatus'],
1275                         \['U', 'VCSUnlock'],
1276                         \['u', 'VCSUpdate'],
1277                         \['v', 'VCSVimDiff'],
1278                         \]
1280 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1281         for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1282                 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1283         endfor
1284 endif
1286 " Section: Menu items {{{1
1287 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1288 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1289 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1290 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1291 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1292 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1293 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1294 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1295 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1296 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1297 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1298 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1300 " Section: Autocommands to restore vimdiff state {{{1
1301 augroup VimDiffRestore
1302         au!
1303         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1304 augroup END
1306 " Section: Optional activation of buffer management {{{1
1308 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1309         call VCSCommandEnableBufferSetup()
1310 endif
1312 " Section: VIM shutdown hook {{{1
1314 " Close all result buffers when VIM exits, to prevent them from being restored
1315 " via viminfo.
1317 " Function: s:CloseAllResultBuffers() {{{2
1318 " Closes all vcscommand result buffers.
1319 function! s:CloseAllResultBuffers()
1320         " This avoids using bufdo as that may load buffers already loaded in another
1321         " vim process, resulting in an error.
1322         let buffnr = 1
1323         let buffmaxnr = bufnr('$')
1324         while buffnr <= buffmaxnr
1325                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1326                         execute 'bw' buffnr
1327                 endif
1328                 let buffnr = buffnr + 1
1329         endwhile
1330 endfunction
1332 augroup VCSCommandVIMShutdown
1333         au!
1334         au VimLeavePre * call s:CloseAllResultBuffers()
1335 augroup END
1337 " Section: Plugin completion {{{1
1339 let loaded_VCSCommand = 2
1341 silent do VCSCommand User VCSPluginFinish
1343 let &cpo = s:save_cpo