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