e88e3afb3b8d61d90b84e630cafd1b2b16d6e87e
[vcscommand.git] / plugin / vcscommand.vim
blobe88e3afb3b8d61d90b84e630cafd1b2b16d6e87e
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 a
277 "   specific VCS, in case more than one potential VCS is detected as useable.
278 "   The format of the variable is either a list or a space-separated string
279 "   containing the ordered-by-preference abbreviations of the preferred VCS
280 "   types.
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 " Stack of dictionaries representing nested options
361 let s:executionContext = []
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         let output = call('system', a:000)
382         if exists('*iconv') && has('multi_byte')
383                 if(strlen(&tenc) && &tenc != &enc)
384                         let output = iconv(output, &tenc, &enc)
385                 else
386                         let originalBuffer = VCSCommandGetOriginalBuffer(VCSCommandGetOption('VCSCommandEncodeAsFile', 0))
387                         if originalBuffer
388                                 let fenc = getbufvar(originalBuffer, '&fenc')
389                                 if fenc != &enc
390                                         let output = iconv(output, fenc, &enc)
391                                 endif
392                         endif
393                 endif
395         endif
396         return output
397 endfunction
399 " Function: s:VCSCommandUtility.addMenuItem(shortcut, command) {{{2
400 " Adds the given menu item.
402 function! s:VCSCommandUtility.addMenuItem(shortcut, command)
403         if s:menuEnabled
404             exe 'amenu <silent> '.s:menuPriority.' '.s:menuRoot.'.'.a:shortcut.' '.a:command
405         endif
406 endfunction
408 " Function: s:VCSCommandUtility.pushContext(context) {{{2
409 " Adds a dictionary containing current options to the stack.
411 function! s:VCSCommandUtility.pushContext(context)
412         call insert(s:executionContext, a:context)
413 endfunction
415 " Function: s:VCSCommandUtility.popContext() {{{2
416 " Removes a dictionary containing current options from the stack.
418 function! s:VCSCommandUtility.popContext()
419         call remove(s:executionContext, 0)
420 endfunction
422 " Function: s:ClearMenu() {{{2
423 " Removes all VCSCommand menu items
424 function! s:ClearMenu()
425         if s:menuEnabled
426                 execute 'aunmenu' s:menuRoot
427         endif
428 endfunction
430 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
431 " Creates the given mapping by prepending the contents of
432 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
433 " mapping it to the given plugin function.  If a mapping exists for the
434 " specified shortcut + prefix, emit an error but continue.  If a mapping
435 " exists for the specified function, do nothing.
437 function! s:CreateMapping(shortcut, expansion, display)
438         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
439         if !hasmapto(a:expansion)
440                 try
441                         execute 'nmap <silent> <unique>' lhs a:expansion
442                 catch /^Vim(.*):E227:/
443                         if(&verbose != 0)
444                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
445                         endif
446                 endtry
447         endif
448 endfunction
450 " Function: s:ExecuteExtensionMapping(mapping) {{{2
451 " Invokes the appropriate extension mapping depending on the type of the
452 " current buffer.
454 function! s:ExecuteExtensionMapping(mapping)
455         let buffer = bufnr('%')
456         let vcsType = VCSCommandGetVCSType(buffer)
457         if !has_key(s:plugins, vcsType)
458                 throw 'Unknown VCS type:  ' . vcsType
459         endif
460         if !has_key(s:plugins[vcsType][2], a:mapping)
461                 throw 'This extended mapping is not defined for ' . vcsType
462         endif
463         silent execute 'normal!' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
464 endfunction
466 " Function: s:ExecuteVCSCommand(command, argList) {{{2
467 " Calls the indicated plugin-specific VCS command on the current buffer.
468 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
469 " occurs.
471 function! s:ExecuteVCSCommand(command, argList)
472         try
473                 let buffer = bufnr('%')
475                 let vcsType = VCSCommandGetVCSType(buffer)
476                 if !has_key(s:plugins, vcsType)
477                         throw 'Unknown VCS type:  ' . vcsType
478                 endif
480                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
481                 let bufferName = bufname(originalBuffer)
483                 " It is already known that the directory is under VCS control.  No further
484                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
485                 " VCS-specific error messages from confusing things.
486                 if !isdirectory(bufferName)
487                         if !filereadable(bufferName)
488                                 throw 'No such file ' . bufferName
489                         endif
490                 endif
492                 let functionMap = s:plugins[vcsType][1]
493                 if !has_key(functionMap, a:command)
494                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
495                 endif
496                 return functionMap[a:command](a:argList)
497         catch
498                 call s:ReportError(v:exception)
499                 return -1
500         endtry
501 endfunction
503 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
504 " Default method of generating the name for VCS result buffers.  This can be
505 " overridden with the VCSResultBufferNameFunction variable.
507 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
508         let fileName = bufname(a:originalBuffer)
509         let bufferName = a:vcsType . ' ' . a:command
510         if strlen(a:statusText) > 0
511                 let bufferName .= ' ' . a:statusText
512         endif
513         let bufferName .= ' ' . fileName
514         let counter = 0
515         let versionedBufferName = bufferName
516         while bufexists(versionedBufferName)
517                 let counter += 1
518                 let versionedBufferName = bufferName . ' (' . counter . ')'
519         endwhile
520         return versionedBufferName
521 endfunction
523 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
524 " Method of generating the name for VCS result buffers that uses the original
525 " file name with the VCS type and command appended as extensions.
527 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
528         let fileName = bufname(a:originalBuffer)
529         let bufferName = a:vcsType . ' ' . a:command
530         if strlen(a:statusText) > 0
531                 let bufferName .= ' ' . a:statusText
532         endif
533         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
534         let counter = 0
535         let versionedBufferName = bufferName
536         while bufexists(versionedBufferName)
537                 let counter += 1
538                 let versionedBufferName = '(' . counter . ') ' . bufferName
539         endwhile
540         return versionedBufferName
541 endfunction
543 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
544 " Creates a new buffer of the given name and associates it with the given
545 " original buffer.
547 function! s:EditFile(command, originalBuffer, statusText)
548         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
550         " Protect against useless buffer set-up
551         let s:isEditFileRunning += 1
552         try
553                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
554                 if editCommand == 'split'
555                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
556                                 rightbelow split
557                         else
558                                 vert rightbelow split
559                         endif
560                 endif
562                 enew
564                 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
566         finally
567                 let s:isEditFileRunning -= 1
568         endtry
569 endfunction
571 " Function:  s:IdentifyVCSType() {{{2
572 " This function implements the non-cached identification strategy for
573 " VcsCommandGetVCSType().
575 " Returns:  VCS type name identified for the given buffer; an exception is
576 " thrown in case no type can be identified.
578 function!  s:IdentifyVCSType(buffer)
579         if exists("g:VCSCommandVCSTypeOverride")
580                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
581                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
582                         if match(fullpath, path) > -1
583                                 return vcsType
584                         endif
585                 endfor
586         endif
587         let matches = []
588         let exactMatch = ''
589         let exactMatchCount = 0
590         for vcsType in keys(s:plugins)
591                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
592                 if identified
593                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
594                                 let exactMatch = vcsType
595                                 let exactMatchCount += 1
596                         endif
597                         call add(matches, [vcsType, identified])
598                 endif
599         endfor
600         if len(matches) == 1
601                 return matches[0][0]
602         elseif len(matches) == 0
603                 throw 'No suitable plugin'
604         else
605                 let preferences = VCSCommandGetOption("VCSCommandVCSTypePreference", [])
606                 if len(preferences) > 0
607                         if type(preferences) == 1
608                                 let listPreferences = split(preferences, '\W\+')
609                                 unlet preferences
610                                 let preferences = listPreferences
611                         endif
612                         for preferred in preferences
613                                 for [vcsType, identified] in matches
614                                         if vcsType ==? preferred
615                                                 return vcsType
616                                         endif
617                                 endfor
618                         endfor
619                 endif
621                 if exactMatchCount == 1
622                         return exactMatch
623                 endif
625                 throw 'can''t identify VCS type for current buffer due to too many matching VCS:  ' . join(map(matches, 'v:val[0]'))
626         endif
627 endfunction
629 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
630 " Creates convenience buffer variables and the name of a vcscommand result
631 " buffer.
633 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
634         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
635         if nameExtension == ''
636                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
637         else
638                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
639         endif
641         let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
643         let b:VCSCommandCommand = a:command
644         let b:VCSCommandOriginalBuffer = a:originalBuffer
645         let b:VCSCommandSourceFile = bufname(a:originalBuffer)
646         let b:VCSCommandVCSType = a:vcsType
647         if a:statusText != ''
648                 let b:VCSCommandStatusText = a:statusText
649         endif
651         setlocal buftype=nofile
652         setlocal noswapfile
653         let &filetype = tolower(a:vcsType . a:command)
655         if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
656                 setlocal bufhidden=delete
657         endif
658         silent noautocmd file `=name`
659 endfunction
661 " Function: s:SetupBuffer() {{{2
662 " Attempts to set the b:VCSCommandBufferInfo variable
664 function! s:SetupBuffer()
665         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
666                 " This buffer is already set up.
667                 return
668         endif
670         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
671                 " No special status for special buffers other than directory buffers.
672                 return
673         endif
675         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
676                 unlet! b:VCSCommandBufferSetup
677                 return
678         endif
680         try
681                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
682                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
683                 silent do VCSCommand User VCSBufferSetup
684         catch /No suitable plugin/
685                 " This is not a VCS-controlled file.
686                 let b:VCSCommandBufferInfo = []
687         endtry
689         let b:VCSCommandBufferSetup = 1
690 endfunction
692 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
693 " Resets the buffer setup state of the original buffer for a given VCS scratch
694 " buffer.
695 " Returns:  The VCS buffer number in a passthrough mode.
697 function! s:MarkOrigBufferForSetup(buffer)
698         checktime
699         if a:buffer > 0
700                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
701                 " This should never not work, but I'm paranoid
702                 if origBuffer != a:buffer
703                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
704                 endif
705         endif
706         return a:buffer
707 endfunction
709 " Function: s:WipeoutCommandBuffers() {{{2
710 " Clears all current VCS output buffers of the specified type for a given source.
712 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
713         let buffer = 1
714         while buffer <= bufnr('$')
715                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
716                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
717                                 execute 'bw' buffer
718                         endif
719                 endif
720                 let buffer = buffer + 1
721         endwhile
722 endfunction
724 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
725 " Checks whether the given buffer is one whose deletion should trigger
726 " restoration of an original buffer after it was diffed.  If so, it executes
727 " the appropriate setting command stored with that original buffer.
729 function! s:VimDiffRestore(vimDiffBuff)
730         let s:isEditFileRunning += 1
731         try
732                 if exists('t:vcsCommandVimDiffSourceBuffer')
733                         if a:vimDiffBuff == t:vcsCommandVimDiffSourceBuffer
734                                 " Original file is being removed.
735                                 unlet! t:vcsCommandVimDiffSourceBuffer
736                                 unlet! t:vcsCommandVimDiffRestoreCmd
737                                 unlet! t:vcsCommandVimDiffScratchList
738                         else
739                                 let index = index(t:vcsCommandVimDiffScratchList, a:vimDiffBuff)
740                                 if index >= 0
741                                         call remove(t:vcsCommandVimDiffScratchList, index)
742                                         if len(t:vcsCommandVimDiffScratchList) == 0
743                                                 if exists('t:vcsCommandVimDiffRestoreCmd')
744                                                         " All scratch buffers are gone, reset the original.
745                                                         " Only restore if the source buffer is still in Diff mode
747                                                         let sourceWinNR = bufwinnr(t:vcsCommandVimDiffSourceBuffer)
748                                                         if sourceWinNR != -1
749                                                                 " The buffer is visible in at least one window
750                                                                 let currentWinNR = winnr()
751                                                                 while winbufnr(sourceWinNR) != -1
752                                                                         if winbufnr(sourceWinNR) == t:vcsCommandVimDiffSourceBuffer
753                                                                                 execute sourceWinNR . 'wincmd w'
754                                                                                 if getwinvar(0, '&diff')
755                                                                                         execute t:vcsCommandVimDiffRestoreCmd
756                                                                                 endif
757                                                                         endif
758                                                                         let sourceWinNR = sourceWinNR + 1
759                                                                 endwhile
760                                                                 execute currentWinNR . 'wincmd w'
761                                                         else
762                                                                 " The buffer is hidden.  It must be visible in order to set the
763                                                                 " diff option.
764                                                                 let currentBufNR = bufnr('')
765                                                                 execute 'hide buffer' t:vcsCommandVimDiffSourceBuffer
766                                                                 if getwinvar(0, '&diff')
767                                                                         execute t:vcsCommandVimDiffRestoreCmd
768                                                                 endif
769                                                                 execute 'hide buffer' currentBufNR
770                                                         endif
772                                                         unlet t:vcsCommandVimDiffRestoreCmd
773                                                 endif
774                                                 " All buffers are gone.
775                                                 unlet t:vcsCommandVimDiffSourceBuffer
776                                                 unlet t:vcsCommandVimDiffScratchList
777                                         endif
778                                 endif
779                         endif
780                 endif
781         finally
782                 let s:isEditFileRunning -= 1
783         endtry
784 endfunction
786 " Section: Generic VCS command functions {{{1
788 " Function: s:VCSAnnotate(...) {{{2
789 function! s:VCSAnnotate(bang, ...)
790         call s:VCSCommandUtility.pushContext({'VCSCommandEncodeAsFile': bufnr('%')})
791         try
792                 let line = line('.')
793                 let currentBuffer = bufnr('%')
794                 let originalBuffer = VCSCommandGetOriginalBuffer(currentBuffer)
796                 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
797                 if annotateBuffer == -1
798                         return -1
799                 endif
800                 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
801                         let vcsType = VCSCommandGetVCSType(annotateBuffer)
802                         let functionMap = s:plugins[vcsType][1]
803                         let splitRegex = ''
804                         if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
805                                 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
806                         endif
807                         let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
808                         if splitRegex == ''
809                                 return annotateBuffer
810                         endif
811                         wincmd J
812                         let originalFileType = getbufvar(originalBuffer, '&ft')
813                         let annotateFileType = getbufvar(annotateBuffer, '&ft')
815                         let saveselection = &selection
816                         set selection=inclusive
817                         try
818                                 execute "normal! 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
819                         finally
820                                 let &selection = saveselection
821                         endtry
823                         call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
824                         set scrollbind
825                         leftabove vert new
826                         normal! 0P
827                         execute "normal!" . (col('$') + (&number ? &numberwidth : 0)). "\<c-w>|"
828                         call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
829                         wincmd l
830                 endif
832                 if currentBuffer == originalBuffer
833                         " Starting from the original source buffer, so the
834                         " current line is relevant.
835                         if a:0 == 0
836                                 " No argument list means that we're annotating
837                                 " the current version, so jumping to the same
838                                 " line is the expected action.
839                                 execute "normal!" line . 'G'
840                                 if has('folding')
841                                         " The execution of the buffer created autocommand
842                                         " re-folds the buffer.  Display the current line
843                                         " unfolded.
844                                         normal! zv
845                                 endif
846                         endif
847                 endif
849                 return annotateBuffer
850         catch
851                 call s:ReportError(v:exception)
852                 return -1
853         finally
854                 call s:VCSCommandUtility.popContext()
855         endtry
856 endfunction
858 " Function: s:VCSCommit() {{{2
859 function! s:VCSCommit(bang, message)
860         try
861                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
862                 if !has_key(s:plugins, vcsType)
863                         throw 'Unknown VCS type:  ' . vcsType
864                 endif
866                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
868                 " Handle the commit message being specified.  If a message is supplied, it
869                 " is used; if bang is supplied, an empty message is used; otherwise, the
870                 " user is provided a buffer from which to edit the commit message.
872                 if strlen(a:message) > 0 || a:bang == '!'
873                         return s:VCSFinishCommit([a:message], originalBuffer)
874                 endif
876                 call s:EditFile('commitlog', originalBuffer, '')
877                 setlocal ft=vcscommit
879                 " Create a commit mapping.
881                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
883                 silent 0put ='VCS: ----------------------------------------------------------------------'
884                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
885                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
887                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
888                         setlocal buftype=acwrite
889                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
890                         silent put ='VCS: or write this buffer'
891                 endif
893                 silent put ='VCS: ----------------------------------------------------------------------'
894                 $
895                 setlocal nomodified
896                 silent do VCSCommand User VCSBufferCreated
897         catch
898                 call s:ReportError(v:exception)
899                 return -1
900         endtry
901 endfunction
903 " Function: s:VCSFinishCommitWithBuffer() {{{2
904 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
905 " which removes all lines starting with 'VCS:'.
907 function! s:VCSFinishCommitWithBuffer()
908         setlocal nomodified
909         let currentBuffer = bufnr('%')
910         let logMessageList = getbufline('%', 1, '$')
911         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
912         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
913         if resultBuffer >= 0
914                 execute 'bw' currentBuffer
915         endif
916         return resultBuffer
917 endfunction
919 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
920 function! s:VCSFinishCommit(logMessageList, originalBuffer)
921         let messageFileName = tempname()
922         if exists('*iconv') && has('multi_byte')
923                 if(strlen(&tenc) && &tenc != &enc)
924                         call map(a:logMessageList, 'iconv(v:val, &enc, &tenc)')
925                 endif
926         endif
927         call writefile(a:logMessageList, messageFileName)
928         try
929                 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
930                 if resultBuffer < 0
931                         return resultBuffer
932                 endif
933                 return s:MarkOrigBufferForSetup(resultBuffer)
934         finally
935                 call delete(messageFileName)
936         endtry
937 endfunction
939 " Function: s:VCSGotoOriginal(bang) {{{2
940 function! s:VCSGotoOriginal(bang)
941         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
942         if originalBuffer > 0
943                 let origWinNR = bufwinnr(originalBuffer)
944                 if origWinNR == -1
945                         execute 'buffer' originalBuffer
946                 else
947                         execute origWinNR . 'wincmd w'
948                 endif
949                 if a:bang == '!'
950                         let buffnr = 1
951                         let buffmaxnr = bufnr('$')
952                         while buffnr <= buffmaxnr
953                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
954                                         execute 'bw' buffnr
955                                 endif
956                                 let buffnr = buffnr + 1
957                         endwhile
958                 endif
959         endif
960 endfunction
962 function! s:VCSDiff(...)  "{{{2
963         call s:VCSCommandUtility.pushContext({'VCSCommandEncodeAsFile': bufnr('%')})
964         try
965                 let resultBuffer = s:ExecuteVCSCommand('Diff', a:000)
966                 if resultBuffer > 0
967                         let &filetype = 'diff'
968                 elseif resultBuffer == 0
969                         echomsg 'No differences found'
970                 endif
971                 return resultBuffer
972         finally
973                 call s:VCSCommandUtility.popContext()
974         endtry
975 endfunction
977 function! s:VCSReview(...)  "{{{2
978         call s:VCSCommandUtility.pushContext({'VCSCommandEncodeAsFile': bufnr('%')})
979         try
980                 let resultBuffer = s:ExecuteVCSCommand('Review', a:000)
981                 if resultBuffer > 0
982                         let &filetype = getbufvar(b:VCSCommandOriginalBuffer, '&filetype')
983                 endif
984                 return resultBuffer
985         finally
986                 call s:VCSCommandUtility.popContext()
987         endtry
988 endfunction
990 " Function: s:VCSVimDiff(...) {{{2
991 function! s:VCSVimDiff(...)
992         try
993                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
994                 if !has_key(s:plugins, vcsType)
995                         throw 'Unknown VCS type:  ' . vcsType
996                 endif
997                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
998                 let s:isEditFileRunning = s:isEditFileRunning + 1
999                 try
1000                         " If there's already a VimDiff'ed window, restore it.
1001                         " There may only be one VCSVimDiff original window at a time.
1003                         if exists('t:vcsCommandVimDiffSourceBuffer') && t:vcsCommandVimDiffSourceBuffer != originalBuffer
1004                                 " Clear the existing vimdiff setup by removing the result buffers.
1005                                 call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
1006                         endif
1008                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
1009                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
1010                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
1012                         " Split and diff
1013                         if(a:0 == 2)
1014                                 " Reset the vimdiff system, as 2 explicit versions were provided.
1015                                 if exists('t:vcsCommandVimDiffSourceBuffer')
1016                                         call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
1017                                 endif
1018                                 let resultBuffer = s:VCSReview(a:1)
1019                                 if resultBuffer < 0
1020                                         echomsg 'Can''t open revision ' . a:1
1021                                         return resultBuffer
1022                                 endif
1023                                 let b:VCSCommandCommand = 'vimdiff'
1024                                 diffthis
1025                                 let t:vcsCommandVimDiffScratchList = [resultBuffer]
1026                                 " If no split method is defined, cheat, and set it to vertical.
1027                                 call s:VCSCommandUtility.pushContext({'VCSCommandSplit': orientation})
1028                                 try
1029                                         let resultBuffer = s:VCSReview(a:2)
1030                                 finally
1031                                         call s:VCSCommandUtility.popContext()
1032                                 endtry
1033                                 if resultBuffer < 0
1034                                         echomsg 'Can''t open revision ' . a:1
1035                                         return resultBuffer
1036                                 endif
1037                                 let b:VCSCommandCommand = 'vimdiff'
1038                                 diffthis
1039                                 let t:vcsCommandVimDiffScratchList += [resultBuffer]
1040                         else
1041                                 " Add new buffer.  Force splitting behavior, otherwise why use vimdiff?
1042                                 call s:VCSCommandUtility.pushContext({'VCSCommandEdit': 'split', 'VCSCommandSplit': orientation})
1043                                 try
1044                                         if(a:0 == 0)
1045                                                 let resultBuffer = s:VCSReview()
1046                                         else
1047                                                 let resultBuffer = s:VCSReview(a:1)
1048                                         endif
1049                                 finally
1050                                         call s:VCSCommandUtility.popContext()
1051                                 endtry
1052                                 if resultBuffer < 0
1053                                         echomsg 'Can''t open current revision'
1054                                         return resultBuffer
1055                                 endif
1056                                 let b:VCSCommandCommand = 'vimdiff'
1057                                 diffthis
1059                                 if !exists('t:vcsCommandVimDiffSourceBuffer')
1060                                         " New instance of vimdiff.
1061                                         let t:vcsCommandVimDiffScratchList = [resultBuffer]
1063                                         " This could have been invoked on a VCS result buffer, not the
1064                                         " original buffer.
1065                                         wincmd W
1066                                         execute 'buffer' originalBuffer
1067                                         " Store info for later original buffer restore
1068                                         let t:vcsCommandVimDiffRestoreCmd =
1069                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
1070                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
1071                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
1072                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
1073                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
1074                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
1075                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
1076                                         if has('cursorbind')
1077                                                 let t:vcsCommandVimDiffRestoreCmd .= '|call setbufvar('.originalBuffer.', ''&cursorbind'', '.getbufvar(originalBuffer, '&cursorbind').')'
1078                                         endif
1079                                         let t:vcsCommandVimDiffRestoreCmd .= '|if &foldmethod==''manual''|execute ''normal! zE''|endif'
1080                                         diffthis
1081                                         wincmd w
1082                                 else
1083                                         " Adding a window to an existing vimdiff
1084                                         let t:vcsCommandVimDiffScratchList += [resultBuffer]
1085                                 endif
1086                         endif
1088                         let t:vcsCommandVimDiffSourceBuffer = originalBuffer
1090                         " Avoid executing the modeline in the current buffer after the autocommand.
1092                         let currentBuffer = bufnr('%')
1093                         let saveModeline = getbufvar(currentBuffer, '&modeline')
1094                         try
1095                                 call setbufvar(currentBuffer, '&modeline', 0)
1096                                 silent do VCSCommand User VCSVimDiffFinish
1097                         finally
1098                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
1099                         endtry
1100                         return resultBuffer
1101                 finally
1102                         let s:isEditFileRunning = s:isEditFileRunning - 1
1103                 endtry
1104         catch
1105                 call s:ReportError(v:exception)
1106                 return -1
1107         endtry
1108 endfunction
1110 " Section: Public functions {{{1
1112 " Function: VCSCommandGetVCSType() {{{2
1113 " This function sets the b:VCSCommandVCSType variable in the given buffer to the
1114 " appropriate source control system name and returns the same name.
1116 " Returns:  VCS type name identified for the given buffer.  An exception is
1117 " thrown if no type can be identified.
1119 " Rules for determining type:
1120 "   1. use previously-cached value
1121 "   2. use value from 'VCSCommandVCSTypeOverride'
1122 "   3. use single match 
1123 "   4. use first matching value from 'VCSCommandTypePreference'
1124 "   5. use single exact match
1125 "   6. error if multiple matching types
1126 "   7. error if no matching types
1128 function! VCSCommandGetVCSType(buffer)
1129         let vcsType = VCSCommandGetOption('VCSCommandVCSTypeExplicitOverride', '')
1130         if len(vcsType) == 0
1131                 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
1132                 if strlen(vcsType) == 0
1133                         let vcsType = s:IdentifyVCSType(a:buffer)
1134                         call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1135                 endif
1136         endif
1137         return vcsType
1138 endfunction
1140 " Function: VCSCommandChdir(directory) {{{2
1141 " Changes the current directory, respecting :lcd changes.
1143 function! VCSCommandChdir(directory)
1144         let command = 'cd'
1145         if exists("*haslocaldir") && haslocaldir()
1146                 let command = 'lcd'
1147         endif
1148         if exists("*fnameescape")
1149                 execute command fnameescape(a:directory)
1150         else
1151                 execute command escape(a:directory, ' ')
1152         endif
1153 endfunction
1155 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1156 " Go to the directory in which the given file is located.
1158 function! VCSCommandChangeToCurrentFileDir(fileName)
1159         let oldCwd = getcwd()
1160         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1161         if strlen(newCwd) > 0
1162                 call VCSCommandChdir(newCwd)
1163         endif
1164         return oldCwd
1165 endfunction
1167 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1168 " Attempts to locate the original file to which VCS operations were applied
1169 " for a given buffer.
1171 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1172         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1173         if origBuffer
1174                 if bufexists(origBuffer)
1175                         return origBuffer
1176                 else
1177                         " Original buffer no longer exists.
1178                         throw 'Original buffer for this VCS buffer no longer exists.'
1179                 endif
1180         else
1181                 " No original buffer
1182                 return a:vcsBuffer
1183         endif
1184 endfunction
1186 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1187 " Allows VCS modules to register themselves.
1189 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1190         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1191         if !empty(a:mappingMap)
1192                                 \ && !exists("g:no_plugin_maps")
1193                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1194                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1195                 for shortcut in keys(a:mappingMap)
1196                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1197                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1198                 endfor
1199         endif
1200         return s:VCSCommandUtility
1201 endfunction
1203 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1204 " General skeleton for VCS function execution.  The given command is executed
1205 " after appending the current buffer name (or substituting it for
1206 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1207 " new buffer.
1209 " The optional 'options' Dictionary may contain the following options:
1210 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1211 "               non-zero exit status, the command is still considered
1212 "               successfuly.  This defaults to zero.
1213 " Returns: name of the new command buffer containing the command results
1215 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1216         let allowNonZeroExit = 0
1217         if has_key(a:options, 'allowNonZeroExit')
1218                 let allowNonZeroExit = a:options.allowNonZeroExit
1219         endif
1221         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1222         if originalBuffer == -1
1223                 throw 'Original buffer no longer exists, aborting.'
1224         endif
1226         let path = resolve(bufname(originalBuffer))
1228         " Work with netrw or other systems where a directory listing is displayed in
1229         " a buffer.
1231         if isdirectory(path)
1232                 let fileName = '.'
1233         else
1234                 let fileName = fnamemodify(path, ':t')
1235         endif
1237         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1238                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1239         else
1240                 let fullCmd = a:cmd . ' -- ' . shellescape(fileName)
1241         endif
1243         " Change to the directory of the current buffer.  This is done for CVS, but
1244         " is left in for other systems as it does not affect them negatively.
1246         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1247         try
1248                 let output = s:VCSCommandUtility.system(fullCmd)
1249         finally
1250                 call VCSCommandChdir(oldCwd)
1251         endtry
1253         " HACK:  if line endings in the repository have been corrupted, the output
1254         " of the command will be confused.
1255         let output = substitute(output, "\r", '', 'g')
1257         if v:shell_error && !allowNonZeroExit
1258                 if strlen(output) == 0
1259                         throw 'Version control command failed'
1260                 else
1261                         let output = substitute(output, '\n', '  ', 'g')
1262                         throw 'Version control command failed:  ' . output
1263                 endif
1264         endif
1266         if strlen(output) == 0
1267                 " Handle case of no output.  In this case, it is important to check the
1268                 " file status, especially since cvs edit/unedit may change the attributes
1269                 " of the file with no visible output.
1271                 checktime
1272                 return 0
1273         endif
1275         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1277         silent 0put=output
1279         " The last command left a blank line at the end of the buffer.  If the
1280         " last line is folded (a side effect of the 'put') then the attempt to
1281         " remove the blank line will kill the last fold.
1282         "
1283         " This could be fixed by explicitly detecting whether the last line is
1284         " within a fold, but I prefer to simply unfold the result buffer altogether.
1286         if has('folding')
1287                 normal! zR
1288         endif
1290         $d
1291         1
1293         " Define the environment and execute user-defined hooks.
1295         silent do VCSCommand User VCSBufferCreated
1296         return bufnr('%')
1297 endfunction
1299 " Function: VCSCommandGetOption(name, default) {{{2
1300 " Grab a user-specified option to override the default provided.  Options are
1301 " searched in the window, buffer, then global spaces.
1303 function! VCSCommandGetOption(name, default)
1304         for context in s:executionContext
1305                 if has_key(context, a:name)
1306                         return context[a:name]
1307                 endif
1308         endfor
1309         if exists('w:' . a:name)
1310                 return w:{a:name}
1311         elseif exists('b:' . a:name)
1312                 return b:{a:name}
1313         elseif exists('g:' . a:name)
1314                 return g:{a:name}
1315         else
1316                 return a:default
1317         endif
1318 endfunction
1320 " Function: VCSCommandDisableBufferSetup() {{{2
1321 " Global function for deactivating the buffer autovariables.
1323 function! VCSCommandDisableBufferSetup()
1324         let g:VCSCommandEnableBufferSetup = 0
1325         silent! augroup! VCSCommandPlugin
1326 endfunction
1328 " Function: VCSCommandEnableBufferSetup() {{{2
1329 " Global function for activating the buffer autovariables.
1331 function! VCSCommandEnableBufferSetup()
1332         let g:VCSCommandEnableBufferSetup = 1
1333         augroup VCSCommandPlugin
1334                 au!
1335                 au BufEnter * call s:SetupBuffer()
1336         augroup END
1338         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1339         " chance to run.
1340         if g:loaded_VCSCommand == 2
1341                 call s:SetupBuffer()
1342         endif
1343 endfunction
1345 " Function: VCSCommandGetStatusLine() {{{2
1346 " Default (sample) status line entry for VCS-controlled files.  This is only
1347 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1348 " variable for how to do this).
1350 function! VCSCommandGetStatusLine()
1351         if exists('b:VCSCommandCommand')
1352                 " This is a result buffer.  Return nothing because the buffer name
1353                 " contains information already.
1354                 return ''
1355         endif
1357         if exists('b:VCSCommandVCSType')
1358                                 \ && exists('g:VCSCommandEnableBufferSetup')
1359                                 \ && g:VCSCommandEnableBufferSetup
1360                                 \ && exists('b:VCSCommandBufferInfo')
1361                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1362         else
1363                 return ''
1364         endif
1365 endfunction
1367 function! VCSCommandSetVCSType(type)
1368         if exists('b:VCSCommandBufferSetup')
1369                 unlet b:VCSCommandBufferSetup
1370         endif
1371         let b:VCSCommandVCSType = a:type
1372         call s:SetupBuffer()
1373 endfunction
1375 " Section: Command definitions {{{1
1376 " Section: Primary commands {{{2
1377 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1378 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1379 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1380 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1381 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1382 com! -nargs=* VCSDiff call s:VCSDiff(<f-args>)
1383 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1384 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1385 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1386 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1387 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1388 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1389 com! -nargs=? VCSReview call s:VCSReview(<f-args>)
1390 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1391 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1392 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1393 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1395 " Section: VCS buffer management commands {{{2
1396 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1397 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1399 " Allow reloading VCSCommand.vim
1400 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
1402 " Section: Plugin command mappings {{{1
1403 if !exists("no_plugin_maps")
1404         nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1405         nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1406         nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1407         nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1408         nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1409         nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1410         nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1411         nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1412         nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1413         nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1414         nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1415         nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1416         nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1417         nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1418         nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1419         nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1420         nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1421 endif
1423 " Section: Default mappings {{{1
1425 let s:defaultMappings = [
1426                         \['a', 'VCSAdd'],
1427                         \['c', 'VCSCommit'],
1428                         \['D', 'VCSDelete'],
1429                         \['d', 'VCSDiff'],
1430                         \['G', 'VCSClearAndGotoOriginal'],
1431                         \['g', 'VCSGotoOriginal'],
1432                         \['i', 'VCSInfo'],
1433                         \['L', 'VCSLock'],
1434                         \['l', 'VCSLog'],
1435                         \['N', 'VCSSplitAnnotate'],
1436                         \['n', 'VCSAnnotate'],
1437                         \['q', 'VCSRevert'],
1438                         \['r', 'VCSReview'],
1439                         \['s', 'VCSStatus'],
1440                         \['U', 'VCSUnlock'],
1441                         \['u', 'VCSUpdate'],
1442                         \['v', 'VCSVimDiff'],
1443                         \]
1445 if !exists("g:no_plugin_maps") && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1446         for [s:shortcut, s:vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1447                 call s:CreateMapping(s:shortcut, '<Plug>' . s:vcsFunction, '''' . s:vcsFunction . '''')
1448         endfor
1449         unlet s:shortcut s:vcsFunction
1450 endif
1451 unlet s:defaultMappings
1453 " Section: Menu items {{{1
1455 let s:menuEnabled = !VCSCommandGetOption('VCSCommandDisableMenu', 0)
1456 let s:menuRoot = VCSCommandGetOption('VCSCommandMenuRoot', '&Plugin.VCS')
1457 let s:menuPriority = VCSCommandGetOption('VCSCommandMenuPriority', '')
1459 for [s:shortcut, s:command] in [
1460                         \['&Add', '<Plug>VCSAdd'],
1461                         \['A&nnotate', '<Plug>VCSAnnotate'],
1462                         \['&Commit', '<Plug>VCSCommit'],
1463                         \['Delete', '<Plug>VCSDelete'],
1464                         \['&Diff', '<Plug>VCSDiff'],
1465                         \['&Info', '<Plug>VCSInfo'],
1466                         \['&Log', '<Plug>VCSLog'],
1467                         \['Revert', '<Plug>VCSRevert'],
1468                         \['&Review', '<Plug>VCSReview'],
1469                         \['&Status', '<Plug>VCSStatus'],
1470                         \['&Update', '<Plug>VCSUpdate'],
1471                         \['&VimDiff', '<Plug>VCSVimDiff']
1472                         \]
1473         call s:VCSCommandUtility.addMenuItem(s:shortcut, s:command)
1474 endfor
1475 unlet s:shortcut s:command
1477 " Section: Autocommands to restore vimdiff state {{{1
1478 augroup VimDiffRestore
1479         au!
1480         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1481 augroup END
1483 " Section: Optional activation of buffer management {{{1
1485 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1486         call VCSCommandEnableBufferSetup()
1487 endif
1489 " Section: VIM shutdown hook {{{1
1491 " Close all result buffers when VIM exits, to prevent them from being restored
1492 " via viminfo.
1494 " Function: s:CloseAllResultBuffers() {{{2
1495 " Closes all vcscommand result buffers.
1496 function! s:CloseAllResultBuffers()
1497         " This avoids using bufdo as that may load buffers already loaded in another
1498         " vim process, resulting in an error.
1499         let buffnr = 1
1500         let buffmaxnr = bufnr('$')
1501         while buffnr <= buffmaxnr
1502                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1503                         execute 'bw' buffnr
1504                 endif
1505                 let buffnr = buffnr + 1
1506         endwhile
1507 endfunction
1509 augroup VCSCommandVIMShutdown
1510         au!
1511         au VimLeavePre * call s:CloseAllResultBuffers()
1512 augroup END
1514 " Section: Plugin completion {{{1
1516 let loaded_VCSCommand = 2
1518 silent do VCSCommand User VCSPluginFinish
1520 let &cpo = s:save_cpo