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