VCSAnnotate: jump to current line.
[vcscommand.git] / plugin / vcscommand.vim
blob2a30310bb5349c2c020111d1614fdd6b17068d3f
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.  Several options include the name of the
37 " version control system in the option name.  Such options use the placeholder
38 " text '{VCSType}', which would be replaced in actual usage with 'CVS' or
39 " 'SVN', for instance.
41 " Command documentation {{{2
43 " VCSAdd           Adds the current file to source control.
45 " VCSAnnotate[!]   Displays the current file with each line annotated with the
46 "                  version in which it was most recently changed.  If an
47 "                  argument is given, the argument is used as a revision
48 "                  number to display.  If not given an argument, it uses the
49 "                  most recent version of the file on the current branch.
50 "                  Additionally, if the current buffer is a VCSAnnotate buffer
51 "                  already, the version number on the current line is used.
53 "                  If '!' is used, the view of the annotated buffer is split
54 "                  so that the annotation is in a separate window from the
55 "                  content, and each is highlighted separately.
57 " VCSBlame         Alias for 'VCSAnnotate'.
59 " VCSCommit[!]     Commits changes to the current file to source control.
61 "                  If called with arguments, the arguments are the log message.
63 "                  If '!' is used, an empty log message is committed.
65 "                  If called with no arguments, this is a two-step command.
66 "                  The first step opens a buffer to accept a log message.
67 "                  When that buffer is written, it is automatically closed and
68 "                  the file is committed using the information from that log
69 "                  message.  The commit can be abandoned if the log message
70 "                  buffer is deleted or wiped before being written.
72 " VCSDelete        Deletes the current file and removes it from source control.
74 " VCSDiff          With no arguments, this displays the differences between
75 "                  the current file and its parent version under source
76 "                  control in a new scratch buffer.
78 "                  With one argument, the diff is performed on the
79 "                  current file against the specified revision.
81 "                  With two arguments, the diff is performed between the
82 "                  specified revisions of the current file.
84 "                  This command uses the 'VCSCommand{VCSType}DiffOpt' variable
85 "                  to specify diff options.  If that variable does not exist,
86 "                  a plugin-specific default is used.  If you wish to have no
87 "                  options, then set it to the empty string.
89 " VCSGotoOriginal  Jumps to the source buffer if the current buffer is a VCS
90 "                  scratch buffer.  If VCSGotoOriginal[!] is used, remove all
91 "                  VCS scratch buffers associated with the original file.
93 " VCSInfo          Displays extended information about the current file in a
94 "                  new scratch buffer.
96 " VCSLock          Locks the current file in order to prevent other users from
97 "                  concurrently modifying it.  The exact semantics of this
98 "                  command depend on the underlying VCS.
100 " VCSLog           Displays the version history of the current file in a new
101 "                  scratch buffer.
103 " VCSRemove        Alias for 'VCSDelete'.
105 " VCSRevert        Replaces the modified version of the current file with the
106 "                  most recent version from the repository.
108 " VCSReview        Displays a particular version of the current file in a new
109 "                  scratch buffer.  If no argument is given, the most recent
110 "                  version of the file on the current branch is retrieved.
112 " VCSStatus        Displays versioning information about the current file in a
113 "                  new scratch buffer.
115 " VCSUnlock        Unlocks the current file in order to allow other users from
116 "                  concurrently modifying it.  The exact semantics of this
117 "                  command depend on the underlying VCS.
119 " VCSUpdate        Updates the current file with any relevant changes from the
120 "                  repository.
122 " VCSVimDiff       Uses vimdiff to display differences between versions of the
123 "                  current file.
125 "                  If no revision is specified, the most recent version of the
126 "                  file on the current branch is used.  With one argument,
127 "                  that argument is used as the revision as above.  With two
128 "                  arguments, the differences between the two revisions is
129 "                  displayed using vimdiff.
131 "                  With either zero or one argument, the original buffer is
132 "                  used to perform the vimdiff.  When the scratch buffer is
133 "                  closed, the original buffer will be returned to normal
134 "                  mode.
136 "                  Once vimdiff mode is started using the above methods,
137 "                  additional vimdiff buffers may be added by passing a single
138 "                  version argument to the command.  There may be up to 4
139 "                  vimdiff buffers total.
141 "                  Using the 2-argument form of the command resets the vimdiff
142 "                  to only those 2 versions.  Additionally, invoking the
143 "                  command on a different file will close the previous vimdiff
144 "                  buffers.
146 " Mapping documentation: {{{2
148 " By default, a mapping is defined for each command.  User-provided mappings
149 " can be used instead by mapping to <Plug>CommandName, for instance:
151 " nmap ,ca <Plug>VCSAdd
153 " The default mappings are as follow:
155 "   <Leader>ca VCSAdd
156 "   <Leader>cn VCSAnnotate
157 "   <Leader>cN VCSAnnotate!
158 "   <Leader>cc VCSCommit
159 "   <Leader>cD VCSDelete
160 "   <Leader>cd VCSDiff
161 "   <Leader>cg VCSGotoOriginal
162 "   <Leader>cG VCSGotoOriginal!
163 "   <Leader>ci VCSInfo
164 "   <Leader>cl VCSLog
165 "   <Leader>cL VCSLock
166 "   <Leader>cr VCSReview
167 "   <Leader>cs VCSStatus
168 "   <Leader>cu VCSUpdate
169 "   <Leader>cU VCSUnlock
170 "   <Leader>cv VCSVimDiff
172 " Options documentation: {{{2
174 " Several variables are checked by the script to determine behavior as follow:
176 " VCSCommandCommitOnWrite
177 "   This variable, if set to a non-zero value, causes the pending commit to
178 "   take place immediately as soon as the log message buffer is written.  If
179 "   set to zero, only the VCSCommit mapping will cause the pending commit to
180 "   occur.  If not set, it defaults to 1.
182 " VCSCommandDeleteOnHide
183 "   This variable, if set to a non-zero value, causes the temporary VCS result
184 "   buffers to automatically delete themselves when hidden.
186 " VCSCommand{VCSType}DiffOpt
187 "   This variable, if set, determines the options passed to the diff command
188 "   of the underlying VCS.  Each VCS plugin defines a default value.
190 " VCSCommandDiffSplit
191 "   This variable overrides the VCSCommandSplit variable, but only for buffers
192 "   created with VCSVimDiff.
194 " VCSCommandDisableAll
195 "   This variable, if set, prevents the plugin or any extensions from loading
196 "   at all.  This is useful when a single runtime distribution is used on
197 "   multiple systems with varying versions.
199 " VCSCommandDisableMappings
200 "   This variable, if set to a non-zero value, prevents the default command
201 "   mappings from being set.
203 " VCSCommandDisableExtensionMappings
204 "   This variable, if set to a non-zero value, prevents the default command
205 "   mappings from being set for commands specific to an individual VCS.
207 " VCSCommandEdit
208 "   This variable controls whether to split the current window to display a
209 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
210 "   If not set, it defaults to 'split'.
212 " VCSCommandEnableBufferSetup
213 "   This variable, if set to a non-zero value, activates VCS buffer management
214 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
215 "   the file is VCS-controlled.  This is useful for displaying version
216 "   information in the status bar.  Additional options may be set by
217 "   individual VCS plugins.
219 " VCSCommandMappings
220 "   This variable, if set, overrides the default mappings used for shortcuts.
221 "   It should be a List of 2-element Lists, each containing a shortcut and
222 "   function name pair.
224 " VCSCommandMapPrefix
225 "   This variable, if set, overrides the default mapping prefix ('<Leader>c').
226 "   This allows customization of the mapping space used by the vcscommand
227 "   shortcuts.
229 " VCSCommandResultBufferNameExtension
230 "   This variable, if set to a non-blank value, is appended to the name of the
231 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
232 "   help avoid problems caused by autocommands dependent on file extension.
234 " VCSCommandResultBufferNameFunction
235 "   This variable, if set, specifies a custom function for naming VCS command
236 "   output buffers.  This function will be passed the following arguments:
238 "   command - name of the VCS command being executed (such as 'Log' or
239 "   'Diff').
241 "   originalBuffer - buffer number of the source file.
243 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
245 "   statusText - extra text associated with the VCS action (such as version
246 "   numbers).
248 " VCSCommandSplit
249 "   This variable controls the orientation of the various window splits that
250 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
251 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
252 "   If set to 'horizontal', the resulting windows will be on stacked on top of
253 "   one another.  If set to 'vertical', the resulting windows will be
254 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
255 "   VCSVimDiff windows.
257 " VCSCommandVCSTypeOverride
258 "   This variable allows the VCS type detection to be overridden on a
259 "   path-by-path basis.  The value of this variable is expected to be a List
260 "   of Lists.  Each high-level List item is a List containing two elements.
261 "   The first element is a regular expression that will be matched against the
262 "   full file name of a given buffer.  If it matches, the second element will
263 "   be used as the VCS type.
265 " Event documentation {{{2
266 "   For additional customization, VCSCommand.vim uses User event autocommand
267 "   hooks.  Each event is in the VCSCommand group, and different patterns
268 "   match the various hooks.
270 "   For instance, the following could be added to the vimrc to provide a 'q'
271 "   mapping to quit a VCS scratch buffer:
273 "   augroup VCSCommand
274 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
275 "   augroup END
277 "   The following hooks are available:
279 "   VCSBufferCreated           This event is fired just after a VCS command
280 "                              output buffer is created.  It is executed
281 "                              within the context of the new buffer.
283 "   VCSBufferSetup             This event is fired just after VCS buffer setup
284 "                              occurs, if enabled.
286 "   VCSPluginInit              This event is fired when the VCSCommand plugin
287 "                              first loads.
289 "   VCSPluginFinish            This event is fired just after the VCSCommand
290 "                              plugin loads.
292 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
293 "                              command executes to allow customization of,
294 "                              for instance, window placement and focus.
296 " Section: Plugin header {{{1
298 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
299 " completes.  This allows various actions to only be taken by functions after
300 " system initialization.
302 if exists('VCSCommandDisableAll')
303         finish
304 endif
306 if exists('loaded_VCSCommand')
307         finish
308 endif
309 let loaded_VCSCommand = 1
311 if v:version < 700
312         echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
313         finish
314 endif
316 let s:save_cpo=&cpo
317 set cpo&vim
319 " Section: Event group setup {{{1
321 augroup VCSCommand
322 augroup END
324 augroup VCSCommandCommit
325 augroup END
327 " Section: Plugin initialization {{{1
328 silent do VCSCommand User VCSPluginInit
330 " Section: Constants declaration {{{1
332 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
333 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
335 " Section: Script variable initialization {{{1
337 " Hidden functions for use by extensions
338 let s:VCSCommandUtility = {}
340 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
341 let s:plugins = {}
343 " temporary values of overridden configuration variables
344 let s:optionOverrides = {}
346 " state flag used to vary behavior of certain automated actions
347 let s:isEditFileRunning = 0
349 " commands needed to restore diff buffers to their original state
350 unlet! s:vimDiffRestoreCmd
352 " original buffer currently reflected in vimdiff windows
353 unlet! s:vimDiffSourceBuffer
356 unlet! s:vimDiffScratchList
358 " Section: Utility functions {{{1
360 " Function: s:ReportError(mapping) {{{2
361 " Displays the given error in a consistent faction.  This is intended to be
362 " invoked from a catch statement.
364 function! s:ReportError(error)
365         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
366 endfunction
368 " Function s:VCSCommandUtility.system(...) {{{2
369 " Replacement for system() function.  This version protects the quoting in the
370 " command line on Windows systems.
372 function! s:VCSCommandUtility.system(...)
373         if (has("win32") || has("win64")) && &sxq !~ '"'
374                 let save_sxq = &sxq
375                 set sxq=\"
376         endif
377         try
378                 return call('system', a:000)
379         finally
380                 if exists("save_sxq")
381                         let &sxq = save_sxq
382                 endif
383         endtry
384 endfunction
386 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
387 " Creates the given mapping by prepending the contents of
388 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
389 " mapping it to the given plugin function.  If a mapping exists for the
390 " specified shortcut + prefix, emit an error but continue.  If a mapping
391 " exists for the specified function, do nothing.
393 function! s:CreateMapping(shortcut, expansion, display)
394         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
395         if !hasmapto(a:expansion)
396                 try
397                         execute 'nmap <silent> <unique>' lhs a:expansion
398                 catch /^Vim(.*):E227:/
399                         if(&verbose != 0)
400                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
401                         endif
402                 endtry
403         endif
404 endfunction
406 " Function: s:ExecuteExtensionMapping(mapping) {{{2
407 " Invokes the appropriate extension mapping depending on the type of the
408 " current buffer.
410 function! s:ExecuteExtensionMapping(mapping)
411         let buffer = bufnr('%')
412         let vcsType = VCSCommandGetVCSType(buffer)
413         if !has_key(s:plugins, vcsType)
414                 throw 'Unknown VCS type:  ' . vcsType
415         endif
416         if !has_key(s:plugins[vcsType][2], a:mapping)
417                 throw 'This extended mapping is not defined for ' . vcsType
418         endif
419         silent execute 'normal' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
420 endfunction
422 " Function: s:ExecuteVCSCommand(command, argList) {{{2
423 " Calls the indicated plugin-specific VCS command on the current buffer.
424 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
425 " occurs.
427 function! s:ExecuteVCSCommand(command, argList)
428         try
429                 let buffer = bufnr('%')
431                 let vcsType = VCSCommandGetVCSType(buffer)
432                 if !has_key(s:plugins, vcsType)
433                         throw 'Unknown VCS type:  ' . vcsType
434                 endif
436                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
437                 let bufferName = bufname(originalBuffer)
439                 " It is already known that the directory is under VCS control.  No further
440                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
441                 " VCS-specific error messages from confusing things.
442                 if !isdirectory(bufferName)
443                         if !filereadable(bufferName)
444                                 throw 'No such file ' . bufferName
445                         endif
446                 endif
448                 let functionMap = s:plugins[vcsType][1]
449                 if !has_key(functionMap, a:command)
450                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
451                 endif
452                 return functionMap[a:command](a:argList)
453         catch
454                 call s:ReportError(v:exception)
455                 return -1
456         endtry
457 endfunction
459 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
460 " Default method of generating the name for VCS result buffers.  This can be
461 " overridden with the VCSResultBufferNameFunction variable.
463 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
464         let fileName = bufname(a:originalBuffer)
465         let bufferName = a:vcsType . ' ' . a:command
466         if strlen(a:statusText) > 0
467                 let bufferName .= ' ' . a:statusText
468         endif
469         let bufferName .= ' ' . fileName
470         let counter = 0
471         let versionedBufferName = bufferName
472         while buflisted(versionedBufferName)
473                 let counter += 1
474                 let versionedBufferName = bufferName . ' (' . counter . ')'
475         endwhile
476         return versionedBufferName
477 endfunction
479 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
480 " Method of generating the name for VCS result buffers that uses the original
481 " file name with the VCS type and command appended as extensions.
483 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
484         let fileName = bufname(a:originalBuffer)
485         let bufferName = a:vcsType . ' ' . a:command
486         if strlen(a:statusText) > 0
487                 let bufferName .= ' ' . a:statusText
488         endif
489         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
490         let counter = 0
491         let versionedBufferName = bufferName
492         while buflisted(versionedBufferName)
493                 let counter += 1
494                 let versionedBufferName = '(' . counter . ') ' . bufferName
495         endwhile
496         return versionedBufferName
497 endfunction
499 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
500 " Creates a new buffer of the given name and associates it with the given
501 " original buffer.
503 function! s:EditFile(command, originalBuffer, statusText)
504         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
506         " Protect against useless buffer set-up
507         let s:isEditFileRunning += 1
508         try
509                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
510                 if editCommand == 'split'
511                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
512                                 rightbelow split
513                         else
514                                 vert rightbelow split
515                         endif
516                 endif
518                 enew
520                 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
522         finally
523                 let s:isEditFileRunning -= 1
524         endtry
525 endfunction
527 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
528 " Creates convenience buffer variables and the name of a vcscommand result
529 " buffer.
531 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
532         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
533         if nameExtension == ''
534                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
535         else
536                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
537         endif
539         let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
541         let b:VCSCommandCommand = a:command
542         let b:VCSCommandOriginalBuffer = a:originalBuffer
543         let b:VCSCommandSourceFile = bufname(a:originalBuffer)
544         let b:VCSCommandVCSType = a:vcsType
545         if a:statusText != ''
546                 let b:VCSCommandStatusText = a:statusText
547         endif
549         setlocal buftype=nofile
550         setlocal noswapfile
551         let &filetype = a:vcsType . a:command
553         if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
554                 setlocal bufhidden=delete
555         endif
556         silent noautocmd file `=name`
557 endfunction
559 " Function: s:SetupBuffer() {{{2
560 " Attempts to set the b:VCSCommandBufferInfo variable
562 function! s:SetupBuffer()
563         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
564                 " This buffer is already set up.
565                 return
566         endif
568         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
569                 " No special status for special buffers other than directory buffers.
570                 return
571         endif
573         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
574                 unlet! b:VCSCommandBufferSetup
575                 return
576         endif
578         try
579                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
580                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
581                 silent do VCSCommand User VCSBufferSetup
582         catch /No suitable plugin/
583                 " This is not a VCS-controlled file.
584                 let b:VCSCommandBufferInfo = []
585         endtry
587         let b:VCSCommandBufferSetup = 1
588 endfunction
590 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
591 " Resets the buffer setup state of the original buffer for a given VCS scratch
592 " buffer.
593 " Returns:  The VCS buffer number in a passthrough mode.
595 function! s:MarkOrigBufferForSetup(buffer)
596         checktime
597         if a:buffer > 0
598                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
599                 " This should never not work, but I'm paranoid
600                 if origBuffer != a:buffer
601                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
602                 endif
603         endif
604         return a:buffer
605 endfunction
607 " Function: s:OverrideOption(option, [value]) {{{2
608 " Provides a temporary override for the given VCS option.  If no value is
609 " passed, the override is disabled.
611 function! s:OverrideOption(option, ...)
612         if a:0 == 0
613                 call remove(s:optionOverrides[a:option], -1)
614         else
615                 if !has_key(s:optionOverrides, a:option)
616                         let s:optionOverrides[a:option] = []
617                 endif
618                 call add(s:optionOverrides[a:option], a:1)
619         endif
620 endfunction
622 " Function: s:WipeoutCommandBuffers() {{{2
623 " Clears all current VCS output buffers of the specified type for a given source.
625 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
626         let buffer = 1
627         while buffer <= bufnr('$')
628                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
629                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
630                                 execute 'bw' buffer
631                         endif
632                 endif
633                 let buffer = buffer + 1
634         endwhile
635 endfunction
637 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
638 " Checks whether the given buffer is one whose deletion should trigger
639 " restoration of an original buffer after it was diffed.  If so, it executes
640 " the appropriate setting command stored with that original buffer.
642 function! s:VimDiffRestore(vimDiffBuff)
643         let s:isEditFileRunning += 1
644         try
645                 if exists('s:vimDiffSourceBuffer')
646                         if a:vimDiffBuff == s:vimDiffSourceBuffer
647                                 " Original file is being removed.
648                                 unlet! s:vimDiffSourceBuffer
649                                 unlet! s:vimDiffRestoreCmd
650                                 unlet! s:vimDiffScratchList
651                         else
652                                 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
653                                 if index >= 0
654                                         call remove(s:vimDiffScratchList, index)
655                                         if len(s:vimDiffScratchList) == 0
656                                                 if exists('s:vimDiffRestoreCmd')
657                                                         " All scratch buffers are gone, reset the original.
658                                                         " Only restore if the source buffer is still in Diff mode
660                                                         let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
661                                                         if sourceWinNR != -1
662                                                                 " The buffer is visible in at least one window
663                                                                 let currentWinNR = winnr()
664                                                                 while winbufnr(sourceWinNR) != -1
665                                                                         if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
666                                                                                 execute sourceWinNR . 'wincmd w'
667                                                                                 if getwinvar(0, '&diff')
668                                                                                         execute s:vimDiffRestoreCmd
669                                                                                 endif
670                                                                         endif
671                                                                         let sourceWinNR = sourceWinNR + 1
672                                                                 endwhile
673                                                                 execute currentWinNR . 'wincmd w'
674                                                         else
675                                                                 " The buffer is hidden.  It must be visible in order to set the
676                                                                 " diff option.
677                                                                 let currentBufNR = bufnr('')
678                                                                 execute 'hide buffer' s:vimDiffSourceBuffer
679                                                                 if getwinvar(0, '&diff')
680                                                                         execute s:vimDiffRestoreCmd
681                                                                 endif
682                                                                 execute 'hide buffer' currentBufNR
683                                                         endif
685                                                         unlet s:vimDiffRestoreCmd
686                                                 endif
687                                                 " All buffers are gone.
688                                                 unlet s:vimDiffSourceBuffer
689                                                 unlet s:vimDiffScratchList
690                                         endif
691                                 endif
692                         endif
693                 endif
694         finally
695                 let s:isEditFileRunning -= 1
696         endtry
697 endfunction
699 " Section: Generic VCS command functions {{{1
701 " Function: s:VCSAnnotate(...) {{{2
702 function! s:VCSAnnotate(bang, ...)
703         try
704                 let line = line('.')
705                 let currentBuffer = bufnr('%')
706                 let originalBuffer = VCSCommandGetOriginalBuffer(currentBuffer)
708                 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
709                 if annotateBuffer == -1
710                         return -1
711                 endif
712                 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
713                         let vcsType = VCSCommandGetVCSType(annotateBuffer)
714                         let functionMap = s:plugins[vcsType][1]
715                         let splitRegex = ''
716                         if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
717                                 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
718                         endif
719                         let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
720                         if splitRegex == ''
721                                 return annotateBuffer
722                         endif
723                         let originalFileType = getbufvar(originalBuffer, '&ft')
724                         let annotateFileType = getbufvar(annotateBuffer, '&ft')
725                         execute "normal 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
726                         call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
727                         set scrollbind
728                         leftabove vert new
729                         normal 0P
730                         execute "normal" . col('$') . "\<c-w>|"
731                         call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
732                         wincmd l
733                 endif
735                 if currentBuffer == originalBuffer
736                         " Starting from the original source buffer, so the
737                         " current line is relevant.
738                         if a:0 == 0
739                                 " No argument list means that we're annotating
740                                 " the current version, so jumping to the same
741                                 " line is the expected action.
742                                 execute "normal" line . 'G'
743                                 if has('folding')
744                                         " The execution of the buffer created autocommand
745                                         " re-folds the buffer.  Display the current line
746                                         " unfolded.
747                                         normal zv
748                                 endif
749                         endif
750                 endif
752                 return annotateBuffer
753         catch
754                 call s:ReportError(v:exception)
755                 return -1
756         endtry
757 endfunction
759 " Function: s:VCSCommit() {{{2
760 function! s:VCSCommit(bang, message)
761         try
762                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
763                 if !has_key(s:plugins, vcsType)
764                         throw 'Unknown VCS type:  ' . vcsType
765                 endif
767                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
769                 " Handle the commit message being specified.  If a message is supplied, it
770                 " is used; if bang is supplied, an empty message is used; otherwise, the
771                 " user is provided a buffer from which to edit the commit message.
773                 if strlen(a:message) > 0 || a:bang == '!'
774                         return s:VCSFinishCommit([a:message], originalBuffer)
775                 endif
777                 call s:EditFile('commitlog', originalBuffer, '')
778                 setlocal ft=vcscommit
780                 " Create a commit mapping.
782                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
784                 silent 0put ='VCS: ----------------------------------------------------------------------'
785                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
786                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
788                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
789                         setlocal buftype=acwrite
790                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
791                         silent put ='VCS: or write this buffer'
792                 endif
794                 silent put ='VCS: ----------------------------------------------------------------------'
795                 $
796                 setlocal nomodified
797         catch
798                 call s:ReportError(v:exception)
799                 return -1
800         endtry
801 endfunction
803 " Function: s:VCSFinishCommitWithBuffer() {{{2
804 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
805 " which removes all lines starting with 'VCS:'.
807 function! s:VCSFinishCommitWithBuffer()
808         setlocal nomodified
809         let currentBuffer = bufnr('%')
810         let logMessageList = getbufline('%', 1, '$')
811         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
812         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
813         if resultBuffer >= 0
814                 execute 'bw' currentBuffer
815         endif
816         return resultBuffer
817 endfunction
819 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
820 function! s:VCSFinishCommit(logMessageList, originalBuffer)
821         let shellSlashBak = &shellslash
822         try
823                 set shellslash
824                 let messageFileName = tempname()
825                 call writefile(a:logMessageList, messageFileName)
826                 try
827                         let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
828                         if resultBuffer < 0
829                                 return resultBuffer
830                         endif
831                         return s:MarkOrigBufferForSetup(resultBuffer)
832                 finally
833                         call delete(messageFileName)
834                 endtry
835         finally
836                 let &shellslash = shellSlashBak
837         endtry
838 endfunction
840 " Function: s:VCSGotoOriginal(bang) {{{2
841 function! s:VCSGotoOriginal(bang)
842         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
843         if originalBuffer > 0
844                 let origWinNR = bufwinnr(originalBuffer)
845                 if origWinNR == -1
846                         execute 'buffer' originalBuffer
847                 else
848                         execute origWinNR . 'wincmd w'
849                 endif
850                 if a:bang == '!'
851                         let buffnr = 1
852                         let buffmaxnr = bufnr('$')
853                         while buffnr <= buffmaxnr
854                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
855                                         execute 'bw' buffnr
856                                 endif
857                                 let buffnr = buffnr + 1
858                         endwhile
859                 endif
860         endif
861 endfunction
863 " Function: s:VCSVimDiff(...) {{{2
864 function! s:VCSVimDiff(...)
865         try
866                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
867                 if !has_key(s:plugins, vcsType)
868                         throw 'Unknown VCS type:  ' . vcsType
869                 endif
870                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
871                 let s:isEditFileRunning = s:isEditFileRunning + 1
872                 try
873                         " If there's already a VimDiff'ed window, restore it.
874                         " There may only be one VCSVimDiff original window at a time.
876                         if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
877                                 " Clear the existing vimdiff setup by removing the result buffers.
878                                 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
879                         endif
881                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
882                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
883                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
885                         " Split and diff
886                         if(a:0 == 2)
887                                 " Reset the vimdiff system, as 2 explicit versions were provided.
888                                 if exists('s:vimDiffSourceBuffer')
889                                         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
890                                 endif
891                                 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
892                                 if resultBuffer < 0
893                                         echomsg 'Can''t open revision ' . a:1
894                                         return resultBuffer
895                                 endif
896                                 let b:VCSCommandCommand = 'vimdiff'
897                                 diffthis
898                                 let s:vimDiffScratchList = [resultBuffer]
899                                 " If no split method is defined, cheat, and set it to vertical.
900                                 try
901                                         call s:OverrideOption('VCSCommandSplit', orientation)
902                                         let resultBuffer = s:plugins[vcsType][1].Review([a:2])
903                                 finally
904                                         call s:OverrideOption('VCSCommandSplit')
905                                 endtry
906                                 if resultBuffer < 0
907                                         echomsg 'Can''t open revision ' . a:1
908                                         return resultBuffer
909                                 endif
910                                 let b:VCSCommandCommand = 'vimdiff'
911                                 diffthis
912                                 let s:vimDiffScratchList += [resultBuffer]
913                         else
914                                 " Add new buffer
915                                 call s:OverrideOption('VCSCommandEdit', 'split')
916                                 try
917                                         " Force splitting behavior, otherwise why use vimdiff?
918                                         call s:OverrideOption('VCSCommandSplit', orientation)
919                                         try
920                                                 if(a:0 == 0)
921                                                         let resultBuffer = s:plugins[vcsType][1].Review([])
922                                                 else
923                                                         let resultBuffer = s:plugins[vcsType][1].Review([a:1])
924                                                 endif
925                                         finally
926                                                 call s:OverrideOption('VCSCommandSplit')
927                                         endtry
928                                 finally
929                                         call s:OverrideOption('VCSCommandEdit')
930                                 endtry
931                                 if resultBuffer < 0
932                                         echomsg 'Can''t open current revision'
933                                         return resultBuffer
934                                 endif
935                                 let b:VCSCommandCommand = 'vimdiff'
936                                 diffthis
938                                 if !exists('s:vimDiffSourceBuffer')
939                                         " New instance of vimdiff.
940                                         let s:vimDiffScratchList = [resultBuffer]
942                                         " This could have been invoked on a VCS result buffer, not the
943                                         " original buffer.
944                                         wincmd W
945                                         execute 'buffer' originalBuffer
946                                         " Store info for later original buffer restore
947                                         let s:vimDiffRestoreCmd =
948                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
949                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
950                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
951                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
952                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
953                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
954                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
955                                                                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
956                                         diffthis
957                                         wincmd w
958                                 else
959                                         " Adding a window to an existing vimdiff
960                                         let s:vimDiffScratchList += [resultBuffer]
961                                 endif
962                         endif
964                         let s:vimDiffSourceBuffer = originalBuffer
966                         " Avoid executing the modeline in the current buffer after the autocommand.
968                         let currentBuffer = bufnr('%')
969                         let saveModeline = getbufvar(currentBuffer, '&modeline')
970                         try
971                                 call setbufvar(currentBuffer, '&modeline', 0)
972                                 silent do VCSCommand User VCSVimDiffFinish
973                         finally
974                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
975                         endtry
976                         return resultBuffer
977                 finally
978                         let s:isEditFileRunning = s:isEditFileRunning - 1
979                 endtry
980         catch
981                 call s:ReportError(v:exception)
982                 return -1
983         endtry
984 endfunction
986 " Section: Public functions {{{1
988 " Function: VCSCommandGetVCSType() {{{2
989 " Sets the b:VCSCommandVCSType variable in the given buffer to the
990 " appropriate source control system name.
992 " This uses the Identify extension function to test the buffer.  If the
993 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
994 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
995 " match is considered inexact, and is only applied if no exact match is found.
996 " Multiple inexact matches is currently considered an error.
998 function! VCSCommandGetVCSType(buffer)
999         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
1000         if strlen(vcsType) > 0
1001                 return vcsType
1002         endif
1003         if exists("g:VCSCommandVCSTypeOverride")
1004                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
1005                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
1006                         if match(fullpath, path) > -1
1007                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1008                                 return vcsType
1009                         endif
1010                 endfor
1011         endif
1012         let matches = []
1013         for vcsType in keys(s:plugins)
1014                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
1015                 if identified
1016                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
1017                                 let matches = [vcsType]
1018                                 break
1019                         else
1020                                 let matches += [vcsType]
1021                         endif
1022                 endif
1023         endfor
1024         if len(matches) == 1
1025                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
1026                 return matches[0]
1027         elseif len(matches) == 0
1028                 throw 'No suitable plugin'
1029         else
1030                 throw 'Too many matching VCS:  ' . join(matches)
1031         endif
1032 endfunction
1034 " Function: VCSCommandChdir(directory) {{{2
1035 " Changes the current directory, respecting :lcd changes.
1037 function! VCSCommandChdir(directory)
1038         let command = 'cd'
1039         if exists("*haslocaldir") && haslocaldir()
1040                 let command = 'lcd'
1041         endif
1042         execute command escape(a:directory, ' ')
1043 endfunction
1045 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1046 " Go to the directory in which the given file is located.
1048 function! VCSCommandChangeToCurrentFileDir(fileName)
1049         let oldCwd = getcwd()
1050         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1051         if strlen(newCwd) > 0
1052                 call VCSCommandChdir(newCwd)
1053         endif
1054         return oldCwd
1055 endfunction
1057 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1058 " Attempts to locate the original file to which VCS operations were applied
1059 " for a given buffer.
1061 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1062         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1063         if origBuffer
1064                 if bufexists(origBuffer)
1065                         return origBuffer
1066                 else
1067                         " Original buffer no longer exists.
1068                         throw 'Original buffer for this VCS buffer no longer exists.'
1069                 endif
1070         else
1071                 " No original buffer
1072                 return a:vcsBuffer
1073         endif
1074 endfunction
1076 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1077 " Allows VCS modules to register themselves.
1079 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1080         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1081         if !empty(a:mappingMap)
1082                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1083                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1084                 for shortcut in keys(a:mappingMap)
1085                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1086                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1087                 endfor
1088         endif
1089         return s:VCSCommandUtility
1090 endfunction
1092 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1093 " General skeleton for VCS function execution.  The given command is executed
1094 " after appending the current buffer name (or substituting it for
1095 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1096 " new buffer.
1098 " The optional 'options' Dictionary may contain the following options:
1099 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1100 "               non-zero exit status, the command is still considered
1101 "               successfuly.  This defaults to zero.
1102 " Returns: name of the new command buffer containing the command results
1104 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1105         let allowNonZeroExit = 0
1106         if has_key(a:options, 'allowNonZeroExit')
1107                 let allowNonZeroExit = a:options.allowNonZeroExit
1108         endif
1110         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1111         if originalBuffer == -1
1112                 throw 'Original buffer no longer exists, aborting.'
1113         endif
1115         let path = resolve(bufname(originalBuffer))
1117         " Work with netrw or other systems where a directory listing is displayed in
1118         " a buffer.
1120         if isdirectory(path)
1121                 let fileName = '.'
1122         else
1123                 let fileName = fnamemodify(path, ':t')
1124         endif
1126         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1127                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1128         else
1129                 let fullCmd = a:cmd . ' -- "' . fileName . '"'
1130         endif
1132         " Change to the directory of the current buffer.  This is done for CVS, but
1133         " is left in for other systems as it does not affect them negatively.
1135         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1136         try
1137                 let output = s:VCSCommandUtility.system(fullCmd)
1138         finally
1139                 call VCSCommandChdir(oldCwd)
1140         endtry
1142         " HACK:  if line endings in the repository have been corrupted, the output
1143         " of the command will be confused.
1144         let output = substitute(output, "\r", '', 'g')
1146         if v:shell_error && !allowNonZeroExit
1147                 if strlen(output) == 0
1148                         throw 'Version control command failed'
1149                 else
1150                         let output = substitute(output, '\n', '  ', 'g')
1151                         throw 'Version control command failed:  ' . output
1152                 endif
1153         endif
1155         if strlen(output) == 0
1156                 " Handle case of no output.  In this case, it is important to check the
1157                 " file status, especially since cvs edit/unedit may change the attributes
1158                 " of the file with no visible output.
1160                 checktime
1161                 return 0
1162         endif
1164         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1166         silent 0put=output
1168         " The last command left a blank line at the end of the buffer.  If the
1169         " last line is folded (a side effect of the 'put') then the attempt to
1170         " remove the blank line will kill the last fold.
1171         "
1172         " This could be fixed by explicitly detecting whether the last line is
1173         " within a fold, but I prefer to simply unfold the result buffer altogether.
1175         if has('folding')
1176                 normal zR
1177         endif
1179         $d
1180         1
1182         " Define the environment and execute user-defined hooks.
1184         silent do VCSCommand User VCSBufferCreated
1185         return bufnr('%')
1186 endfunction
1188 " Function: VCSCommandGetOption(name, default) {{{2
1189 " Grab a user-specified option to override the default provided.  Options are
1190 " searched in the window, buffer, then global spaces.
1192 function! VCSCommandGetOption(name, default)
1193         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1194                 return s:optionOverrides[a:name][-1]
1195         elseif exists('w:' . a:name)
1196                 return w:{a:name}
1197         elseif exists('b:' . a:name)
1198                 return b:{a:name}
1199         elseif exists('g:' . a:name)
1200                 return g:{a:name}
1201         else
1202                 return a:default
1203         endif
1204 endfunction
1206 " Function: VCSCommandDisableBufferSetup() {{{2
1207 " Global function for deactivating the buffer autovariables.
1209 function! VCSCommandDisableBufferSetup()
1210         let g:VCSCommandEnableBufferSetup = 0
1211         silent! augroup! VCSCommandPlugin
1212 endfunction
1214 " Function: VCSCommandEnableBufferSetup() {{{2
1215 " Global function for activating the buffer autovariables.
1217 function! VCSCommandEnableBufferSetup()
1218         let g:VCSCommandEnableBufferSetup = 1
1219         augroup VCSCommandPlugin
1220                 au!
1221                 au BufEnter * call s:SetupBuffer()
1222         augroup END
1224         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1225         " chance to run.
1226         if g:loaded_VCSCommand == 2
1227                 call s:SetupBuffer()
1228         endif
1229 endfunction
1231 " Function: VCSCommandGetStatusLine() {{{2
1232 " Default (sample) status line entry for VCS-controlled files.  This is only
1233 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1234 " variable for how to do this).
1236 function! VCSCommandGetStatusLine()
1237         if exists('b:VCSCommandCommand')
1238                 " This is a result buffer.  Return nothing because the buffer name
1239                 " contains information already.
1240                 return ''
1241         endif
1243         if exists('b:VCSCommandVCSType')
1244                                 \ && exists('g:VCSCommandEnableBufferSetup')
1245                                 \ && g:VCSCommandEnableBufferSetup
1246                                 \ && exists('b:VCSCommandBufferInfo')
1247                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1248         else
1249                 return ''
1250         endif
1251 endfunction
1253 " Section: Command definitions {{{1
1254 " Section: Primary commands {{{2
1255 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1256 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1257 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1258 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1259 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1260 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1261 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1262 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1263 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1264 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1265 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1266 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1267 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1268 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1269 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1270 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1271 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1273 " Section: VCS buffer management commands {{{2
1274 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1275 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1277 " Allow reloading VCSCommand.vim
1278 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
1280 " Section: Plugin command mappings {{{1
1281 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1282 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1283 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1284 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1285 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1286 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1287 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1288 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1289 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1290 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1291 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1292 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1293 nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1294 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1295 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1296 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1297 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1299 " Section: Default mappings {{{1
1301 let s:defaultMappings = [
1302                         \['a', 'VCSAdd'],
1303                         \['c', 'VCSCommit'],
1304                         \['D', 'VCSDelete'],
1305                         \['d', 'VCSDiff'],
1306                         \['G', 'VCSClearAndGotoOriginal'],
1307                         \['g', 'VCSGotoOriginal'],
1308                         \['i', 'VCSInfo'],
1309                         \['L', 'VCSLock'],
1310                         \['l', 'VCSLog'],
1311                         \['N', 'VCSSplitAnnotate'],
1312                         \['n', 'VCSAnnotate'],
1313                         \['q', 'VCSRevert'],
1314                         \['r', 'VCSReview'],
1315                         \['s', 'VCSStatus'],
1316                         \['U', 'VCSUnlock'],
1317                         \['u', 'VCSUpdate'],
1318                         \['v', 'VCSVimDiff'],
1319                         \]
1321 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1322         for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1323                 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1324         endfor
1325 endif
1327 " Section: Menu items {{{1
1328 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1329 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1330 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1331 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1332 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1333 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1334 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1335 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1336 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1337 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1338 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1339 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1341 " Section: Autocommands to restore vimdiff state {{{1
1342 augroup VimDiffRestore
1343         au!
1344         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1345 augroup END
1347 " Section: Optional activation of buffer management {{{1
1349 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1350         call VCSCommandEnableBufferSetup()
1351 endif
1353 " Section: VIM shutdown hook {{{1
1355 " Close all result buffers when VIM exits, to prevent them from being restored
1356 " via viminfo.
1358 " Function: s:CloseAllResultBuffers() {{{2
1359 " Closes all vcscommand result buffers.
1360 function! s:CloseAllResultBuffers()
1361         " This avoids using bufdo as that may load buffers already loaded in another
1362         " vim process, resulting in an error.
1363         let buffnr = 1
1364         let buffmaxnr = bufnr('$')
1365         while buffnr <= buffmaxnr
1366                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1367                         execute 'bw' buffnr
1368                 endif
1369                 let buffnr = buffnr + 1
1370         endwhile
1371 endfunction
1373 augroup VCSCommandVIMShutdown
1374         au!
1375         au VimLeavePre * call s:CloseAllResultBuffers()
1376 augroup END
1378 " Section: Plugin completion {{{1
1380 let loaded_VCSCommand = 2
1382 silent do VCSCommand User VCSPluginFinish
1384 let &cpo = s:save_cpo