1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of various Version
4 " Control Systems, such as CVS, SVN, SVK, and git.
6 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
8 " Copyright (c) 2008 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 " If '!' is used, the view of the annotated buffer is split
55 " so that the annotation is in a separate window from the
56 " content, and each is highlighted separately.
58 " VCSBlame Alias for 'VCSAnnotate'.
60 " VCSCommit[!] Commits changes to the current file to source control.
62 " If called with arguments, the arguments are the log message.
64 " If '!' is used, an empty log message is committed.
66 " If called with no arguments, this is a two-step command.
67 " The first step opens a buffer to accept a log message.
68 " When that buffer is written, it is automatically closed and
69 " the file is committed using the information from that log
70 " message. The commit can be abandoned if the log message
71 " buffer is deleted or wiped before being written.
73 " VCSDelete Deletes the current file and removes it from source control.
75 " VCSDiff With no arguments, this displays the differences between
76 " the current file and its parent version under source
77 " control in a new scratch buffer.
79 " With one argument, the diff is performed on the
80 " current file against the specified revision.
82 " With two arguments, the diff is performed between the
83 " specified revisions of the current file.
85 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
86 " to specify diff options. If that variable does not exist,
87 " a plugin-specific default is used. If you wish to have no
88 " options, then set it to the empty string.
90 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
91 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
92 " VCS scratch buffers associated with the original file.
94 " VCSInfo Displays extended information about the current file in a
97 " VCSLock Locks the current file in order to prevent other users from
98 " concurrently modifying it. The exact semantics of this
99 " command depend on the underlying VCS.
101 " VCSLog Displays the version history of the current file in a new
104 " VCSRemove Alias for 'VCSDelete'.
106 " VCSRevert Replaces the modified version of the current file with the
107 " most recent version from the repository.
109 " VCSReview Displays a particular version of the current file in a new
110 " scratch buffer. If no argument is given, the most recent
111 " version of the file on the current branch is retrieved.
113 " VCSStatus Displays versioning information about the current file in a
114 " new scratch buffer.
116 " VCSUnlock Unlocks the current file in order to allow other users from
117 " concurrently modifying it. The exact semantics of this
118 " command depend on the underlying VCS.
120 " VCSUpdate Updates the current file with any relevant changes from the
123 " VCSVimDiff Uses vimdiff to display differences between versions of the
126 " If no revision is specified, the most recent version of the
127 " file on the current branch is used. With one argument,
128 " that argument is used as the revision as above. With two
129 " arguments, the differences between the two revisions is
130 " displayed using vimdiff.
132 " With either zero or one argument, the original buffer is
133 " used to perform the vimdiff. When the scratch buffer is
134 " closed, the original buffer will be returned to normal
137 " Once vimdiff mode is started using the above methods,
138 " additional vimdiff buffers may be added by passing a single
139 " version argument to the command. There may be up to 4
140 " vimdiff buffers total.
142 " Using the 2-argument form of the command resets the vimdiff
143 " to only those 2 versions. Additionally, invoking the
144 " command on a different file will close the previous vimdiff
147 " Mapping documentation: {{{2
149 " By default, a mapping is defined for each command. User-provided mappings
150 " can be used instead by mapping to <Plug>CommandName, for instance:
152 " nmap ,ca <Plug>VCSAdd
154 " The default mappings are as follow:
157 " <Leader>cn VCSAnnotate
158 " <Leader>cN VCSAnnotate!
159 " <Leader>cc VCSCommit
160 " <Leader>cD VCSDelete
162 " <Leader>cg VCSGotoOriginal
163 " <Leader>cG VCSGotoOriginal!
167 " <Leader>cr VCSReview
168 " <Leader>cs VCSStatus
169 " <Leader>cu VCSUpdate
170 " <Leader>cU VCSUnlock
171 " <Leader>cv VCSVimDiff
173 " Options documentation: {{{2
175 " Several variables are checked by the script to determine behavior as follow:
177 " VCSCommandCommitOnWrite
178 " This variable, if set to a non-zero value, causes the pending commit to
179 " take place immediately as soon as the log message buffer is written. If
180 " set to zero, only the VCSCommit mapping will cause the pending commit to
181 " occur. If not set, it defaults to 1.
183 " VCSCommandDeleteOnHide
184 " This variable, if set to a non-zero value, causes the temporary VCS result
185 " buffers to automatically delete themselves when hidden.
187 " VCSCommand{VCSType}DiffOpt
188 " This variable, if set, determines the options passed to the diff command
189 " of the underlying VCS. Each VCS plugin defines a default value.
191 " VCSCommandDiffSplit
192 " This variable overrides the VCSCommandSplit variable, but only for buffers
193 " created with VCSVimDiff.
195 " VCSCommandDisableAll
196 " This variable, if set, prevents the plugin or any extensions from loading
197 " at all. This is useful when a single runtime distribution is used on
198 " multiple systems with varying versions.
200 " VCSCommandDisableMappings
201 " This variable, if set to a non-zero value, prevents the default command
202 " mappings from being set.
204 " VCSCommandDisableExtensionMappings
205 " This variable, if set to a non-zero value, prevents the default command
206 " mappings from being set for commands specific to an individual VCS.
209 " This variable controls whether to split the current window to display a
210 " scratch buffer ('split'), or to display it in the current buffer ('edit').
211 " If not set, it defaults to 'split'.
213 " VCSCommandEnableBufferSetup
214 " This variable, if set to a non-zero value, activates VCS buffer management
215 " mode. This mode means that the buffer variable 'VCSRevision' is set if
216 " the file is VCS-controlled. This is useful for displaying version
217 " information in the status bar. Additional options may be set by
218 " individual VCS plugins.
221 " This variable, if set, overrides the default mappings used for shortcuts.
222 " It should be a List of 2-element Lists, each containing a shortcut and
223 " function name pair.
225 " VCSCommandMapPrefix
226 " This variable, if set, overrides the default mapping prefix ('<Leader>c').
227 " This allows customization of the mapping space used by the vcscommand
230 " VCSCommandResultBufferNameExtension
231 " This variable, if set to a non-blank value, is appended to the name of the
232 " VCS command output buffers. For example, '.vcs'. Using this option may
233 " help avoid problems caused by autocommands dependent on file extension.
235 " VCSCommandResultBufferNameFunction
236 " This variable, if set, specifies a custom function for naming VCS command
237 " output buffers. This function will be passed the following arguments:
239 " command - name of the VCS command being executed (such as 'Log' or
242 " originalBuffer - buffer number of the source file.
244 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
246 " statusText - extra text associated with the VCS action (such as version
250 " This variable controls the orientation of the various window splits that
251 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
252 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
253 " If set to 'horizontal', the resulting windows will be on stacked on top of
254 " one another. If set to 'vertical', the resulting windows will be
255 " side-by-side. If not set, it defaults to 'horizontal' for all but
256 " VCSVimDiff windows.
258 " VCSCommandVCSTypeOverride
259 " This variable allows the VCS type detection to be overridden on a
260 " path-by-path basis. The value of this variable is expected to be a List
261 " of Lists. Each high-level List item is a List containing two elements.
262 " The first element is a regular expression that will be matched against the
263 " full file name of a given buffer. If it matches, the second element will
264 " be used as the VCS type.
266 " Event documentation {{{2
267 " For additional customization, VCSCommand.vim uses User event autocommand
268 " hooks. Each event is in the VCSCommand group, and different patterns
269 " match the various hooks.
271 " For instance, the following could be added to the vimrc to provide a 'q'
272 " mapping to quit a VCS scratch buffer:
275 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
278 " The following hooks are available:
280 " VCSBufferCreated This event is fired just after a VCS command
281 " output buffer is created. It is executed
282 " within the context of the new buffer.
284 " VCSBufferSetup This event is fired just after VCS buffer setup
285 " occurs, if enabled.
287 " VCSPluginInit This event is fired when the VCSCommand plugin
290 " VCSPluginFinish This event is fired just after the VCSCommand
293 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
294 " command executes to allow customization of,
295 " for instance, window placement and focus.
297 " Section: Plugin header {{{1
299 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
300 " completes. This allows various actions to only be taken by functions after
301 " system initialization.
303 if exists('VCSCommandDisableAll')
307 if exists('loaded_VCSCommand')
310 let loaded_VCSCommand = 1
313 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
320 " Section: Event group setup {{{1
325 augroup VCSCommandCommit
328 " Section: Plugin initialization {{{1
329 silent do VCSCommand User VCSPluginInit
331 " Section: Constants declaration {{{1
333 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
334 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
336 " Section: Script variable initialization {{{1
338 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
341 " temporary values of overridden configuration variables
342 let s:optionOverrides = {}
344 " state flag used to vary behavior of certain automated actions
345 let s:isEditFileRunning = 0
347 " commands needed to restore diff buffers to their original state
348 unlet! s:vimDiffRestoreCmd
350 " original buffer currently reflected in vimdiff windows
351 unlet! s:vimDiffSourceBuffer
354 unlet! s:vimDiffScratchList
356 " Section: Utility functions {{{1
358 " Function: s:ReportError(mapping) {{{2
359 " Displays the given error in a consistent faction. This is intended to be
360 " invoked from a catch statement.
362 function! s:ReportError(error)
363 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
367 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
368 " Creates the given mapping by prepending the contents of
369 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
370 " mapping it to the given plugin function. If a mapping exists for the
371 " specified shortcut + prefix, emit an error but continue. If a mapping
372 " exists for the specified function, do nothing.
374 function! s:CreateMapping(shortcut, expansion, display)
375 let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
376 if !hasmapto(a:expansion)
378 execute 'nmap <silent> <unique>' lhs a:expansion
379 catch /^Vim(.*):E227:/
381 echohl WarningMsg|echomsg 'VCSCommand: mapping ''' . lhs . ''' already exists, refusing to overwrite. The mapping for ' . a:display . ' will not be available.'|echohl None
387 " Function: s:ExecuteExtensionMapping(mapping) {{{2
388 " Invokes the appropriate extension mapping depending on the type of the
391 function! s:ExecuteExtensionMapping(mapping)
392 let buffer = bufnr('%')
393 let vcsType = VCSCommandGetVCSType(buffer)
394 if !has_key(s:plugins, vcsType)
395 throw 'Unknown VCS type: ' . vcsType
397 if !has_key(s:plugins[vcsType][2], a:mapping)
398 throw 'This extended mapping is not defined for ' . vcsType
400 silent execute 'normal' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
403 " Function: s:ExecuteVCSCommand(command, argList) {{{2
404 " Calls the indicated plugin-specific VCS command on the current buffer.
405 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
408 function! s:ExecuteVCSCommand(command, argList)
410 let buffer = bufnr('%')
412 let vcsType = VCSCommandGetVCSType(buffer)
413 if !has_key(s:plugins, vcsType)
414 throw 'Unknown VCS type: ' . vcsType
417 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
418 let bufferName = bufname(originalBuffer)
420 " It is already known that the directory is under VCS control. No further
421 " checks are needed. Otherwise, perform some basic sanity checks to avoid
422 " VCS-specific error messages from confusing things.
423 if !isdirectory(bufferName)
424 if !filereadable(bufferName)
425 throw 'No such file ' . bufferName
429 let functionMap = s:plugins[vcsType][1]
430 if !has_key(functionMap, a:command)
431 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
433 return functionMap[a:command](a:argList)
435 call s:ReportError(v:exception)
440 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
441 " Default method of generating the name for VCS result buffers. This can be
442 " overridden with the VCSResultBufferNameFunction variable.
444 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
445 let fileName = bufname(a:originalBuffer)
446 let bufferName = a:vcsType . ' ' . a:command
447 if strlen(a:statusText) > 0
448 let bufferName .= ' ' . a:statusText
450 let bufferName .= ' ' . fileName
452 let versionedBufferName = bufferName
453 while buflisted(versionedBufferName)
455 let versionedBufferName = bufferName . ' (' . counter . ')'
457 return versionedBufferName
460 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
461 " Method of generating the name for VCS result buffers that uses the original
462 " file name with the VCS type and command appended as extensions.
464 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
465 let fileName = bufname(a:originalBuffer)
466 let bufferName = a:vcsType . ' ' . a:command
467 if strlen(a:statusText) > 0
468 let bufferName .= ' ' . a:statusText
470 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
472 let versionedBufferName = bufferName
473 while buflisted(versionedBufferName)
475 let versionedBufferName = '(' . counter . ') ' . bufferName
477 return versionedBufferName
480 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
481 " Creates a new buffer of the given name and associates it with the given
484 function! s:EditFile(command, originalBuffer, statusText)
485 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
487 " Protect against useless buffer set-up
488 let s:isEditFileRunning += 1
490 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
491 if editCommand == 'split'
492 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
495 vert rightbelow split
501 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
504 let s:isEditFileRunning -= 1
508 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
509 " Creates convenience buffer variables and the name of a vcscommand result
512 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
513 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
514 if nameExtension == ''
515 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
517 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
520 let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
522 let b:VCSCommandCommand = a:command
523 let b:VCSCommandOriginalBuffer = a:originalBuffer
524 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
525 let b:VCSCommandVCSType = a:vcsType
526 if a:statusText != ''
527 let b:VCSCommandStatusText = a:statusText
530 setlocal buftype=nofile
532 let &filetype = a:vcsType . a:command
534 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
535 setlocal bufhidden=delete
537 silent noautocmd file `=name`
540 " Function: s:SetupBuffer() {{{2
541 " Attempts to set the b:VCSCommandBufferInfo variable
543 function! s:SetupBuffer()
544 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
545 " This buffer is already set up.
549 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
550 " No special status for special buffers other than directory buffers.
554 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
555 unlet! b:VCSCommandBufferSetup
560 let vcsType = VCSCommandGetVCSType(bufnr('%'))
561 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
562 silent do VCSCommand User VCSBufferSetup
563 catch /No suitable plugin/
564 " This is not a VCS-controlled file.
565 let b:VCSCommandBufferInfo = []
568 let b:VCSCommandBufferSetup = 1
571 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
572 " Resets the buffer setup state of the original buffer for a given VCS scratch
574 " Returns: The VCS buffer number in a passthrough mode.
576 function! s:MarkOrigBufferForSetup(buffer)
579 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
580 " This should never not work, but I'm paranoid
581 if origBuffer != a:buffer
582 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
588 " Function: s:OverrideOption(option, [value]) {{{2
589 " Provides a temporary override for the given VCS option. If no value is
590 " passed, the override is disabled.
592 function! s:OverrideOption(option, ...)
594 call remove(s:optionOverrides[a:option], -1)
596 if !has_key(s:optionOverrides, a:option)
597 let s:optionOverrides[a:option] = []
599 call add(s:optionOverrides[a:option], a:1)
603 " Function: s:WipeoutCommandBuffers() {{{2
604 " Clears all current VCS output buffers of the specified type for a given source.
606 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
608 while buffer <= bufnr('$')
609 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
610 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
614 let buffer = buffer + 1
618 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
619 " Checks whether the given buffer is one whose deletion should trigger
620 " restoration of an original buffer after it was diffed. If so, it executes
621 " the appropriate setting command stored with that original buffer.
623 function! s:VimDiffRestore(vimDiffBuff)
624 let s:isEditFileRunning += 1
626 if exists('s:vimDiffSourceBuffer')
627 if a:vimDiffBuff == s:vimDiffSourceBuffer
628 " Original file is being removed.
629 unlet! s:vimDiffSourceBuffer
630 unlet! s:vimDiffRestoreCmd
631 unlet! s:vimDiffScratchList
633 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
635 call remove(s:vimDiffScratchList, index)
636 if len(s:vimDiffScratchList) == 0
637 if exists('s:vimDiffRestoreCmd')
638 " All scratch buffers are gone, reset the original.
639 " Only restore if the source buffer is still in Diff mode
641 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
643 " The buffer is visible in at least one window
644 let currentWinNR = winnr()
645 while winbufnr(sourceWinNR) != -1
646 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
647 execute sourceWinNR . 'wincmd w'
648 if getwinvar(0, '&diff')
649 execute s:vimDiffRestoreCmd
652 let sourceWinNR = sourceWinNR + 1
654 execute currentWinNR . 'wincmd w'
656 " The buffer is hidden. It must be visible in order to set the
658 let currentBufNR = bufnr('')
659 execute 'hide buffer' s:vimDiffSourceBuffer
660 if getwinvar(0, '&diff')
661 execute s:vimDiffRestoreCmd
663 execute 'hide buffer' currentBufNR
666 unlet s:vimDiffRestoreCmd
668 " All buffers are gone.
669 unlet s:vimDiffSourceBuffer
670 unlet s:vimDiffScratchList
676 let s:isEditFileRunning -= 1
680 " Section: Generic VCS command functions {{{1
682 " Function: s:VCSAnnotate(...) {{{2
683 function! s:VCSAnnotate(bang, ...)
685 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
686 if annotateBuffer == -1
689 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
690 let vcsType = VCSCommandGetVCSType(annotateBuffer)
691 let functionMap = s:plugins[vcsType][1]
693 if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
694 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
696 let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
698 return annotateBuffer
700 let originalBuffer = VCSCommandGetOriginalBuffer(annotateBuffer)
701 let originalFileType = getbufvar(originalBuffer, '&ft')
702 let annotateFileType = getbufvar(annotateBuffer, '&ft')
703 execute "normal 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
704 call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
708 execute "normal" . col('$') . "\<c-w>|"
709 call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
712 return annotateBuffer
714 call s:ReportError(v:exception)
719 " Function: s:VCSCommit() {{{2
720 function! s:VCSCommit(bang, message)
722 let vcsType = VCSCommandGetVCSType(bufnr('%'))
723 if !has_key(s:plugins, vcsType)
724 throw 'Unknown VCS type: ' . vcsType
727 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
729 " Handle the commit message being specified. If a message is supplied, it
730 " is used; if bang is supplied, an empty message is used; otherwise, the
731 " user is provided a buffer from which to edit the commit message.
733 if strlen(a:message) > 0 || a:bang == '!'
734 return s:VCSFinishCommit([a:message], originalBuffer)
737 call s:EditFile('commitlog', originalBuffer, '')
738 setlocal ft=vcscommit
740 " Create a commit mapping.
742 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
744 silent 0put ='VCS: ----------------------------------------------------------------------'
745 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
746 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
748 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
749 setlocal buftype=acwrite
750 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
751 silent put ='VCS: or write this buffer'
754 silent put ='VCS: ----------------------------------------------------------------------'
758 call s:ReportError(v:exception)
763 " Function: s:VCSFinishCommitWithBuffer() {{{2
764 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
765 " which removes all lines starting with 'VCS:'.
767 function! s:VCSFinishCommitWithBuffer()
769 let currentBuffer = bufnr('%')
770 let logMessageList = getbufline('%', 1, '$')
771 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
772 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
774 execute 'bw' currentBuffer
779 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
780 function! s:VCSFinishCommit(logMessageList, originalBuffer)
781 let shellSlashBak = &shellslash
784 let messageFileName = tempname()
785 call writefile(a:logMessageList, messageFileName)
787 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
791 return s:MarkOrigBufferForSetup(resultBuffer)
793 call delete(messageFileName)
796 let &shellslash = shellSlashBak
800 " Function: s:VCSGotoOriginal(bang) {{{2
801 function! s:VCSGotoOriginal(bang)
802 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
803 if originalBuffer > 0
804 let origWinNR = bufwinnr(originalBuffer)
806 execute 'buffer' originalBuffer
808 execute origWinNR . 'wincmd w'
812 let buffmaxnr = bufnr('$')
813 while buffnr <= buffmaxnr
814 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
817 let buffnr = buffnr + 1
823 " Function: s:VCSVimDiff(...) {{{2
824 function! s:VCSVimDiff(...)
826 let vcsType = VCSCommandGetVCSType(bufnr('%'))
827 if !has_key(s:plugins, vcsType)
828 throw 'Unknown VCS type: ' . vcsType
830 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
831 let s:isEditFileRunning = s:isEditFileRunning + 1
833 " If there's already a VimDiff'ed window, restore it.
834 " There may only be one VCSVimDiff original window at a time.
836 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
837 " Clear the existing vimdiff setup by removing the result buffers.
838 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
841 let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
842 let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
843 let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
847 " Reset the vimdiff system, as 2 explicit versions were provided.
848 if exists('s:vimDiffSourceBuffer')
849 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
851 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
853 echomsg 'Can''t open revision ' . a:1
856 let b:VCSCommandCommand = 'vimdiff'
858 let s:vimDiffScratchList = [resultBuffer]
859 " If no split method is defined, cheat, and set it to vertical.
861 call s:OverrideOption('VCSCommandSplit', orientation)
862 let resultBuffer = s:plugins[vcsType][1].Review([a:2])
864 call s:OverrideOption('VCSCommandSplit')
867 echomsg 'Can''t open revision ' . a:1
870 let b:VCSCommandCommand = 'vimdiff'
872 let s:vimDiffScratchList += [resultBuffer]
875 call s:OverrideOption('VCSCommandEdit', 'split')
877 " Force splitting behavior, otherwise why use vimdiff?
878 call s:OverrideOption('VCSCommandSplit', orientation)
881 let resultBuffer = s:plugins[vcsType][1].Review([])
883 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
886 call s:OverrideOption('VCSCommandSplit')
889 call s:OverrideOption('VCSCommandEdit')
892 echomsg 'Can''t open current revision'
895 let b:VCSCommandCommand = 'vimdiff'
898 if !exists('s:vimDiffSourceBuffer')
899 " New instance of vimdiff.
900 let s:vimDiffScratchList = [resultBuffer]
902 " This could have been invoked on a VCS result buffer, not the
905 execute 'buffer' originalBuffer
906 " Store info for later original buffer restore
907 let s:vimDiffRestoreCmd =
908 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
909 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
910 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
911 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
912 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
913 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
914 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
915 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
919 " Adding a window to an existing vimdiff
920 let s:vimDiffScratchList += [resultBuffer]
924 let s:vimDiffSourceBuffer = originalBuffer
926 " Avoid executing the modeline in the current buffer after the autocommand.
928 let currentBuffer = bufnr('%')
929 let saveModeline = getbufvar(currentBuffer, '&modeline')
931 call setbufvar(currentBuffer, '&modeline', 0)
932 silent do VCSCommand User VCSVimDiffFinish
934 call setbufvar(currentBuffer, '&modeline', saveModeline)
938 let s:isEditFileRunning = s:isEditFileRunning - 1
941 call s:ReportError(v:exception)
946 " Section: Public functions {{{1
948 " Function: VCSCommandGetVCSType() {{{2
949 " Sets the b:VCSCommandVCSType variable in the given buffer to the
950 " appropriate source control system name.
952 " This uses the Identify extension function to test the buffer. If the
953 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
954 " exact. If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
955 " match is considered inexact, and is only applied if no exact match is found.
956 " Multiple inexact matches is currently considered an error.
958 function! VCSCommandGetVCSType(buffer)
959 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
960 if strlen(vcsType) > 0
963 if exists("g:VCSCommandVCSTypeOverride")
964 let fullpath = fnamemodify(bufname(a:buffer), ':p')
965 for [path, vcsType] in g:VCSCommandVCSTypeOverride
966 if match(fullpath, path) > -1
967 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
973 for vcsType in keys(s:plugins)
974 let identified = s:plugins[vcsType][1].Identify(a:buffer)
976 if identified == g:VCSCOMMAND_IDENTIFY_EXACT
977 let matches = [vcsType]
980 let matches += [vcsType]
985 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
987 elseif len(matches) == 0
988 throw 'No suitable plugin'
990 throw 'Too many matching VCS: ' . join(matches)
994 " Function: VCSCommandChdir(directory) {{{2
995 " Changes the current directory, respecting :lcd changes.
997 function! VCSCommandChdir(directory)
999 if exists("*haslocaldir") && haslocaldir()
1002 execute command escape(a:directory, ' ')
1005 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1006 " Go to the directory in which the given file is located.
1008 function! VCSCommandChangeToCurrentFileDir(fileName)
1009 let oldCwd = getcwd()
1010 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1011 if strlen(newCwd) > 0
1012 call VCSCommandChdir(newCwd)
1017 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1018 " Attempts to locate the original file to which VCS operations were applied
1019 " for a given buffer.
1021 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1022 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1024 if bufexists(origBuffer)
1027 " Original buffer no longer exists.
1028 throw 'Original buffer for this VCS buffer no longer exists.'
1031 " No original buffer
1036 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1037 " Allows VCS modules to register themselves.
1039 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1040 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1041 if !empty(a:mappingMap)
1042 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1043 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1044 for shortcut in keys(a:mappingMap)
1045 let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1046 call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1051 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1052 " General skeleton for VCS function execution. The given command is executed
1053 " after appending the current buffer name (or substituting it for
1054 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
1057 " The optional 'options' Dictionary may contain the following options:
1058 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
1059 " non-zero exit status, the command is still considered
1060 " successfuly. This defaults to zero.
1061 " Returns: name of the new command buffer containing the command results
1063 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1064 let allowNonZeroExit = 0
1065 if has_key(a:options, 'allowNonZeroExit')
1066 let allowNonZeroExit = a:options.allowNonZeroExit
1069 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1070 if originalBuffer == -1
1071 throw 'Original buffer no longer exists, aborting.'
1074 let path = resolve(bufname(originalBuffer))
1076 " Work with netrw or other systems where a directory listing is displayed in
1079 if isdirectory(path)
1082 let fileName = fnamemodify(path, ':t')
1085 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1086 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1088 let fullCmd = a:cmd . ' "' . fileName . '"'
1091 " Change to the directory of the current buffer. This is done for CVS, but
1092 " is left in for other systems as it does not affect them negatively.
1094 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1096 let output = system(fullCmd)
1098 call VCSCommandChdir(oldCwd)
1101 " HACK: if line endings in the repository have been corrupted, the output
1102 " of the command will be confused.
1103 let output = substitute(output, "\r", '', 'g')
1105 if v:shell_error && !allowNonZeroExit
1106 if strlen(output) == 0
1107 throw 'Version control command failed'
1109 let output = substitute(output, '\n', ' ', 'g')
1110 throw 'Version control command failed: ' . output
1114 if strlen(output) == 0
1115 " Handle case of no output. In this case, it is important to check the
1116 " file status, especially since cvs edit/unedit may change the attributes
1117 " of the file with no visible output.
1123 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1127 " The last command left a blank line at the end of the buffer. If the
1128 " last line is folded (a side effect of the 'put') then the attempt to
1129 " remove the blank line will kill the last fold.
1131 " This could be fixed by explicitly detecting whether the last line is
1132 " within a fold, but I prefer to simply unfold the result buffer altogether.
1141 " Define the environment and execute user-defined hooks.
1143 silent do VCSCommand User VCSBufferCreated
1147 " Function: VCSCommandGetOption(name, default) {{{2
1148 " Grab a user-specified option to override the default provided. Options are
1149 " searched in the window, buffer, then global spaces.
1151 function! VCSCommandGetOption(name, default)
1152 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1153 return s:optionOverrides[a:name][-1]
1154 elseif exists('w:' . a:name)
1156 elseif exists('b:' . a:name)
1158 elseif exists('g:' . a:name)
1165 " Function: VCSCommandDisableBufferSetup() {{{2
1166 " Global function for deactivating the buffer autovariables.
1168 function! VCSCommandDisableBufferSetup()
1169 let g:VCSCommandEnableBufferSetup = 0
1170 silent! augroup! VCSCommandPlugin
1173 " Function: VCSCommandEnableBufferSetup() {{{2
1174 " Global function for activating the buffer autovariables.
1176 function! VCSCommandEnableBufferSetup()
1177 let g:VCSCommandEnableBufferSetup = 1
1178 augroup VCSCommandPlugin
1180 au BufEnter * call s:SetupBuffer()
1183 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1185 if g:loaded_VCSCommand == 2
1186 call s:SetupBuffer()
1190 " Function: VCSCommandGetStatusLine() {{{2
1191 " Default (sample) status line entry for VCS-controlled files. This is only
1192 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1193 " variable for how to do this).
1195 function! VCSCommandGetStatusLine()
1196 if exists('b:VCSCommandCommand')
1197 " This is a result buffer. Return nothing because the buffer name
1198 " contains information already.
1202 if exists('b:VCSCommandVCSType')
1203 \ && exists('g:VCSCommandEnableBufferSetup')
1204 \ && g:VCSCommandEnableBufferSetup
1205 \ && exists('b:VCSCommandBufferInfo')
1206 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1212 " Section: Command definitions {{{1
1213 " Section: Primary commands {{{2
1214 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1215 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1216 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1217 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1218 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1219 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1220 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1221 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1222 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1223 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1224 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1225 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1226 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1227 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1228 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1229 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1230 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1232 " Section: VCS buffer management commands {{{2
1233 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1234 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1236 " Allow reloading VCSCommand.vim
1237 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
1239 " Section: Plugin command mappings {{{1
1240 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1241 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1242 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1243 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1244 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1245 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1246 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1247 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1248 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1249 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1250 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1251 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1252 nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1253 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1254 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1255 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1256 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1258 " Section: Default mappings {{{1
1260 let s:defaultMappings = [
1262 \['c', 'VCSCommit'],
1263 \['D', 'VCSDelete'],
1265 \['G', 'VCSClearAndGotoOriginal'],
1266 \['g', 'VCSGotoOriginal'],
1270 \['N', 'VCSSplitAnnotate'],
1271 \['n', 'VCSAnnotate'],
1272 \['q', 'VCSRevert'],
1273 \['r', 'VCSReview'],
1274 \['s', 'VCSStatus'],
1275 \['U', 'VCSUnlock'],
1276 \['u', 'VCSUpdate'],
1277 \['v', 'VCSVimDiff'],
1280 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1281 for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1282 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1286 " Section: Menu items {{{1
1287 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1288 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1289 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1290 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1291 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1292 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1293 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1294 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1295 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1296 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1297 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1298 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1300 " Section: Autocommands to restore vimdiff state {{{1
1301 augroup VimDiffRestore
1303 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1306 " Section: Optional activation of buffer management {{{1
1308 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1309 call VCSCommandEnableBufferSetup()
1312 " Section: VIM shutdown hook {{{1
1314 " Close all result buffers when VIM exits, to prevent them from being restored
1317 " Function: s:CloseAllResultBuffers() {{{2
1318 " Closes all vcscommand result buffers.
1319 function! s:CloseAllResultBuffers()
1320 " This avoids using bufdo as that may load buffers already loaded in another
1321 " vim process, resulting in an error.
1323 let buffmaxnr = bufnr('$')
1324 while buffnr <= buffmaxnr
1325 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1328 let buffnr = buffnr + 1
1332 augroup VCSCommandVIMShutdown
1334 au VimLeavePre * call s:CloseAllResultBuffers()
1337 " Section: Plugin completion {{{1
1339 let loaded_VCSCommand = 2
1341 silent do VCSCommand User VCSPluginFinish
1343 let &cpo = s:save_cpo