1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
6 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
8 " Copyright (c) 2007 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
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. Those plugins should be placed in a
37 " subdirectory of the standard plugin directory named 'vcscommand'. Several
38 " options include the name of the version control system in the option name.
39 " Such options use the placeholder text '{VCSType}', which would be replaced
40 " in actual usage with 'CVS' or 'SVN', for instance.
42 " Command documentation {{{2
44 " VCSAdd Adds the current file to source control.
46 " VCSAnnotate Displays the current file with each line annotated with the
47 " version in which it was most recently changed. If an
48 " argument is given, the argument is used as a revision
49 " number to display. If not given an argument, it uses the
50 " most recent version of the file on the current branch.
51 " Additionally, if the current buffer is a VCSAnnotate buffer
52 " already, the version number on the current line is used.
54 " VCSBlame Alias for 'VCSAnnotate'.
56 " VCSCommit[!] Commits changes to the current file to source control.
58 " If called with arguments, the arguments are the log message.
60 " If '!' is used, an empty log message is committed.
62 " If called with no arguments, this is a two-step command.
63 " The first step opens a buffer to accept a log message.
64 " When that buffer is written, it is automatically closed and
65 " the file is committed using the information from that log
66 " message. The commit can be abandoned if the log message
67 " buffer is deleted or wiped before being written.
69 " VCSDelete Deletes the current file and removes it from source control.
71 " VCSDiff With no arguments, this displays the differences between
72 " the current file and its parent version under source
73 " control in a new scratch buffer.
75 " With one argument, the diff is performed on the
76 " current file against the specified revision.
78 " With two arguments, the diff is performed between the
79 " specified revisions of the current file.
81 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
82 " to specify diff options. If that variable does not exist,
83 " a plugin-specific default is used. If you wish to have no
84 " options, then set it to the empty string.
86 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
87 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
88 " VCS scratch buffers associated with the original file.
90 " VCSInfo Displays extended information about the current file in a
93 " VCSLock Locks the current file in order to prevent other users from
94 " concurrently modifying it. The exact semantics of this
95 " command depend on the underlying VCS.
97 " VCSLog Displays the version history of the current file in a new
100 " VCSRemove Alias for 'VCSDelete'.
102 " VCSRevert Replaces the modified version of the current file with the
103 " most recent version from the repository.
105 " VCSReview Displays a particular version of the current file in a new
106 " scratch buffer. If no argument is given, the most recent
107 " version of the file on the current branch is retrieved.
109 " VCSStatus Displays versioning information about the current file in a
110 " new scratch buffer.
112 " VCSUnlock Unlocks the current file in order to allow other users from
113 " concurrently modifying it. The exact semantics of this
114 " command depend on the underlying VCS.
116 " VCSUpdate Updates the current file with any relevant changes from the
119 " VCSVimDiff Uses vimdiff to display differences between versions of the
122 " If no revision is specified, the most recent version of the
123 " file on the current branch is used. With one argument,
124 " that argument is used as the revision as above. With two
125 " arguments, the differences between the two revisions is
126 " displayed using vimdiff.
128 " With either zero or one argument, the original buffer is
129 " used to perform the vimdiff. When the scratch buffer is
130 " closed, the original buffer will be returned to normal
133 " Once vimdiff mode is started using the above methods,
134 " additional vimdiff buffers may be added by passing a single
135 " version argument to the command. There may be up to 4
136 " vimdiff buffers total.
138 " Using the 2-argument form of the command resets the vimdiff
139 " to only those 2 versions. Additionally, invoking the
140 " command on a different file will close the previous vimdiff
143 " Mapping documentation: {{{2
145 " By default, a mapping is defined for each command. User-provided mappings
146 " can be used instead by mapping to <Plug>CommandName, for instance:
148 " nmap ,ca <Plug>VCSAdd
150 " The default mappings are as follow:
153 " <Leader>cn VCSAnnotate
154 " <Leader>cc VCSCommit
155 " <Leader>cD VCSDelete
157 " <Leader>cg VCSGotoOriginal
158 " <Leader>cG VCSGotoOriginal!
162 " <Leader>cr VCSReview
163 " <Leader>cs VCSStatus
164 " <Leader>cu VCSUpdate
165 " <Leader>cU VCSUnlock
166 " <Leader>cv VCSVimDiff
168 " Options documentation: {{{2
170 " Several variables are checked by the script to determine behavior as follow:
172 " VCSCommandCommitOnWrite
173 " This variable, if set to a non-zero value, causes the pending commit to
174 " take place immediately as soon as the log message buffer is written. If
175 " set to zero, only the VCSCommit mapping will cause the pending commit to
176 " occur. If not set, it defaults to 1.
178 " VCSCommandDeleteOnHide
179 " This variable, if set to a non-zero value, causes the temporary VCS result
180 " buffers to automatically delete themselves when hidden.
182 " VCSCommand{VCSType}DiffOpt
183 " This variable, if set, determines the options passed to the diff command
184 " of the underlying VCS. Each VCS plugin defines a default value.
186 " VCSCommandDiffSplit
187 " This variable overrides the VCSCommandSplit variable, but only for buffers
188 " created with VCSVimDiff.
190 " VCSCommandDisableMappings
191 " This variable, if set to a non-zero value, prevents the default command
192 " mappings from being set.
194 " VCSCommandDisableExtensionMappings
195 " This variable, if set to a non-zero value, prevents the default command
196 " mappings from being set for commands specific to an individual VCS.
199 " This variable controls whether to split the current window to display a
200 " scratch buffer ('split'), or to display it in the current buffer ('edit').
201 " If not set, it defaults to 'split'.
203 " VCSCommandEnableBufferSetup
204 " This variable, if set to a non-zero value, activates VCS buffer management
205 " mode. This mode means that the buffer variable 'VCSRevision' is set if
206 " the file is VCS-controlled. This is useful for displaying version
207 " information in the status bar. Additional options may be set by
208 " individual VCS plugins.
210 " VCSCommandResultBufferNameExtension
211 " This variable, if set to a non-blank value, is appended to the name of the
212 " VCS command output buffers. For example, '.vcs'. Using this option may
213 " help avoid problems caused by autocommands dependent on file extension.
215 " VCSCommandResultBufferNameFunction
216 " This variable, if set, specifies a custom function for naming VCS command
217 " output buffers. This function will be passed the following arguments:
219 " command - name of the VCS command being executed (such as 'Log' or
222 " originalBuffer - buffer number of the source file.
224 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
226 " statusText - extra text associated with the VCS action (such as version
230 " This variable controls the orientation of the various window splits that
231 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
232 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
233 " If set to 'horizontal', the resulting windows will be on stacked on top of
234 " one another. If set to 'vertical', the resulting windows will be
235 " side-by-side. If not set, it defaults to 'horizontal' for all but
236 " VCSVimDiff windows.
238 " Event documentation {{{2
239 " For additional customization, VCSCommand.vim uses User event autocommand
240 " hooks. Each event is in the VCSCommand group, and different patterns
241 " match the various hooks.
243 " For instance, the following could be added to the vimrc to provide a 'q'
244 " mapping to quit a VCS scratch buffer:
247 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
250 " The following hooks are available:
252 " VCSBufferCreated This event is fired just after a VCS command
253 " output buffer is created. It is executed
254 " within the context of the new buffer.
256 " VCSBufferSetup This event is fired just after VCS buffer setup
257 " occurs, if enabled.
259 " VCSPluginInit This event is fired when the VCSCommand plugin
262 " VCSPluginFinish This event is fired just after the VCSCommand
265 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
266 " command executes to allow customization of,
267 " for instance, window placement and focus.
269 " Section: Plugin header {{{1
271 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
272 " completes. This allows various actions to only be taken by functions after
273 " system initialization.
275 if exists('loaded_VCSCommand')
278 let loaded_VCSCommand = 1
281 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
288 " Section: Event group setup {{{1
293 augroup VCSCommandCommit
296 " Section: Plugin initialization {{{1
297 silent do VCSCommand User VCSPluginInit
299 " Section: Constants declaration {{{1
301 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
302 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
304 " Section: Script variable initialization {{{1
306 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
309 " temporary values of overridden configuration variables
310 let s:optionOverrides = {}
312 " state flag used to vary behavior of certain automated actions
313 let s:isEditFileRunning = 0
315 " commands needed to restore diff buffers to their original state
316 unlet! s:vimDiffRestoreCmd
318 " original buffer currently reflected in vimdiff windows
319 unlet! s:vimDiffSourceBuffer
322 unlet! s:vimDiffScratchList
324 " Section: Utility functions {{{1
326 " Function: s:ReportError(mapping) {{{2
327 " Displays the given error in a consistent faction. This is intended to be
328 " invoked from a catch statement.
330 function! s:ReportError(error)
331 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
334 " Function: s:ExecuteExtensionMapping(mapping) {{{2
335 " Invokes the appropriate extension mapping depending on the type of the
338 function! s:ExecuteExtensionMapping(mapping)
339 let buffer = bufnr('%')
340 let vcsType = VCSCommandGetVCSType(buffer)
341 if !has_key(s:plugins, vcsType)
342 throw 'Unknown VCS type: ' . vcsType
344 if !has_key(s:plugins[vcsType][2], a:mapping)
345 throw 'This extended mapping is not defined for ' . vcsType
347 silent execute 'normal' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
350 " Function: s:ExecuteVCSCommand(command, argList) {{{2
351 " Calls the indicated plugin-specific VCS command on the current buffer.
352 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
355 function! s:ExecuteVCSCommand(command, argList)
357 let buffer = bufnr('%')
359 let vcsType = VCSCommandGetVCSType(buffer)
360 if !has_key(s:plugins, vcsType)
361 throw 'Unknown VCS type: ' . vcsType
364 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
365 let bufferName = bufname(originalBuffer)
367 " It is already known that the directory is under VCS control. No further
368 " checks are needed. Otherwise, perform some basic sanity checks to avoid
369 " VCS-specific error messages from confusing things.
370 if !isdirectory(bufferName)
371 if !filereadable(bufferName)
372 throw 'No such file ' . bufferName
376 let functionMap = s:plugins[vcsType][1]
377 if !has_key(functionMap, a:command)
378 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
380 return functionMap[a:command](a:argList)
382 call s:ReportError(v:exception)
387 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
388 " Default method of generating the name for VCS result buffers. This can be
389 " overridden with the VCSResultBufferNameFunction variable.
391 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
392 let fileName = bufname(a:originalBuffer)
393 let bufferName = a:vcsType . ' ' . a:command
394 if strlen(a:statusText) > 0
395 let bufferName .= ' ' . a:statusText
397 let bufferName .= ' ' . fileName
399 let versionedBufferName = bufferName
400 while buflisted(versionedBufferName)
402 let versionedBufferName = bufferName . ' (' . counter . ')'
404 return versionedBufferName
407 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
408 " Method of generating the name for VCS result buffers that uses the original
409 " file name with the VCS type and command appended as extensions.
411 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
412 let fileName = bufname(a:originalBuffer)
413 let bufferName = a:vcsType . ' ' . a:command
414 if strlen(a:statusText) > 0
415 let bufferName .= ' ' . a:statusText
417 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
419 let versionedBufferName = bufferName
420 while buflisted(versionedBufferName)
422 let versionedBufferName = '(' . counter . ') ' . bufferName
424 return versionedBufferName
427 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
428 " Creates a new buffer of the given name and associates it with the given
431 function! s:EditFile(command, originalBuffer, statusText)
432 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
434 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
435 if nameExtension == ''
436 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
438 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
441 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
443 " Protect against useless buffer set-up
444 let s:isEditFileRunning += 1
446 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
447 if editCommand == 'split'
448 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
451 vert rightbelow split
454 edit `=resultBufferName`
455 let b:VCSCommandCommand = a:command
456 let b:VCSCommandOriginalBuffer = a:originalBuffer
457 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
458 let b:VCSCommandVCSType = vcsType
462 let &filetype = vcsType . a:command
464 if a:statusText != ''
465 let b:VCSCommandStatusText = a:statusText
468 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
472 let s:isEditFileRunning -= 1
477 " Function: s:SetupBuffer() {{{2
478 " Attempts to set the b:VCSCommandBufferInfo variable
480 function! s:SetupBuffer()
481 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
482 " This buffer is already set up.
486 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
487 " No special status for special buffers other than directory buffers.
491 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
492 unlet! b:VCSCommandBufferSetup
497 let vcsType = VCSCommandGetVCSType(bufnr('%'))
498 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
499 silent do VCSCommand User VCSBufferSetup
500 catch /No suitable plugin/
501 " This is not a VCS-controlled file.
502 let b:VCSCommandBufferInfo = []
505 let b:VCSCommandBufferSetup = 1
508 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
509 " Resets the buffer setup state of the original buffer for a given VCS scratch
511 " Returns: The VCS buffer number in a passthrough mode.
513 function! s:MarkOrigBufferForSetup(buffer)
516 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
517 " This should never not work, but I'm paranoid
518 if origBuffer != a:buffer
519 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
525 " Function: s:OverrideOption(option, [value]) {{{2
526 " Provides a temporary override for the given VCS option. If no value is
527 " passed, the override is disabled.
529 function! s:OverrideOption(option, ...)
531 call remove(s:optionOverrides[a:option], -1)
533 if !has_key(s:optionOverrides, a:option)
534 let s:optionOverrides[a:option] = []
536 call add(s:optionOverrides[a:option], a:1)
540 " Function: s:WipeoutCommandBuffers() {{{2
541 " Clears all current VCS output buffers of the specified type for a given source.
543 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
545 while buffer <= bufnr('$')
546 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
547 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
551 let buffer = buffer + 1
555 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
556 " Checks whether the given buffer is one whose deletion should trigger
557 " restoration of an original buffer after it was diffed. If so, it executes
558 " the appropriate setting command stored with that original buffer.
560 function! s:VimDiffRestore(vimDiffBuff)
561 let s:isEditFileRunning += 1
563 if exists('s:vimDiffSourceBuffer')
564 if a:vimDiffBuff == s:vimDiffSourceBuffer
565 " Original file is being removed.
566 unlet! s:vimDiffSourceBuffer
567 unlet! s:vimDiffRestoreCmd
568 unlet! s:vimDiffScratchList
570 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
572 call remove(s:vimDiffScratchList, index)
573 if len(s:vimDiffScratchList) == 0
574 if exists('s:vimDiffRestoreCmd')
575 " All scratch buffers are gone, reset the original.
576 " Only restore if the source buffer is still in Diff mode
578 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
580 " The buffer is visible in at least one window
581 let currentWinNR = winnr()
582 while winbufnr(sourceWinNR) != -1
583 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
584 execute sourceWinNR . 'wincmd w'
585 if getwinvar(0, '&diff')
586 execute s:vimDiffRestoreCmd
589 let sourceWinNR = sourceWinNR + 1
591 execute currentWinNR . 'wincmd w'
593 " The buffer is hidden. It must be visible in order to set the
595 let currentBufNR = bufnr('')
596 execute 'hide buffer' s:vimDiffSourceBuffer
597 if getwinvar(0, '&diff')
598 execute s:vimDiffRestoreCmd
600 execute 'hide buffer' currentBufNR
603 unlet s:vimDiffRestoreCmd
605 " All buffers are gone.
606 unlet s:vimDiffSourceBuffer
607 unlet s:vimDiffScratchList
613 let s:isEditFileRunning -= 1
617 " Section: Generic VCS command functions {{{1
619 " Function: s:VCSCommit() {{{2
620 function! s:VCSCommit(bang, message)
622 let vcsType = VCSCommandGetVCSType(bufnr('%'))
623 if !has_key(s:plugins, vcsType)
624 throw 'Unknown VCS type: ' . vcsType
627 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
629 " Handle the commit message being specified. If a message is supplied, it
630 " is used; if bang is supplied, an empty message is used; otherwise, the
631 " user is provided a buffer from which to edit the commit message.
633 if strlen(a:message) > 0 || a:bang == '!'
634 return s:VCSFinishCommit([a:message], originalBuffer)
637 call s:EditFile('commitlog', originalBuffer, '')
640 " Create a commit mapping.
642 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
644 silent 0put ='VCS: ----------------------------------------------------------------------'
645 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
646 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
648 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
650 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
651 silent put ='VCS: or write this buffer'
654 silent put ='VCS: ----------------------------------------------------------------------'
658 call s:ReportError(v:exception)
663 " Function: s:VCSFinishCommitWithBuffer() {{{2
664 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
665 " which removes all lines starting with 'VCS:'.
667 function! s:VCSFinishCommitWithBuffer()
669 let currentBuffer = bufnr('%')
670 let logMessageList = getbufline('%', 1, '$')
671 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
672 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
674 execute 'bw' currentBuffer
679 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
680 function! s:VCSFinishCommit(logMessageList, originalBuffer)
681 let shellSlashBak = &shellslash
684 let messageFileName = tempname()
685 call writefile(a:logMessageList, messageFileName)
687 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
691 return s:MarkOrigBufferForSetup(resultBuffer)
693 call delete(messageFileName)
696 let &shellslash = shellSlashBak
700 " Function: s:VCSGotoOriginal(bang) {{{2
701 function! s:VCSGotoOriginal(bang)
702 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
703 if originalBuffer > 0
704 let origWinNR = bufwinnr(originalBuffer)
706 execute 'buffer' originalBuffer
708 execute origWinNR . 'wincmd w'
712 let buffmaxnr = bufnr('$')
713 while buffnr <= buffmaxnr
714 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
717 let buffnr = buffnr + 1
723 " Function: s:VCSVimDiff(...) {{{2
724 function! s:VCSVimDiff(...)
726 let vcsType = VCSCommandGetVCSType(bufnr('%'))
727 if !has_key(s:plugins, vcsType)
728 throw 'Unknown VCS type: ' . vcsType
730 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
731 let s:isEditFileRunning = s:isEditFileRunning + 1
733 " If there's already a VimDiff'ed window, restore it.
734 " There may only be one VCSVimDiff original window at a time.
736 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
737 " Clear the existing vimdiff setup by removing the result buffers.
738 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
743 " Reset the vimdiff system, as 2 explicit versions were provided.
744 if exists('s:vimDiffSourceBuffer')
745 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
747 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
749 echomsg 'Can''t open revision ' . a:1
752 let b:VCSCommandCommand = 'vimdiff'
754 let s:vimDiffScratchList = [resultBuffer]
755 " If no split method is defined, cheat, and set it to vertical.
757 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
758 let resultBuffer = s:plugins[vcsType][1].Review([a:2])
760 call s:OverrideOption('VCSCommandSplit')
763 echomsg 'Can''t open revision ' . a:1
766 let b:VCSCommandCommand = 'vimdiff'
768 let s:vimDiffScratchList += [resultBuffer]
771 call s:OverrideOption('VCSCommandEdit', 'split')
773 " Force splitting behavior, otherwise why use vimdiff?
774 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
777 let resultBuffer = s:plugins[vcsType][1].Review([])
779 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
782 call s:OverrideOption('VCSCommandSplit')
785 call s:OverrideOption('VCSCommandEdit')
788 echomsg 'Can''t open current revision'
791 let b:VCSCommandCommand = 'vimdiff'
794 if !exists('s:vimDiffSourceBuffer')
795 " New instance of vimdiff.
796 let s:vimDiffScratchList = [resultBuffer]
798 " This could have been invoked on a VCS result buffer, not the
801 execute 'buffer' originalBuffer
802 " Store info for later original buffer restore
803 let s:vimDiffRestoreCmd =
804 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
805 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
806 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
807 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
808 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
809 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
810 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
811 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
815 " Adding a window to an existing vimdiff
816 let s:vimDiffScratchList += [resultBuffer]
820 let s:vimDiffSourceBuffer = originalBuffer
822 " Avoid executing the modeline in the current buffer after the autocommand.
824 let currentBuffer = bufnr('%')
825 let saveModeline = getbufvar(currentBuffer, '&modeline')
827 call setbufvar(currentBuffer, '&modeline', 0)
828 silent do VCSCommand User VCSVimDiffFinish
830 call setbufvar(currentBuffer, '&modeline', saveModeline)
834 let s:isEditFileRunning = s:isEditFileRunning - 1
837 call s:ReportError(v:exception)
842 " Section: Public functions {{{1
844 " Function: VCSCommandGetVCSType() {{{2
845 " Sets the b:VCSCommandVCSType variable in the given buffer to the
846 " appropriate source control system name.
848 " This uses the Identify extension function to test the buffer. If the
849 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
850 " exact. If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
851 " match is considered inexact, and is only applied if no exact match is found.
852 " Multiple inexact matches is currently considered an error.
854 function! VCSCommandGetVCSType(buffer)
855 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
856 if strlen(vcsType) > 0
860 for vcsType in keys(s:plugins)
861 let identified = s:plugins[vcsType][1].Identify(a:buffer)
863 if identified == g:VCSCOMMAND_IDENTIFY_EXACT
864 let matches = [vcsType]
867 let matches += [vcsType]
872 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
874 elseif len(matches) == 0
875 throw 'No suitable plugin'
877 throw 'Too many matching VCS: ' . join(matches)
881 " Function: VCSCommandChdir(directory) {{{2
882 " Changes the current directory, respecting :lcd changes.
884 function! VCSCommandChdir(directory)
886 if exists("*haslocaldir") && haslocaldir()
889 execute command escape(a:directory, ' ')
892 " Function: VCSCommandChangeToCurrentFileDir() {{{2
893 " Go to the directory in which the given file is located.
895 function! VCSCommandChangeToCurrentFileDir(fileName)
896 let oldCwd = getcwd()
897 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
898 if strlen(newCwd) > 0
899 call VCSCommandChdir(newCwd)
904 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
905 " Attempts to locate the original file to which VCS operations were applied
906 " for a given buffer.
908 function! VCSCommandGetOriginalBuffer(vcsBuffer)
909 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
911 if bufexists(origBuffer)
914 " Original buffer no longer exists.
915 throw 'Original buffer for this VCS buffer no longer exists.'
923 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
924 " Allows VCS modules to register themselves.
926 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
927 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
928 if !empty(a:mappingMap)
929 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
930 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
931 for mapname in keys(a:mappingMap)
932 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
937 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
938 " General skeleton for VCS function execution. The given command is executed
939 " after appending the current buffer name (or substituting it for
940 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
943 " The optional 'options' Dictionary may contain the following options:
944 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
945 " non-zero exit status, the command is still considered
946 " successfuly. This defaults to zero.
947 " Returns: name of the new command buffer containing the command results
949 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
950 let allowNonZeroExit = 0
951 if has_key(a:options, 'allowNonZeroExit')
952 let allowNonZeroExit = a:options.allowNonZeroExit
955 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
956 if originalBuffer == -1
957 throw 'Original buffer no longer exists, aborting.'
960 let path = resolve(bufname(originalBuffer))
962 " Work with netrw or other systems where a directory listing is displayed in
968 let fileName = fnamemodify(path, ':t')
971 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
972 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
974 let fullCmd = a:cmd . ' "' . fileName . '"'
977 " Change to the directory of the current buffer. This is done for CVS, but
978 " is left in for other systems as it does not affect them negatively.
980 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
982 let output = system(fullCmd)
984 call VCSCommandChdir(oldCwd)
987 " HACK: if line endings in the repository have been corrupted, the output
988 " of the command will be confused.
989 let output = substitute(output, "\r", '', 'g')
991 if v:shell_error && !allowNonZeroExit
992 if strlen(output) == 0
993 throw 'Version control command failed'
995 let output = substitute(output, '\n', ' ', 'g')
996 throw 'Version control command failed: ' . output
1000 if strlen(output) == 0
1001 " Handle case of no output. In this case, it is important to check the
1002 " file status, especially since cvs edit/unedit may change the attributes
1003 " of the file with no visible output.
1009 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1013 " The last command left a blank line at the end of the buffer. If the
1014 " last line is folded (a side effect of the 'put') then the attempt to
1015 " remove the blank line will kill the last fold.
1017 " This could be fixed by explicitly detecting whether the last line is
1018 " within a fold, but I prefer to simply unfold the result buffer altogether.
1027 " Define the environment and execute user-defined hooks.
1029 silent do VCSCommand User VCSBufferCreated
1033 " Function: VCSCommandGetOption(name, default) {{{2
1034 " Grab a user-specified option to override the default provided. Options are
1035 " searched in the window, buffer, then global spaces.
1037 function! VCSCommandGetOption(name, default)
1038 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1039 return s:optionOverrides[a:name][-1]
1040 elseif exists('w:' . a:name)
1042 elseif exists('b:' . a:name)
1044 elseif exists('g:' . a:name)
1051 " Function: VCSCommandDisableBufferSetup() {{{2
1052 " Global function for deactivating the buffer autovariables.
1054 function! VCSCommandDisableBufferSetup()
1055 let g:VCSCommandEnableBufferSetup = 0
1056 silent! augroup! VCSCommandPlugin
1059 " Function: VCSCommandEnableBufferSetup() {{{2
1060 " Global function for activating the buffer autovariables.
1062 function! VCSCommandEnableBufferSetup()
1063 let g:VCSCommandEnableBufferSetup = 1
1064 augroup VCSCommandPlugin
1066 au BufEnter * call s:SetupBuffer()
1069 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1071 if g:loaded_VCSCommand == 2
1072 call s:SetupBuffer()
1076 " Function: VCSCommandGetStatusLine() {{{2
1077 " Default (sample) status line entry for VCS-controlled files. This is only
1078 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1079 " variable for how to do this).
1081 function! VCSCommandGetStatusLine()
1082 if exists('b:VCSCommandCommand')
1083 " This is a result buffer. Return nothing because the buffer name
1084 " contains information already.
1088 if exists('b:VCSCommandVCSType')
1089 \ && exists('g:VCSCommandEnableBufferSetup')
1090 \ && g:VCSCommandEnableBufferSetup
1091 \ && exists('b:VCSCommandBufferInfo')
1092 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1098 " Section: Command definitions {{{1
1099 " Section: Primary commands {{{2
1100 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1101 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1102 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1103 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1104 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1105 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1106 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1107 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1108 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1109 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1110 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1111 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1112 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1113 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1114 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1115 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1116 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1118 " Section: VCS buffer management commands {{{2
1119 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1120 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1122 " Allow reloading VCSCommand.vim
1123 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
1125 " Section: Plugin command mappings {{{1
1126 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1127 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1128 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1129 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1130 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1131 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1132 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1133 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1134 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1135 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1136 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1137 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1138 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1139 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1140 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1141 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1143 " Section: Default mappings {{{1
1145 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1146 if !hasmapto('<Plug>VCSAdd')
1147 nmap <unique> <Leader>ca <Plug>VCSAdd
1149 if !hasmapto('<Plug>VCSAnnotate')
1150 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1152 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1153 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1155 if !hasmapto('<Plug>VCSCommit')
1156 nmap <unique> <Leader>cc <Plug>VCSCommit
1158 if !hasmapto('<Plug>VCSDelete')
1159 nmap <unique> <Leader>cD <Plug>VCSDelete
1161 if !hasmapto('<Plug>VCSDiff')
1162 nmap <unique> <Leader>cd <Plug>VCSDiff
1164 if !hasmapto('<Plug>VCSGotoOriginal')
1165 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1167 if !hasmapto('<Plug>VCSInfo')
1168 nmap <unique> <Leader>ci <Plug>VCSInfo
1170 if !hasmapto('<Plug>VCSLock')
1171 nmap <unique> <Leader>cL <Plug>VCSLock
1173 if !hasmapto('<Plug>VCSLog')
1174 nmap <unique> <Leader>cl <Plug>VCSLog
1176 if !hasmapto('<Plug>VCSRevert')
1177 nmap <unique> <Leader>cq <Plug>VCSRevert
1179 if !hasmapto('<Plug>VCSReview')
1180 nmap <unique> <Leader>cr <Plug>VCSReview
1182 if !hasmapto('<Plug>VCSStatus')
1183 nmap <unique> <Leader>cs <Plug>VCSStatus
1185 if !hasmapto('<Plug>VCSUnlock')
1186 nmap <unique> <Leader>cU <Plug>VCSUnlock
1188 if !hasmapto('<Plug>VCSUpdate')
1189 nmap <unique> <Leader>cu <Plug>VCSUpdate
1191 if !hasmapto('<Plug>VCSVimDiff')
1192 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1196 " Section: Menu items {{{1
1197 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1198 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1199 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1200 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1201 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1202 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1203 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1204 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1205 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1206 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1207 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1208 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1210 " Section: Autocommands to restore vimdiff state {{{1
1211 augroup VimDiffRestore
1213 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1216 " Section: Optional activation of buffer management {{{1
1218 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1219 call VCSCommandEnableBufferSetup()
1222 " Section: VIM shutdown hook {{{1
1224 " Close all result buffers when VIM exits, to prevent them from being restored
1227 " Function: s:CloseAllResultBuffers() {{{2
1228 " Closes all vcscommand result buffers.
1229 function! s:CloseAllResultBuffers()
1230 " This avoids using bufdo as that may load buffers already loaded in another
1231 " vim process, resulting in an error.
1233 let buffmaxnr = bufnr('$')
1234 while buffnr <= buffmaxnr
1235 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1238 let buffnr = buffnr + 1
1242 augroup VCSCommandVIMShutdown
1244 au VimLeavePre * call s:CloseAllResultBuffers()
1247 " Section: Plugin completion {{{1
1249 let loaded_VCSCommand = 2
1251 silent do VCSCommand User VCSPluginFinish
1253 let &cpo = s:save_cpo