1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
5 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
7 " Copyright (c) 2008 Bob Hiestand
9 " Permission is hereby granted, free of charge, to any person obtaining a copy
10 " of this software and associated documentation files (the "Software"), to
11 " deal in the Software without restriction, including without limitation the
12 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
13 " sell copies of the Software, and to permit persons to whom the Software is
14 " furnished to do so, subject to the following conditions:
16 " The above copyright notice and this permission notice shall be included in
17 " all copies or substantial portions of the Software.
19 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
27 " Section: Documentation {{{1
29 " Provides functions to invoke various source control commands on the current
30 " file (either the current buffer, or, in the case of an directory buffer, the
31 " directory and all subdirectories associated with the current buffer). The
32 " output of the commands is captured in a new scratch window.
34 " This plugin needs additional extension plugins, each specific to a source
35 " control system, to function. Those plugins should be placed in a
36 " subdirectory of the standard plugin directory named 'vcscommand'. Several
37 " options include the name of the version control system in the option name.
38 " Such options use the placeholder text '{VCSType}', which would be replaced
39 " in actual usage with 'CVS' or '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 " VCSBlame Alias for 'VCSAnnotate'.
55 " VCSCommit[!] Commits changes to the current file to source control.
57 " If called with arguments, the arguments are the log message.
59 " If '!' is used, an empty log message is committed.
61 " If called with no arguments, this is a two-step command.
62 " The first step opens a buffer to accept a log message.
63 " When that buffer is written, it is automatically closed and
64 " the file is committed using the information from that log
65 " message. The commit can be abandoned if the log message
66 " buffer is deleted or wiped before being written.
68 " VCSDelete Deletes the current file and removes it from source control.
70 " VCSDiff With no arguments, this displays the differences between
71 " the current file and its parent version under source
72 " control in a new scratch buffer.
74 " With one argument, the diff is performed on the
75 " current file against the specified revision.
77 " With two arguments, the diff is performed between the
78 " specified revisions of the current file.
80 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
81 " to specify diff options. If that variable does not exist,
82 " a plugin-specific default is used. If you wish to have no
83 " options, then set it to the empty string.
85 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
86 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
87 " VCS scratch buffers associated with the original file.
89 " VCSInfo Displays extended information about the current file in a
92 " VCSLock Locks the current file in order to prevent other users from
93 " concurrently modifying it. The exact semantics of this
94 " command depend on the underlying VCS.
96 " VCSLog Displays the version history of the current file in a new
99 " VCSRemove Alias for 'VCSDelete'.
101 " VCSRevert Replaces the modified version of the current file with the
102 " most recent version from the repository.
104 " VCSReview Displays a particular version of the current file in a new
105 " scratch buffer. If no argument is given, the most recent
106 " version of the file on the current branch is retrieved.
108 " VCSStatus Displays versioning information about the current file in a
109 " new scratch buffer.
111 " VCSUnlock Unlocks the current file in order to allow other users from
112 " concurrently modifying it. The exact semantics of this
113 " command depend on the underlying VCS.
115 " VCSUpdate Updates the current file with any relevant changes from the
118 " VCSVimDiff Uses vimdiff to display differences between versions of the
121 " If no revision is specified, the most recent version of the
122 " file on the current branch is used. With one argument,
123 " that argument is used as the revision as above. With two
124 " arguments, the differences between the two revisions is
125 " displayed using vimdiff.
127 " With either zero or one argument, the original buffer is
128 " used to perform the vimdiff. When the scratch buffer is
129 " closed, the original buffer will be returned to normal
132 " Once vimdiff mode is started using the above methods,
133 " additional vimdiff buffers may be added by passing a single
134 " version argument to the command. There may be up to 4
135 " vimdiff buffers total.
137 " Using the 2-argument form of the command resets the vimdiff
138 " to only those 2 versions. Additionally, invoking the
139 " command on a different file will close the previous vimdiff
142 " Mapping documentation: {{{2
144 " By default, a mapping is defined for each command. User-provided mappings
145 " can be used instead by mapping to <Plug>CommandName, for instance:
147 " nmap ,ca <Plug>VCSAdd
149 " The default mappings are as follow:
152 " <Leader>cn VCSAnnotate
153 " <Leader>cc VCSCommit
154 " <Leader>cD VCSDelete
156 " <Leader>cg VCSGotoOriginal
157 " <Leader>cG VCSGotoOriginal!
161 " <Leader>cr VCSReview
162 " <Leader>cs VCSStatus
163 " <Leader>cu VCSUpdate
164 " <Leader>cU VCSUnlock
165 " <Leader>cv VCSVimDiff
167 " Options documentation: {{{2
169 " Several variables are checked by the script to determine behavior as follow:
171 " VCSCommandCommitOnWrite
172 " This variable, if set to a non-zero value, causes the pending commit to
173 " take place immediately as soon as the log message buffer is written. If
174 " set to zero, only the VCSCommit mapping will cause the pending commit to
175 " occur. If not set, it defaults to 1.
177 " VCSCommandDeleteOnHide
178 " This variable, if set to a non-zero value, causes the temporary VCS result
179 " buffers to automatically delete themselves when hidden.
181 " VCSCommand{VCSType}DiffOpt
182 " This variable, if set, determines the options passed to the diff command
183 " of the underlying VCS. Each VCS plugin defines a default value.
185 " VCSCommandDiffSplit
186 " This variable overrides the VCSCommandSplit variable, but only for buffers
187 " created with VCSVimDiff.
189 " VCSCommandDisableMappings
190 " This variable, if set to a non-zero value, prevents the default command
191 " mappings from being set.
193 " VCSCommandDisableExtensionMappings
194 " This variable, if set to a non-zero value, prevents the default command
195 " mappings from being set for commands specific to an individual VCS.
198 " This variable controls whether to split the current window to display a
199 " scratch buffer ('split'), or to display it in the current buffer ('edit').
200 " If not set, it defaults to 'split'.
202 " VCSCommandEnableBufferSetup
203 " This variable, if set to a non-zero value, activates VCS buffer management
204 " mode. This mode means that the buffer variable 'VCSRevision' is set if
205 " the file is VCS-controlled. This is useful for displaying version
206 " information in the status bar. Additional options may be set by
207 " individual VCS plugins.
209 " VCSCommandResultBufferNameExtension
210 " This variable, if set to a non-blank value, is appended to the name of the
211 " VCS command output buffers. For example, '.vcs'. Using this option may
212 " help avoid problems caused by autocommands dependent on file extension.
214 " VCSCommandResultBufferNameFunction
215 " This variable, if set, specifies a custom function for naming VCS command
216 " output buffers. This function will be passed the following arguments:
218 " command - name of the VCS command being executed (such as 'Log' or
221 " originalBuffer - buffer number of the source file.
223 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
225 " statusText - extra text associated with the VCS action (such as version
229 " This variable controls the orientation of the various window splits that
230 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
231 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
232 " If set to 'horizontal', the resulting windows will be on stacked on top of
233 " one another. If set to 'vertical', the resulting windows will be
234 " side-by-side. If not set, it defaults to 'horizontal' for all but
235 " VCSVimDiff windows.
237 " Event documentation {{{2
238 " For additional customization, VCSCommand.vim uses User event autocommand
239 " hooks. Each event is in the VCSCommand group, and different patterns
240 " match the various hooks.
242 " For instance, the following could be added to the vimrc to provide a 'q'
243 " mapping to quit a VCS scratch buffer:
246 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
249 " The following hooks are available:
251 " VCSBufferCreated This event is fired just after a VCS command
252 " output buffer is created. It is executed
253 " within the context of the new buffer.
255 " VCSBufferSetup This event is fired just after VCS buffer setup
256 " occurs, if enabled.
258 " VCSPluginInit This event is fired when the VCSCommand plugin
261 " VCSPluginFinish This event is fired just after the VCSCommand
264 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
265 " command executes to allow customization of,
266 " for instance, window placement and focus.
268 " Section: Plugin header {{{1
270 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
271 " completes. This allows various actions to only be taken by functions after
272 " system initialization.
274 if exists('loaded_VCSCommand')
277 let loaded_VCSCommand = 1
280 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
287 " Section: Event group setup {{{1
292 augroup VCSCommandCommit
295 " Section: Plugin initialization {{{1
296 silent do VCSCommand User VCSPluginInit
298 " Section: Constants declaration {{{1
300 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
301 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
303 " Section: Script variable initialization {{{1
305 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
308 " temporary values of overridden configuration variables
309 let s:optionOverrides = {}
311 " state flag used to vary behavior of certain automated actions
312 let s:isEditFileRunning = 0
314 " commands needed to restore diff buffers to their original state
315 unlet! s:vimDiffRestoreCmd
317 " original buffer currently reflected in vimdiff windows
318 unlet! s:vimDiffSourceBuffer
321 unlet! s:vimDiffScratchList
323 " Section: Utility functions {{{1
325 " Function: s:ReportError(mapping) {{{2
326 " Displays the given error in a consistent faction. This is intended to be
327 " invoked from a catch statement.
329 function! s:ReportError(error)
330 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
333 " Function: s:ExecuteExtensionMapping(mapping) {{{2
334 " Invokes the appropriate extension mapping depending on the type of the
337 function! s:ExecuteExtensionMapping(mapping)
338 let buffer = bufnr('%')
339 let vcsType = VCSCommandGetVCSType(buffer)
340 if !has_key(s:plugins, vcsType)
341 throw 'Unknown VCS type: ' . vcsType
343 if !has_key(s:plugins[vcsType][2], a:mapping)
344 throw 'This extended mapping is not defined for ' . vcsType
346 silent execute 'normal' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
349 " Function: s:ExecuteVCSCommand(command, argList) {{{2
350 " Calls the indicated plugin-specific VCS command on the current buffer.
351 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
354 function! s:ExecuteVCSCommand(command, argList)
356 let buffer = bufnr('%')
358 let vcsType = VCSCommandGetVCSType(buffer)
359 if !has_key(s:plugins, vcsType)
360 throw 'Unknown VCS type: ' . vcsType
363 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
364 let bufferName = bufname(originalBuffer)
366 " It is already known that the directory is under VCS control. No further
367 " checks are needed. Otherwise, perform some basic sanity checks to avoid
368 " VCS-specific error messages from confusing things.
369 if !isdirectory(bufferName)
370 if !filereadable(bufferName)
371 throw 'No such file ' . bufferName
375 let functionMap = s:plugins[vcsType][1]
376 if !has_key(functionMap, a:command)
377 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
379 return functionMap[a:command](a:argList)
381 call s:ReportError(v:exception)
386 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
387 " Default method of generating the name for VCS result buffers. This can be
388 " overridden with the VCSResultBufferNameFunction variable.
390 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
391 let fileName = bufname(a:originalBuffer)
392 let bufferName = a:vcsType . ' ' . a:command
393 if strlen(a:statusText) > 0
394 let bufferName .= ' ' . a:statusText
396 let bufferName .= ' ' . fileName
398 let versionedBufferName = bufferName
399 while buflisted(versionedBufferName)
401 let versionedBufferName = bufferName . ' (' . counter . ')'
403 return versionedBufferName
406 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
407 " Method of generating the name for VCS result buffers that uses the original
408 " file name with the VCS type and command appended as extensions.
410 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
411 let fileName = bufname(a:originalBuffer)
412 let bufferName = a:vcsType . ' ' . a:command
413 if strlen(a:statusText) > 0
414 let bufferName .= ' ' . a:statusText
416 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
418 let versionedBufferName = bufferName
419 while buflisted(versionedBufferName)
421 let versionedBufferName = '(' . counter . ') ' . bufferName
423 return versionedBufferName
426 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
427 " Creates a new buffer of the given name and associates it with the given
430 function! s:EditFile(command, originalBuffer, statusText)
431 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
433 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
434 if nameExtension == ''
435 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
437 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
440 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
442 " Protect against useless buffer set-up
443 let s:isEditFileRunning += 1
445 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
446 if editCommand == 'split'
447 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
450 vert rightbelow split
456 let b:VCSCommandCommand = a:command
457 let b:VCSCommandOriginalBuffer = a:originalBuffer
458 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
459 let b:VCSCommandVCSType = vcsType
461 setlocal buftype=nofile
463 let &filetype = vcsType . a:command
465 if a:statusText != ''
466 let b:VCSCommandStatusText = a:statusText
469 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
470 setlocal bufhidden=delete
472 silent noautocmd file `=resultBufferName`
474 let s:isEditFileRunning -= 1
478 " Function: s:SetupBuffer() {{{2
479 " Attempts to set the b:VCSCommandBufferInfo variable
481 function! s:SetupBuffer()
482 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
483 " This buffer is already set up.
487 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
488 " No special status for special buffers other than directory buffers.
492 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
493 unlet! b:VCSCommandBufferSetup
498 let vcsType = VCSCommandGetVCSType(bufnr('%'))
499 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
500 silent do VCSCommand User VCSBufferSetup
501 catch /No suitable plugin/
502 " This is not a VCS-controlled file.
503 let b:VCSCommandBufferInfo = []
506 let b:VCSCommandBufferSetup = 1
509 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
510 " Resets the buffer setup state of the original buffer for a given VCS scratch
512 " Returns: The VCS buffer number in a passthrough mode.
514 function! s:MarkOrigBufferForSetup(buffer)
517 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
518 " This should never not work, but I'm paranoid
519 if origBuffer != a:buffer
520 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
526 " Function: s:OverrideOption(option, [value]) {{{2
527 " Provides a temporary override for the given VCS option. If no value is
528 " passed, the override is disabled.
530 function! s:OverrideOption(option, ...)
532 call remove(s:optionOverrides[a:option], -1)
534 if !has_key(s:optionOverrides, a:option)
535 let s:optionOverrides[a:option] = []
537 call add(s:optionOverrides[a:option], a:1)
541 " Function: s:WipeoutCommandBuffers() {{{2
542 " Clears all current VCS output buffers of the specified type for a given source.
544 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
546 while buffer <= bufnr('$')
547 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
548 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
552 let buffer = buffer + 1
556 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
557 " Checks whether the given buffer is one whose deletion should trigger
558 " restoration of an original buffer after it was diffed. If so, it executes
559 " the appropriate setting command stored with that original buffer.
561 function! s:VimDiffRestore(vimDiffBuff)
562 let s:isEditFileRunning += 1
564 if exists('s:vimDiffSourceBuffer')
565 if a:vimDiffBuff == s:vimDiffSourceBuffer
566 " Original file is being removed.
567 unlet! s:vimDiffSourceBuffer
568 unlet! s:vimDiffRestoreCmd
569 unlet! s:vimDiffScratchList
571 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
573 call remove(s:vimDiffScratchList, index)
574 if len(s:vimDiffScratchList) == 0
575 if exists('s:vimDiffRestoreCmd')
576 " All scratch buffers are gone, reset the original.
577 " Only restore if the source buffer is still in Diff mode
579 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
581 " The buffer is visible in at least one window
582 let currentWinNR = winnr()
583 while winbufnr(sourceWinNR) != -1
584 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
585 execute sourceWinNR . 'wincmd w'
586 if getwinvar(0, '&diff')
587 execute s:vimDiffRestoreCmd
590 let sourceWinNR = sourceWinNR + 1
592 execute currentWinNR . 'wincmd w'
594 " The buffer is hidden. It must be visible in order to set the
596 let currentBufNR = bufnr('')
597 execute 'hide buffer' s:vimDiffSourceBuffer
598 if getwinvar(0, '&diff')
599 execute s:vimDiffRestoreCmd
601 execute 'hide buffer' currentBufNR
604 unlet s:vimDiffRestoreCmd
606 " All buffers are gone.
607 unlet s:vimDiffSourceBuffer
608 unlet s:vimDiffScratchList
614 let s:isEditFileRunning -= 1
618 " Section: Generic VCS command functions {{{1
620 " Function: s:VCSCommit() {{{2
621 function! s:VCSCommit(bang, message)
623 let vcsType = VCSCommandGetVCSType(bufnr('%'))
624 if !has_key(s:plugins, vcsType)
625 throw 'Unknown VCS type: ' . vcsType
628 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
630 " Handle the commit message being specified. If a message is supplied, it
631 " is used; if bang is supplied, an empty message is used; otherwise, the
632 " user is provided a buffer from which to edit the commit message.
634 if strlen(a:message) > 0 || a:bang == '!'
635 return s:VCSFinishCommit([a:message], originalBuffer)
638 call s:EditFile('commitlog', originalBuffer, '')
639 setlocal ft=vcscommit
641 " Create a commit mapping.
643 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
645 silent 0put ='VCS: ----------------------------------------------------------------------'
646 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
647 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
649 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
650 setlocal buftype=acwrite
651 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
652 silent put ='VCS: or write this buffer'
655 silent put ='VCS: ----------------------------------------------------------------------'
659 call s:ReportError(v:exception)
664 " Function: s:VCSFinishCommitWithBuffer() {{{2
665 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
666 " which removes all lines starting with 'VCS:'.
668 function! s:VCSFinishCommitWithBuffer()
670 let currentBuffer = bufnr('%')
671 let logMessageList = getbufline('%', 1, '$')
672 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
673 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
675 execute 'bw' currentBuffer
680 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
681 function! s:VCSFinishCommit(logMessageList, originalBuffer)
682 let shellSlashBak = &shellslash
685 let messageFileName = tempname()
686 call writefile(a:logMessageList, messageFileName)
688 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
692 return s:MarkOrigBufferForSetup(resultBuffer)
694 call delete(messageFileName)
697 let &shellslash = shellSlashBak
701 " Function: s:VCSGotoOriginal(bang) {{{2
702 function! s:VCSGotoOriginal(bang)
703 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
704 if originalBuffer > 0
705 let origWinNR = bufwinnr(originalBuffer)
707 execute 'buffer' originalBuffer
709 execute origWinNR . 'wincmd w'
713 let buffmaxnr = bufnr('$')
714 while buffnr <= buffmaxnr
715 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
718 let buffnr = buffnr + 1
724 " Function: s:VCSVimDiff(...) {{{2
725 function! s:VCSVimDiff(...)
727 let vcsType = VCSCommandGetVCSType(bufnr('%'))
728 if !has_key(s:plugins, vcsType)
729 throw 'Unknown VCS type: ' . vcsType
731 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
732 let s:isEditFileRunning = s:isEditFileRunning + 1
734 " If there's already a VimDiff'ed window, restore it.
735 " There may only be one VCSVimDiff original window at a time.
737 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
738 " Clear the existing vimdiff setup by removing the result buffers.
739 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
744 " Reset the vimdiff system, as 2 explicit versions were provided.
745 if exists('s:vimDiffSourceBuffer')
746 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
748 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
750 echomsg 'Can''t open revision ' . a:1
753 let b:VCSCommandCommand = 'vimdiff'
755 let s:vimDiffScratchList = [resultBuffer]
756 " If no split method is defined, cheat, and set it to vertical.
758 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
759 let resultBuffer = s:plugins[vcsType][1].Review([a:2])
761 call s:OverrideOption('VCSCommandSplit')
764 echomsg 'Can''t open revision ' . a:1
767 let b:VCSCommandCommand = 'vimdiff'
769 let s:vimDiffScratchList += [resultBuffer]
772 call s:OverrideOption('VCSCommandEdit', 'split')
774 " Force splitting behavior, otherwise why use vimdiff?
775 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
778 let resultBuffer = s:plugins[vcsType][1].Review([])
780 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
783 call s:OverrideOption('VCSCommandSplit')
786 call s:OverrideOption('VCSCommandEdit')
789 echomsg 'Can''t open current revision'
792 let b:VCSCommandCommand = 'vimdiff'
795 if !exists('s:vimDiffSourceBuffer')
796 " New instance of vimdiff.
797 let s:vimDiffScratchList = [resultBuffer]
799 " This could have been invoked on a VCS result buffer, not the
802 execute 'buffer' originalBuffer
803 " Store info for later original buffer restore
804 let s:vimDiffRestoreCmd =
805 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
806 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
807 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
808 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
809 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
810 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
811 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
812 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
816 " Adding a window to an existing vimdiff
817 let s:vimDiffScratchList += [resultBuffer]
821 let s:vimDiffSourceBuffer = originalBuffer
823 " Avoid executing the modeline in the current buffer after the autocommand.
825 let currentBuffer = bufnr('%')
826 let saveModeline = getbufvar(currentBuffer, '&modeline')
828 call setbufvar(currentBuffer, '&modeline', 0)
829 silent do VCSCommand User VCSVimDiffFinish
831 call setbufvar(currentBuffer, '&modeline', saveModeline)
835 let s:isEditFileRunning = s:isEditFileRunning - 1
838 call s:ReportError(v:exception)
843 " Section: Public functions {{{1
845 " Function: VCSCommandGetVCSType() {{{2
846 " Sets the b:VCSCommandVCSType variable in the given buffer to the
847 " appropriate source control system name.
849 " This uses the Identify extension function to test the buffer. If the
850 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
851 " exact. If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
852 " match is considered inexact, and is only applied if no exact match is found.
853 " Multiple inexact matches is currently considered an error.
855 function! VCSCommandGetVCSType(buffer)
856 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
857 if strlen(vcsType) > 0
861 for vcsType in keys(s:plugins)
862 let identified = s:plugins[vcsType][1].Identify(a:buffer)
864 if identified == g:VCSCOMMAND_IDENTIFY_EXACT
865 let matches = [vcsType]
868 let matches += [vcsType]
873 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
875 elseif len(matches) == 0
876 throw 'No suitable plugin'
878 throw 'Too many matching VCS: ' . join(matches)
882 " Function: VCSCommandChdir(directory) {{{2
883 " Changes the current directory, respecting :lcd changes.
885 function! VCSCommandChdir(directory)
887 if exists("*haslocaldir") && haslocaldir()
890 execute command escape(a:directory, ' ')
893 " Function: VCSCommandChangeToCurrentFileDir() {{{2
894 " Go to the directory in which the given file is located.
896 function! VCSCommandChangeToCurrentFileDir(fileName)
897 let oldCwd = getcwd()
898 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
899 if strlen(newCwd) > 0
900 call VCSCommandChdir(newCwd)
905 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
906 " Attempts to locate the original file to which VCS operations were applied
907 " for a given buffer.
909 function! VCSCommandGetOriginalBuffer(vcsBuffer)
910 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
912 if bufexists(origBuffer)
915 " Original buffer no longer exists.
916 throw 'Original buffer for this VCS buffer no longer exists.'
924 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
925 " Allows VCS modules to register themselves.
927 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
928 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
929 if !empty(a:mappingMap)
930 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
931 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
932 for mapname in keys(a:mappingMap)
933 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
938 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
939 " General skeleton for VCS function execution. The given command is executed
940 " after appending the current buffer name (or substituting it for
941 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
944 " The optional 'options' Dictionary may contain the following options:
945 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
946 " non-zero exit status, the command is still considered
947 " successfuly. This defaults to zero.
948 " Returns: name of the new command buffer containing the command results
950 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
951 let allowNonZeroExit = 0
952 if has_key(a:options, 'allowNonZeroExit')
953 let allowNonZeroExit = a:options.allowNonZeroExit
956 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
957 if originalBuffer == -1
958 throw 'Original buffer no longer exists, aborting.'
961 let path = resolve(bufname(originalBuffer))
963 " Work with netrw or other systems where a directory listing is displayed in
969 let fileName = fnamemodify(path, ':t')
972 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
973 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
975 let fullCmd = a:cmd . ' "' . fileName . '"'
978 " Change to the directory of the current buffer. This is done for CVS, but
979 " is left in for other systems as it does not affect them negatively.
981 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
983 let output = system(fullCmd)
985 call VCSCommandChdir(oldCwd)
988 " HACK: if line endings in the repository have been corrupted, the output
989 " of the command will be confused.
990 let output = substitute(output, "\r", '', 'g')
992 if v:shell_error && !allowNonZeroExit
993 if strlen(output) == 0
994 throw 'Version control command failed'
996 let output = substitute(output, '\n', ' ', 'g')
997 throw 'Version control command failed: ' . output
1001 if strlen(output) == 0
1002 " Handle case of no output. In this case, it is important to check the
1003 " file status, especially since cvs edit/unedit may change the attributes
1004 " of the file with no visible output.
1010 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1014 " The last command left a blank line at the end of the buffer. If the
1015 " last line is folded (a side effect of the 'put') then the attempt to
1016 " remove the blank line will kill the last fold.
1018 " This could be fixed by explicitly detecting whether the last line is
1019 " within a fold, but I prefer to simply unfold the result buffer altogether.
1028 " Define the environment and execute user-defined hooks.
1030 silent do VCSCommand User VCSBufferCreated
1034 " Function: VCSCommandGetOption(name, default) {{{2
1035 " Grab a user-specified option to override the default provided. Options are
1036 " searched in the window, buffer, then global spaces.
1038 function! VCSCommandGetOption(name, default)
1039 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1040 return s:optionOverrides[a:name][-1]
1041 elseif exists('w:' . a:name)
1043 elseif exists('b:' . a:name)
1045 elseif exists('g:' . a:name)
1052 " Function: VCSCommandDisableBufferSetup() {{{2
1053 " Global function for deactivating the buffer autovariables.
1055 function! VCSCommandDisableBufferSetup()
1056 let g:VCSCommandEnableBufferSetup = 0
1057 silent! augroup! VCSCommandPlugin
1060 " Function: VCSCommandEnableBufferSetup() {{{2
1061 " Global function for activating the buffer autovariables.
1063 function! VCSCommandEnableBufferSetup()
1064 let g:VCSCommandEnableBufferSetup = 1
1065 augroup VCSCommandPlugin
1067 au BufEnter * call s:SetupBuffer()
1070 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1072 if g:loaded_VCSCommand == 2
1073 call s:SetupBuffer()
1077 " Function: VCSCommandGetStatusLine() {{{2
1078 " Default (sample) status line entry for VCS-controlled files. This is only
1079 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1080 " variable for how to do this).
1082 function! VCSCommandGetStatusLine()
1083 if exists('b:VCSCommandCommand')
1084 " This is a result buffer. Return nothing because the buffer name
1085 " contains information already.
1089 if exists('b:VCSCommandVCSType')
1090 \ && exists('g:VCSCommandEnableBufferSetup')
1091 \ && g:VCSCommandEnableBufferSetup
1092 \ && exists('b:VCSCommandBufferInfo')
1093 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1099 " Section: Command definitions {{{1
1100 " Section: Primary commands {{{2
1101 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1102 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1103 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1104 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1105 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1106 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1107 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1108 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1109 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1110 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1111 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1112 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1113 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1114 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1115 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1116 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1117 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1119 " Section: VCS buffer management commands {{{2
1120 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1121 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1123 " Allow reloading VCSCommand.vim
1124 com! VCSReload let savedPlugins = s:plugins|let s:plugins = {}|aunmenu Plugin.VCS|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for plugin in values(savedPlugins)|execute 'source' plugin[0]|endfor|unlet savedPlugins
1126 " Section: Plugin command mappings {{{1
1127 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1128 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1129 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1130 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1131 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1132 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1133 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1134 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1135 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1136 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1137 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1138 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1139 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1140 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1141 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1142 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1144 " Section: Default mappings {{{1
1146 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1147 if !hasmapto('<Plug>VCSAdd')
1148 nmap <unique> <Leader>ca <Plug>VCSAdd
1150 if !hasmapto('<Plug>VCSAnnotate')
1151 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1153 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1154 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1156 if !hasmapto('<Plug>VCSCommit')
1157 nmap <unique> <Leader>cc <Plug>VCSCommit
1159 if !hasmapto('<Plug>VCSDelete')
1160 nmap <unique> <Leader>cD <Plug>VCSDelete
1162 if !hasmapto('<Plug>VCSDiff')
1163 nmap <unique> <Leader>cd <Plug>VCSDiff
1165 if !hasmapto('<Plug>VCSGotoOriginal')
1166 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1168 if !hasmapto('<Plug>VCSInfo')
1169 nmap <unique> <Leader>ci <Plug>VCSInfo
1171 if !hasmapto('<Plug>VCSLock')
1172 nmap <unique> <Leader>cL <Plug>VCSLock
1174 if !hasmapto('<Plug>VCSLog')
1175 nmap <unique> <Leader>cl <Plug>VCSLog
1177 if !hasmapto('<Plug>VCSRevert')
1178 nmap <unique> <Leader>cq <Plug>VCSRevert
1180 if !hasmapto('<Plug>VCSReview')
1181 nmap <unique> <Leader>cr <Plug>VCSReview
1183 if !hasmapto('<Plug>VCSStatus')
1184 nmap <unique> <Leader>cs <Plug>VCSStatus
1186 if !hasmapto('<Plug>VCSUnlock')
1187 nmap <unique> <Leader>cU <Plug>VCSUnlock
1189 if !hasmapto('<Plug>VCSUpdate')
1190 nmap <unique> <Leader>cu <Plug>VCSUpdate
1192 if !hasmapto('<Plug>VCSVimDiff')
1193 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1197 " Section: Menu items {{{1
1198 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1199 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1200 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1201 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1202 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1203 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1204 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1205 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1206 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1207 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1208 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1209 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1211 " Section: Autocommands to restore vimdiff state {{{1
1212 augroup VimDiffRestore
1214 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1217 " Section: Optional activation of buffer management {{{1
1219 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1220 call VCSCommandEnableBufferSetup()
1223 " Section: VIM shutdown hook {{{1
1225 " Close all result buffers when VIM exits, to prevent them from being restored
1228 " Function: s:CloseAllResultBuffers() {{{2
1229 " Closes all vcscommand result buffers.
1230 function! s:CloseAllResultBuffers()
1231 " This avoids using bufdo as that may load buffers already loaded in another
1232 " vim process, resulting in an error.
1234 let buffmaxnr = bufnr('$')
1235 while buffnr <= buffmaxnr
1236 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1239 let buffnr = buffnr + 1
1243 augroup VCSCommandVIMShutdown
1245 au VimLeavePre * call s:CloseAllResultBuffers()
1248 " Section: Plugin completion {{{1
1250 let loaded_VCSCommand = 2
1252 silent do VCSCommand User VCSPluginFinish
1254 let &cpo = s:save_cpo