Removed copyright dates.
[vcscommand.git] / plugin / vcscommand.vim
blob039a99f7eb68092f8327a755dd2abf4bb0322fe5
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) 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 " Section: Utility functions {{{1
351 " Function: s:ReportError(mapping) {{{2
352 " Displays the given error in a consistent faction.  This is intended to be
353 " invoked from a catch statement.
355 function! s:ReportError(error)
356         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
357 endfunction
359 " Function s:VCSCommandUtility.system(...) {{{2
360 " Replacement for system() function.  This version protects the quoting in the
361 " command line on Windows systems.
363 function! s:VCSCommandUtility.system(...)
364         if (has("win32") || has("win64")) && &sxq !~ '"'
365                 let save_sxq = &sxq
366                 set sxq=\"
367         endif
368         try
369                 return call('system', a:000)
370         finally
371                 if exists("save_sxq")
372                         let &sxq = save_sxq
373                 endif
374         endtry
375 endfunction
377 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
378 " Creates the given mapping by prepending the contents of
379 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
380 " mapping it to the given plugin function.  If a mapping exists for the
381 " specified shortcut + prefix, emit an error but continue.  If a mapping
382 " exists for the specified function, do nothing.
384 function! s:CreateMapping(shortcut, expansion, display)
385         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
386         if !hasmapto(a:expansion)
387                 try
388                         execute 'nmap <silent> <unique>' lhs a:expansion
389                 catch /^Vim(.*):E227:/
390                         if(&verbose != 0)
391                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
392                         endif
393                 endtry
394         endif
395 endfunction
397 " Function: s:ExecuteExtensionMapping(mapping) {{{2
398 " Invokes the appropriate extension mapping depending on the type of the
399 " current buffer.
401 function! s:ExecuteExtensionMapping(mapping)
402         let buffer = bufnr('%')
403         let vcsType = VCSCommandGetVCSType(buffer)
404         if !has_key(s:plugins, vcsType)
405                 throw 'Unknown VCS type:  ' . vcsType
406         endif
407         if !has_key(s:plugins[vcsType][2], a:mapping)
408                 throw 'This extended mapping is not defined for ' . vcsType
409         endif
410         silent execute 'normal' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
411 endfunction
413 " Function: s:ExecuteVCSCommand(command, argList) {{{2
414 " Calls the indicated plugin-specific VCS command on the current buffer.
415 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
416 " occurs.
418 function! s:ExecuteVCSCommand(command, argList)
419         try
420                 let buffer = bufnr('%')
422                 let vcsType = VCSCommandGetVCSType(buffer)
423                 if !has_key(s:plugins, vcsType)
424                         throw 'Unknown VCS type:  ' . vcsType
425                 endif
427                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
428                 let bufferName = bufname(originalBuffer)
430                 " It is already known that the directory is under VCS control.  No further
431                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
432                 " VCS-specific error messages from confusing things.
433                 if !isdirectory(bufferName)
434                         if !filereadable(bufferName)
435                                 throw 'No such file ' . bufferName
436                         endif
437                 endif
439                 let functionMap = s:plugins[vcsType][1]
440                 if !has_key(functionMap, a:command)
441                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
442                 endif
443                 return functionMap[a:command](a:argList)
444         catch
445                 call s:ReportError(v:exception)
446                 return -1
447         endtry
448 endfunction
450 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
451 " Default method of generating the name for VCS result buffers.  This can be
452 " overridden with the VCSResultBufferNameFunction variable.
454 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
455         let fileName = bufname(a:originalBuffer)
456         let bufferName = a:vcsType . ' ' . a:command
457         if strlen(a:statusText) > 0
458                 let bufferName .= ' ' . a:statusText
459         endif
460         let bufferName .= ' ' . fileName
461         let counter = 0
462         let versionedBufferName = bufferName
463         while bufexists(versionedBufferName)
464                 let counter += 1
465                 let versionedBufferName = bufferName . ' (' . counter . ')'
466         endwhile
467         return versionedBufferName
468 endfunction
470 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
471 " Method of generating the name for VCS result buffers that uses the original
472 " file name with the VCS type and command appended as extensions.
474 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
475         let fileName = bufname(a:originalBuffer)
476         let bufferName = a:vcsType . ' ' . a:command
477         if strlen(a:statusText) > 0
478                 let bufferName .= ' ' . a:statusText
479         endif
480         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
481         let counter = 0
482         let versionedBufferName = bufferName
483         while bufexists(versionedBufferName)
484                 let counter += 1
485                 let versionedBufferName = '(' . counter . ') ' . bufferName
486         endwhile
487         return versionedBufferName
488 endfunction
490 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
491 " Creates a new buffer of the given name and associates it with the given
492 " original buffer.
494 function! s:EditFile(command, originalBuffer, statusText)
495         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
497         " Protect against useless buffer set-up
498         let s:isEditFileRunning += 1
499         try
500                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
501                 if editCommand == 'split'
502                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
503                                 rightbelow split
504                         else
505                                 vert rightbelow split
506                         endif
507                 endif
509                 enew
511                 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
513         finally
514                 let s:isEditFileRunning -= 1
515         endtry
516 endfunction
518 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
519 " Creates convenience buffer variables and the name of a vcscommand result
520 " buffer.
522 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
523         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
524         if nameExtension == ''
525                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
526         else
527                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
528         endif
530         let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
532         let b:VCSCommandCommand = a:command
533         let b:VCSCommandOriginalBuffer = a:originalBuffer
534         let b:VCSCommandSourceFile = bufname(a:originalBuffer)
535         let b:VCSCommandVCSType = a:vcsType
536         if a:statusText != ''
537                 let b:VCSCommandStatusText = a:statusText
538         endif
540         setlocal buftype=nofile
541         setlocal noswapfile
542         let &filetype = tolower(a:vcsType . a:command)
544         if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
545                 setlocal bufhidden=delete
546         endif
547         silent noautocmd file `=name`
548 endfunction
550 " Function: s:SetupBuffer() {{{2
551 " Attempts to set the b:VCSCommandBufferInfo variable
553 function! s:SetupBuffer()
554         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
555                 " This buffer is already set up.
556                 return
557         endif
559         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
560                 " No special status for special buffers other than directory buffers.
561                 return
562         endif
564         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
565                 unlet! b:VCSCommandBufferSetup
566                 return
567         endif
569         try
570                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
571                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
572                 silent do VCSCommand User VCSBufferSetup
573         catch /No suitable plugin/
574                 " This is not a VCS-controlled file.
575                 let b:VCSCommandBufferInfo = []
576         endtry
578         let b:VCSCommandBufferSetup = 1
579 endfunction
581 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
582 " Resets the buffer setup state of the original buffer for a given VCS scratch
583 " buffer.
584 " Returns:  The VCS buffer number in a passthrough mode.
586 function! s:MarkOrigBufferForSetup(buffer)
587         checktime
588         if a:buffer > 0
589                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
590                 " This should never not work, but I'm paranoid
591                 if origBuffer != a:buffer
592                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
593                 endif
594         endif
595         return a:buffer
596 endfunction
598 " Function: s:OverrideOption(option, [value]) {{{2
599 " Provides a temporary override for the given VCS option.  If no value is
600 " passed, the override is disabled.
602 function! s:OverrideOption(option, ...)
603         if a:0 == 0
604                 call remove(s:optionOverrides[a:option], -1)
605         else
606                 if !has_key(s:optionOverrides, a:option)
607                         let s:optionOverrides[a:option] = []
608                 endif
609                 call add(s:optionOverrides[a:option], a:1)
610         endif
611 endfunction
613 " Function: s:WipeoutCommandBuffers() {{{2
614 " Clears all current VCS output buffers of the specified type for a given source.
616 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
617         let buffer = 1
618         while buffer <= bufnr('$')
619                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
620                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
621                                 execute 'bw' buffer
622                         endif
623                 endif
624                 let buffer = buffer + 1
625         endwhile
626 endfunction
628 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
629 " Checks whether the given buffer is one whose deletion should trigger
630 " restoration of an original buffer after it was diffed.  If so, it executes
631 " the appropriate setting command stored with that original buffer.
633 function! s:VimDiffRestore(vimDiffBuff)
634         let s:isEditFileRunning += 1
635         try
636                 if exists('t:vcsCommandVimDiffSourceBuffer')
637                         if a:vimDiffBuff == t:vcsCommandVimDiffSourceBuffer
638                                 " Original file is being removed.
639                                 unlet! t:vcsCommandVimDiffSourceBuffer
640                                 unlet! t:vcsCommandVimDiffRestoreCmd
641                                 unlet! t:vcsCommandVimDiffScratchList
642                         else
643                                 let index = index(t:vcsCommandVimDiffScratchList, a:vimDiffBuff)
644                                 if index >= 0
645                                         call remove(t:vcsCommandVimDiffScratchList, index)
646                                         if len(t:vcsCommandVimDiffScratchList) == 0
647                                                 if exists('t:vcsCommandVimDiffRestoreCmd')
648                                                         " All scratch buffers are gone, reset the original.
649                                                         " Only restore if the source buffer is still in Diff mode
651                                                         let sourceWinNR = bufwinnr(t:vcsCommandVimDiffSourceBuffer)
652                                                         if sourceWinNR != -1
653                                                                 " The buffer is visible in at least one window
654                                                                 let currentWinNR = winnr()
655                                                                 while winbufnr(sourceWinNR) != -1
656                                                                         if winbufnr(sourceWinNR) == t:vcsCommandVimDiffSourceBuffer
657                                                                                 execute sourceWinNR . 'wincmd w'
658                                                                                 if getwinvar(0, '&diff')
659                                                                                         execute t:vcsCommandVimDiffRestoreCmd
660                                                                                 endif
661                                                                         endif
662                                                                         let sourceWinNR = sourceWinNR + 1
663                                                                 endwhile
664                                                                 execute currentWinNR . 'wincmd w'
665                                                         else
666                                                                 " The buffer is hidden.  It must be visible in order to set the
667                                                                 " diff option.
668                                                                 let currentBufNR = bufnr('')
669                                                                 execute 'hide buffer' t:vcsCommandVimDiffSourceBuffer
670                                                                 if getwinvar(0, '&diff')
671                                                                         execute t:vcsCommandVimDiffRestoreCmd
672                                                                 endif
673                                                                 execute 'hide buffer' currentBufNR
674                                                         endif
676                                                         unlet t:vcsCommandVimDiffRestoreCmd
677                                                 endif
678                                                 " All buffers are gone.
679                                                 unlet t:vcsCommandVimDiffSourceBuffer
680                                                 unlet t:vcsCommandVimDiffScratchList
681                                         endif
682                                 endif
683                         endif
684                 endif
685         finally
686                 let s:isEditFileRunning -= 1
687         endtry
688 endfunction
690 " Section: Generic VCS command functions {{{1
692 " Function: s:VCSAnnotate(...) {{{2
693 function! s:VCSAnnotate(bang, ...)
694         try
695                 let line = line('.')
696                 let currentBuffer = bufnr('%')
697                 let originalBuffer = VCSCommandGetOriginalBuffer(currentBuffer)
699                 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
700                 if annotateBuffer == -1
701                         return -1
702                 endif
703                 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
704                         let vcsType = VCSCommandGetVCSType(annotateBuffer)
705                         let functionMap = s:plugins[vcsType][1]
706                         let splitRegex = ''
707                         if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
708                                 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
709                         endif
710                         let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
711                         if splitRegex == ''
712                                 return annotateBuffer
713                         endif
714                         let originalFileType = getbufvar(originalBuffer, '&ft')
715                         let annotateFileType = getbufvar(annotateBuffer, '&ft')
716                         execute "normal 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
717                         call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
718                         set scrollbind
719                         leftabove vert new
720                         normal 0P
721                         execute "normal" . col('$') . "\<c-w>|"
722                         call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
723                         wincmd l
724                 endif
726                 if currentBuffer == originalBuffer
727                         " Starting from the original source buffer, so the
728                         " current line is relevant.
729                         if a:0 == 0
730                                 " No argument list means that we're annotating
731                                 " the current version, so jumping to the same
732                                 " line is the expected action.
733                                 execute "normal" line . 'G'
734                                 if has('folding')
735                                         " The execution of the buffer created autocommand
736                                         " re-folds the buffer.  Display the current line
737                                         " unfolded.
738                                         normal zv
739                                 endif
740                         endif
741                 endif
743                 return annotateBuffer
744         catch
745                 call s:ReportError(v:exception)
746                 return -1
747         endtry
748 endfunction
750 " Function: s:VCSCommit() {{{2
751 function! s:VCSCommit(bang, message)
752         try
753                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
754                 if !has_key(s:plugins, vcsType)
755                         throw 'Unknown VCS type:  ' . vcsType
756                 endif
758                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
760                 " Handle the commit message being specified.  If a message is supplied, it
761                 " is used; if bang is supplied, an empty message is used; otherwise, the
762                 " user is provided a buffer from which to edit the commit message.
764                 if strlen(a:message) > 0 || a:bang == '!'
765                         return s:VCSFinishCommit([a:message], originalBuffer)
766                 endif
768                 call s:EditFile('commitlog', originalBuffer, '')
769                 setlocal ft=vcscommit
771                 " Create a commit mapping.
773                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
775                 silent 0put ='VCS: ----------------------------------------------------------------------'
776                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
777                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
779                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
780                         setlocal buftype=acwrite
781                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
782                         silent put ='VCS: or write this buffer'
783                 endif
785                 silent put ='VCS: ----------------------------------------------------------------------'
786                 $
787                 setlocal nomodified
788                 silent do VCSCommand User VCSBufferCreated
789         catch
790                 call s:ReportError(v:exception)
791                 return -1
792         endtry
793 endfunction
795 " Function: s:VCSFinishCommitWithBuffer() {{{2
796 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
797 " which removes all lines starting with 'VCS:'.
799 function! s:VCSFinishCommitWithBuffer()
800         setlocal nomodified
801         let currentBuffer = bufnr('%')
802         let logMessageList = getbufline('%', 1, '$')
803         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
804         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
805         if resultBuffer >= 0
806                 execute 'bw' currentBuffer
807         endif
808         return resultBuffer
809 endfunction
811 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
812 function! s:VCSFinishCommit(logMessageList, originalBuffer)
813         let messageFileName = tempname()
814         call writefile(a:logMessageList, messageFileName)
815         try
816                 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
817                 if resultBuffer < 0
818                         return resultBuffer
819                 endif
820                 return s:MarkOrigBufferForSetup(resultBuffer)
821         finally
822                 call delete(messageFileName)
823         endtry
824 endfunction
826 " Function: s:VCSGotoOriginal(bang) {{{2
827 function! s:VCSGotoOriginal(bang)
828         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
829         if originalBuffer > 0
830                 let origWinNR = bufwinnr(originalBuffer)
831                 if origWinNR == -1
832                         execute 'buffer' originalBuffer
833                 else
834                         execute origWinNR . 'wincmd w'
835                 endif
836                 if a:bang == '!'
837                         let buffnr = 1
838                         let buffmaxnr = bufnr('$')
839                         while buffnr <= buffmaxnr
840                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
841                                         execute 'bw' buffnr
842                                 endif
843                                 let buffnr = buffnr + 1
844                         endwhile
845                 endif
846         endif
847 endfunction
849 function! s:VCSDiff(...)  "{{{2
850         let resultBuffer = s:ExecuteVCSCommand('Diff', a:000)
851         if resultBuffer > 0
852                 let &filetype = 'diff'
853         elseif resultBuffer == 0
854                 echomsg 'No differences found'
855         endif
856         return resultBuffer
857 endfunction
859 function! s:VCSReview(...)  "{{{2
860         let resultBuffer = s:ExecuteVCSCommand('Review', a:000)
861         if resultBuffer > 0
862                 let &filetype = getbufvar(b:VCSCommandOriginalBuffer, '&filetype')
863         endif
864         return resultBuffer
865 endfunction
867 " Function: s:VCSVimDiff(...) {{{2
868 function! s:VCSVimDiff(...)
869         try
870                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
871                 if !has_key(s:plugins, vcsType)
872                         throw 'Unknown VCS type:  ' . vcsType
873                 endif
874                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
875                 let s:isEditFileRunning = s:isEditFileRunning + 1
876                 try
877                         " If there's already a VimDiff'ed window, restore it.
878                         " There may only be one VCSVimDiff original window at a time.
880                         if exists('t:vcsCommandVimDiffSourceBuffer') && t:vcsCommandVimDiffSourceBuffer != originalBuffer
881                                 " Clear the existing vimdiff setup by removing the result buffers.
882                                 call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
883                         endif
885                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
886                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
887                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
889                         " Split and diff
890                         if(a:0 == 2)
891                                 " Reset the vimdiff system, as 2 explicit versions were provided.
892                                 if exists('t:vcsCommandVimDiffSourceBuffer')
893                                         call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
894                                 endif
895                                 let resultBuffer = s:VCSReview(a:1)
896                                 if resultBuffer < 0
897                                         echomsg 'Can''t open revision ' . a:1
898                                         return resultBuffer
899                                 endif
900                                 let b:VCSCommandCommand = 'vimdiff'
901                                 diffthis
902                                 let t:vcsCommandVimDiffScratchList = [resultBuffer]
903                                 " If no split method is defined, cheat, and set it to vertical.
904                                 try
905                                         call s:OverrideOption('VCSCommandSplit', orientation)
906                                         let resultBuffer = s:VCSReview(a:2)
907                                 finally
908                                         call s:OverrideOption('VCSCommandSplit')
909                                 endtry
910                                 if resultBuffer < 0
911                                         echomsg 'Can''t open revision ' . a:1
912                                         return resultBuffer
913                                 endif
914                                 let b:VCSCommandCommand = 'vimdiff'
915                                 diffthis
916                                 let t:vcsCommandVimDiffScratchList += [resultBuffer]
917                         else
918                                 " Add new buffer
919                                 call s:OverrideOption('VCSCommandEdit', 'split')
920                                 try
921                                         " Force splitting behavior, otherwise why use vimdiff?
922                                         call s:OverrideOption('VCSCommandSplit', orientation)
923                                         try
924                                                 if(a:0 == 0)
925                                                         let resultBuffer = s:VCSReview()
926                                                 else
927                                                         let resultBuffer = s:VCSReview(a:1)
928                                                 endif
929                                         finally
930                                                 call s:OverrideOption('VCSCommandSplit')
931                                         endtry
932                                 finally
933                                         call s:OverrideOption('VCSCommandEdit')
934                                 endtry
935                                 if resultBuffer < 0
936                                         echomsg 'Can''t open current revision'
937                                         return resultBuffer
938                                 endif
939                                 let b:VCSCommandCommand = 'vimdiff'
940                                 diffthis
942                                 if !exists('t:vcsCommandVimDiffSourceBuffer')
943                                         " New instance of vimdiff.
944                                         let t:vcsCommandVimDiffScratchList = [resultBuffer]
946                                         " This could have been invoked on a VCS result buffer, not the
947                                         " original buffer.
948                                         wincmd W
949                                         execute 'buffer' originalBuffer
950                                         " Store info for later original buffer restore
951                                         let t:vcsCommandVimDiffRestoreCmd =
952                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
953                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
954                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
955                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
956                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
957                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
958                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
959                                                                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
960                                         diffthis
961                                         wincmd w
962                                 else
963                                         " Adding a window to an existing vimdiff
964                                         let t:vcsCommandVimDiffScratchList += [resultBuffer]
965                                 endif
966                         endif
968                         let t:vcsCommandVimDiffSourceBuffer = originalBuffer
970                         " Avoid executing the modeline in the current buffer after the autocommand.
972                         let currentBuffer = bufnr('%')
973                         let saveModeline = getbufvar(currentBuffer, '&modeline')
974                         try
975                                 call setbufvar(currentBuffer, '&modeline', 0)
976                                 silent do VCSCommand User VCSVimDiffFinish
977                         finally
978                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
979                         endtry
980                         return resultBuffer
981                 finally
982                         let s:isEditFileRunning = s:isEditFileRunning - 1
983                 endtry
984         catch
985                 call s:ReportError(v:exception)
986                 return -1
987         endtry
988 endfunction
990 " Section: Public functions {{{1
992 " Function: VCSCommandGetVCSType() {{{2
993 " Sets the b:VCSCommandVCSType variable in the given buffer to the
994 " appropriate source control system name.
996 " This uses the Identify extension function to test the buffer.  If the
997 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
998 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
999 " match is considered inexact, and is only applied if no exact match is found.
1000 " Multiple inexact matches is currently considered an error.
1002 function! VCSCommandGetVCSType(buffer)
1003         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
1004         if strlen(vcsType) > 0
1005                 return vcsType
1006         endif
1007         if exists("g:VCSCommandVCSTypeOverride")
1008                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
1009                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
1010                         if match(fullpath, path) > -1
1011                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1012                                 return vcsType
1013                         endif
1014                 endfor
1015         endif
1016         let matches = []
1017         for vcsType in keys(s:plugins)
1018                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
1019                 if identified
1020                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
1021                                 let matches = [vcsType]
1022                                 break
1023                         else
1024                                 let matches += [vcsType]
1025                         endif
1026                 endif
1027         endfor
1028         if len(matches) == 1
1029                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
1030                 return matches[0]
1031         elseif len(matches) == 0
1032                 throw 'No suitable plugin'
1033         else
1034                 throw 'Too many matching VCS:  ' . join(matches)
1035         endif
1036 endfunction
1038 " Function: VCSCommandChdir(directory) {{{2
1039 " Changes the current directory, respecting :lcd changes.
1041 function! VCSCommandChdir(directory)
1042         let command = 'cd'
1043         if exists("*haslocaldir") && haslocaldir()
1044                 let command = 'lcd'
1045         endif
1046         execute command escape(a:directory, ' ')
1047 endfunction
1049 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1050 " Go to the directory in which the given file is located.
1052 function! VCSCommandChangeToCurrentFileDir(fileName)
1053         let oldCwd = getcwd()
1054         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1055         if strlen(newCwd) > 0
1056                 call VCSCommandChdir(newCwd)
1057         endif
1058         return oldCwd
1059 endfunction
1061 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1062 " Attempts to locate the original file to which VCS operations were applied
1063 " for a given buffer.
1065 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1066         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1067         if origBuffer
1068                 if bufexists(origBuffer)
1069                         return origBuffer
1070                 else
1071                         " Original buffer no longer exists.
1072                         throw 'Original buffer for this VCS buffer no longer exists.'
1073                 endif
1074         else
1075                 " No original buffer
1076                 return a:vcsBuffer
1077         endif
1078 endfunction
1080 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1081 " Allows VCS modules to register themselves.
1083 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1084         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1085         if !empty(a:mappingMap)
1086                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1087                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1088                 for shortcut in keys(a:mappingMap)
1089                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1090                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1091                 endfor
1092         endif
1093         return s:VCSCommandUtility
1094 endfunction
1096 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1097 " General skeleton for VCS function execution.  The given command is executed
1098 " after appending the current buffer name (or substituting it for
1099 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1100 " new buffer.
1102 " The optional 'options' Dictionary may contain the following options:
1103 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1104 "               non-zero exit status, the command is still considered
1105 "               successfuly.  This defaults to zero.
1106 " Returns: name of the new command buffer containing the command results
1108 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1109         let allowNonZeroExit = 0
1110         if has_key(a:options, 'allowNonZeroExit')
1111                 let allowNonZeroExit = a:options.allowNonZeroExit
1112         endif
1114         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1115         if originalBuffer == -1
1116                 throw 'Original buffer no longer exists, aborting.'
1117         endif
1119         let path = resolve(bufname(originalBuffer))
1121         " Work with netrw or other systems where a directory listing is displayed in
1122         " a buffer.
1124         if isdirectory(path)
1125                 let fileName = '.'
1126         else
1127                 let fileName = fnamemodify(path, ':t')
1128         endif
1130         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1131                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1132         else
1133                 let fullCmd = a:cmd . ' -- "' . fileName . '"'
1134         endif
1136         " Change to the directory of the current buffer.  This is done for CVS, but
1137         " is left in for other systems as it does not affect them negatively.
1139         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1140         try
1141                 let output = s:VCSCommandUtility.system(fullCmd)
1142         finally
1143                 call VCSCommandChdir(oldCwd)
1144         endtry
1146         " HACK:  if line endings in the repository have been corrupted, the output
1147         " of the command will be confused.
1148         let output = substitute(output, "\r", '', 'g')
1150         if v:shell_error && !allowNonZeroExit
1151                 if strlen(output) == 0
1152                         throw 'Version control command failed'
1153                 else
1154                         let output = substitute(output, '\n', '  ', 'g')
1155                         throw 'Version control command failed:  ' . output
1156                 endif
1157         endif
1159         if strlen(output) == 0
1160                 " Handle case of no output.  In this case, it is important to check the
1161                 " file status, especially since cvs edit/unedit may change the attributes
1162                 " of the file with no visible output.
1164                 checktime
1165                 return 0
1166         endif
1168         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1170         silent 0put=output
1172         " The last command left a blank line at the end of the buffer.  If the
1173         " last line is folded (a side effect of the 'put') then the attempt to
1174         " remove the blank line will kill the last fold.
1175         "
1176         " This could be fixed by explicitly detecting whether the last line is
1177         " within a fold, but I prefer to simply unfold the result buffer altogether.
1179         if has('folding')
1180                 normal zR
1181         endif
1183         $d
1184         1
1186         " Define the environment and execute user-defined hooks.
1188         silent do VCSCommand User VCSBufferCreated
1189         return bufnr('%')
1190 endfunction
1192 " Function: VCSCommandGetOption(name, default) {{{2
1193 " Grab a user-specified option to override the default provided.  Options are
1194 " searched in the window, buffer, then global spaces.
1196 function! VCSCommandGetOption(name, default)
1197         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1198                 return s:optionOverrides[a:name][-1]
1199         elseif exists('w:' . a:name)
1200                 return w:{a:name}
1201         elseif exists('b:' . a:name)
1202                 return b:{a:name}
1203         elseif exists('g:' . a:name)
1204                 return g:{a:name}
1205         else
1206                 return a:default
1207         endif
1208 endfunction
1210 " Function: VCSCommandDisableBufferSetup() {{{2
1211 " Global function for deactivating the buffer autovariables.
1213 function! VCSCommandDisableBufferSetup()
1214         let g:VCSCommandEnableBufferSetup = 0
1215         silent! augroup! VCSCommandPlugin
1216 endfunction
1218 " Function: VCSCommandEnableBufferSetup() {{{2
1219 " Global function for activating the buffer autovariables.
1221 function! VCSCommandEnableBufferSetup()
1222         let g:VCSCommandEnableBufferSetup = 1
1223         augroup VCSCommandPlugin
1224                 au!
1225                 au BufEnter * call s:SetupBuffer()
1226         augroup END
1228         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1229         " chance to run.
1230         if g:loaded_VCSCommand == 2
1231                 call s:SetupBuffer()
1232         endif
1233 endfunction
1235 " Function: VCSCommandGetStatusLine() {{{2
1236 " Default (sample) status line entry for VCS-controlled files.  This is only
1237 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1238 " variable for how to do this).
1240 function! VCSCommandGetStatusLine()
1241         if exists('b:VCSCommandCommand')
1242                 " This is a result buffer.  Return nothing because the buffer name
1243                 " contains information already.
1244                 return ''
1245         endif
1247         if exists('b:VCSCommandVCSType')
1248                                 \ && exists('g:VCSCommandEnableBufferSetup')
1249                                 \ && g:VCSCommandEnableBufferSetup
1250                                 \ && exists('b:VCSCommandBufferInfo')
1251                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1252         else
1253                 return ''
1254         endif
1255 endfunction
1257 " Section: Command definitions {{{1
1258 " Section: Primary commands {{{2
1259 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1260 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1261 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1262 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1263 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1264 com! -nargs=* VCSDiff call s:VCSDiff(<f-args>)
1265 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1266 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1267 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1268 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1269 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1270 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1271 com! -nargs=? VCSReview call s:VCSReview(<f-args>)
1272 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1273 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1274 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1275 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1277 " Section: VCS buffer management commands {{{2
1278 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1279 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1281 " Allow reloading VCSCommand.vim
1282 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
1284 " Section: Plugin command mappings {{{1
1285 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1286 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1287 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1288 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1289 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1290 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1291 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1292 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1293 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1294 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1295 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1296 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1297 nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1298 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1299 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1300 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1301 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1303 " Section: Default mappings {{{1
1305 let s:defaultMappings = [
1306                         \['a', 'VCSAdd'],
1307                         \['c', 'VCSCommit'],
1308                         \['D', 'VCSDelete'],
1309                         \['d', 'VCSDiff'],
1310                         \['G', 'VCSClearAndGotoOriginal'],
1311                         \['g', 'VCSGotoOriginal'],
1312                         \['i', 'VCSInfo'],
1313                         \['L', 'VCSLock'],
1314                         \['l', 'VCSLog'],
1315                         \['N', 'VCSSplitAnnotate'],
1316                         \['n', 'VCSAnnotate'],
1317                         \['q', 'VCSRevert'],
1318                         \['r', 'VCSReview'],
1319                         \['s', 'VCSStatus'],
1320                         \['U', 'VCSUnlock'],
1321                         \['u', 'VCSUpdate'],
1322                         \['v', 'VCSVimDiff'],
1323                         \]
1325 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1326         for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1327                 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1328         endfor
1329 endif
1331 " Section: Menu items {{{1
1332 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1333 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1334 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1335 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1336 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1337 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1338 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1339 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1340 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1341 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1342 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1343 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1345 " Section: Autocommands to restore vimdiff state {{{1
1346 augroup VimDiffRestore
1347         au!
1348         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1349 augroup END
1351 " Section: Optional activation of buffer management {{{1
1353 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1354         call VCSCommandEnableBufferSetup()
1355 endif
1357 " Section: VIM shutdown hook {{{1
1359 " Close all result buffers when VIM exits, to prevent them from being restored
1360 " via viminfo.
1362 " Function: s:CloseAllResultBuffers() {{{2
1363 " Closes all vcscommand result buffers.
1364 function! s:CloseAllResultBuffers()
1365         " This avoids using bufdo as that may load buffers already loaded in another
1366         " vim process, resulting in an error.
1367         let buffnr = 1
1368         let buffmaxnr = bufnr('$')
1369         while buffnr <= buffmaxnr
1370                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1371                         execute 'bw' buffnr
1372                 endif
1373                 let buffnr = buffnr + 1
1374         endwhile
1375 endfunction
1377 augroup VCSCommandVIMShutdown
1378         au!
1379         au VimLeavePre * call s:CloseAllResultBuffers()
1380 augroup END
1382 " Section: Plugin completion {{{1
1384 let loaded_VCSCommand = 2
1386 silent do VCSCommand User VCSPluginFinish
1388 let &cpo = s:save_cpo