1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
6 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
8 " Copyright (c) 2007 Bob Hiestand
10 " Permission is hereby granted, free of charge, to any person obtaining a copy
11 " of this software and associated documentation files (the "Software"), to
12 " deal in the Software without restriction, including without limitation the
13 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
14 " sell copies of the Software, and to permit persons to whom the Software is
15 " furnished to do so, subject to the following conditions:
17 " The above copyright notice and this permission notice shall be included in
18 " all copies or substantial portions of the Software.
20 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 " Section: Documentation {{{1
30 " Provides functions to invoke various source control commands on the current
31 " file (either the current buffer, or, in the case of an directory buffer, the
32 " directory and all subdirectories associated with the current buffer). The
33 " output of the commands is captured in a new scratch window.
35 " This plugin needs additional extension plugins, each specific to a source
36 " control system, to function. Those plugins should be placed in a
37 " subdirectory of the standard plugin directory named 'vcscommand'. Several
38 " options include the name of the version control system in the option name.
39 " Such options use the placeholder text '{VCSType}', which would be replaced
40 " in actual usage with 'CVS' or 'SVN', for instance.
42 " Command documentation {{{2
44 " VCSAdd Adds the current file to source control.
46 " VCSAnnotate Displays the current file with each line annotated with the
47 " version in which it was most recently changed. If an
48 " argument is given, the argument is used as a revision
49 " number to display. If not given an argument, it uses the
50 " most recent version of the file on the current branch.
51 " Additionally, if the current buffer is a VCSAnnotate buffer
52 " already, the version number on the current line is used.
54 " VCSCommit[!] Commits changes to the current file to source control.
56 " If called with arguments, the arguments are the log message.
58 " If '!' is used, an empty log message is committed.
60 " If called with no arguments, this is a two-step command.
61 " The first step opens a buffer to accept a log message.
62 " When that buffer is written, it is automatically closed and
63 " the file is committed using the information from that log
64 " message. The commit can be abandoned if the log message
65 " buffer is deleted or wiped before being written.
67 " VCSDelete Deletes the current file and removes it from source control.
69 " VCSDiff With no arguments, this displays the differences between
70 " the current file and its parent version under source
71 " control in a new scratch buffer.
73 " With one argument, the diff is performed on the
74 " current file against the specified revision.
76 " With two arguments, the diff is performed between the
77 " specified revisions of the current file.
79 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
80 " to specify diff options. If that variable does not exist,
81 " a plugin-specific default is used. If you wish to have no
82 " options, then set it to the empty string.
84 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
85 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
86 " VCS scratch buffers associated with the original file.
88 " VCSInfo Displays extended information about the current file in a
91 " VCSLock Locks the current file in order to prevent other users from
92 " concurrently modifying it. The exact semantics of this
93 " command depend on the underlying VCS.
95 " VCSLog Displays the version history of the current file in a new
98 " VCSRevert Replaces the modified version of the current file with the
99 " most recent version from the repository.
101 " VCSReview Displays a particular version of the current file in a new
102 " scratch buffer. If no argument is given, the most recent
103 " version of the file on the current branch is retrieved.
105 " VCSStatus Displays versioning information about the current file in a
106 " new scratch buffer.
108 " VCSUnlock Unlocks the current file in order to allow other users from
109 " concurrently modifying it. The exact semantics of this
110 " command depend on the underlying VCS.
112 " VCSUpdate Updates the current file with any relevant changes from the
115 " VCSVimDiff Uses vimdiff to display differences between versions of the
118 " If no revision is specified, the most recent version of the
119 " file on the current branch is used. With one argument,
120 " that argument is used as the revision as above. With two
121 " arguments, the differences between the two revisions is
122 " displayed using vimdiff.
124 " With either zero or one argument, the original buffer is
125 " used to perform the vimdiff. When the scratch buffer is
126 " closed, the original buffer will be returned to normal
129 " Once vimdiff mode is started using the above methods,
130 " additional vimdiff buffers may be added by passing a single
131 " version argument to the command. There may be up to 4
132 " vimdiff buffers total.
134 " Using the 2-argument form of the command resets the vimdiff
135 " to only those 2 versions. Additionally, invoking the
136 " command on a different file will close the previous vimdiff
139 " Mapping documentation: {{{2
141 " By default, a mapping is defined for each command. User-provided mappings
142 " can be used instead by mapping to <Plug>CommandName, for instance:
144 " nmap ,ca <Plug>VCSAdd
146 " The default mappings are as follow:
149 " <Leader>cn VCSAnnotate
150 " <Leader>cc VCSCommit
151 " <Leader>cD VCSDelete
153 " <Leader>cg VCSGotoOriginal
154 " <Leader>cG VCSGotoOriginal!
158 " <Leader>cr VCSReview
159 " <Leader>cs VCSStatus
160 " <Leader>cu VCSUpdate
161 " <Leader>cU VCSUnlock
162 " <Leader>cv VCSVimDiff
164 " Options documentation: {{{2
166 " Several variables are checked by the script to determine behavior as follow:
168 " VCSCommandCommitOnWrite
169 " This variable, if set to a non-zero value, causes the pending commit to
170 " take place immediately as soon as the log message buffer is written. If
171 " set to zero, only the VCSCommit mapping will cause the pending commit to
172 " occur. If not set, it defaults to 1.
174 " VCSCommandDeleteOnHide
175 " This variable, if set to a non-zero value, causes the temporary VCS result
176 " buffers to automatically delete themselves when hidden.
178 " VCSCommand{VCSType}DiffOpt
179 " This variable, if set, determines the options passed to the diff command
180 " of the underlying VCS. Each VCS plugin defines a default value.
182 " VCSCommandDiffSplit
183 " This variable overrides the VCSCommandSplit variable, but only for buffers
184 " created with VCSVimDiff.
187 " This variable controls whether to split the current window to display a
188 " scratch buffer ('split'), or to display it in the current buffer ('edit').
189 " If not set, it defaults to 'split'.
191 " VCSCommandEnableBufferSetup
192 " This variable, if set to a non-zero value, activates VCS buffer management
193 " mode. This mode means that the buffer variable 'VCSRevision' is set if
194 " the file is VCS-controlled. This is useful for displaying version
195 " information in the status bar. Additional options may be set by
196 " individual VCS plugins.
198 " VCSCommandResultBufferNameExtension
199 " This variable, if set to a non-blank value, is appended to the name of the
200 " VCS command output buffers. For example, '.vcs'. Using this option may
201 " help avoid problems caused by autocommands dependent on file extension.
203 " VCSCommandResultBufferNameFunction
204 " This variable, if set, specifies a custom function for naming VCS command
205 " output buffers. This function will be passed the following arguments:
207 " command - name of the VCS command being executed (such as 'Log' or
210 " originalBuffer - buffer number of the source file.
212 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
214 " statusText - extra text associated with the VCS action (such as version
218 " This variable controls the orientation of the various window splits that
219 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
220 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
221 " If set to 'horizontal', the resulting windows will be on stacked on top of
222 " one another. If set to 'vertical', the resulting windows will be
223 " side-by-side. If not set, it defaults to 'horizontal' for all but
224 " VCSVimDiff windows.
226 " Event documentation {{{2
227 " For additional customization, VCSCommand.vim uses User event autocommand
228 " hooks. Each event is in the VCSCommand group, and different patterns
229 " match the various hooks.
231 " For instance, the following could be added to the vimrc to provide a 'q'
232 " mapping to quit a VCS scratch buffer:
235 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
238 " The following hooks are available:
240 " VCSBufferCreated This event is fired just after a VCS command
241 " output buffer is created. It is executed
242 " within the context of the new buffer.
244 " VCSBufferSetup This event is fired just after VCS buffer setup
245 " occurs, if enabled.
247 " VCSLoadExtensions This event is fired just before the
248 " VCSPluginFinish event. It is intended to be
249 " used only by VCS extensions to register
250 " themselves with VCSCommand if they are sourced
253 " VCSPluginInit This event is fired when the VCSCommand plugin
256 " VCSPluginFinish This event is fired just after the VCSCommand
259 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
260 " command executes to allow customization of,
261 " for instance, window placement and focus.
263 " Section: Plugin header {{{1
265 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
266 " completes. This allows various actions to only be taken by functions after
267 " system initialization.
269 if exists('loaded_VCSCommand')
272 let loaded_VCSCommand = 1
275 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
279 " Section: Event group setup {{{1
284 augroup VCSCommandCommit
287 " Section: Plugin initialization {{{1
288 silent do VCSCommand User VCSPluginInit
290 " Section: Script variable initialization {{{1
293 let s:pluginFiles = []
294 let s:extendedMappings = {}
295 let s:optionOverrides = {}
296 let s:isEditFileRunning = 0
298 unlet! s:vimDiffRestoreCmd
299 unlet! s:vimDiffSourceBuffer
300 unlet! s:vimDiffScratchList
302 " Section: Utility functions {{{1
304 " Function: s:ReportError(mapping) {{{2
305 " Displays the given error in a consistent faction. This is intended to be
306 " invoked from a catch statement.
308 function! s:ReportError(error)
309 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
312 " Function: s:ExecuteExtensionMapping(mapping) {{{2
313 " Invokes the appropriate extension mapping depending on the type of the
316 function! s:ExecuteExtensionMapping(mapping)
317 let buffer = bufnr('%')
318 let vcsType = VCSCommandGetVCSType(buffer)
319 if !has_key(s:extendedMappings, vcsType)
320 throw 'Unknown VCS type: ' . vcsType
322 if !has_key(s:extendedMappings[vcsType], a:mapping)
323 throw 'This extended mapping is not defined for ' . vcsType
325 silent execute 'normal' ':' . s:extendedMappings[vcsType][a:mapping] . "\<CR>"
328 " Function: s:ExecuteVCSCommand(command, argList) {{{2
329 " Calls the indicated plugin-specific VCS command on the current buffer.
330 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
333 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
335 let buffer = bufnr('%')
337 let vcsType = VCSCommandGetVCSType(buffer)
338 if !has_key(s:plugins, vcsType)
339 throw 'Unknown VCS type: ' . vcsType
342 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
343 let bufferName = bufname(originalBuffer)
344 if !isdirectory(bufferName) && !filereadable(bufferName)
345 throw 'No such file ' . bufferName
349 let revision = VCSCommandGetRevision()
351 throw 'Unable to obtain version information.'
352 elseif revision == 'Unknown'
353 throw 'Item not under source control'
354 elseif revision == 'New'
355 throw 'Operation not available on newly-added item.'
359 let functionMap = s:plugins[vcsType]
360 if !has_key(functionMap, a:command)
361 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
363 return functionMap[a:command](a:argList)
365 call s:ReportError(v:exception)
370 " Function: s:CreateCommandBuffer(cmd, cmdName, originalBuffer, statusText) {{{2
371 " Creates a new scratch buffer and captures the output from execution of the
372 " given command. The name of the scratch buffer is returned.
374 function! s:CreateCommandBuffer(cmd, cmdName, originalBuffer, statusText)
375 let output = system(a:cmd)
377 " HACK: if line endings in the repository have been corrupted, the output
378 " of the command will be confused.
379 let output = substitute(output, "\r", '', 'g')
381 " HACK: CVS diff command does not return proper error codes
382 if v:shell_error && (a:cmdName != 'diff' || getbufvar(a:originalBuffer, 'VCSCommandVCSType') != 'CVS')
383 if strlen(output) == 0
384 throw 'Version control command failed'
386 let output = substitute(output, '\n', ' ', 'g')
387 throw 'Version control command failed: ' . output
390 if strlen(output) == 0
391 " Handle case of no output. In this case, it is important to check the
392 " file status, especially since cvs edit/unedit may change the attributes
393 " of the file with no visible output.
399 call s:EditFile(a:cmdName, a:originalBuffer, a:statusText)
403 " The last command left a blank line at the end of the buffer. If the
404 " last line is folded (a side effect of the 'put') then the attempt to
405 " remove the blank line will kill the last fold.
407 " This could be fixed by explicitly detecting whether the last line is
408 " within a fold, but I prefer to simply unfold the result buffer altogether.
417 " Define the environment and execute user-defined hooks.
419 silent do VCSCommand User VCSBufferCreated
423 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
424 " Default method of generating the name for VCS result buffers. This can be
425 " overridden with the VCSResultBufferNameFunction variable.
427 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
428 let fileName = bufname(a:originalBuffer)
429 let bufferName = a:vcsType . ' ' . a:command
430 if strlen(a:statusText) > 0
431 let bufferName .= ' ' . a:statusText
433 let bufferName .= ' ' . fileName
435 let versionedBufferName = bufferName
436 while buflisted(versionedBufferName)
438 let versionedBufferName = bufferName . ' (' . counter . ')'
440 return versionedBufferName
443 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
444 " Method of generating the name for VCS result buffers that uses the original
445 " file name with the VCS type and command appended as extensions.
447 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
448 let fileName = bufname(a:originalBuffer)
449 let bufferName = a:vcsType . ' ' . a:command
450 if strlen(a:statusText) > 0
451 let bufferName .= ' ' . a:statusText
453 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
455 let versionedBufferName = bufferName
456 while buflisted(versionedBufferName)
458 let versionedBufferName = '(' . counter . ') ' . bufferName
460 return versionedBufferName
463 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
464 " Creates a new buffer of the given name and associates it with the given
467 function! s:EditFile(command, originalBuffer, statusText)
468 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
470 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
471 if nameExtension == ''
472 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
474 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
477 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
479 " Protect against useless buffer set-up
480 let s:isEditFileRunning += 1
482 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
483 if editCommand == 'split'
484 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
487 vert rightbelow split
490 edit `=resultBufferName`
491 let b:VCSCommandCommand = a:command
492 let b:VCSCommandOriginalBuffer = a:originalBuffer
493 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
494 let b:VCSCommandVCSType = vcsType
498 let &filetype = vcsType . a:command
500 if a:statusText != ''
501 let b:VCSCommandStatusText = a:statusText
504 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
508 let s:isEditFileRunning -= 1
513 " Function: s:SetupBuffer() {{{2
514 " Attempts to set the b:VCSCommandBufferInfo variable
516 function! s:SetupBuffer()
517 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
518 " This buffer is already set up.
522 if strlen(&buftype) > 0 || !filereadable(@%)
523 " No special status for special buffers.
527 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
528 unlet! b:VCSCommandBufferSetup
533 let vcsType = VCSCommandGetVCSType(bufnr('%'))
534 let b:VCSCommandBufferInfo = s:plugins[vcsType].GetBufferInfo()
535 silent do VCSCommand User VCSBufferSetup
536 catch /No suitable plugin/
537 " This is not a VCS-controlled file.
538 let b:VCSCommandBufferInfo = []
541 let b:VCSCommandBufferSetup = 1
544 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
545 " Resets the buffer setup state of the original buffer for a given VCS scratch
547 " Returns: The VCS buffer number in a passthrough mode.
549 function! s:MarkOrigBufferForSetup(buffer)
552 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
553 " This should never not work, but I'm paranoid
554 if origBuffer != a:buffer
555 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
561 " Function: s:OverrideOption(option, [value]) {{{2
562 " Provides a temporary override for the given VCS option. If no value is
563 " passed, the override is disabled.
565 function! s:OverrideOption(option, ...)
567 call remove(s:optionOverrides[a:option], -1)
569 if !has_key(s:optionOverrides, a:option)
570 let s:optionOverrides[a:option] = []
572 call add(s:optionOverrides[a:option], a:1)
576 " Function: s:WipeoutCommandBuffers() {{{2
577 " Clears all current VCS output buffers of the specified type for a given source.
579 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
581 while buffer <= bufnr('$')
582 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
583 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
587 let buffer = buffer + 1
591 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
592 " Checks whether the given buffer is one whose deletion should trigger
593 " restoration of an original buffer after it was diffed. If so, it executes
594 " the appropriate setting command stored with that original buffer.
596 function! s:VimDiffRestore(vimDiffBuff)
597 let s:isEditFileRunning += 1
599 if exists('s:vimDiffSourceBuffer')
600 if a:vimDiffBuff == s:vimDiffSourceBuffer
601 " Original file is being removed.
602 unlet! s:vimDiffSourceBuffer
603 unlet! s:vimDiffRestoreCmd
604 unlet! s:vimDiffScratchList
606 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
608 call remove(s:vimDiffScratchList, index)
609 if len(s:vimDiffScratchList) == 0
610 if exists('s:vimDiffRestoreCmd')
611 " All scratch buffers are gone, reset the original.
612 " Only restore if the source buffer is still in Diff mode
614 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
616 " The buffer is visible in at least one window
617 let currentWinNR = winnr()
618 while winbufnr(sourceWinNR) != -1
619 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
620 execute sourceWinNR . 'wincmd w'
621 if getwinvar(0, '&diff')
622 execute s:vimDiffRestoreCmd
625 let sourceWinNR = sourceWinNR + 1
627 execute currentWinNR . 'wincmd w'
629 " The buffer is hidden. It must be visible in order to set the
631 let currentBufNR = bufnr('')
632 execute 'hide buffer' s:vimDiffSourceBuffer
633 if getwinvar(0, '&diff')
634 execute s:vimDiffRestoreCmd
636 execute 'hide buffer' currentBufNR
639 unlet s:vimDiffRestoreCmd
641 " All buffers are gone.
642 unlet s:vimDiffSourceBuffer
643 unlet s:vimDiffScratchList
649 let s:isEditFileRunning -= 1
653 " Section: Generic VCS command functions {{{1
655 " Function: s:VCSCommit() {{{2
656 function! s:VCSCommit(bang, message)
658 let vcsType = VCSCommandGetVCSType(bufnr('%'))
659 if !has_key(s:plugins, vcsType)
660 throw 'Unknown VCS type: ' . vcsType
663 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
665 " Handle the commit message being specified. If a message is supplied, it
666 " is used; if bang is supplied, an empty message is used; otherwise, the
667 " user is provided a buffer from which to edit the commit message.
669 if strlen(a:message) > 0 || a:bang == '!'
670 return s:VCSFinishCommit([a:message], originalBuffer)
673 call s:EditFile('commitlog', originalBuffer, '')
676 " Create a commit mapping.
678 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
680 silent 0put ='VCS: ----------------------------------------------------------------------'
681 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
682 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
684 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
686 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
687 silent put ='VCS: or write this buffer'
690 silent put ='VCS: ----------------------------------------------------------------------'
694 call s:ReportError(v:exception)
699 " Function: s:VCSFinishCommitWithBuffer() {{{2
700 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
701 " which removes all lines starting with 'VCS:'.
703 function! s:VCSFinishCommitWithBuffer()
705 let currentBuffer = bufnr('%')
706 let logMessageList = getbufline('%', 1, '$')
707 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
708 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
710 execute 'bw' currentBuffer
715 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
716 function! s:VCSFinishCommit(logMessageList, originalBuffer)
717 let shellSlashBak = &shellslash
720 let messageFileName = tempname()
721 call writefile(a:logMessageList, messageFileName)
723 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
727 return s:MarkOrigBufferForSetup(resultBuffer)
729 call delete(messageFileName)
732 let &shellslash = shellSlashBak
736 " Function: s:VCSGotoOriginal(bang) {{{2
737 function! s:VCSGotoOriginal(bang)
738 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
739 if originalBuffer > 0
740 let origWinNR = bufwinnr(originalBuffer)
742 execute 'buffer' originalBuffer
744 execute origWinNR . 'wincmd w'
748 let buffmaxnr = bufnr('$')
749 while buffnr <= buffmaxnr
750 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
753 let buffnr = buffnr + 1
759 " Function: s:VCSVimDiff(...) {{{2
760 function! s:VCSVimDiff(...)
762 let vcsType = VCSCommandGetVCSType(bufnr('%'))
763 if !has_key(s:plugins, vcsType)
764 throw 'Unknown VCS type: ' . vcsType
766 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
767 let s:isEditFileRunning = s:isEditFileRunning + 1
769 " If there's already a VimDiff'ed window, restore it.
770 " There may only be one VCSVimDiff original window at a time.
772 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
773 " Clear the existing vimdiff setup by removing the result buffers.
774 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
779 " Reset the vimdiff system, as 2 explicit versions were provided.
780 if exists('s:vimDiffSourceBuffer')
781 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
783 let resultBuffer = s:plugins[vcsType].Review([a:1])
785 echomsg 'Can''t open revision ' . a:1
788 let b:VCSCommandCommand = 'vimdiff'
790 let s:vimDiffScratchList = [resultBuffer]
791 " If no split method is defined, cheat, and set it to vertical.
793 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
794 let resultBuffer = s:plugins[vcsType].Review([a:2])
796 call s:OverrideOption('VCSCommandSplit')
799 echomsg 'Can''t open revision ' . a:1
802 let b:VCSCommandCommand = 'vimdiff'
804 let s:vimDiffScratchList += [resultBuffer]
807 call s:OverrideOption('VCSCommandEdit', 'split')
809 " Force splitting behavior, otherwise why use vimdiff?
810 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
813 let resultBuffer = s:plugins[vcsType].Review([])
815 let resultBuffer = s:plugins[vcsType].Review([a:1])
818 call s:OverrideOption('VCSCommandSplit')
821 call s:OverrideOption('VCSCommandEdit')
824 echomsg 'Can''t open current revision'
827 let b:VCSCommandCommand = 'vimdiff'
830 if !exists('s:vimDiffSourceBuffer')
831 " New instance of vimdiff.
832 let s:vimDiffScratchList = [resultBuffer]
834 " This could have been invoked on a VCS result buffer, not the
837 execute 'buffer' originalBuffer
838 " Store info for later original buffer restore
839 let s:vimDiffRestoreCmd =
840 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
841 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
842 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
843 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
844 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
845 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
846 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
850 " Adding a window to an existing vimdiff
851 let s:vimDiffScratchList += [resultBuffer]
855 let s:vimDiffSourceBuffer = originalBuffer
857 " Avoid executing the modeline in the current buffer after the autocommand.
859 let currentBuffer = bufnr('%')
860 let saveModeline = getbufvar(currentBuffer, '&modeline')
862 call setbufvar(currentBuffer, '&modeline', 0)
863 silent do VCSCommand User VCSVimDiffFinish
865 call setbufvar(currentBuffer, '&modeline', saveModeline)
869 let s:isEditFileRunning = s:isEditFileRunning - 1
872 call s:ReportError(v:exception)
877 " Section: Public functions {{{1
879 " Function: VCSCommandGetVCSType() {{{2
880 " Sets the b:VCSCommandVCSType variable in the given buffer to the
881 " appropriate source control system name.
883 function! VCSCommandGetVCSType(buffer)
884 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
885 if strlen(vcsType) > 0
888 for vcsType in keys(s:plugins)
889 if s:plugins[vcsType].Identify(a:buffer)
890 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
894 throw 'No suitable plugin'
897 " Function: VCSCommandChangeToCurrentFileDir() {{{2
898 " Go to the directory in which the given file is located.
900 function! VCSCommandChangeToCurrentFileDir(fileName)
901 let oldCwd = getcwd()
902 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
903 if strlen(newCwd) > 0
904 execute 'cd' escape(newCwd, ' ')
909 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
910 " Attempts to locate the original file to which VCS operations were applied
911 " for a given buffer.
913 function! VCSCommandGetOriginalBuffer(vcsBuffer)
914 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
916 if bufexists(origBuffer)
919 " Original buffer no longer exists.
920 throw 'Original buffer for this VCS buffer no longer exists.'
928 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
929 " Allows VCS modules to register themselves.
931 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
932 let s:plugins[a:name] = a:commandMap
933 call add(s:pluginFiles, a:file)
934 let s:extendedMappings[a:name] = a:mappingMap
935 if(!empty(a:mappingMap))
936 for mapname in keys(a:mappingMap)
937 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
942 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
943 " General skeleton for VCS function execution.
944 " Returns: name of the new command buffer containing the command results
946 function! VCSCommandDoCommand(cmd, cmdName, statusText)
947 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
948 if originalBuffer == -1
949 throw 'Original buffer no longer exists, aborting.'
952 let fileName = resolve(bufname(originalBuffer))
954 " Work with netrw or other systems where a directory listing is displayed in
957 if isdirectory(fileName)
958 let realFileName = '.'
960 let realFileName = fnamemodify(fileName, ':t')
963 let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
965 let fullCmd = a:cmd . ' "' . realFileName . '"'
966 let resultBuffer = s:CreateCommandBuffer(fullCmd, a:cmdName, originalBuffer, a:statusText)
969 execute 'cd' escape(oldCwd, ' ')
973 " Function: VCSCommandGetOption(name, default) {{{2
974 " Grab a user-specified option to override the default provided. Options are
975 " searched in the window, buffer, then global spaces.
977 function! VCSCommandGetOption(name, default)
978 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
979 return s:optionOverrides[a:name][-1]
980 elseif exists('w:' . a:name)
982 elseif exists('b:' . a:name)
984 elseif exists('g:' . a:name)
991 " Function: VCSCommandGetRevision() {{{2
992 " Global function for retrieving the current buffer's revision number.
993 " Returns: Revision number or an empty string if an error occurs.
995 function! VCSCommandGetRevision()
996 if !exists('b:VCSCommandBufferInfo')
997 let b:VCSCommandBufferInfo = s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1000 if len(b:VCSCommandBufferInfo) > 0
1001 return b:VCSCommandBufferInfo[0]
1007 " Function: VCSCommandDisableBufferSetup() {{{2
1008 " Global function for deactivating the buffer autovariables.
1010 function! VCSCommandDisableBufferSetup()
1011 let g:VCSCommandEnableBufferSetup = 0
1012 silent! augroup! VCSCommandPlugin
1015 " Function: VCSCommandEnableBufferSetup() {{{2
1016 " Global function for activating the buffer autovariables.
1018 function! VCSCommandEnableBufferSetup()
1019 let g:VCSCommandEnableBufferSetup = 1
1020 augroup VCSCommandPlugin
1022 au BufEnter * call s:SetupBuffer()
1025 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1027 if g:loaded_VCSCommand == 2
1028 call s:SetupBuffer()
1032 " Function: VCSCommandGetStatusLine() {{{2
1033 " Default (sample) status line entry for VCS-controlled files. This is only
1034 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1035 " variable for how to do this).
1037 function! VCSCommandGetStatusLine()
1038 if exists('b:VCSCommandCommand')
1039 " This is a result buffer. Return nothing because the buffer name
1040 " contains information already.
1044 if exists('b:VCSCommandVCSType')
1045 \ && exists('g:VCSCommandEnableBufferSetup')
1046 \ && g:VCSCommandEnableBufferSetup
1047 \ && exists('b:VCSCommandBufferInfo')
1048 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1054 " Section: Command definitions {{{1
1055 " Section: Primary commands {{{2
1056 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1057 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1058 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1059 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1060 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1061 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1062 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1063 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1064 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1065 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1066 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1067 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1068 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1069 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1070 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1072 " Section: VCS buffer management commands {{{2
1073 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1074 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1076 " Allow reloading VCSCommand.vim
1077 com! VCSReload let savedPluginFiles = s:pluginFiles|aunmenu Plugin.VCS|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for file in savedPluginFiles|execute 'source' file|endfor
1079 " Section: Plugin command mappings {{{1
1080 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1081 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1082 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1083 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1084 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1085 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1086 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1087 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1088 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1089 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1090 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1091 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1092 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1093 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1094 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1095 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1097 " Section: Default mappings {{{1
1098 if !hasmapto('<Plug>VCSAdd')
1099 nmap <unique> <Leader>ca <Plug>VCSAdd
1101 if !hasmapto('<Plug>VCSAnnotate')
1102 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1104 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1105 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1107 if !hasmapto('<Plug>VCSCommit')
1108 nmap <unique> <Leader>cc <Plug>VCSCommit
1110 if !hasmapto('<Plug>VCSDelete')
1111 nmap <unique> <Leader>cD <Plug>VCSDelete
1113 if !hasmapto('<Plug>VCSDiff')
1114 nmap <unique> <Leader>cd <Plug>VCSDiff
1116 if !hasmapto('<Plug>VCSGotoOriginal')
1117 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1119 if !hasmapto('<Plug>VCSInfo')
1120 nmap <unique> <Leader>ci <Plug>VCSInfo
1122 if !hasmapto('<Plug>VCSLock')
1123 nmap <unique> <Leader>cL <Plug>VCSLock
1125 if !hasmapto('<Plug>VCSLog')
1126 nmap <unique> <Leader>cl <Plug>VCSLog
1128 if !hasmapto('<Plug>VCSRevert')
1129 nmap <unique> <Leader>cq <Plug>VCSRevert
1131 if !hasmapto('<Plug>VCSReview')
1132 nmap <unique> <Leader>cr <Plug>VCSReview
1134 if !hasmapto('<Plug>VCSStatus')
1135 nmap <unique> <Leader>cs <Plug>VCSStatus
1137 if !hasmapto('<Plug>VCSUnlock')
1138 nmap <unique> <Leader>cU <Plug>VCSUnlock
1140 if !hasmapto('<Plug>VCSUpdate')
1141 nmap <unique> <Leader>cu <Plug>VCSUpdate
1143 if !hasmapto('<Plug>VCSVimDiff')
1144 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1147 " Section: Menu items {{{1
1148 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1149 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1150 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1151 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1152 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1153 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1154 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1155 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1156 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1157 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1158 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1159 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1161 " Section: Autocommands to restore vimdiff state {{{1
1162 augroup VimDiffRestore
1164 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1167 " Section: Optional activation of buffer management {{{1
1169 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1170 call VCSCommandEnableBufferSetup()
1173 " Section: Plugin completion {{{1
1175 let loaded_VCSCommand = 2
1177 " Load delayed extension plugin registration.
1178 silent do VCSCommand User VCSLoadExtensions
1179 au! VCSCommand User VCSLoadExtensions
1181 silent do VCSCommand User VCSPluginFinish