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: Script variable initialization {{{1
301 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
304 " temporary values of overridden configuration variables
305 let s:optionOverrides = {}
307 " state flag used to vary behavior of certain automated actions
308 let s:isEditFileRunning = 0
310 " commands needed to restore diff buffers to their original state
311 unlet! s:vimDiffRestoreCmd
313 " original buffer currently reflected in vimdiff windows
314 unlet! s:vimDiffSourceBuffer
317 unlet! s:vimDiffScratchList
319 " Section: Utility functions {{{1
321 " Function: s:ReportError(mapping) {{{2
322 " Displays the given error in a consistent faction. This is intended to be
323 " invoked from a catch statement.
325 function! s:ReportError(error)
326 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
329 " Function: s:ExecuteExtensionMapping(mapping) {{{2
330 " Invokes the appropriate extension mapping depending on the type of the
333 function! s:ExecuteExtensionMapping(mapping)
334 let buffer = bufnr('%')
335 let vcsType = VCSCommandGetVCSType(buffer)
336 if !has_key(s:plugins, vcsType)
337 throw 'Unknown VCS type: ' . vcsType
339 if !has_key(s:plugins[vcsType][2], a:mapping)
340 throw 'This extended mapping is not defined for ' . vcsType
342 silent execute 'normal' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
345 " Function: s:ExecuteVCSCommand(command, argList) {{{2
346 " Calls the indicated plugin-specific VCS command on the current buffer.
347 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
350 function! s:ExecuteVCSCommand(command, argList)
352 let buffer = bufnr('%')
354 let vcsType = VCSCommandGetVCSType(buffer)
355 if !has_key(s:plugins, vcsType)
356 throw 'Unknown VCS type: ' . vcsType
359 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
360 let bufferName = bufname(originalBuffer)
362 " It is already known that the directory is under VCS control. No further
363 " checks are needed. Otherwise, perform some basic sanity checks to avoid
364 " VCS-specific error messages from confusing things.
365 if !isdirectory(bufferName)
366 if !filereadable(bufferName)
367 throw 'No such file ' . bufferName
371 let functionMap = s:plugins[vcsType][1]
372 if !has_key(functionMap, a:command)
373 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
375 return functionMap[a:command](a:argList)
377 call s:ReportError(v:exception)
382 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
383 " Default method of generating the name for VCS result buffers. This can be
384 " overridden with the VCSResultBufferNameFunction variable.
386 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
387 let fileName = bufname(a:originalBuffer)
388 let bufferName = a:vcsType . ' ' . a:command
389 if strlen(a:statusText) > 0
390 let bufferName .= ' ' . a:statusText
392 let bufferName .= ' ' . fileName
394 let versionedBufferName = bufferName
395 while buflisted(versionedBufferName)
397 let versionedBufferName = bufferName . ' (' . counter . ')'
399 return versionedBufferName
402 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
403 " Method of generating the name for VCS result buffers that uses the original
404 " file name with the VCS type and command appended as extensions.
406 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
407 let fileName = bufname(a:originalBuffer)
408 let bufferName = a:vcsType . ' ' . a:command
409 if strlen(a:statusText) > 0
410 let bufferName .= ' ' . a:statusText
412 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
414 let versionedBufferName = bufferName
415 while buflisted(versionedBufferName)
417 let versionedBufferName = '(' . counter . ') ' . bufferName
419 return versionedBufferName
422 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
423 " Creates a new buffer of the given name and associates it with the given
426 function! s:EditFile(command, originalBuffer, statusText)
427 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
429 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
430 if nameExtension == ''
431 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
433 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
436 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
438 " Protect against useless buffer set-up
439 let s:isEditFileRunning += 1
441 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
442 if editCommand == 'split'
443 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
446 vert rightbelow split
449 edit `=resultBufferName`
450 let b:VCSCommandCommand = a:command
451 let b:VCSCommandOriginalBuffer = a:originalBuffer
452 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
453 let b:VCSCommandVCSType = vcsType
457 let &filetype = vcsType . a:command
459 if a:statusText != ''
460 let b:VCSCommandStatusText = a:statusText
463 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
467 let s:isEditFileRunning -= 1
472 " Function: s:SetupBuffer() {{{2
473 " Attempts to set the b:VCSCommandBufferInfo variable
475 function! s:SetupBuffer()
476 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
477 " This buffer is already set up.
481 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
482 " No special status for special buffers other than directory buffers.
486 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
487 unlet! b:VCSCommandBufferSetup
492 let vcsType = VCSCommandGetVCSType(bufnr('%'))
493 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
494 silent do VCSCommand User VCSBufferSetup
495 catch /No suitable plugin/
496 " This is not a VCS-controlled file.
497 let b:VCSCommandBufferInfo = []
500 let b:VCSCommandBufferSetup = 1
503 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
504 " Resets the buffer setup state of the original buffer for a given VCS scratch
506 " Returns: The VCS buffer number in a passthrough mode.
508 function! s:MarkOrigBufferForSetup(buffer)
511 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
512 " This should never not work, but I'm paranoid
513 if origBuffer != a:buffer
514 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
520 " Function: s:OverrideOption(option, [value]) {{{2
521 " Provides a temporary override for the given VCS option. If no value is
522 " passed, the override is disabled.
524 function! s:OverrideOption(option, ...)
526 call remove(s:optionOverrides[a:option], -1)
528 if !has_key(s:optionOverrides, a:option)
529 let s:optionOverrides[a:option] = []
531 call add(s:optionOverrides[a:option], a:1)
535 " Function: s:WipeoutCommandBuffers() {{{2
536 " Clears all current VCS output buffers of the specified type for a given source.
538 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
540 while buffer <= bufnr('$')
541 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
542 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
546 let buffer = buffer + 1
550 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
551 " Checks whether the given buffer is one whose deletion should trigger
552 " restoration of an original buffer after it was diffed. If so, it executes
553 " the appropriate setting command stored with that original buffer.
555 function! s:VimDiffRestore(vimDiffBuff)
556 let s:isEditFileRunning += 1
558 if exists('s:vimDiffSourceBuffer')
559 if a:vimDiffBuff == s:vimDiffSourceBuffer
560 " Original file is being removed.
561 unlet! s:vimDiffSourceBuffer
562 unlet! s:vimDiffRestoreCmd
563 unlet! s:vimDiffScratchList
565 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
567 call remove(s:vimDiffScratchList, index)
568 if len(s:vimDiffScratchList) == 0
569 if exists('s:vimDiffRestoreCmd')
570 " All scratch buffers are gone, reset the original.
571 " Only restore if the source buffer is still in Diff mode
573 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
575 " The buffer is visible in at least one window
576 let currentWinNR = winnr()
577 while winbufnr(sourceWinNR) != -1
578 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
579 execute sourceWinNR . 'wincmd w'
580 if getwinvar(0, '&diff')
581 execute s:vimDiffRestoreCmd
584 let sourceWinNR = sourceWinNR + 1
586 execute currentWinNR . 'wincmd w'
588 " The buffer is hidden. It must be visible in order to set the
590 let currentBufNR = bufnr('')
591 execute 'hide buffer' s:vimDiffSourceBuffer
592 if getwinvar(0, '&diff')
593 execute s:vimDiffRestoreCmd
595 execute 'hide buffer' currentBufNR
598 unlet s:vimDiffRestoreCmd
600 " All buffers are gone.
601 unlet s:vimDiffSourceBuffer
602 unlet s:vimDiffScratchList
608 let s:isEditFileRunning -= 1
612 " Section: Generic VCS command functions {{{1
614 " Function: s:VCSCommit() {{{2
615 function! s:VCSCommit(bang, message)
617 let vcsType = VCSCommandGetVCSType(bufnr('%'))
618 if !has_key(s:plugins, vcsType)
619 throw 'Unknown VCS type: ' . vcsType
622 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
624 " Handle the commit message being specified. If a message is supplied, it
625 " is used; if bang is supplied, an empty message is used; otherwise, the
626 " user is provided a buffer from which to edit the commit message.
628 if strlen(a:message) > 0 || a:bang == '!'
629 return s:VCSFinishCommit([a:message], originalBuffer)
632 call s:EditFile('commitlog', originalBuffer, '')
635 " Create a commit mapping.
637 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
639 silent 0put ='VCS: ----------------------------------------------------------------------'
640 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
641 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
643 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
645 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
646 silent put ='VCS: or write this buffer'
649 silent put ='VCS: ----------------------------------------------------------------------'
653 call s:ReportError(v:exception)
658 " Function: s:VCSFinishCommitWithBuffer() {{{2
659 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
660 " which removes all lines starting with 'VCS:'.
662 function! s:VCSFinishCommitWithBuffer()
664 let currentBuffer = bufnr('%')
665 let logMessageList = getbufline('%', 1, '$')
666 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
667 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
669 execute 'bw' currentBuffer
674 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
675 function! s:VCSFinishCommit(logMessageList, originalBuffer)
676 let shellSlashBak = &shellslash
679 let messageFileName = tempname()
680 call writefile(a:logMessageList, messageFileName)
682 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
686 return s:MarkOrigBufferForSetup(resultBuffer)
688 call delete(messageFileName)
691 let &shellslash = shellSlashBak
695 " Function: s:VCSGotoOriginal(bang) {{{2
696 function! s:VCSGotoOriginal(bang)
697 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
698 if originalBuffer > 0
699 let origWinNR = bufwinnr(originalBuffer)
701 execute 'buffer' originalBuffer
703 execute origWinNR . 'wincmd w'
707 let buffmaxnr = bufnr('$')
708 while buffnr <= buffmaxnr
709 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
712 let buffnr = buffnr + 1
718 " Function: s:VCSVimDiff(...) {{{2
719 function! s:VCSVimDiff(...)
721 let vcsType = VCSCommandGetVCSType(bufnr('%'))
722 if !has_key(s:plugins, vcsType)
723 throw 'Unknown VCS type: ' . vcsType
725 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
726 let s:isEditFileRunning = s:isEditFileRunning + 1
728 " If there's already a VimDiff'ed window, restore it.
729 " There may only be one VCSVimDiff original window at a time.
731 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
732 " Clear the existing vimdiff setup by removing the result buffers.
733 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
738 " Reset the vimdiff system, as 2 explicit versions were provided.
739 if exists('s:vimDiffSourceBuffer')
740 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
742 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
744 echomsg 'Can''t open revision ' . a:1
747 let b:VCSCommandCommand = 'vimdiff'
749 let s:vimDiffScratchList = [resultBuffer]
750 " If no split method is defined, cheat, and set it to vertical.
752 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
753 let resultBuffer = s:plugins[vcsType][1].Review([a:2])
755 call s:OverrideOption('VCSCommandSplit')
758 echomsg 'Can''t open revision ' . a:1
761 let b:VCSCommandCommand = 'vimdiff'
763 let s:vimDiffScratchList += [resultBuffer]
766 call s:OverrideOption('VCSCommandEdit', 'split')
768 " Force splitting behavior, otherwise why use vimdiff?
769 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
772 let resultBuffer = s:plugins[vcsType][1].Review([])
774 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
777 call s:OverrideOption('VCSCommandSplit')
780 call s:OverrideOption('VCSCommandEdit')
783 echomsg 'Can''t open current revision'
786 let b:VCSCommandCommand = 'vimdiff'
789 if !exists('s:vimDiffSourceBuffer')
790 " New instance of vimdiff.
791 let s:vimDiffScratchList = [resultBuffer]
793 " This could have been invoked on a VCS result buffer, not the
796 execute 'buffer' originalBuffer
797 " Store info for later original buffer restore
798 let s:vimDiffRestoreCmd =
799 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
800 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
801 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
802 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
803 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
804 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
805 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
806 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
810 " Adding a window to an existing vimdiff
811 let s:vimDiffScratchList += [resultBuffer]
815 let s:vimDiffSourceBuffer = originalBuffer
817 " Avoid executing the modeline in the current buffer after the autocommand.
819 let currentBuffer = bufnr('%')
820 let saveModeline = getbufvar(currentBuffer, '&modeline')
822 call setbufvar(currentBuffer, '&modeline', 0)
823 silent do VCSCommand User VCSVimDiffFinish
825 call setbufvar(currentBuffer, '&modeline', saveModeline)
829 let s:isEditFileRunning = s:isEditFileRunning - 1
832 call s:ReportError(v:exception)
837 " Section: Public functions {{{1
839 " Function: VCSCommandGetVCSType() {{{2
840 " Sets the b:VCSCommandVCSType variable in the given buffer to the
841 " appropriate source control system name.
843 function! VCSCommandGetVCSType(buffer)
844 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
845 if strlen(vcsType) > 0
848 for vcsType in keys(s:plugins)
849 if s:plugins[vcsType][1].Identify(a:buffer)
850 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
854 throw 'No suitable plugin'
857 " Function: VCSCommandChdir(directory) {{{2
858 " Changes the current directory, respecting :lcd changes.
860 function! VCSCommandChdir(directory)
862 if exists("*haslocaldir") && haslocaldir()
865 execute command escape(a:directory, ' ')
868 " Function: VCSCommandChangeToCurrentFileDir() {{{2
869 " Go to the directory in which the given file is located.
871 function! VCSCommandChangeToCurrentFileDir(fileName)
872 let oldCwd = getcwd()
873 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
874 if strlen(newCwd) > 0
875 call VCSCommandChdir(newCwd)
880 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
881 " Attempts to locate the original file to which VCS operations were applied
882 " for a given buffer.
884 function! VCSCommandGetOriginalBuffer(vcsBuffer)
885 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
887 if bufexists(origBuffer)
890 " Original buffer no longer exists.
891 throw 'Original buffer for this VCS buffer no longer exists.'
899 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
900 " Allows VCS modules to register themselves.
902 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
903 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
904 if !empty(a:mappingMap)
905 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
906 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
907 for mapname in keys(a:mappingMap)
908 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
913 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
914 " General skeleton for VCS function execution. The given command is executed
915 " after appending the current buffer name (or substituting it for
916 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
919 " The optional 'options' Dictionary may contain the following options:
920 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
921 " non-zero exit status, the command is still considered
922 " successfuly. This defaults to zero.
923 " Returns: name of the new command buffer containing the command results
925 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
926 let allowNonZeroExit = 0
927 if has_key(a:options, 'allowNonZeroExit')
928 let allowNonZeroExit = a:options.allowNonZeroExit
931 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
932 if originalBuffer == -1
933 throw 'Original buffer no longer exists, aborting.'
936 let path = resolve(bufname(originalBuffer))
938 " Work with netrw or other systems where a directory listing is displayed in
944 let fileName = fnamemodify(path, ':t')
947 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
948 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
950 let fullCmd = a:cmd . ' "' . fileName . '"'
953 " Change to the directory of the current buffer. This is done for CVS, but
954 " is left in for other systems as it does not affect them negatively.
956 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
958 let output = system(fullCmd)
960 call VCSCommandChdir(oldCwd)
963 " HACK: if line endings in the repository have been corrupted, the output
964 " of the command will be confused.
965 let output = substitute(output, "\r", '', 'g')
967 if v:shell_error && !allowNonZeroExit
968 if strlen(output) == 0
969 throw 'Version control command failed'
971 let output = substitute(output, '\n', ' ', 'g')
972 throw 'Version control command failed: ' . output
976 if strlen(output) == 0
977 " Handle case of no output. In this case, it is important to check the
978 " file status, especially since cvs edit/unedit may change the attributes
979 " of the file with no visible output.
985 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
989 " The last command left a blank line at the end of the buffer. If the
990 " last line is folded (a side effect of the 'put') then the attempt to
991 " remove the blank line will kill the last fold.
993 " This could be fixed by explicitly detecting whether the last line is
994 " within a fold, but I prefer to simply unfold the result buffer altogether.
1003 " Define the environment and execute user-defined hooks.
1005 silent do VCSCommand User VCSBufferCreated
1009 " Function: VCSCommandGetOption(name, default) {{{2
1010 " Grab a user-specified option to override the default provided. Options are
1011 " searched in the window, buffer, then global spaces.
1013 function! VCSCommandGetOption(name, default)
1014 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1015 return s:optionOverrides[a:name][-1]
1016 elseif exists('w:' . a:name)
1018 elseif exists('b:' . a:name)
1020 elseif exists('g:' . a:name)
1027 " Function: VCSCommandDisableBufferSetup() {{{2
1028 " Global function for deactivating the buffer autovariables.
1030 function! VCSCommandDisableBufferSetup()
1031 let g:VCSCommandEnableBufferSetup = 0
1032 silent! augroup! VCSCommandPlugin
1035 " Function: VCSCommandEnableBufferSetup() {{{2
1036 " Global function for activating the buffer autovariables.
1038 function! VCSCommandEnableBufferSetup()
1039 let g:VCSCommandEnableBufferSetup = 1
1040 augroup VCSCommandPlugin
1042 au BufEnter * call s:SetupBuffer()
1045 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1047 if g:loaded_VCSCommand == 2
1048 call s:SetupBuffer()
1052 " Function: VCSCommandGetStatusLine() {{{2
1053 " Default (sample) status line entry for VCS-controlled files. This is only
1054 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1055 " variable for how to do this).
1057 function! VCSCommandGetStatusLine()
1058 if exists('b:VCSCommandCommand')
1059 " This is a result buffer. Return nothing because the buffer name
1060 " contains information already.
1064 if exists('b:VCSCommandVCSType')
1065 \ && exists('g:VCSCommandEnableBufferSetup')
1066 \ && g:VCSCommandEnableBufferSetup
1067 \ && exists('b:VCSCommandBufferInfo')
1068 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1074 " Section: Command definitions {{{1
1075 " Section: Primary commands {{{2
1076 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1077 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1078 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1079 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1080 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1081 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1082 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1083 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1084 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1085 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1086 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1087 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1088 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1089 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1090 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1091 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1092 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1094 " Section: VCS buffer management commands {{{2
1095 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1096 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1098 " Allow reloading VCSCommand.vim
1099 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
1101 " Section: Plugin command mappings {{{1
1102 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1103 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1104 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1105 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1106 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1107 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1108 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1109 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1110 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1111 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1112 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1113 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1114 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1115 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1116 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1117 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1119 " Section: Default mappings {{{1
1121 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1122 if !hasmapto('<Plug>VCSAdd')
1123 nmap <unique> <Leader>ca <Plug>VCSAdd
1125 if !hasmapto('<Plug>VCSAnnotate')
1126 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1128 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1129 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1131 if !hasmapto('<Plug>VCSCommit')
1132 nmap <unique> <Leader>cc <Plug>VCSCommit
1134 if !hasmapto('<Plug>VCSDelete')
1135 nmap <unique> <Leader>cD <Plug>VCSDelete
1137 if !hasmapto('<Plug>VCSDiff')
1138 nmap <unique> <Leader>cd <Plug>VCSDiff
1140 if !hasmapto('<Plug>VCSGotoOriginal')
1141 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1143 if !hasmapto('<Plug>VCSInfo')
1144 nmap <unique> <Leader>ci <Plug>VCSInfo
1146 if !hasmapto('<Plug>VCSLock')
1147 nmap <unique> <Leader>cL <Plug>VCSLock
1149 if !hasmapto('<Plug>VCSLog')
1150 nmap <unique> <Leader>cl <Plug>VCSLog
1152 if !hasmapto('<Plug>VCSRevert')
1153 nmap <unique> <Leader>cq <Plug>VCSRevert
1155 if !hasmapto('<Plug>VCSReview')
1156 nmap <unique> <Leader>cr <Plug>VCSReview
1158 if !hasmapto('<Plug>VCSStatus')
1159 nmap <unique> <Leader>cs <Plug>VCSStatus
1161 if !hasmapto('<Plug>VCSUnlock')
1162 nmap <unique> <Leader>cU <Plug>VCSUnlock
1164 if !hasmapto('<Plug>VCSUpdate')
1165 nmap <unique> <Leader>cu <Plug>VCSUpdate
1167 if !hasmapto('<Plug>VCSVimDiff')
1168 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1172 " Section: Menu items {{{1
1173 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1174 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1175 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1176 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1177 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1178 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1179 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1180 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1181 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1182 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1183 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1184 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1186 " Section: Autocommands to restore vimdiff state {{{1
1187 augroup VimDiffRestore
1189 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1192 " Section: Optional activation of buffer management {{{1
1194 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1195 call VCSCommandEnableBufferSetup()
1198 " Section: VIM shutdown hook {{{1
1200 " Close all result buffers when VIM exits, to prevent them from being restored
1203 " Function: s:CloseAllResultBuffers() {{{2
1204 " Closes all vcscommand result buffers.
1205 function! s:CloseAllResultBuffers()
1206 " This avoids using bufdo as that may load buffers already loaded in another
1207 " vim process, resulting in an error.
1209 let buffmaxnr = bufnr('$')
1210 while buffnr <= buffmaxnr
1211 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1214 let buffnr = buffnr + 1
1218 augroup VCSCommandVIMShutdown
1220 au VimLeavePre * call s:CloseAllResultBuffers()
1223 " Section: Plugin completion {{{1
1225 let loaded_VCSCommand = 2
1227 silent do VCSCommand User VCSPluginFinish
1229 let &cpo = s:save_cpo