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 " 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 " VCSCommandDisableAll
191 " This variable, if set, prevents the plugin or any extensions from loading
192 " at all. This is useful when a single runtime distribution is used on
193 " multiple systems with varying versions.
195 " VCSCommandDisableMappings
196 " This variable, if set to a non-zero value, prevents the default command
197 " mappings from being set.
199 " VCSCommandDisableExtensionMappings
200 " This variable, if set to a non-zero value, prevents the default command
201 " mappings from being set for commands specific to an individual VCS.
204 " This variable controls whether to split the current window to display a
205 " scratch buffer ('split'), or to display it in the current buffer ('edit').
206 " If not set, it defaults to 'split'.
208 " VCSCommandEnableBufferSetup
209 " This variable, if set to a non-zero value, activates VCS buffer management
210 " mode. This mode means that the buffer variable 'VCSRevision' is set if
211 " the file is VCS-controlled. This is useful for displaying version
212 " information in the status bar. Additional options may be set by
213 " individual VCS plugins.
216 " This variable, if set, overrides the default mappings used for shortcuts.
217 " It should be a List of 2-element Lists, each containing a shortcut and
218 " function name pair.
220 " VCSCommandMapPrefix
221 " This variable, if set, overrides the default mapping prefix ('<Leader>c').
222 " This allows customization of the mapping space used by the vcscommand
225 " VCSCommandResultBufferNameExtension
226 " This variable, if set to a non-blank value, is appended to the name of the
227 " VCS command output buffers. For example, '.vcs'. Using this option may
228 " help avoid problems caused by autocommands dependent on file extension.
230 " VCSCommandResultBufferNameFunction
231 " This variable, if set, specifies a custom function for naming VCS command
232 " output buffers. This function will be passed the following arguments:
234 " command - name of the VCS command being executed (such as 'Log' or
237 " originalBuffer - buffer number of the source file.
239 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
241 " statusText - extra text associated with the VCS action (such as version
245 " This variable controls the orientation of the various window splits that
246 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
247 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
248 " If set to 'horizontal', the resulting windows will be on stacked on top of
249 " one another. If set to 'vertical', the resulting windows will be
250 " side-by-side. If not set, it defaults to 'horizontal' for all but
251 " VCSVimDiff windows.
253 " VCSCommandVCSTypeOverride
254 " This variable allows the VCS type detection to be overridden on a
255 " path-by-path basis. The value of this variable is expected to be a List
256 " of Lists. Each high-level List item is a List containing two elements.
257 " The first element is a regular expression that will be matched against the
258 " full file name of a given buffer. If it matches, the second element will
259 " be used as the VCS type.
261 " Event documentation {{{2
262 " For additional customization, VCSCommand.vim uses User event autocommand
263 " hooks. Each event is in the VCSCommand group, and different patterns
264 " match the various hooks.
266 " For instance, the following could be added to the vimrc to provide a 'q'
267 " mapping to quit a VCS scratch buffer:
270 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
273 " The following hooks are available:
275 " VCSBufferCreated This event is fired just after a VCS command
276 " output buffer is created. It is executed
277 " within the context of the new buffer.
279 " VCSBufferSetup This event is fired just after VCS buffer setup
280 " occurs, if enabled.
282 " VCSPluginInit This event is fired when the VCSCommand plugin
285 " VCSPluginFinish This event is fired just after the VCSCommand
288 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
289 " command executes to allow customization of,
290 " for instance, window placement and focus.
292 " Section: Plugin header {{{1
294 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
295 " completes. This allows various actions to only be taken by functions after
296 " system initialization.
298 if exists('VCSCommandDisableAll')
302 if exists('loaded_VCSCommand')
305 let loaded_VCSCommand = 1
308 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
315 " Section: Event group setup {{{1
320 augroup VCSCommandCommit
323 " Section: Plugin initialization {{{1
324 silent do VCSCommand User VCSPluginInit
326 " Section: Constants declaration {{{1
328 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
329 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
331 " Section: Script variable initialization {{{1
333 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
336 " temporary values of overridden configuration variables
337 let s:optionOverrides = {}
339 " state flag used to vary behavior of certain automated actions
340 let s:isEditFileRunning = 0
342 " commands needed to restore diff buffers to their original state
343 unlet! s:vimDiffRestoreCmd
345 " original buffer currently reflected in vimdiff windows
346 unlet! s:vimDiffSourceBuffer
349 unlet! s:vimDiffScratchList
351 " Section: Utility functions {{{1
353 " Function: s:ReportError(mapping) {{{2
354 " Displays the given error in a consistent faction. This is intended to be
355 " invoked from a catch statement.
357 function! s:ReportError(error)
358 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
362 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
363 " Creates the given mapping by prepending the contents of
364 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
365 " mapping it to the given plugin function. If a mapping exists for the
366 " specified shortcut + prefix, emit an error but continue. If a mapping
367 " exists for the specified function, do nothing.
369 function! s:CreateMapping(shortcut, expansion, display)
370 let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
371 if !hasmapto(a:expansion)
373 execute 'nmap <silent> <unique>' lhs a:expansion
374 catch /^Vim(.*):E227:/
376 echohl WarningMsg|echomsg 'VCSCommand: mapping ''' . lhs . ''' already exists, refusing to overwrite. The mapping for ' . a:display . ' will not be available.'|echohl None
382 " Function: s:ExecuteExtensionMapping(mapping) {{{2
383 " Invokes the appropriate extension mapping depending on the type of the
386 function! s:ExecuteExtensionMapping(mapping)
387 let buffer = bufnr('%')
388 let vcsType = VCSCommandGetVCSType(buffer)
389 if !has_key(s:plugins, vcsType)
390 throw 'Unknown VCS type: ' . vcsType
392 if !has_key(s:plugins[vcsType][2], a:mapping)
393 throw 'This extended mapping is not defined for ' . vcsType
395 silent execute 'normal' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
398 " Function: s:ExecuteVCSCommand(command, argList) {{{2
399 " Calls the indicated plugin-specific VCS command on the current buffer.
400 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
403 function! s:ExecuteVCSCommand(command, argList)
405 let buffer = bufnr('%')
407 let vcsType = VCSCommandGetVCSType(buffer)
408 if !has_key(s:plugins, vcsType)
409 throw 'Unknown VCS type: ' . vcsType
412 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
413 let bufferName = bufname(originalBuffer)
415 " It is already known that the directory is under VCS control. No further
416 " checks are needed. Otherwise, perform some basic sanity checks to avoid
417 " VCS-specific error messages from confusing things.
418 if !isdirectory(bufferName)
419 if !filereadable(bufferName)
420 throw 'No such file ' . bufferName
424 let functionMap = s:plugins[vcsType][1]
425 if !has_key(functionMap, a:command)
426 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
428 return functionMap[a:command](a:argList)
430 call s:ReportError(v:exception)
435 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
436 " Default method of generating the name for VCS result buffers. This can be
437 " overridden with the VCSResultBufferNameFunction variable.
439 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
440 let fileName = bufname(a:originalBuffer)
441 let bufferName = a:vcsType . ' ' . a:command
442 if strlen(a:statusText) > 0
443 let bufferName .= ' ' . a:statusText
445 let bufferName .= ' ' . fileName
447 let versionedBufferName = bufferName
448 while buflisted(versionedBufferName)
450 let versionedBufferName = bufferName . ' (' . counter . ')'
452 return versionedBufferName
455 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
456 " Method of generating the name for VCS result buffers that uses the original
457 " file name with the VCS type and command appended as extensions.
459 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
460 let fileName = bufname(a:originalBuffer)
461 let bufferName = a:vcsType . ' ' . a:command
462 if strlen(a:statusText) > 0
463 let bufferName .= ' ' . a:statusText
465 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
467 let versionedBufferName = bufferName
468 while buflisted(versionedBufferName)
470 let versionedBufferName = '(' . counter . ') ' . bufferName
472 return versionedBufferName
475 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
476 " Creates a new buffer of the given name and associates it with the given
479 function! s:EditFile(command, originalBuffer, statusText)
480 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
482 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
483 if nameExtension == ''
484 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
486 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
489 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
491 " Protect against useless buffer set-up
492 let s:isEditFileRunning += 1
494 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
495 if editCommand == 'split'
496 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
499 vert rightbelow split
505 let b:VCSCommandCommand = a:command
506 let b:VCSCommandOriginalBuffer = a:originalBuffer
507 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
508 let b:VCSCommandVCSType = vcsType
510 setlocal buftype=nofile
512 let &filetype = vcsType . a:command
514 if a:statusText != ''
515 let b:VCSCommandStatusText = a:statusText
518 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
519 setlocal bufhidden=delete
521 silent noautocmd file `=resultBufferName`
523 let s:isEditFileRunning -= 1
527 " Function: s:SetupBuffer() {{{2
528 " Attempts to set the b:VCSCommandBufferInfo variable
530 function! s:SetupBuffer()
531 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
532 " This buffer is already set up.
536 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
537 " No special status for special buffers other than directory buffers.
541 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
542 unlet! b:VCSCommandBufferSetup
547 let vcsType = VCSCommandGetVCSType(bufnr('%'))
548 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
549 silent do VCSCommand User VCSBufferSetup
550 catch /No suitable plugin/
551 " This is not a VCS-controlled file.
552 let b:VCSCommandBufferInfo = []
555 let b:VCSCommandBufferSetup = 1
558 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
559 " Resets the buffer setup state of the original buffer for a given VCS scratch
561 " Returns: The VCS buffer number in a passthrough mode.
563 function! s:MarkOrigBufferForSetup(buffer)
566 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
567 " This should never not work, but I'm paranoid
568 if origBuffer != a:buffer
569 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
575 " Function: s:OverrideOption(option, [value]) {{{2
576 " Provides a temporary override for the given VCS option. If no value is
577 " passed, the override is disabled.
579 function! s:OverrideOption(option, ...)
581 call remove(s:optionOverrides[a:option], -1)
583 if !has_key(s:optionOverrides, a:option)
584 let s:optionOverrides[a:option] = []
586 call add(s:optionOverrides[a:option], a:1)
590 " Function: s:WipeoutCommandBuffers() {{{2
591 " Clears all current VCS output buffers of the specified type for a given source.
593 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
595 while buffer <= bufnr('$')
596 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
597 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
601 let buffer = buffer + 1
605 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
606 " Checks whether the given buffer is one whose deletion should trigger
607 " restoration of an original buffer after it was diffed. If so, it executes
608 " the appropriate setting command stored with that original buffer.
610 function! s:VimDiffRestore(vimDiffBuff)
611 let s:isEditFileRunning += 1
613 if exists('s:vimDiffSourceBuffer')
614 if a:vimDiffBuff == s:vimDiffSourceBuffer
615 " Original file is being removed.
616 unlet! s:vimDiffSourceBuffer
617 unlet! s:vimDiffRestoreCmd
618 unlet! s:vimDiffScratchList
620 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
622 call remove(s:vimDiffScratchList, index)
623 if len(s:vimDiffScratchList) == 0
624 if exists('s:vimDiffRestoreCmd')
625 " All scratch buffers are gone, reset the original.
626 " Only restore if the source buffer is still in Diff mode
628 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
630 " The buffer is visible in at least one window
631 let currentWinNR = winnr()
632 while winbufnr(sourceWinNR) != -1
633 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
634 execute sourceWinNR . 'wincmd w'
635 if getwinvar(0, '&diff')
636 execute s:vimDiffRestoreCmd
639 let sourceWinNR = sourceWinNR + 1
641 execute currentWinNR . 'wincmd w'
643 " The buffer is hidden. It must be visible in order to set the
645 let currentBufNR = bufnr('')
646 execute 'hide buffer' s:vimDiffSourceBuffer
647 if getwinvar(0, '&diff')
648 execute s:vimDiffRestoreCmd
650 execute 'hide buffer' currentBufNR
653 unlet s:vimDiffRestoreCmd
655 " All buffers are gone.
656 unlet s:vimDiffSourceBuffer
657 unlet s:vimDiffScratchList
663 let s:isEditFileRunning -= 1
667 " Section: Generic VCS command functions {{{1
669 " Function: s:VCSCommit() {{{2
670 function! s:VCSCommit(bang, message)
672 let vcsType = VCSCommandGetVCSType(bufnr('%'))
673 if !has_key(s:plugins, vcsType)
674 throw 'Unknown VCS type: ' . vcsType
677 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
679 " Handle the commit message being specified. If a message is supplied, it
680 " is used; if bang is supplied, an empty message is used; otherwise, the
681 " user is provided a buffer from which to edit the commit message.
683 if strlen(a:message) > 0 || a:bang == '!'
684 return s:VCSFinishCommit([a:message], originalBuffer)
687 call s:EditFile('commitlog', originalBuffer, '')
688 setlocal ft=vcscommit
690 " Create a commit mapping.
692 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
694 silent 0put ='VCS: ----------------------------------------------------------------------'
695 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
696 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
698 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
699 setlocal buftype=acwrite
700 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
701 silent put ='VCS: or write this buffer'
704 silent put ='VCS: ----------------------------------------------------------------------'
708 call s:ReportError(v:exception)
713 " Function: s:VCSFinishCommitWithBuffer() {{{2
714 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
715 " which removes all lines starting with 'VCS:'.
717 function! s:VCSFinishCommitWithBuffer()
719 let currentBuffer = bufnr('%')
720 let logMessageList = getbufline('%', 1, '$')
721 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
722 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
724 execute 'bw' currentBuffer
729 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
730 function! s:VCSFinishCommit(logMessageList, originalBuffer)
731 let shellSlashBak = &shellslash
734 let messageFileName = tempname()
735 call writefile(a:logMessageList, messageFileName)
737 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
741 return s:MarkOrigBufferForSetup(resultBuffer)
743 call delete(messageFileName)
746 let &shellslash = shellSlashBak
750 " Function: s:VCSGotoOriginal(bang) {{{2
751 function! s:VCSGotoOriginal(bang)
752 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
753 if originalBuffer > 0
754 let origWinNR = bufwinnr(originalBuffer)
756 execute 'buffer' originalBuffer
758 execute origWinNR . 'wincmd w'
762 let buffmaxnr = bufnr('$')
763 while buffnr <= buffmaxnr
764 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
767 let buffnr = buffnr + 1
773 " Function: s:VCSVimDiff(...) {{{2
774 function! s:VCSVimDiff(...)
776 let vcsType = VCSCommandGetVCSType(bufnr('%'))
777 if !has_key(s:plugins, vcsType)
778 throw 'Unknown VCS type: ' . vcsType
780 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
781 let s:isEditFileRunning = s:isEditFileRunning + 1
783 " If there's already a VimDiff'ed window, restore it.
784 " There may only be one VCSVimDiff original window at a time.
786 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
787 " Clear the existing vimdiff setup by removing the result buffers.
788 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
791 let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
792 let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
793 let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
797 " Reset the vimdiff system, as 2 explicit versions were provided.
798 if exists('s:vimDiffSourceBuffer')
799 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
801 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
803 echomsg 'Can''t open revision ' . a:1
806 let b:VCSCommandCommand = 'vimdiff'
808 let s:vimDiffScratchList = [resultBuffer]
809 " If no split method is defined, cheat, and set it to vertical.
811 call s:OverrideOption('VCSCommandSplit', orientation)
812 let resultBuffer = s:plugins[vcsType][1].Review([a:2])
814 call s:OverrideOption('VCSCommandSplit')
817 echomsg 'Can''t open revision ' . a:1
820 let b:VCSCommandCommand = 'vimdiff'
822 let s:vimDiffScratchList += [resultBuffer]
825 call s:OverrideOption('VCSCommandEdit', 'split')
827 " Force splitting behavior, otherwise why use vimdiff?
828 call s:OverrideOption('VCSCommandSplit', orientation)
831 let resultBuffer = s:plugins[vcsType][1].Review([])
833 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
836 call s:OverrideOption('VCSCommandSplit')
839 call s:OverrideOption('VCSCommandEdit')
842 echomsg 'Can''t open current revision'
845 let b:VCSCommandCommand = 'vimdiff'
848 if !exists('s:vimDiffSourceBuffer')
849 " New instance of vimdiff.
850 let s:vimDiffScratchList = [resultBuffer]
852 " This could have been invoked on a VCS result buffer, not the
855 execute 'buffer' originalBuffer
856 " Store info for later original buffer restore
857 let s:vimDiffRestoreCmd =
858 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
859 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
860 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
861 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
862 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
863 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
864 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
865 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
869 " Adding a window to an existing vimdiff
870 let s:vimDiffScratchList += [resultBuffer]
874 let s:vimDiffSourceBuffer = originalBuffer
876 " Avoid executing the modeline in the current buffer after the autocommand.
878 let currentBuffer = bufnr('%')
879 let saveModeline = getbufvar(currentBuffer, '&modeline')
881 call setbufvar(currentBuffer, '&modeline', 0)
882 silent do VCSCommand User VCSVimDiffFinish
884 call setbufvar(currentBuffer, '&modeline', saveModeline)
888 let s:isEditFileRunning = s:isEditFileRunning - 1
891 call s:ReportError(v:exception)
896 " Section: Public functions {{{1
898 " Function: VCSCommandGetVCSType() {{{2
899 " Sets the b:VCSCommandVCSType variable in the given buffer to the
900 " appropriate source control system name.
902 " This uses the Identify extension function to test the buffer. If the
903 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
904 " exact. If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
905 " match is considered inexact, and is only applied if no exact match is found.
906 " Multiple inexact matches is currently considered an error.
908 function! VCSCommandGetVCSType(buffer)
909 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
910 if strlen(vcsType) > 0
913 if exists("g:VCSCommandVCSTypeOverride")
914 let fullpath = fnamemodify(bufname(a:buffer), ':p')
915 for [path, vcsType] in g:VCSCommandVCSTypeOverride
916 if match(fullpath, path) > -1
917 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
923 for vcsType in keys(s:plugins)
924 let identified = s:plugins[vcsType][1].Identify(a:buffer)
926 if identified == g:VCSCOMMAND_IDENTIFY_EXACT
927 let matches = [vcsType]
930 let matches += [vcsType]
935 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
937 elseif len(matches) == 0
938 throw 'No suitable plugin'
940 throw 'Too many matching VCS: ' . join(matches)
944 " Function: VCSCommandChdir(directory) {{{2
945 " Changes the current directory, respecting :lcd changes.
947 function! VCSCommandChdir(directory)
949 if exists("*haslocaldir") && haslocaldir()
952 execute command escape(a:directory, ' ')
955 " Function: VCSCommandChangeToCurrentFileDir() {{{2
956 " Go to the directory in which the given file is located.
958 function! VCSCommandChangeToCurrentFileDir(fileName)
959 let oldCwd = getcwd()
960 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
961 if strlen(newCwd) > 0
962 call VCSCommandChdir(newCwd)
967 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
968 " Attempts to locate the original file to which VCS operations were applied
969 " for a given buffer.
971 function! VCSCommandGetOriginalBuffer(vcsBuffer)
972 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
974 if bufexists(origBuffer)
977 " Original buffer no longer exists.
978 throw 'Original buffer for this VCS buffer no longer exists.'
986 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
987 " Allows VCS modules to register themselves.
989 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
990 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
991 if !empty(a:mappingMap)
992 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
993 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
994 for shortcut in keys(a:mappingMap)
995 let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
996 call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1001 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1002 " General skeleton for VCS function execution. The given command is executed
1003 " after appending the current buffer name (or substituting it for
1004 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
1007 " The optional 'options' Dictionary may contain the following options:
1008 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
1009 " non-zero exit status, the command is still considered
1010 " successfuly. This defaults to zero.
1011 " Returns: name of the new command buffer containing the command results
1013 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1014 let allowNonZeroExit = 0
1015 if has_key(a:options, 'allowNonZeroExit')
1016 let allowNonZeroExit = a:options.allowNonZeroExit
1019 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1020 if originalBuffer == -1
1021 throw 'Original buffer no longer exists, aborting.'
1024 let path = resolve(bufname(originalBuffer))
1026 " Work with netrw or other systems where a directory listing is displayed in
1029 if isdirectory(path)
1032 let fileName = fnamemodify(path, ':t')
1035 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1036 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1038 let fullCmd = a:cmd . ' "' . fileName . '"'
1041 " Change to the directory of the current buffer. This is done for CVS, but
1042 " is left in for other systems as it does not affect them negatively.
1044 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1046 let output = system(fullCmd)
1048 call VCSCommandChdir(oldCwd)
1051 " HACK: if line endings in the repository have been corrupted, the output
1052 " of the command will be confused.
1053 let output = substitute(output, "\r", '', 'g')
1055 if v:shell_error && !allowNonZeroExit
1056 if strlen(output) == 0
1057 throw 'Version control command failed'
1059 let output = substitute(output, '\n', ' ', 'g')
1060 throw 'Version control command failed: ' . output
1064 if strlen(output) == 0
1065 " Handle case of no output. In this case, it is important to check the
1066 " file status, especially since cvs edit/unedit may change the attributes
1067 " of the file with no visible output.
1073 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1077 " The last command left a blank line at the end of the buffer. If the
1078 " last line is folded (a side effect of the 'put') then the attempt to
1079 " remove the blank line will kill the last fold.
1081 " This could be fixed by explicitly detecting whether the last line is
1082 " within a fold, but I prefer to simply unfold the result buffer altogether.
1091 " Define the environment and execute user-defined hooks.
1093 silent do VCSCommand User VCSBufferCreated
1097 " Function: VCSCommandGetOption(name, default) {{{2
1098 " Grab a user-specified option to override the default provided. Options are
1099 " searched in the window, buffer, then global spaces.
1101 function! VCSCommandGetOption(name, default)
1102 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1103 return s:optionOverrides[a:name][-1]
1104 elseif exists('w:' . a:name)
1106 elseif exists('b:' . a:name)
1108 elseif exists('g:' . a:name)
1115 " Function: VCSCommandDisableBufferSetup() {{{2
1116 " Global function for deactivating the buffer autovariables.
1118 function! VCSCommandDisableBufferSetup()
1119 let g:VCSCommandEnableBufferSetup = 0
1120 silent! augroup! VCSCommandPlugin
1123 " Function: VCSCommandEnableBufferSetup() {{{2
1124 " Global function for activating the buffer autovariables.
1126 function! VCSCommandEnableBufferSetup()
1127 let g:VCSCommandEnableBufferSetup = 1
1128 augroup VCSCommandPlugin
1130 au BufEnter * call s:SetupBuffer()
1133 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1135 if g:loaded_VCSCommand == 2
1136 call s:SetupBuffer()
1140 " Function: VCSCommandGetStatusLine() {{{2
1141 " Default (sample) status line entry for VCS-controlled files. This is only
1142 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1143 " variable for how to do this).
1145 function! VCSCommandGetStatusLine()
1146 if exists('b:VCSCommandCommand')
1147 " This is a result buffer. Return nothing because the buffer name
1148 " contains information already.
1152 if exists('b:VCSCommandVCSType')
1153 \ && exists('g:VCSCommandEnableBufferSetup')
1154 \ && g:VCSCommandEnableBufferSetup
1155 \ && exists('b:VCSCommandBufferInfo')
1156 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1162 " Section: Command definitions {{{1
1163 " Section: Primary commands {{{2
1164 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1165 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1166 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1167 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1168 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1169 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1170 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1171 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1172 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1173 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1174 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1175 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1176 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1177 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1178 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1179 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1180 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1182 " Section: VCS buffer management commands {{{2
1183 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1184 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1186 " Allow reloading VCSCommand.vim
1187 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
1189 " Section: Plugin command mappings {{{1
1190 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1191 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1192 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1193 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1194 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1195 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1196 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1197 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1198 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1199 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1200 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1201 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1202 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1203 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1204 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1205 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1207 " Section: Default mappings {{{1
1209 let s:defaultMappings = [
1211 \['c', 'VCSCommit'],
1212 \['D', 'VCSDelete'],
1214 \['G', 'VCSClearAndGotoOriginal'],
1215 \['g', 'VCSGotoOriginal'],
1219 \['n', 'VCSAnnotate'],
1220 \['q', 'VCSRevert'],
1221 \['r', 'VCSReview'],
1222 \['s', 'VCSStatus'],
1223 \['U', 'VCSUnlock'],
1224 \['u', 'VCSUpdate'],
1225 \['v', 'VCSVimDiff'],
1228 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1229 for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1230 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1234 " Section: Menu items {{{1
1235 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1236 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1237 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1238 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1239 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1240 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1241 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1242 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1243 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1244 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1245 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1246 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1248 " Section: Autocommands to restore vimdiff state {{{1
1249 augroup VimDiffRestore
1251 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1254 " Section: Optional activation of buffer management {{{1
1256 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1257 call VCSCommandEnableBufferSetup()
1260 " Section: VIM shutdown hook {{{1
1262 " Close all result buffers when VIM exits, to prevent them from being restored
1265 " Function: s:CloseAllResultBuffers() {{{2
1266 " Closes all vcscommand result buffers.
1267 function! s:CloseAllResultBuffers()
1268 " This avoids using bufdo as that may load buffers already loaded in another
1269 " vim process, resulting in an error.
1271 let buffmaxnr = bufnr('$')
1272 while buffnr <= buffmaxnr
1273 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1276 let buffnr = buffnr + 1
1280 augroup VCSCommandVIMShutdown
1282 au VimLeavePre * call s:CloseAllResultBuffers()
1285 " Section: Plugin completion {{{1
1287 let loaded_VCSCommand = 2
1289 silent do VCSCommand User VCSPluginFinish
1291 let &cpo = s:save_cpo