use case-insenstive operator instead of altering comparands
[vcscommand.git] / plugin / vcscommand.vim
blob0e7ccca35727a5b34a02887b0f3f05014a669bbc
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 " VCSCommandDisableMenu
208 "   This variable, if set to a non-zero value, prevents the default command
209 "   menu from being set.
211 " VCSCommandEdit
212 "   This variable controls whether to split the current window to display a
213 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
214 "   If not set, it defaults to 'split'.
216 " VCSCommandEnableBufferSetup
217 "   This variable, if set to a non-zero value, activates VCS buffer management
218 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
219 "   the file is VCS-controlled.  This is useful for displaying version
220 "   information in the status bar.  Additional options may be set by
221 "   individual VCS plugins.
223 " VCSCommandMappings
224 "   This variable, if set, overrides the default mappings used for shortcuts.
225 "   It should be a List of 2-element Lists, each containing a shortcut and
226 "   function name pair.
228 " VCSCommandMapPrefix
229 "   This variable, if set, overrides the default mapping prefix ('<Leader>c').
230 "   This allows customization of the mapping space used by the vcscommand
231 "   shortcuts.
233 " VCSCommandMenuPriority
234 "   This variable, if set, overrides the default menu priority '' (empty)
236 " VCSCommandMenuRoot
237 "   This variable, if set, overrides the default menu root 'Plugin.VCS'
239 " VCSCommandResultBufferNameExtension
240 "   This variable, if set to a non-blank value, is appended to the name of the
241 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
242 "   help avoid problems caused by autocommands dependent on file extension.
244 " VCSCommandResultBufferNameFunction
245 "   This variable, if set, specifies a custom function for naming VCS command
246 "   output buffers.  This function will be passed the following arguments:
248 "   command - name of the VCS command being executed (such as 'Log' or
249 "   'Diff').
251 "   originalBuffer - buffer number of the source file.
253 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
255 "   statusText - extra text associated with the VCS action (such as version
256 "   numbers).
258 " VCSCommandSplit
259 "   This variable controls the orientation of the various window splits that
260 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
261 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
262 "   If set to 'horizontal', the resulting windows will be on stacked on top of
263 "   one another.  If set to 'vertical', the resulting windows will be
264 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
265 "   VCSVimDiff windows.
267 " VCSCommandVCSTypeOverride
268 "   This variable allows the VCS type detection to be overridden on a
269 "   path-by-path basis.  The value of this variable is expected to be a List
270 "   of Lists.  Each high-level List item is a List containing two elements.
271 "   The first element is a regular expression that will be matched against the
272 "   full file name of a given buffer.  If it matches, the second element will
273 "   be used as the VCS type.
275 " VCSCommandVCSTypePreference
276 "   This variable allows the VCS type detection to be weighted towards
277 "   a specific VCS, in case more than one potential VCS is detected as useable.
278 "   The format of the variable is a string containing the abbreviations of the
279 "   preferred VCS types, separated by spaces. eg: 'git bzr cvs'. When there is
280 "   ambiguity as to which VCS should be used.
282 " Event documentation {{{2
283 "   For additional customization, VCSCommand.vim uses User event autocommand
284 "   hooks.  Each event is in the VCSCommand group, and different patterns
285 "   match the various hooks.
287 "   For instance, the following could be added to the vimrc to provide a 'q'
288 "   mapping to quit a VCS scratch buffer:
290 "   augroup VCSCommand
291 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
292 "   augroup END
294 "   The following hooks are available:
296 "   VCSBufferCreated           This event is fired just after a VCS command
297 "                              output buffer is created.  It is executed
298 "                              within the context of the new buffer.
300 "   VCSBufferSetup             This event is fired just after VCS buffer setup
301 "                              occurs, if enabled.
303 "   VCSPluginInit              This event is fired when the VCSCommand plugin
304 "                              first loads.
306 "   VCSPluginFinish            This event is fired just after the VCSCommand
307 "                              plugin loads.
309 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
310 "                              command executes to allow customization of,
311 "                              for instance, window placement and focus.
313 " Section: Plugin header {{{1
315 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
316 " completes.  This allows various actions to only be taken by functions after
317 " system initialization.
319 if exists('VCSCommandDisableAll')
320         finish
321 endif
323 if exists('loaded_VCSCommand')
324         finish
325 endif
326 let loaded_VCSCommand = 1
328 if v:version < 700
329         echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
330         finish
331 endif
333 let s:save_cpo=&cpo
334 set cpo&vim
336 " Section: Event group setup {{{1
338 augroup VCSCommand
339 augroup END
341 augroup VCSCommandCommit
342 augroup END
344 " Section: Plugin initialization {{{1
345 silent do VCSCommand User VCSPluginInit
347 " Section: Constants declaration {{{1
349 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
350 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
352 " Section: Script variable initialization {{{1
354 " Hidden functions for use by extensions
355 let s:VCSCommandUtility = {}
357 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
358 let s:plugins = {}
360 " temporary values of overridden configuration variables
361 let s:optionOverrides = {}
363 " state flag used to vary behavior of certain automated actions
364 let s:isEditFileRunning = 0
366 " Section: Utility functions {{{1
368 " Function: s:ReportError(mapping) {{{2
369 " Displays the given error in a consistent faction.  This is intended to be
370 " invoked from a catch statement.
372 function! s:ReportError(error)
373         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
374 endfunction
376 " Function: s:VCSCommandUtility.system(...) {{{2
377 " Replacement for system() function.  This version protects the quoting in the
378 " command line on Windows systems.
380 function! s:VCSCommandUtility.system(...)
381         if (has("win32") || has("win64")) && &sxq !~ '"'
382                 let save_sxq = &sxq
383                 set sxq=\"
384         endif
385         try
386                 if exists('*iconv')
387                         return iconv(call('system', a:000), &tenc, &enc)
388                 endif
389                 return call('system', a:000)
390         finally
391                 if exists("save_sxq")
392                         let &sxq = save_sxq
393                 endif
394         endtry
395 endfunction
397 " Function: s:VCSCommandUtility.addMenuItem(shortcut, command) {{{2
398 " Adds the given menu item.
400 function! s:VCSCommandUtility.addMenuItem(shortcut, command)
401         if s:menuEnabled
402             exe 'amenu <silent> '.s:menuPriority.' '.s:menuRoot.'.'.a:shortcut.' '.a:command
403         endif
404 endfunction
406 " Function: s:ClearMenu() {{{2
407 " Removes all VCSCommand menu items
408 function! s:ClearMenu()
409         if s:menuEnabled
410                 execute 'aunmenu' s:menuRoot
411         endif
412 endfunction
414 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
415 " Creates the given mapping by prepending the contents of
416 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
417 " mapping it to the given plugin function.  If a mapping exists for the
418 " specified shortcut + prefix, emit an error but continue.  If a mapping
419 " exists for the specified function, do nothing.
421 function! s:CreateMapping(shortcut, expansion, display)
422         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
423         if !hasmapto(a:expansion)
424                 try
425                         execute 'nmap <silent> <unique>' lhs a:expansion
426                 catch /^Vim(.*):E227:/
427                         if(&verbose != 0)
428                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
429                         endif
430                 endtry
431         endif
432 endfunction
434 " Function: s:ExecuteExtensionMapping(mapping) {{{2
435 " Invokes the appropriate extension mapping depending on the type of the
436 " current buffer.
438 function! s:ExecuteExtensionMapping(mapping)
439         let buffer = bufnr('%')
440         let vcsType = VCSCommandGetVCSType(buffer)
441         if !has_key(s:plugins, vcsType)
442                 throw 'Unknown VCS type:  ' . vcsType
443         endif
444         if !has_key(s:plugins[vcsType][2], a:mapping)
445                 throw 'This extended mapping is not defined for ' . vcsType
446         endif
447         silent execute 'normal!' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
448 endfunction
450 " Function: s:ExecuteVCSCommand(command, argList) {{{2
451 " Calls the indicated plugin-specific VCS command on the current buffer.
452 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
453 " occurs.
455 function! s:ExecuteVCSCommand(command, argList)
456         try
457                 let buffer = bufnr('%')
459                 let vcsType = VCSCommandGetVCSType(buffer)
460                 if !has_key(s:plugins, vcsType)
461                         throw 'Unknown VCS type:  ' . vcsType
462                 endif
464                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
465                 let bufferName = bufname(originalBuffer)
467                 " It is already known that the directory is under VCS control.  No further
468                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
469                 " VCS-specific error messages from confusing things.
470                 if !isdirectory(bufferName)
471                         if !filereadable(bufferName)
472                                 throw 'No such file ' . bufferName
473                         endif
474                 endif
476                 let functionMap = s:plugins[vcsType][1]
477                 if !has_key(functionMap, a:command)
478                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
479                 endif
480                 return functionMap[a:command](a:argList)
481         catch
482                 call s:ReportError(v:exception)
483                 return -1
484         endtry
485 endfunction
487 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
488 " Default method of generating the name for VCS result buffers.  This can be
489 " overridden with the VCSResultBufferNameFunction variable.
491 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
492         let fileName = bufname(a:originalBuffer)
493         let bufferName = a:vcsType . ' ' . a:command
494         if strlen(a:statusText) > 0
495                 let bufferName .= ' ' . a:statusText
496         endif
497         let bufferName .= ' ' . fileName
498         let counter = 0
499         let versionedBufferName = bufferName
500         while bufexists(versionedBufferName)
501                 let counter += 1
502                 let versionedBufferName = bufferName . ' (' . counter . ')'
503         endwhile
504         return versionedBufferName
505 endfunction
507 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
508 " Method of generating the name for VCS result buffers that uses the original
509 " file name with the VCS type and command appended as extensions.
511 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
512         let fileName = bufname(a:originalBuffer)
513         let bufferName = a:vcsType . ' ' . a:command
514         if strlen(a:statusText) > 0
515                 let bufferName .= ' ' . a:statusText
516         endif
517         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
518         let counter = 0
519         let versionedBufferName = bufferName
520         while bufexists(versionedBufferName)
521                 let counter += 1
522                 let versionedBufferName = '(' . counter . ') ' . bufferName
523         endwhile
524         return versionedBufferName
525 endfunction
527 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
528 " Creates a new buffer of the given name and associates it with the given
529 " original buffer.
531 function! s:EditFile(command, originalBuffer, statusText)
532         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
534         " Protect against useless buffer set-up
535         let s:isEditFileRunning += 1
536         try
537                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
538                 if editCommand == 'split'
539                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
540                                 rightbelow split
541                         else
542                                 vert rightbelow split
543                         endif
544                 endif
546                 enew
548                 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
550         finally
551                 let s:isEditFileRunning -= 1
552         endtry
553 endfunction
555 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
556 " Creates convenience buffer variables and the name of a vcscommand result
557 " buffer.
559 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
560         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
561         if nameExtension == ''
562                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
563         else
564                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
565         endif
567         let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
569         let b:VCSCommandCommand = a:command
570         let b:VCSCommandOriginalBuffer = a:originalBuffer
571         let b:VCSCommandSourceFile = bufname(a:originalBuffer)
572         let b:VCSCommandVCSType = a:vcsType
573         if a:statusText != ''
574                 let b:VCSCommandStatusText = a:statusText
575         endif
577         setlocal buftype=nofile
578         setlocal noswapfile
579         let &filetype = tolower(a:vcsType . a:command)
581         if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
582                 setlocal bufhidden=delete
583         endif
584         silent noautocmd file `=name`
585 endfunction
587 " Function: s:SetupBuffer() {{{2
588 " Attempts to set the b:VCSCommandBufferInfo variable
590 function! s:SetupBuffer()
591         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
592                 " This buffer is already set up.
593                 return
594         endif
596         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
597                 " No special status for special buffers other than directory buffers.
598                 return
599         endif
601         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
602                 unlet! b:VCSCommandBufferSetup
603                 return
604         endif
606         try
607                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
608                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
609                 silent do VCSCommand User VCSBufferSetup
610         catch /No suitable plugin/
611                 " This is not a VCS-controlled file.
612                 let b:VCSCommandBufferInfo = []
613         endtry
615         let b:VCSCommandBufferSetup = 1
616 endfunction
618 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
619 " Resets the buffer setup state of the original buffer for a given VCS scratch
620 " buffer.
621 " Returns:  The VCS buffer number in a passthrough mode.
623 function! s:MarkOrigBufferForSetup(buffer)
624         checktime
625         if a:buffer > 0
626                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
627                 " This should never not work, but I'm paranoid
628                 if origBuffer != a:buffer
629                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
630                 endif
631         endif
632         return a:buffer
633 endfunction
635 " Function: s:OverrideOption(option, [value]) {{{2
636 " Provides a temporary override for the given VCS option.  If no value is
637 " passed, the override is disabled.
639 function! s:OverrideOption(option, ...)
640         if a:0 == 0
641                 call remove(s:optionOverrides[a:option], -1)
642         else
643                 if !has_key(s:optionOverrides, a:option)
644                         let s:optionOverrides[a:option] = []
645                 endif
646                 call add(s:optionOverrides[a:option], a:1)
647         endif
648 endfunction
650 " Function: s:WipeoutCommandBuffers() {{{2
651 " Clears all current VCS output buffers of the specified type for a given source.
653 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
654         let buffer = 1
655         while buffer <= bufnr('$')
656                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
657                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
658                                 execute 'bw' buffer
659                         endif
660                 endif
661                 let buffer = buffer + 1
662         endwhile
663 endfunction
665 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
666 " Checks whether the given buffer is one whose deletion should trigger
667 " restoration of an original buffer after it was diffed.  If so, it executes
668 " the appropriate setting command stored with that original buffer.
670 function! s:VimDiffRestore(vimDiffBuff)
671         let s:isEditFileRunning += 1
672         try
673                 if exists('t:vcsCommandVimDiffSourceBuffer')
674                         if a:vimDiffBuff == t:vcsCommandVimDiffSourceBuffer
675                                 " Original file is being removed.
676                                 unlet! t:vcsCommandVimDiffSourceBuffer
677                                 unlet! t:vcsCommandVimDiffRestoreCmd
678                                 unlet! t:vcsCommandVimDiffScratchList
679                         else
680                                 let index = index(t:vcsCommandVimDiffScratchList, a:vimDiffBuff)
681                                 if index >= 0
682                                         call remove(t:vcsCommandVimDiffScratchList, index)
683                                         if len(t:vcsCommandVimDiffScratchList) == 0
684                                                 if exists('t:vcsCommandVimDiffRestoreCmd')
685                                                         " All scratch buffers are gone, reset the original.
686                                                         " Only restore if the source buffer is still in Diff mode
688                                                         let sourceWinNR = bufwinnr(t:vcsCommandVimDiffSourceBuffer)
689                                                         if sourceWinNR != -1
690                                                                 " The buffer is visible in at least one window
691                                                                 let currentWinNR = winnr()
692                                                                 while winbufnr(sourceWinNR) != -1
693                                                                         if winbufnr(sourceWinNR) == t:vcsCommandVimDiffSourceBuffer
694                                                                                 execute sourceWinNR . 'wincmd w'
695                                                                                 if getwinvar(0, '&diff')
696                                                                                         execute t:vcsCommandVimDiffRestoreCmd
697                                                                                 endif
698                                                                         endif
699                                                                         let sourceWinNR = sourceWinNR + 1
700                                                                 endwhile
701                                                                 execute currentWinNR . 'wincmd w'
702                                                         else
703                                                                 " The buffer is hidden.  It must be visible in order to set the
704                                                                 " diff option.
705                                                                 let currentBufNR = bufnr('')
706                                                                 execute 'hide buffer' t:vcsCommandVimDiffSourceBuffer
707                                                                 if getwinvar(0, '&diff')
708                                                                         execute t:vcsCommandVimDiffRestoreCmd
709                                                                 endif
710                                                                 execute 'hide buffer' currentBufNR
711                                                         endif
713                                                         unlet t:vcsCommandVimDiffRestoreCmd
714                                                 endif
715                                                 " All buffers are gone.
716                                                 unlet t:vcsCommandVimDiffSourceBuffer
717                                                 unlet t:vcsCommandVimDiffScratchList
718                                         endif
719                                 endif
720                         endif
721                 endif
722         finally
723                 let s:isEditFileRunning -= 1
724         endtry
725 endfunction
727 " Section: Generic VCS command functions {{{1
729 " Function: s:VCSAnnotate(...) {{{2
730 function! s:VCSAnnotate(bang, ...)
731         try
732                 let line = line('.')
733                 let currentBuffer = bufnr('%')
734                 let originalBuffer = VCSCommandGetOriginalBuffer(currentBuffer)
736                 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
737                 if annotateBuffer == -1
738                         return -1
739                 endif
740                 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
741                         let vcsType = VCSCommandGetVCSType(annotateBuffer)
742                         let functionMap = s:plugins[vcsType][1]
743                         let splitRegex = ''
744                         if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
745                                 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
746                         endif
747                         let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
748                         if splitRegex == ''
749                                 return annotateBuffer
750                         endif
751                         let originalFileType = getbufvar(originalBuffer, '&ft')
752                         let annotateFileType = getbufvar(annotateBuffer, '&ft')
753                         execute "normal! 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
754                         call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
755                         set scrollbind
756                         leftabove vert new
757                         normal! 0P
758                         execute "normal!" . (col('$') + (&number ? &numberwidth : 0)). "\<c-w>|"
759                         call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
760                         wincmd l
761                 endif
763                 if currentBuffer == originalBuffer
764                         " Starting from the original source buffer, so the
765                         " current line is relevant.
766                         if a:0 == 0
767                                 " No argument list means that we're annotating
768                                 " the current version, so jumping to the same
769                                 " line is the expected action.
770                                 execute "normal!" line . 'G'
771                                 if has('folding')
772                                         " The execution of the buffer created autocommand
773                                         " re-folds the buffer.  Display the current line
774                                         " unfolded.
775                                         normal! zv
776                                 endif
777                         endif
778                 endif
780                 return annotateBuffer
781         catch
782                 call s:ReportError(v:exception)
783                 return -1
784         endtry
785 endfunction
787 " Function: s:VCSCommit() {{{2
788 function! s:VCSCommit(bang, message)
789         try
790                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
791                 if !has_key(s:plugins, vcsType)
792                         throw 'Unknown VCS type:  ' . vcsType
793                 endif
795                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
797                 " Handle the commit message being specified.  If a message is supplied, it
798                 " is used; if bang is supplied, an empty message is used; otherwise, the
799                 " user is provided a buffer from which to edit the commit message.
801                 if strlen(a:message) > 0 || a:bang == '!'
802                         return s:VCSFinishCommit([a:message], originalBuffer)
803                 endif
805                 call s:EditFile('commitlog', originalBuffer, '')
806                 setlocal ft=vcscommit
808                 " Create a commit mapping.
810                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
812                 silent 0put ='VCS: ----------------------------------------------------------------------'
813                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
814                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
816                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
817                         setlocal buftype=acwrite
818                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
819                         silent put ='VCS: or write this buffer'
820                 endif
822                 silent put ='VCS: ----------------------------------------------------------------------'
823                 $
824                 setlocal nomodified
825                 silent do VCSCommand User VCSBufferCreated
826         catch
827                 call s:ReportError(v:exception)
828                 return -1
829         endtry
830 endfunction
832 " Function: s:VCSFinishCommitWithBuffer() {{{2
833 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
834 " which removes all lines starting with 'VCS:'.
836 function! s:VCSFinishCommitWithBuffer()
837         setlocal nomodified
838         let currentBuffer = bufnr('%')
839         let logMessageList = getbufline('%', 1, '$')
840         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
841         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
842         if resultBuffer >= 0
843                 execute 'bw' currentBuffer
844         endif
845         return resultBuffer
846 endfunction
848 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
849 function! s:VCSFinishCommit(logMessageList, originalBuffer)
850         let messageFileName = tempname()
851         call writefile(a:logMessageList, messageFileName)
852         try
853                 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
854                 if resultBuffer < 0
855                         return resultBuffer
856                 endif
857                 return s:MarkOrigBufferForSetup(resultBuffer)
858         finally
859                 call delete(messageFileName)
860         endtry
861 endfunction
863 " Function: s:VCSGotoOriginal(bang) {{{2
864 function! s:VCSGotoOriginal(bang)
865         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
866         if originalBuffer > 0
867                 let origWinNR = bufwinnr(originalBuffer)
868                 if origWinNR == -1
869                         execute 'buffer' originalBuffer
870                 else
871                         execute origWinNR . 'wincmd w'
872                 endif
873                 if a:bang == '!'
874                         let buffnr = 1
875                         let buffmaxnr = bufnr('$')
876                         while buffnr <= buffmaxnr
877                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
878                                         execute 'bw' buffnr
879                                 endif
880                                 let buffnr = buffnr + 1
881                         endwhile
882                 endif
883         endif
884 endfunction
886 function! s:VCSDiff(...)  "{{{2
887         let resultBuffer = s:ExecuteVCSCommand('Diff', a:000)
888         if resultBuffer > 0
889                 let &filetype = 'diff'
890         elseif resultBuffer == 0
891                 echomsg 'No differences found'
892         endif
893         return resultBuffer
894 endfunction
896 function! s:VCSReview(...)  "{{{2
897         let resultBuffer = s:ExecuteVCSCommand('Review', a:000)
898         if resultBuffer > 0
899                 let &filetype = getbufvar(b:VCSCommandOriginalBuffer, '&filetype')
900         endif
901         return resultBuffer
902 endfunction
904 " Function: s:VCSVimDiff(...) {{{2
905 function! s:VCSVimDiff(...)
906         try
907                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
908                 if !has_key(s:plugins, vcsType)
909                         throw 'Unknown VCS type:  ' . vcsType
910                 endif
911                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
912                 let s:isEditFileRunning = s:isEditFileRunning + 1
913                 try
914                         " If there's already a VimDiff'ed window, restore it.
915                         " There may only be one VCSVimDiff original window at a time.
917                         if exists('t:vcsCommandVimDiffSourceBuffer') && t:vcsCommandVimDiffSourceBuffer != originalBuffer
918                                 " Clear the existing vimdiff setup by removing the result buffers.
919                                 call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
920                         endif
922                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
923                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
924                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
926                         " Split and diff
927                         if(a:0 == 2)
928                                 " Reset the vimdiff system, as 2 explicit versions were provided.
929                                 if exists('t:vcsCommandVimDiffSourceBuffer')
930                                         call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
931                                 endif
932                                 let resultBuffer = s:VCSReview(a:1)
933                                 if resultBuffer < 0
934                                         echomsg 'Can''t open revision ' . a:1
935                                         return resultBuffer
936                                 endif
937                                 let b:VCSCommandCommand = 'vimdiff'
938                                 diffthis
939                                 let t:vcsCommandVimDiffScratchList = [resultBuffer]
940                                 " If no split method is defined, cheat, and set it to vertical.
941                                 try
942                                         call s:OverrideOption('VCSCommandSplit', orientation)
943                                         let resultBuffer = s:VCSReview(a:2)
944                                 finally
945                                         call s:OverrideOption('VCSCommandSplit')
946                                 endtry
947                                 if resultBuffer < 0
948                                         echomsg 'Can''t open revision ' . a:1
949                                         return resultBuffer
950                                 endif
951                                 let b:VCSCommandCommand = 'vimdiff'
952                                 diffthis
953                                 let t:vcsCommandVimDiffScratchList += [resultBuffer]
954                         else
955                                 " Add new buffer
956                                 call s:OverrideOption('VCSCommandEdit', 'split')
957                                 try
958                                         " Force splitting behavior, otherwise why use vimdiff?
959                                         call s:OverrideOption('VCSCommandSplit', orientation)
960                                         try
961                                                 if(a:0 == 0)
962                                                         let resultBuffer = s:VCSReview()
963                                                 else
964                                                         let resultBuffer = s:VCSReview(a:1)
965                                                 endif
966                                         finally
967                                                 call s:OverrideOption('VCSCommandSplit')
968                                         endtry
969                                 finally
970                                         call s:OverrideOption('VCSCommandEdit')
971                                 endtry
972                                 if resultBuffer < 0
973                                         echomsg 'Can''t open current revision'
974                                         return resultBuffer
975                                 endif
976                                 let b:VCSCommandCommand = 'vimdiff'
977                                 diffthis
979                                 if !exists('t:vcsCommandVimDiffSourceBuffer')
980                                         " New instance of vimdiff.
981                                         let t:vcsCommandVimDiffScratchList = [resultBuffer]
983                                         " This could have been invoked on a VCS result buffer, not the
984                                         " original buffer.
985                                         wincmd W
986                                         execute 'buffer' originalBuffer
987                                         " Store info for later original buffer restore
988                                         let t:vcsCommandVimDiffRestoreCmd =
989                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
990                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
991                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
992                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
993                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
994                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
995                                                                 \ . '|call setbufvar('.originalBuffer.', ''&cursorbind'', '.getbufvar(originalBuffer, '&cursorbind').')'
996                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
997                                                                 \ . '|if &foldmethod==''manual''|execute ''normal! zE''|endif'
998                                         diffthis
999                                         wincmd w
1000                                 else
1001                                         " Adding a window to an existing vimdiff
1002                                         let t:vcsCommandVimDiffScratchList += [resultBuffer]
1003                                 endif
1004                         endif
1006                         let t:vcsCommandVimDiffSourceBuffer = originalBuffer
1008                         " Avoid executing the modeline in the current buffer after the autocommand.
1010                         let currentBuffer = bufnr('%')
1011                         let saveModeline = getbufvar(currentBuffer, '&modeline')
1012                         try
1013                                 call setbufvar(currentBuffer, '&modeline', 0)
1014                                 silent do VCSCommand User VCSVimDiffFinish
1015                         finally
1016                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
1017                         endtry
1018                         return resultBuffer
1019                 finally
1020                         let s:isEditFileRunning = s:isEditFileRunning - 1
1021                 endtry
1022         catch
1023                 call s:ReportError(v:exception)
1024                 return -1
1025         endtry
1026 endfunction
1028 " Section: Public functions {{{1
1030 " Function: VCSCommandGetVCSType() {{{2
1031 " Sets the b:VCSCommandVCSType variable in the given buffer to the
1032 " appropriate source control system name.
1034 " This uses the Identify extension function to test the buffer.  If the
1035 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
1036 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
1037 " match is considered inexact, and is only applied if no exact match is found.
1038 " Multiple inexact matches is currently considered an error.
1040 function! VCSCommandGetVCSType(buffer)
1041         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
1042         if strlen(vcsType) > 0
1043                 return vcsType
1044         endif
1045         if exists("g:VCSCommandVCSTypeOverride")
1046                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
1047                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
1048                         if match(fullpath, path) > -1
1049                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1050                                 return vcsType
1051                         endif
1052                 endfor
1053         endif
1054         let matches = []
1055         for vcsType in keys(s:plugins)
1056                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
1057                 if identified
1058                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
1059                                 let matches = [vcsType]
1060                                 break
1061                         else
1062                                 let matches += [vcsType]
1063                         endif
1064                 endif
1065         endfor
1066         if len(matches) == 1
1067                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
1068                 return matches[0]
1069         elseif len(matches) == 0
1070                 throw 'No suitable plugin'
1071         else
1072                 let preferences = VCSCommandGetOption("VCSCommandVCSTypePreference", "")
1073                 if len(preferences) > 0
1074                         for preferred in split(preferences, '\W\+')
1075                                 for vcsType in matches
1076                                         if vcsType ==? preferred
1077                                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1078                                                 return vcsType
1079                                         endif
1080                                 endfor
1081                         endfor
1082                 endif
1083                 throw 'Too many matching VCS:  ' . join(matches)
1084         endif
1085 endfunction
1087 " Function: VCSCommandChdir(directory) {{{2
1088 " Changes the current directory, respecting :lcd changes.
1090 function! VCSCommandChdir(directory)
1091         let command = 'cd'
1092         if exists("*haslocaldir") && haslocaldir()
1093                 let command = 'lcd'
1094         endif
1095         if exists("*fnameescape")
1096                 execute command fnameescape(a:directory)
1097         else
1098                 execute command escape(a:directory, ' ')
1099         endif
1100 endfunction
1102 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1103 " Go to the directory in which the given file is located.
1105 function! VCSCommandChangeToCurrentFileDir(fileName)
1106         let oldCwd = getcwd()
1107         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1108         if strlen(newCwd) > 0
1109                 call VCSCommandChdir(newCwd)
1110         endif
1111         return oldCwd
1112 endfunction
1114 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1115 " Attempts to locate the original file to which VCS operations were applied
1116 " for a given buffer.
1118 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1119         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1120         if origBuffer
1121                 if bufexists(origBuffer)
1122                         return origBuffer
1123                 else
1124                         " Original buffer no longer exists.
1125                         throw 'Original buffer for this VCS buffer no longer exists.'
1126                 endif
1127         else
1128                 " No original buffer
1129                 return a:vcsBuffer
1130         endif
1131 endfunction
1133 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1134 " Allows VCS modules to register themselves.
1136 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1137         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1138         if !empty(a:mappingMap)
1139                                 \ && !exists("g:no_plugin_maps")
1140                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1141                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1142                 for shortcut in keys(a:mappingMap)
1143                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1144                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1145                 endfor
1146         endif
1147         return s:VCSCommandUtility
1148 endfunction
1150 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1151 " General skeleton for VCS function execution.  The given command is executed
1152 " after appending the current buffer name (or substituting it for
1153 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1154 " new buffer.
1156 " The optional 'options' Dictionary may contain the following options:
1157 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1158 "               non-zero exit status, the command is still considered
1159 "               successfuly.  This defaults to zero.
1160 " Returns: name of the new command buffer containing the command results
1162 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1163         let allowNonZeroExit = 0
1164         if has_key(a:options, 'allowNonZeroExit')
1165                 let allowNonZeroExit = a:options.allowNonZeroExit
1166         endif
1168         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1169         if originalBuffer == -1
1170                 throw 'Original buffer no longer exists, aborting.'
1171         endif
1173         let path = resolve(bufname(originalBuffer))
1175         " Work with netrw or other systems where a directory listing is displayed in
1176         " a buffer.
1178         if isdirectory(path)
1179                 let fileName = '.'
1180         else
1181                 let fileName = fnamemodify(path, ':t')
1182         endif
1184         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1185                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1186         else
1187                 let fullCmd = a:cmd . ' -- ' . shellescape(fileName)
1188         endif
1190         " Change to the directory of the current buffer.  This is done for CVS, but
1191         " is left in for other systems as it does not affect them negatively.
1193         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1194         try
1195                 let output = s:VCSCommandUtility.system(fullCmd)
1196         finally
1197                 call VCSCommandChdir(oldCwd)
1198         endtry
1200         " HACK:  if line endings in the repository have been corrupted, the output
1201         " of the command will be confused.
1202         let output = substitute(output, "\r", '', 'g')
1204         if v:shell_error && !allowNonZeroExit
1205                 if strlen(output) == 0
1206                         throw 'Version control command failed'
1207                 else
1208                         let output = substitute(output, '\n', '  ', 'g')
1209                         throw 'Version control command failed:  ' . output
1210                 endif
1211         endif
1213         if strlen(output) == 0
1214                 " Handle case of no output.  In this case, it is important to check the
1215                 " file status, especially since cvs edit/unedit may change the attributes
1216                 " of the file with no visible output.
1218                 checktime
1219                 return 0
1220         endif
1222         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1224         silent 0put=output
1226         " The last command left a blank line at the end of the buffer.  If the
1227         " last line is folded (a side effect of the 'put') then the attempt to
1228         " remove the blank line will kill the last fold.
1229         "
1230         " This could be fixed by explicitly detecting whether the last line is
1231         " within a fold, but I prefer to simply unfold the result buffer altogether.
1233         if has('folding')
1234                 normal! zR
1235         endif
1237         $d
1238         1
1240         " Define the environment and execute user-defined hooks.
1242         silent do VCSCommand User VCSBufferCreated
1243         return bufnr('%')
1244 endfunction
1246 " Function: VCSCommandGetOption(name, default) {{{2
1247 " Grab a user-specified option to override the default provided.  Options are
1248 " searched in the window, buffer, then global spaces.
1250 function! VCSCommandGetOption(name, default)
1251         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1252                 return s:optionOverrides[a:name][-1]
1253         elseif exists('w:' . a:name)
1254                 return w:{a:name}
1255         elseif exists('b:' . a:name)
1256                 return b:{a:name}
1257         elseif exists('g:' . a:name)
1258                 return g:{a:name}
1259         else
1260                 return a:default
1261         endif
1262 endfunction
1264 " Function: VCSCommandDisableBufferSetup() {{{2
1265 " Global function for deactivating the buffer autovariables.
1267 function! VCSCommandDisableBufferSetup()
1268         let g:VCSCommandEnableBufferSetup = 0
1269         silent! augroup! VCSCommandPlugin
1270 endfunction
1272 " Function: VCSCommandEnableBufferSetup() {{{2
1273 " Global function for activating the buffer autovariables.
1275 function! VCSCommandEnableBufferSetup()
1276         let g:VCSCommandEnableBufferSetup = 1
1277         augroup VCSCommandPlugin
1278                 au!
1279                 au BufEnter * call s:SetupBuffer()
1280         augroup END
1282         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1283         " chance to run.
1284         if g:loaded_VCSCommand == 2
1285                 call s:SetupBuffer()
1286         endif
1287 endfunction
1289 " Function: VCSCommandGetStatusLine() {{{2
1290 " Default (sample) status line entry for VCS-controlled files.  This is only
1291 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1292 " variable for how to do this).
1294 function! VCSCommandGetStatusLine()
1295         if exists('b:VCSCommandCommand')
1296                 " This is a result buffer.  Return nothing because the buffer name
1297                 " contains information already.
1298                 return ''
1299         endif
1301         if exists('b:VCSCommandVCSType')
1302                                 \ && exists('g:VCSCommandEnableBufferSetup')
1303                                 \ && g:VCSCommandEnableBufferSetup
1304                                 \ && exists('b:VCSCommandBufferInfo')
1305                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1306         else
1307                 return ''
1308         endif
1309 endfunction
1311 function! VCSCommandSetVCSType(type)
1312         if exists('b:VCSCommandBufferSetup')
1313                 unlet b:VCSCommandBufferSetup
1314         endif
1315         let b:VCSCommandVCSType = a:type
1316         call s:SetupBuffer()
1317 endfunction
1319 " Section: Command definitions {{{1
1320 " Section: Primary commands {{{2
1321 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1322 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1323 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1324 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1325 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1326 com! -nargs=* VCSDiff call s:VCSDiff(<f-args>)
1327 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1328 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1329 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1330 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1331 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1332 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1333 com! -nargs=? VCSReview call s:VCSReview(<f-args>)
1334 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1335 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1336 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1337 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1339 " Section: VCS buffer management commands {{{2
1340 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1341 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1343 " Allow reloading VCSCommand.vim
1344 com! VCSReload let savedPlugins = s:plugins|let s:plugins = {}|call s:ClearMenu()|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for plugin in values(savedPlugins)|execute 'source' plugin[0]|endfor|unlet savedPlugins
1346 " Section: Plugin command mappings {{{1
1347 if !exists("no_plugin_maps")
1348         nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1349         nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1350         nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1351         nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1352         nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1353         nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1354         nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1355         nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1356         nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1357         nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1358         nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1359         nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1360         nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1361         nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1362         nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1363         nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1364         nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1365 endif
1367 " Section: Default mappings {{{1
1369 let s:defaultMappings = [
1370                         \['a', 'VCSAdd'],
1371                         \['c', 'VCSCommit'],
1372                         \['D', 'VCSDelete'],
1373                         \['d', 'VCSDiff'],
1374                         \['G', 'VCSClearAndGotoOriginal'],
1375                         \['g', 'VCSGotoOriginal'],
1376                         \['i', 'VCSInfo'],
1377                         \['L', 'VCSLock'],
1378                         \['l', 'VCSLog'],
1379                         \['N', 'VCSSplitAnnotate'],
1380                         \['n', 'VCSAnnotate'],
1381                         \['q', 'VCSRevert'],
1382                         \['r', 'VCSReview'],
1383                         \['s', 'VCSStatus'],
1384                         \['U', 'VCSUnlock'],
1385                         \['u', 'VCSUpdate'],
1386                         \['v', 'VCSVimDiff'],
1387                         \]
1389 if !exists("g:no_plugin_maps") && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1390         for [s:shortcut, s:vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1391                 call s:CreateMapping(s:shortcut, '<Plug>' . s:vcsFunction, '''' . s:vcsFunction . '''')
1392         endfor
1393         unlet s:shortcut s:vcsFunction
1394 endif
1395 unlet s:defaultMappings
1397 " Section: Menu items {{{1
1399 let s:menuEnabled = !VCSCommandGetOption('VCSCommandDisableMenu', 0)
1400 let s:menuRoot = VCSCommandGetOption('VCSCommandMenuRoot', '&Plugin.VCS')
1401 let s:menuPriority = VCSCommandGetOption('VCSCommandMenuPriority', '')
1403 for [s:shortcut, s:command] in [
1404                         \['&Add', '<Plug>VCSAdd'],
1405                         \['A&nnotate', '<Plug>VCSAnnotate'],
1406                         \['&Commit', '<Plug>VCSCommit'],
1407                         \['Delete', '<Plug>VCSDelete'],
1408                         \['&Diff', '<Plug>VCSDiff'],
1409                         \['&Info', '<Plug>VCSInfo'],
1410                         \['&Log', '<Plug>VCSLog'],
1411                         \['Revert', '<Plug>VCSRevert'],
1412                         \['&Review', '<Plug>VCSReview'],
1413                         \['&Status', '<Plug>VCSStatus'],
1414                         \['&Update', '<Plug>VCSUpdate'],
1415                         \['&VimDiff', '<Plug>VCSVimDiff']
1416                         \]
1417         call s:VCSCommandUtility.addMenuItem(s:shortcut, s:command)
1418 endfor
1419 unlet s:shortcut s:command
1421 " Section: Autocommands to restore vimdiff state {{{1
1422 augroup VimDiffRestore
1423         au!
1424         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1425 augroup END
1427 " Section: Optional activation of buffer management {{{1
1429 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1430         call VCSCommandEnableBufferSetup()
1431 endif
1433 " Section: VIM shutdown hook {{{1
1435 " Close all result buffers when VIM exits, to prevent them from being restored
1436 " via viminfo.
1438 " Function: s:CloseAllResultBuffers() {{{2
1439 " Closes all vcscommand result buffers.
1440 function! s:CloseAllResultBuffers()
1441         " This avoids using bufdo as that may load buffers already loaded in another
1442         " vim process, resulting in an error.
1443         let buffnr = 1
1444         let buffmaxnr = bufnr('$')
1445         while buffnr <= buffmaxnr
1446                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1447                         execute 'bw' buffnr
1448                 endif
1449                 let buffnr = buffnr + 1
1450         endwhile
1451 endfunction
1453 augroup VCSCommandVIMShutdown
1454         au!
1455         au VimLeavePre * call s:CloseAllResultBuffers()
1456 augroup END
1458 " Section: Plugin completion {{{1
1460 let loaded_VCSCommand = 2
1462 silent do VCSCommand User VCSPluginFinish
1464 let &cpo = s:save_cpo