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>
9 " Copyright (c) 2008 Bob Hiestand
11 " Permission is hereby granted, free of charge, to any person obtaining a copy
12 " of this software and associated documentation files (the "Software"), to
13 " deal in the Software without restriction, including without limitation the
14 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
15 " sell copies of the Software, and to permit persons to whom the Software is
16 " furnished to do so, subject to the following conditions:
18 " The above copyright notice and this permission notice shall be included in
19 " all copies or substantial portions of the Software.
21 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
29 " Section: Documentation {{{1
31 " Provides functions to invoke various source control commands on the current
32 " file (either the current buffer, or, in the case of an directory buffer, the
33 " directory and all subdirectories associated with the current buffer). The
34 " output of the commands is captured in a new scratch window.
36 " This plugin needs additional extension plugins, each specific to a source
37 " control system, to function. Those plugins should be placed in a
38 " subdirectory of the standard plugin directory named 'vcscommand'. Several
39 " options include the name of the version control system in the option name.
40 " Such options use the placeholder text '{VCSType}', which would be replaced
41 " in actual usage with 'CVS' or 'SVN', for instance.
43 " Command documentation {{{2
45 " VCSAdd Adds the current file to source control.
47 " VCSAnnotate Displays the current file with each line annotated with the
48 " version in which it was most recently changed. If an
49 " argument is given, the argument is used as a revision
50 " number to display. If not given an argument, it uses the
51 " most recent version of the file on the current branch.
52 " Additionally, if the current buffer is a VCSAnnotate buffer
53 " already, the version number on the current line is used.
55 " VCSBlame Alias for 'VCSAnnotate'.
57 " VCSCommit[!] Commits changes to the current file to source control.
59 " If called with arguments, the arguments are the log message.
61 " If '!' is used, an empty log message is committed.
63 " If called with no arguments, this is a two-step command.
64 " The first step opens a buffer to accept a log message.
65 " When that buffer is written, it is automatically closed and
66 " the file is committed using the information from that log
67 " message. The commit can be abandoned if the log message
68 " buffer is deleted or wiped before being written.
70 " VCSDelete Deletes the current file and removes it from source control.
72 " VCSDiff With no arguments, this displays the differences between
73 " the current file and its parent version under source
74 " control in a new scratch buffer.
76 " With one argument, the diff is performed on the
77 " current file against the specified revision.
79 " With two arguments, the diff is performed between the
80 " specified revisions of the current file.
82 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
83 " to specify diff options. If that variable does not exist,
84 " a plugin-specific default is used. If you wish to have no
85 " options, then set it to the empty string.
87 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
88 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
89 " VCS scratch buffers associated with the original file.
91 " VCSInfo Displays extended information about the current file in a
94 " VCSLock Locks the current file in order to prevent other users from
95 " concurrently modifying it. The exact semantics of this
96 " command depend on the underlying VCS.
98 " VCSLog Displays the version history of the current file in a new
101 " VCSRemove Alias for 'VCSDelete'.
103 " VCSRevert Replaces the modified version of the current file with the
104 " most recent version from the repository.
106 " VCSReview Displays a particular version of the current file in a new
107 " scratch buffer. If no argument is given, the most recent
108 " version of the file on the current branch is retrieved.
110 " VCSStatus Displays versioning information about the current file in a
111 " new scratch buffer.
113 " VCSUnlock Unlocks the current file in order to allow other users from
114 " concurrently modifying it. The exact semantics of this
115 " command depend on the underlying VCS.
117 " VCSUpdate Updates the current file with any relevant changes from the
120 " VCSVimDiff Uses vimdiff to display differences between versions of the
123 " If no revision is specified, the most recent version of the
124 " file on the current branch is used. With one argument,
125 " that argument is used as the revision as above. With two
126 " arguments, the differences between the two revisions is
127 " displayed using vimdiff.
129 " With either zero or one argument, the original buffer is
130 " used to perform the vimdiff. When the scratch buffer is
131 " closed, the original buffer will be returned to normal
134 " Once vimdiff mode is started using the above methods,
135 " additional vimdiff buffers may be added by passing a single
136 " version argument to the command. There may be up to 4
137 " vimdiff buffers total.
139 " Using the 2-argument form of the command resets the vimdiff
140 " to only those 2 versions. Additionally, invoking the
141 " command on a different file will close the previous vimdiff
144 " Mapping documentation: {{{2
146 " By default, a mapping is defined for each command. User-provided mappings
147 " can be used instead by mapping to <Plug>CommandName, for instance:
149 " nmap ,ca <Plug>VCSAdd
151 " The default mappings are as follow:
154 " <Leader>cn VCSAnnotate
155 " <Leader>cc VCSCommit
156 " <Leader>cD VCSDelete
158 " <Leader>cg VCSGotoOriginal
159 " <Leader>cG VCSGotoOriginal!
163 " <Leader>cr VCSReview
164 " <Leader>cs VCSStatus
165 " <Leader>cu VCSUpdate
166 " <Leader>cU VCSUnlock
167 " <Leader>cv VCSVimDiff
169 " Options documentation: {{{2
171 " Several variables are checked by the script to determine behavior as follow:
173 " VCSCommandCommitOnWrite
174 " This variable, if set to a non-zero value, causes the pending commit to
175 " take place immediately as soon as the log message buffer is written. If
176 " set to zero, only the VCSCommit mapping will cause the pending commit to
177 " occur. If not set, it defaults to 1.
179 " VCSCommandDeleteOnHide
180 " This variable, if set to a non-zero value, causes the temporary VCS result
181 " buffers to automatically delete themselves when hidden.
183 " VCSCommand{VCSType}DiffOpt
184 " This variable, if set, determines the options passed to the diff command
185 " of the underlying VCS. Each VCS plugin defines a default value.
187 " VCSCommandDiffSplit
188 " This variable overrides the VCSCommandSplit variable, but only for buffers
189 " created with VCSVimDiff.
191 " VCSCommandDisableAll
192 " This variable, if set, prevents the plugin or any extensions from loading
193 " at all. This is useful when a single runtime distribution is used on
194 " multiple systems with varying versions.
196 " VCSCommandDisableMappings
197 " This variable, if set to a non-zero value, prevents the default command
198 " mappings from being set.
200 " VCSCommandDisableExtensionMappings
201 " This variable, if set to a non-zero value, prevents the default command
202 " mappings from being set for commands specific to an individual VCS.
205 " This variable controls whether to split the current window to display a
206 " scratch buffer ('split'), or to display it in the current buffer ('edit').
207 " If not set, it defaults to 'split'.
209 " VCSCommandEnableBufferSetup
210 " This variable, if set to a non-zero value, activates VCS buffer management
211 " mode. This mode means that the buffer variable 'VCSRevision' is set if
212 " the file is VCS-controlled. This is useful for displaying version
213 " information in the status bar. Additional options may be set by
214 " individual VCS plugins.
217 " This variable, if set, overrides the default mappings used for shortcuts.
218 " It should be a List of 2-element Lists, each containing a shortcut and
219 " function name pair.
221 " VCSCommandMapPrefix
222 " This variable, if set, overrides the default mapping prefix ('<Leader>c').
223 " This allows customization of the mapping space used by the vcscommand
226 " VCSCommandResultBufferNameExtension
227 " This variable, if set to a non-blank value, is appended to the name of the
228 " VCS command output buffers. For example, '.vcs'. Using this option may
229 " help avoid problems caused by autocommands dependent on file extension.
231 " VCSCommandResultBufferNameFunction
232 " This variable, if set, specifies a custom function for naming VCS command
233 " output buffers. This function will be passed the following arguments:
235 " command - name of the VCS command being executed (such as 'Log' or
238 " originalBuffer - buffer number of the source file.
240 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
242 " statusText - extra text associated with the VCS action (such as version
246 " This variable controls the orientation of the various window splits that
247 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
248 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
249 " If set to 'horizontal', the resulting windows will be on stacked on top of
250 " one another. If set to 'vertical', the resulting windows will be
251 " side-by-side. If not set, it defaults to 'horizontal' for all but
252 " VCSVimDiff windows.
254 " VCSCommandVCSTypeOverride
255 " This variable allows the VCS type detection to be overridden on a
256 " path-by-path basis. The value of this variable is expected to be a List
257 " of Lists. Each high-level List item is a List containing two elements.
258 " The first element is a regular expression that will be matched against the
259 " full file name of a given buffer. If it matches, the second element will
260 " be used as the VCS type.
262 " Event documentation {{{2
263 " For additional customization, VCSCommand.vim uses User event autocommand
264 " hooks. Each event is in the VCSCommand group, and different patterns
265 " match the various hooks.
267 " For instance, the following could be added to the vimrc to provide a 'q'
268 " mapping to quit a VCS scratch buffer:
271 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
274 " The following hooks are available:
276 " VCSBufferCreated This event is fired just after a VCS command
277 " output buffer is created. It is executed
278 " within the context of the new buffer.
280 " VCSBufferSetup This event is fired just after VCS buffer setup
281 " occurs, if enabled.
283 " VCSPluginInit This event is fired when the VCSCommand plugin
286 " VCSPluginFinish This event is fired just after the VCSCommand
289 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
290 " command executes to allow customization of,
291 " for instance, window placement and focus.
293 " Section: Plugin header {{{1
295 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
296 " completes. This allows various actions to only be taken by functions after
297 " system initialization.
299 if exists('VCSCommandDisableAll')
303 if exists('loaded_VCSCommand')
306 let loaded_VCSCommand = 1
309 "echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
316 " Section: Event group setup {{{1
321 augroup VCSCommandCommit
324 " Section: Plugin initialization {{{1
325 silent do VCSCommand User VCSPluginInit
327 " Section: Constants declaration {{{1
329 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
330 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
332 " Section: Script variable initialization {{{1
334 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
337 " temporary values of overridden configuration variables
338 let s:optionOverrides = {}
340 " state flag used to vary behavior of certain automated actions
341 let s:isEditFileRunning = 0
343 " commands needed to restore diff buffers to their original state
344 unlet! s:vimDiffRestoreCmd
346 " original buffer currently reflected in vimdiff windows
347 unlet! s:vimDiffSourceBuffer
350 unlet! s:vimDiffScratchList
352 " Section: Utility functions {{{1
354 " Function: s:ReportError(mapping) {{{2
355 " Displays the given error in a consistent faction. This is intended to be
356 " invoked from a catch statement.
358 function! s:ReportError(error)
359 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
363 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
364 " Creates the given mapping by prepending the contents of
365 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
366 " mapping it to the given plugin function. If a mapping exists for the
367 " specified shortcut + prefix, emit an error but continue. If a mapping
368 " exists for the specified function, do nothing.
370 function! s:CreateMapping(shortcut, expansion, display)
371 let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
372 if !hasmapto(a:expansion)
374 execute 'nmap <silent> <unique>' lhs a:expansion
375 catch /^Vim(.*):E227:/
377 echohl WarningMsg|echomsg 'VCSCommand: mapping ''' . lhs . ''' already exists, refusing to overwrite. The mapping for ' . a:display . ' will not be available.'|echohl None
383 " Function: s:ExecuteExtensionMapping(mapping) {{{2
384 " Invokes the appropriate extension mapping depending on the type of the
387 function! s:ExecuteExtensionMapping(mapping)
388 let buffer = bufnr('%')
389 let vcsType = VCSCommandGetVCSType(buffer)
390 if !has_key(s:plugins, vcsType)
391 throw 'Unknown VCS type: ' . vcsType
393 if !has_key(s:plugins[vcsType][2], a:mapping)
394 throw 'This extended mapping is not defined for ' . vcsType
396 silent execute 'normal' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
399 " Function: s:ExecuteVCSCommand(command, argList) {{{2
400 " Calls the indicated plugin-specific VCS command on the current buffer.
401 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
404 function! s:ExecuteVCSCommand(command, argList)
406 let buffer = bufnr('%')
408 let vcsType = VCSCommandGetVCSType(buffer)
409 if !has_key(s:plugins, vcsType)
410 throw 'Unknown VCS type: ' . vcsType
413 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
414 let bufferName = bufname(originalBuffer)
416 " It is already known that the directory is under VCS control. No further
417 " checks are needed. Otherwise, perform some basic sanity checks to avoid
418 " VCS-specific error messages from confusing things.
419 if !isdirectory(bufferName)
420 if !filereadable(bufferName)
421 throw 'No such file ' . bufferName
425 let functionMap = s:plugins[vcsType][1]
426 if !has_key(functionMap, a:command)
427 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
429 return functionMap[a:command](a:argList)
431 call s:ReportError(v:exception)
436 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
437 " Default method of generating the name for VCS result buffers. This can be
438 " overridden with the VCSResultBufferNameFunction variable.
440 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
441 let fileName = bufname(a:originalBuffer)
442 let bufferName = a:vcsType . ' ' . a:command
443 if strlen(a:statusText) > 0
444 let bufferName .= ' ' . a:statusText
446 let bufferName .= ' ' . fileName
448 let versionedBufferName = bufferName
449 while buflisted(versionedBufferName)
451 let versionedBufferName = bufferName . ' (' . counter . ')'
453 return versionedBufferName
456 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
457 " Method of generating the name for VCS result buffers that uses the original
458 " file name with the VCS type and command appended as extensions.
460 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
461 let fileName = bufname(a:originalBuffer)
462 let bufferName = a:vcsType . ' ' . a:command
463 if strlen(a:statusText) > 0
464 let bufferName .= ' ' . a:statusText
466 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
468 let versionedBufferName = bufferName
469 while buflisted(versionedBufferName)
471 let versionedBufferName = '(' . counter . ') ' . bufferName
473 return versionedBufferName
476 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
477 " Creates a new buffer of the given name and associates it with the given
480 function! s:EditFile(command, originalBuffer, statusText)
481 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
483 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
484 if nameExtension == ''
485 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
487 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
490 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
492 " Protect against useless buffer set-up
493 let s:isEditFileRunning += 1
495 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
496 if editCommand == 'split'
497 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
500 vert rightbelow split
506 let b:VCSCommandCommand = a:command
507 let b:VCSCommandOriginalBuffer = a:originalBuffer
508 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
509 let b:VCSCommandVCSType = vcsType
511 setlocal buftype=nofile
513 let &filetype = vcsType . a:command
515 if a:statusText != ''
516 let b:VCSCommandStatusText = a:statusText
519 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
520 setlocal bufhidden=delete
522 silent noautocmd file `=resultBufferName`
524 let s:isEditFileRunning -= 1
528 " Function: s:SetupBuffer() {{{2
529 " Attempts to set the b:VCSCommandBufferInfo variable
531 function! s:SetupBuffer()
532 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
533 " This buffer is already set up.
537 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
538 " No special status for special buffers other than directory buffers.
542 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
543 unlet! b:VCSCommandBufferSetup
548 let vcsType = VCSCommandGetVCSType(bufnr('%'))
549 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
550 silent do VCSCommand User VCSBufferSetup
551 catch /No suitable plugin/
552 " This is not a VCS-controlled file.
553 let b:VCSCommandBufferInfo = []
556 let b:VCSCommandBufferSetup = 1
559 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
560 " Resets the buffer setup state of the original buffer for a given VCS scratch
562 " Returns: The VCS buffer number in a passthrough mode.
564 function! s:MarkOrigBufferForSetup(buffer)
567 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
568 " This should never not work, but I'm paranoid
569 if origBuffer != a:buffer
570 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
576 " Function: s:OverrideOption(option, [value]) {{{2
577 " Provides a temporary override for the given VCS option. If no value is
578 " passed, the override is disabled.
580 function! s:OverrideOption(option, ...)
582 call remove(s:optionOverrides[a:option], -1)
584 if !has_key(s:optionOverrides, a:option)
585 let s:optionOverrides[a:option] = []
587 call add(s:optionOverrides[a:option], a:1)
591 " Function: s:WipeoutCommandBuffers() {{{2
592 " Clears all current VCS output buffers of the specified type for a given source.
594 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
596 while buffer <= bufnr('$')
597 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
598 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
602 let buffer = buffer + 1
606 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
607 " Checks whether the given buffer is one whose deletion should trigger
608 " restoration of an original buffer after it was diffed. If so, it executes
609 " the appropriate setting command stored with that original buffer.
611 function! s:VimDiffRestore(vimDiffBuff)
612 let s:isEditFileRunning += 1
614 if exists('s:vimDiffSourceBuffer')
615 if a:vimDiffBuff == s:vimDiffSourceBuffer
616 " Original file is being removed.
617 unlet! s:vimDiffSourceBuffer
618 unlet! s:vimDiffRestoreCmd
619 unlet! s:vimDiffScratchList
621 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
623 call remove(s:vimDiffScratchList, index)
624 if len(s:vimDiffScratchList) == 0
625 if exists('s:vimDiffRestoreCmd')
626 " All scratch buffers are gone, reset the original.
627 " Only restore if the source buffer is still in Diff mode
629 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
631 " The buffer is visible in at least one window
632 let currentWinNR = winnr()
633 while winbufnr(sourceWinNR) != -1
634 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
635 execute sourceWinNR . 'wincmd w'
636 if getwinvar(0, '&diff')
637 execute s:vimDiffRestoreCmd
640 let sourceWinNR = sourceWinNR + 1
642 execute currentWinNR . 'wincmd w'
644 " The buffer is hidden. It must be visible in order to set the
646 let currentBufNR = bufnr('')
647 execute 'hide buffer' s:vimDiffSourceBuffer
648 if getwinvar(0, '&diff')
649 execute s:vimDiffRestoreCmd
651 execute 'hide buffer' currentBufNR
654 unlet s:vimDiffRestoreCmd
656 " All buffers are gone.
657 unlet s:vimDiffSourceBuffer
658 unlet s:vimDiffScratchList
664 let s:isEditFileRunning -= 1
668 " Section: Generic VCS command functions {{{1
670 " Function: s:VCSCommit() {{{2
671 function! s:VCSCommit(bang, message)
673 let vcsType = VCSCommandGetVCSType(bufnr('%'))
674 if !has_key(s:plugins, vcsType)
675 throw 'Unknown VCS type: ' . vcsType
678 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
680 " Handle the commit message being specified. If a message is supplied, it
681 " is used; if bang is supplied, an empty message is used; otherwise, the
682 " user is provided a buffer from which to edit the commit message.
684 if strlen(a:message) > 0 || a:bang == '!'
685 return s:VCSFinishCommit([a:message], originalBuffer)
688 call s:EditFile('commitlog', originalBuffer, '')
689 setlocal ft=vcscommit
691 " Create a commit mapping.
693 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
695 silent 0put ='VCS: ----------------------------------------------------------------------'
696 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
697 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
699 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
700 setlocal buftype=acwrite
701 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
702 silent put ='VCS: or write this buffer'
705 silent put ='VCS: ----------------------------------------------------------------------'
709 call s:ReportError(v:exception)
714 " Function: s:VCSFinishCommitWithBuffer() {{{2
715 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
716 " which removes all lines starting with 'VCS:'.
718 function! s:VCSFinishCommitWithBuffer()
720 let currentBuffer = bufnr('%')
721 let logMessageList = getbufline('%', 1, '$')
722 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
723 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
725 execute 'bw' currentBuffer
730 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
731 function! s:VCSFinishCommit(logMessageList, originalBuffer)
732 let shellSlashBak = &shellslash
735 let messageFileName = tempname()
736 call writefile(a:logMessageList, messageFileName)
738 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
742 return s:MarkOrigBufferForSetup(resultBuffer)
744 call delete(messageFileName)
747 let &shellslash = shellSlashBak
751 " Function: s:VCSGotoOriginal(bang) {{{2
752 function! s:VCSGotoOriginal(bang)
753 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
754 if originalBuffer > 0
755 let origWinNR = bufwinnr(originalBuffer)
757 execute 'buffer' originalBuffer
759 execute origWinNR . 'wincmd w'
763 let buffmaxnr = bufnr('$')
764 while buffnr <= buffmaxnr
765 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
768 let buffnr = buffnr + 1
774 " Function: s:VCSVimDiff(...) {{{2
775 function! s:VCSVimDiff(...)
777 let vcsType = VCSCommandGetVCSType(bufnr('%'))
778 if !has_key(s:plugins, vcsType)
779 throw 'Unknown VCS type: ' . vcsType
781 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
782 let s:isEditFileRunning = s:isEditFileRunning + 1
784 " If there's already a VimDiff'ed window, restore it.
785 " There may only be one VCSVimDiff original window at a time.
787 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
788 " Clear the existing vimdiff setup by removing the result buffers.
789 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
792 let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
793 let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
794 let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
798 " Reset the vimdiff system, as 2 explicit versions were provided.
799 if exists('s:vimDiffSourceBuffer')
800 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
802 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
804 echomsg 'Can''t open revision ' . a:1
807 let b:VCSCommandCommand = 'vimdiff'
809 let s:vimDiffScratchList = [resultBuffer]
810 " If no split method is defined, cheat, and set it to vertical.
812 call s:OverrideOption('VCSCommandSplit', orientation)
813 let resultBuffer = s:plugins[vcsType][1].Review([a:2])
815 call s:OverrideOption('VCSCommandSplit')
818 echomsg 'Can''t open revision ' . a:1
821 let b:VCSCommandCommand = 'vimdiff'
823 let s:vimDiffScratchList += [resultBuffer]
826 call s:OverrideOption('VCSCommandEdit', 'split')
828 " Force splitting behavior, otherwise why use vimdiff?
829 call s:OverrideOption('VCSCommandSplit', orientation)
832 let resultBuffer = s:plugins[vcsType][1].Review([])
834 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
837 call s:OverrideOption('VCSCommandSplit')
840 call s:OverrideOption('VCSCommandEdit')
843 echomsg 'Can''t open current revision'
846 let b:VCSCommandCommand = 'vimdiff'
849 if !exists('s:vimDiffSourceBuffer')
850 " New instance of vimdiff.
851 let s:vimDiffScratchList = [resultBuffer]
853 " This could have been invoked on a VCS result buffer, not the
856 execute 'buffer' originalBuffer
857 " Store info for later original buffer restore
858 let s:vimDiffRestoreCmd =
859 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
860 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
861 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
862 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
863 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
864 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
865 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
866 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
870 " Adding a window to an existing vimdiff
871 let s:vimDiffScratchList += [resultBuffer]
875 let s:vimDiffSourceBuffer = originalBuffer
877 " Avoid executing the modeline in the current buffer after the autocommand.
879 let currentBuffer = bufnr('%')
880 let saveModeline = getbufvar(currentBuffer, '&modeline')
882 call setbufvar(currentBuffer, '&modeline', 0)
883 silent do VCSCommand User VCSVimDiffFinish
885 call setbufvar(currentBuffer, '&modeline', saveModeline)
889 let s:isEditFileRunning = s:isEditFileRunning - 1
892 call s:ReportError(v:exception)
897 " Section: Public functions {{{1
899 " Function: VCSCommandGetVCSType() {{{2
900 " Sets the b:VCSCommandVCSType variable in the given buffer to the
901 " appropriate source control system name.
903 " This uses the Identify extension function to test the buffer. If the
904 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
905 " exact. If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
906 " match is considered inexact, and is only applied if no exact match is found.
907 " Multiple inexact matches is currently considered an error.
909 function! VCSCommandGetVCSType(buffer)
910 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
911 if strlen(vcsType) > 0
914 if exists("g:VCSCommandVCSTypeOverride")
915 let fullpath = fnamemodify(bufname(a:buffer), ':p')
916 for [path, vcsType] in g:VCSCommandVCSTypeOverride
917 if match(fullpath, path) > -1
918 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
924 for vcsType in keys(s:plugins)
925 let identified = s:plugins[vcsType][1].Identify(a:buffer)
927 if identified == g:VCSCOMMAND_IDENTIFY_EXACT
928 let matches = [vcsType]
931 let matches += [vcsType]
936 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
938 elseif len(matches) == 0
939 throw 'No suitable plugin'
941 throw 'Too many matching VCS: ' . join(matches)
945 " Function: VCSCommandChdir(directory) {{{2
946 " Changes the current directory, respecting :lcd changes.
948 function! VCSCommandChdir(directory)
950 if exists("*haslocaldir") && haslocaldir()
953 execute command escape(a:directory, ' ')
956 " Function: VCSCommandChangeToCurrentFileDir() {{{2
957 " Go to the directory in which the given file is located.
959 function! VCSCommandChangeToCurrentFileDir(fileName)
960 let oldCwd = getcwd()
961 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
962 if strlen(newCwd) > 0
963 call VCSCommandChdir(newCwd)
968 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
969 " Attempts to locate the original file to which VCS operations were applied
970 " for a given buffer.
972 function! VCSCommandGetOriginalBuffer(vcsBuffer)
973 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
975 if bufexists(origBuffer)
978 " Original buffer no longer exists.
979 throw 'Original buffer for this VCS buffer no longer exists.'
987 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
988 " Allows VCS modules to register themselves.
990 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
991 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
992 if !empty(a:mappingMap)
993 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
994 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
995 for shortcut in keys(a:mappingMap)
996 let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
997 call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1002 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1003 " General skeleton for VCS function execution. The given command is executed
1004 " after appending the current buffer name (or substituting it for
1005 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
1008 " The optional 'options' Dictionary may contain the following options:
1009 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
1010 " non-zero exit status, the command is still considered
1011 " successfuly. This defaults to zero.
1012 " Returns: name of the new command buffer containing the command results
1014 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1015 let allowNonZeroExit = 0
1016 if has_key(a:options, 'allowNonZeroExit')
1017 let allowNonZeroExit = a:options.allowNonZeroExit
1020 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1021 if originalBuffer == -1
1022 throw 'Original buffer no longer exists, aborting.'
1025 let path = resolve(bufname(originalBuffer))
1027 " Work with netrw or other systems where a directory listing is displayed in
1030 if isdirectory(path)
1033 let fileName = fnamemodify(path, ':t')
1036 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1037 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1039 let fullCmd = a:cmd . ' "' . fileName . '"'
1042 " Change to the directory of the current buffer. This is done for CVS, but
1043 " is left in for other systems as it does not affect them negatively.
1045 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1047 let output = system(fullCmd)
1049 call VCSCommandChdir(oldCwd)
1052 " HACK: if line endings in the repository have been corrupted, the output
1053 " of the command will be confused.
1054 let output = substitute(output, "\r", '', 'g')
1056 if v:shell_error && !allowNonZeroExit
1057 if strlen(output) == 0
1058 throw 'Version control command failed'
1060 let output = substitute(output, '\n', ' ', 'g')
1061 throw 'Version control command failed: ' . output
1065 if strlen(output) == 0
1066 " Handle case of no output. In this case, it is important to check the
1067 " file status, especially since cvs edit/unedit may change the attributes
1068 " of the file with no visible output.
1074 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1078 " The last command left a blank line at the end of the buffer. If the
1079 " last line is folded (a side effect of the 'put') then the attempt to
1080 " remove the blank line will kill the last fold.
1082 " This could be fixed by explicitly detecting whether the last line is
1083 " within a fold, but I prefer to simply unfold the result buffer altogether.
1092 " Define the environment and execute user-defined hooks.
1094 silent do VCSCommand User VCSBufferCreated
1098 " Function: VCSCommandGetOption(name, default) {{{2
1099 " Grab a user-specified option to override the default provided. Options are
1100 " searched in the window, buffer, then global spaces.
1102 function! VCSCommandGetOption(name, default)
1103 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1104 return s:optionOverrides[a:name][-1]
1105 elseif exists('w:' . a:name)
1107 elseif exists('b:' . a:name)
1109 elseif exists('g:' . a:name)
1116 " Function: VCSCommandDisableBufferSetup() {{{2
1117 " Global function for deactivating the buffer autovariables.
1119 function! VCSCommandDisableBufferSetup()
1120 let g:VCSCommandEnableBufferSetup = 0
1121 silent! augroup! VCSCommandPlugin
1124 " Function: VCSCommandEnableBufferSetup() {{{2
1125 " Global function for activating the buffer autovariables.
1127 function! VCSCommandEnableBufferSetup()
1128 let g:VCSCommandEnableBufferSetup = 1
1129 augroup VCSCommandPlugin
1131 au BufEnter * call s:SetupBuffer()
1134 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1136 if g:loaded_VCSCommand == 2
1137 call s:SetupBuffer()
1141 " Function: VCSCommandGetStatusLine() {{{2
1142 " Default (sample) status line entry for VCS-controlled files. This is only
1143 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1144 " variable for how to do this).
1146 function! VCSCommandGetStatusLine()
1147 if exists('b:VCSCommandCommand')
1148 " This is a result buffer. Return nothing because the buffer name
1149 " contains information already.
1153 if exists('b:VCSCommandVCSType')
1154 \ && exists('g:VCSCommandEnableBufferSetup')
1155 \ && g:VCSCommandEnableBufferSetup
1156 \ && exists('b:VCSCommandBufferInfo')
1157 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1163 " Section: Command definitions {{{1
1164 " Section: Primary commands {{{2
1165 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1166 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1167 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1168 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1169 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1170 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1171 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1172 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1173 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1174 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1175 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1176 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1177 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1178 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1179 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1180 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1181 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1183 " Section: VCS buffer management commands {{{2
1184 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1185 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1187 " Allow reloading VCSCommand.vim
1188 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
1190 " Section: Plugin command mappings {{{1
1191 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1192 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1193 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1194 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1195 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1196 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1197 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1198 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1199 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1200 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1201 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1202 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1203 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1204 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1205 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1206 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1208 " Section: Default mappings {{{1
1210 let s:defaultMappings = [
1212 \['c', 'VCSCommit'],
1213 \['D', 'VCSDelete'],
1215 \['G', 'VCSClearAndGotoOriginal'],
1216 \['g', 'VCSGotoOriginal'],
1220 \['n', 'VCSAnnotate'],
1221 \['q', 'VCSRevert'],
1222 \['r', 'VCSReview'],
1223 \['s', 'VCSStatus'],
1224 \['U', 'VCSUnlock'],
1225 \['u', 'VCSUpdate'],
1226 \['v', 'VCSVimDiff'],
1229 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1230 for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1231 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1235 " Section: Menu items {{{1
1236 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1237 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1238 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1239 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1240 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1241 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1242 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1243 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1244 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1245 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1246 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1247 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1249 " Section: Autocommands to restore vimdiff state {{{1
1250 augroup VimDiffRestore
1252 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1255 " Section: Optional activation of buffer management {{{1
1257 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1258 call VCSCommandEnableBufferSetup()
1261 " Section: VIM shutdown hook {{{1
1263 " Close all result buffers when VIM exits, to prevent them from being restored
1266 " Function: s:CloseAllResultBuffers() {{{2
1267 " Closes all vcscommand result buffers.
1268 function! s:CloseAllResultBuffers()
1269 " This avoids using bufdo as that may load buffers already loaded in another
1270 " vim process, resulting in an error.
1272 let buffmaxnr = bufnr('$')
1273 while buffnr <= buffmaxnr
1274 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1277 let buffnr = buffnr + 1
1281 augroup VCSCommandVIMShutdown
1283 au VimLeavePre * call s:CloseAllResultBuffers()
1286 " Section: Plugin completion {{{1
1288 let loaded_VCSCommand = 2
1290 silent do VCSCommand User VCSPluginFinish
1292 let &cpo = s:save_cpo