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