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.
186 " VCSCommandDisableMappings
187 " This variable, if set to a non-zero value, prevents the default command
188 " mappings from being set.
190 " VCSCommandDisableExtensionMappings
191 " This variable, if set to a non-zero value, prevents the default command
192 " mappings from being set for commands specific to an individual VCS.
195 " This variable controls whether to split the current window to display a
196 " scratch buffer ('split'), or to display it in the current buffer ('edit').
197 " If not set, it defaults to 'split'.
199 " VCSCommandEnableBufferSetup
200 " This variable, if set to a non-zero value, activates VCS buffer management
201 " mode. This mode means that the buffer variable 'VCSRevision' is set if
202 " the file is VCS-controlled. This is useful for displaying version
203 " information in the status bar. Additional options may be set by
204 " individual VCS plugins.
206 " VCSCommandResultBufferNameExtension
207 " This variable, if set to a non-blank value, is appended to the name of the
208 " VCS command output buffers. For example, '.vcs'. Using this option may
209 " help avoid problems caused by autocommands dependent on file extension.
211 " VCSCommandResultBufferNameFunction
212 " This variable, if set, specifies a custom function for naming VCS command
213 " output buffers. This function will be passed the following arguments:
215 " command - name of the VCS command being executed (such as 'Log' or
218 " originalBuffer - buffer number of the source file.
220 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
222 " statusText - extra text associated with the VCS action (such as version
226 " This variable controls the orientation of the various window splits that
227 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
228 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
229 " If set to 'horizontal', the resulting windows will be on stacked on top of
230 " one another. If set to 'vertical', the resulting windows will be
231 " side-by-side. If not set, it defaults to 'horizontal' for all but
232 " VCSVimDiff windows.
234 " Event documentation {{{2
235 " For additional customization, VCSCommand.vim uses User event autocommand
236 " hooks. Each event is in the VCSCommand group, and different patterns
237 " match the various hooks.
239 " For instance, the following could be added to the vimrc to provide a 'q'
240 " mapping to quit a VCS scratch buffer:
243 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
246 " The following hooks are available:
248 " VCSBufferCreated This event is fired just after a VCS command
249 " output buffer is created. It is executed
250 " within the context of the new buffer.
252 " VCSBufferSetup This event is fired just after VCS buffer setup
253 " occurs, if enabled.
255 " VCSPluginInit This event is fired when the VCSCommand plugin
258 " VCSPluginFinish This event is fired just after the VCSCommand
261 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
262 " command executes to allow customization of,
263 " for instance, window placement and focus.
265 " Section: Plugin header {{{1
267 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
268 " completes. This allows various actions to only be taken by functions after
269 " system initialization.
271 if exists('loaded_VCSCommand')
274 let loaded_VCSCommand = 1
277 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
284 " Section: Event group setup {{{1
289 augroup VCSCommandCommit
292 " Section: Plugin initialization {{{1
293 silent do VCSCommand User VCSPluginInit
295 " Section: Script variable initialization {{{1
298 let s:pluginFiles = []
299 let s:extendedMappings = {}
300 let s:optionOverrides = {}
301 let s:isEditFileRunning = 0
303 unlet! s:vimDiffRestoreCmd
304 unlet! s:vimDiffSourceBuffer
305 unlet! s:vimDiffScratchList
307 " Section: Utility functions {{{1
309 " Function: s:ReportError(mapping) {{{2
310 " Displays the given error in a consistent faction. This is intended to be
311 " invoked from a catch statement.
313 function! s:ReportError(error)
314 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
317 " Function: s:ExecuteExtensionMapping(mapping) {{{2
318 " Invokes the appropriate extension mapping depending on the type of the
321 function! s:ExecuteExtensionMapping(mapping)
322 let buffer = bufnr('%')
323 let vcsType = VCSCommandGetVCSType(buffer)
324 if !has_key(s:extendedMappings, vcsType)
325 throw 'Unknown VCS type: ' . vcsType
327 if !has_key(s:extendedMappings[vcsType], a:mapping)
328 throw 'This extended mapping is not defined for ' . vcsType
330 silent execute 'normal' ':' . s:extendedMappings[vcsType][a:mapping] . "\<CR>"
333 " Function: s:ExecuteVCSCommand(command, argList) {{{2
334 " Calls the indicated plugin-specific VCS command on the current buffer.
335 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
338 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
340 let buffer = bufnr('%')
342 let vcsType = VCSCommandGetVCSType(buffer)
343 if !has_key(s:plugins, vcsType)
344 throw 'Unknown VCS type: ' . vcsType
347 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
348 let bufferName = bufname(originalBuffer)
350 " It is already known that the directory is under VCS control. No further
351 " checks are needed. Otherwise, perform some basic sanity checks to avoid
352 " VCS-specific error messages from confusing things.
353 if !isdirectory(bufferName)
354 if !filereadable(bufferName)
355 throw 'No such file ' . bufferName
358 if isdirectory(bufferName)
360 let revision = VCSCommandGetRevision()
362 throw 'Unable to obtain version information.'
363 elseif revision == 'Unknown'
364 throw 'Item not under source control'
365 elseif revision == 'New'
366 throw 'Operation not available on newly-added item.'
371 let functionMap = s:plugins[vcsType]
372 if !has_key(functionMap, a:command)
373 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
375 return functionMap[a:command](a:argList)
377 call s:ReportError(v:exception)
382 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
383 " Default method of generating the name for VCS result buffers. This can be
384 " overridden with the VCSResultBufferNameFunction variable.
386 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
387 let fileName = bufname(a:originalBuffer)
388 let bufferName = a:vcsType . ' ' . a:command
389 if strlen(a:statusText) > 0
390 let bufferName .= ' ' . a:statusText
392 let bufferName .= ' ' . fileName
394 let versionedBufferName = bufferName
395 while buflisted(versionedBufferName)
397 let versionedBufferName = bufferName . ' (' . counter . ')'
399 return versionedBufferName
402 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
403 " Method of generating the name for VCS result buffers that uses the original
404 " file name with the VCS type and command appended as extensions.
406 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
407 let fileName = bufname(a:originalBuffer)
408 let bufferName = a:vcsType . ' ' . a:command
409 if strlen(a:statusText) > 0
410 let bufferName .= ' ' . a:statusText
412 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
414 let versionedBufferName = bufferName
415 while buflisted(versionedBufferName)
417 let versionedBufferName = '(' . counter . ') ' . bufferName
419 return versionedBufferName
422 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
423 " Creates a new buffer of the given name and associates it with the given
426 function! s:EditFile(command, originalBuffer, statusText)
427 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
429 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
430 if nameExtension == ''
431 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
433 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
436 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
438 " Protect against useless buffer set-up
439 let s:isEditFileRunning += 1
441 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
442 if editCommand == 'split'
443 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
446 vert rightbelow split
449 edit `=resultBufferName`
450 let b:VCSCommandCommand = a:command
451 let b:VCSCommandOriginalBuffer = a:originalBuffer
452 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
453 let b:VCSCommandVCSType = vcsType
457 let &filetype = vcsType . a:command
459 if a:statusText != ''
460 let b:VCSCommandStatusText = a:statusText
463 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
467 let s:isEditFileRunning -= 1
472 " Function: s:SetupBuffer() {{{2
473 " Attempts to set the b:VCSCommandBufferInfo variable
475 function! s:SetupBuffer()
476 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
477 " This buffer is already set up.
481 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
482 " No special status for special buffers other than directory buffers.
486 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
487 unlet! b:VCSCommandBufferSetup
492 let vcsType = VCSCommandGetVCSType(bufnr('%'))
493 let b:VCSCommandBufferInfo = s:plugins[vcsType].GetBufferInfo()
494 silent do VCSCommand User VCSBufferSetup
495 catch /No suitable plugin/
496 " This is not a VCS-controlled file.
497 let b:VCSCommandBufferInfo = []
500 let b:VCSCommandBufferSetup = 1
503 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
504 " Resets the buffer setup state of the original buffer for a given VCS scratch
506 " Returns: The VCS buffer number in a passthrough mode.
508 function! s:MarkOrigBufferForSetup(buffer)
511 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
512 " This should never not work, but I'm paranoid
513 if origBuffer != a:buffer
514 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
520 " Function: s:OverrideOption(option, [value]) {{{2
521 " Provides a temporary override for the given VCS option. If no value is
522 " passed, the override is disabled.
524 function! s:OverrideOption(option, ...)
526 call remove(s:optionOverrides[a:option], -1)
528 if !has_key(s:optionOverrides, a:option)
529 let s:optionOverrides[a:option] = []
531 call add(s:optionOverrides[a:option], a:1)
535 " Function: s:WipeoutCommandBuffers() {{{2
536 " Clears all current VCS output buffers of the specified type for a given source.
538 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
540 while buffer <= bufnr('$')
541 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
542 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
546 let buffer = buffer + 1
550 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
551 " Checks whether the given buffer is one whose deletion should trigger
552 " restoration of an original buffer after it was diffed. If so, it executes
553 " the appropriate setting command stored with that original buffer.
555 function! s:VimDiffRestore(vimDiffBuff)
556 let s:isEditFileRunning += 1
558 if exists('s:vimDiffSourceBuffer')
559 if a:vimDiffBuff == s:vimDiffSourceBuffer
560 " Original file is being removed.
561 unlet! s:vimDiffSourceBuffer
562 unlet! s:vimDiffRestoreCmd
563 unlet! s:vimDiffScratchList
565 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
567 call remove(s:vimDiffScratchList, index)
568 if len(s:vimDiffScratchList) == 0
569 if exists('s:vimDiffRestoreCmd')
570 " All scratch buffers are gone, reset the original.
571 " Only restore if the source buffer is still in Diff mode
573 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
575 " The buffer is visible in at least one window
576 let currentWinNR = winnr()
577 while winbufnr(sourceWinNR) != -1
578 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
579 execute sourceWinNR . 'wincmd w'
580 if getwinvar(0, '&diff')
581 execute s:vimDiffRestoreCmd
584 let sourceWinNR = sourceWinNR + 1
586 execute currentWinNR . 'wincmd w'
588 " The buffer is hidden. It must be visible in order to set the
590 let currentBufNR = bufnr('')
591 execute 'hide buffer' s:vimDiffSourceBuffer
592 if getwinvar(0, '&diff')
593 execute s:vimDiffRestoreCmd
595 execute 'hide buffer' currentBufNR
598 unlet s:vimDiffRestoreCmd
600 " All buffers are gone.
601 unlet s:vimDiffSourceBuffer
602 unlet s:vimDiffScratchList
608 let s:isEditFileRunning -= 1
612 " Section: Generic VCS command functions {{{1
614 " Function: s:VCSCommit() {{{2
615 function! s:VCSCommit(bang, message)
617 let vcsType = VCSCommandGetVCSType(bufnr('%'))
618 if !has_key(s:plugins, vcsType)
619 throw 'Unknown VCS type: ' . vcsType
622 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
624 " Handle the commit message being specified. If a message is supplied, it
625 " is used; if bang is supplied, an empty message is used; otherwise, the
626 " user is provided a buffer from which to edit the commit message.
628 if strlen(a:message) > 0 || a:bang == '!'
629 return s:VCSFinishCommit([a:message], originalBuffer)
632 call s:EditFile('commitlog', originalBuffer, '')
635 " Create a commit mapping.
637 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
639 silent 0put ='VCS: ----------------------------------------------------------------------'
640 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
641 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
643 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
645 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
646 silent put ='VCS: or write this buffer'
649 silent put ='VCS: ----------------------------------------------------------------------'
653 call s:ReportError(v:exception)
658 " Function: s:VCSFinishCommitWithBuffer() {{{2
659 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
660 " which removes all lines starting with 'VCS:'.
662 function! s:VCSFinishCommitWithBuffer()
664 let currentBuffer = bufnr('%')
665 let logMessageList = getbufline('%', 1, '$')
666 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
667 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
669 execute 'bw' currentBuffer
674 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
675 function! s:VCSFinishCommit(logMessageList, originalBuffer)
676 let shellSlashBak = &shellslash
679 let messageFileName = tempname()
680 call writefile(a:logMessageList, messageFileName)
682 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
686 return s:MarkOrigBufferForSetup(resultBuffer)
688 call delete(messageFileName)
691 let &shellslash = shellSlashBak
695 " Function: s:VCSGotoOriginal(bang) {{{2
696 function! s:VCSGotoOriginal(bang)
697 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
698 if originalBuffer > 0
699 let origWinNR = bufwinnr(originalBuffer)
701 execute 'buffer' originalBuffer
703 execute origWinNR . 'wincmd w'
707 let buffmaxnr = bufnr('$')
708 while buffnr <= buffmaxnr
709 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
712 let buffnr = buffnr + 1
718 " Function: s:VCSVimDiff(...) {{{2
719 function! s:VCSVimDiff(...)
721 let vcsType = VCSCommandGetVCSType(bufnr('%'))
722 if !has_key(s:plugins, vcsType)
723 throw 'Unknown VCS type: ' . vcsType
725 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
726 let s:isEditFileRunning = s:isEditFileRunning + 1
728 " If there's already a VimDiff'ed window, restore it.
729 " There may only be one VCSVimDiff original window at a time.
731 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
732 " Clear the existing vimdiff setup by removing the result buffers.
733 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
738 " Reset the vimdiff system, as 2 explicit versions were provided.
739 if exists('s:vimDiffSourceBuffer')
740 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
742 let resultBuffer = s:plugins[vcsType].Review([a:1])
744 echomsg 'Can''t open revision ' . a:1
747 let b:VCSCommandCommand = 'vimdiff'
749 let s:vimDiffScratchList = [resultBuffer]
750 " If no split method is defined, cheat, and set it to vertical.
752 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
753 let resultBuffer = s:plugins[vcsType].Review([a:2])
755 call s:OverrideOption('VCSCommandSplit')
758 echomsg 'Can''t open revision ' . a:1
761 let b:VCSCommandCommand = 'vimdiff'
763 let s:vimDiffScratchList += [resultBuffer]
766 call s:OverrideOption('VCSCommandEdit', 'split')
768 " Force splitting behavior, otherwise why use vimdiff?
769 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
772 let resultBuffer = s:plugins[vcsType].Review([])
774 let resultBuffer = s:plugins[vcsType].Review([a:1])
777 call s:OverrideOption('VCSCommandSplit')
780 call s:OverrideOption('VCSCommandEdit')
783 echomsg 'Can''t open current revision'
786 let b:VCSCommandCommand = 'vimdiff'
789 if !exists('s:vimDiffSourceBuffer')
790 " New instance of vimdiff.
791 let s:vimDiffScratchList = [resultBuffer]
793 " This could have been invoked on a VCS result buffer, not the
796 execute 'buffer' originalBuffer
797 " Store info for later original buffer restore
798 let s:vimDiffRestoreCmd =
799 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
800 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
801 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
802 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
803 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
804 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
805 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
809 " Adding a window to an existing vimdiff
810 let s:vimDiffScratchList += [resultBuffer]
814 let s:vimDiffSourceBuffer = originalBuffer
816 " Avoid executing the modeline in the current buffer after the autocommand.
818 let currentBuffer = bufnr('%')
819 let saveModeline = getbufvar(currentBuffer, '&modeline')
821 call setbufvar(currentBuffer, '&modeline', 0)
822 silent do VCSCommand User VCSVimDiffFinish
824 call setbufvar(currentBuffer, '&modeline', saveModeline)
828 let s:isEditFileRunning = s:isEditFileRunning - 1
831 call s:ReportError(v:exception)
836 " Section: Public functions {{{1
838 " Function: VCSCommandGetVCSType() {{{2
839 " Sets the b:VCSCommandVCSType variable in the given buffer to the
840 " appropriate source control system name.
842 function! VCSCommandGetVCSType(buffer)
843 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
844 if strlen(vcsType) > 0
847 for vcsType in keys(s:plugins)
848 if s:plugins[vcsType].Identify(a:buffer)
849 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
853 throw 'No suitable plugin'
856 " Function: VCSCommandChdir(directory) {{{2
857 " Changes the current directory, respecting :lcd changes.
859 function! VCSCommandChdir(directory)
861 if exists("*haslocaldir") && haslocaldir()
864 execute command escape(a:directory, ' ')
867 " Function: VCSCommandChangeToCurrentFileDir() {{{2
868 " Go to the directory in which the given file is located.
870 function! VCSCommandChangeToCurrentFileDir(fileName)
871 let oldCwd = getcwd()
872 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
873 if strlen(newCwd) > 0
874 call VCSCommandChdir(newCwd)
879 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
880 " Attempts to locate the original file to which VCS operations were applied
881 " for a given buffer.
883 function! VCSCommandGetOriginalBuffer(vcsBuffer)
884 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
886 if bufexists(origBuffer)
889 " Original buffer no longer exists.
890 throw 'Original buffer for this VCS buffer no longer exists.'
898 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
899 " Allows VCS modules to register themselves.
901 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
902 let s:plugins[a:name] = a:commandMap
903 call add(s:pluginFiles, a:file)
904 let s:extendedMappings[a:name] = a:mappingMap
905 if !empty(a:mappingMap)
906 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
907 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
908 for mapname in keys(a:mappingMap)
909 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
914 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
915 " General skeleton for VCS function execution.
916 " Returns: name of the new command buffer containing the command results
918 function! VCSCommandDoCommand(cmd, cmdName, statusText)
919 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
920 if originalBuffer == -1
921 throw 'Original buffer no longer exists, aborting.'
924 let fileName = resolve(bufname(originalBuffer))
926 " Work with netrw or other systems where a directory listing is displayed in
929 if isdirectory(fileName)
930 let realFileName = '.'
932 let realFileName = fnamemodify(fileName, ':t')
935 " Change to the directory of the current buffer. This is done for CVS, but
936 " is left in for other systems as it does not affect them negatively.
938 let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
940 let output = system(a:cmd . ' "' . realFileName . '"')
942 call VCSCommandChdir(oldCwd)
945 " HACK: if line endings in the repository have been corrupted, the output
946 " of the command will be confused.
947 let output = substitute(output, "\r", '', 'g')
949 " HACK: CVS diff command does not return proper error codes
950 if v:shell_error && (a:cmdName != 'diff' || getbufvar(originalBuffer, 'VCSCommandVCSType') != 'CVS')
951 if strlen(output) == 0
952 throw 'Version control command failed'
954 let output = substitute(output, '\n', ' ', 'g')
955 throw 'Version control command failed: ' . output
958 if strlen(output) == 0
959 " Handle case of no output. In this case, it is important to check the
960 " file status, especially since cvs edit/unedit may change the attributes
961 " of the file with no visible output.
967 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
971 " The last command left a blank line at the end of the buffer. If the
972 " last line is folded (a side effect of the 'put') then the attempt to
973 " remove the blank line will kill the last fold.
975 " This could be fixed by explicitly detecting whether the last line is
976 " within a fold, but I prefer to simply unfold the result buffer altogether.
985 " Define the environment and execute user-defined hooks.
987 silent do VCSCommand User VCSBufferCreated
991 " Function: VCSCommandGetOption(name, default) {{{2
992 " Grab a user-specified option to override the default provided. Options are
993 " searched in the window, buffer, then global spaces.
995 function! VCSCommandGetOption(name, default)
996 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
997 return s:optionOverrides[a:name][-1]
998 elseif exists('w:' . a:name)
1000 elseif exists('b:' . a:name)
1002 elseif exists('g:' . a:name)
1009 " Function: VCSCommandGetRevision() {{{2
1010 " Global function for retrieving the current buffer's revision number.
1011 " Returns: Revision number or an empty string if an error occurs.
1013 function! VCSCommandGetRevision()
1014 if !exists('b:VCSCommandBufferInfo')
1015 let b:VCSCommandBufferInfo = s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1018 if len(b:VCSCommandBufferInfo) > 0
1019 return b:VCSCommandBufferInfo[0]
1025 " Function: VCSCommandDisableBufferSetup() {{{2
1026 " Global function for deactivating the buffer autovariables.
1028 function! VCSCommandDisableBufferSetup()
1029 let g:VCSCommandEnableBufferSetup = 0
1030 silent! augroup! VCSCommandPlugin
1033 " Function: VCSCommandEnableBufferSetup() {{{2
1034 " Global function for activating the buffer autovariables.
1036 function! VCSCommandEnableBufferSetup()
1037 let g:VCSCommandEnableBufferSetup = 1
1038 augroup VCSCommandPlugin
1040 au BufEnter * call s:SetupBuffer()
1043 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1045 if g:loaded_VCSCommand == 2
1046 call s:SetupBuffer()
1050 " Function: VCSCommandGetStatusLine() {{{2
1051 " Default (sample) status line entry for VCS-controlled files. This is only
1052 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1053 " variable for how to do this).
1055 function! VCSCommandGetStatusLine()
1056 if exists('b:VCSCommandCommand')
1057 " This is a result buffer. Return nothing because the buffer name
1058 " contains information already.
1062 if exists('b:VCSCommandVCSType')
1063 \ && exists('g:VCSCommandEnableBufferSetup')
1064 \ && g:VCSCommandEnableBufferSetup
1065 \ && exists('b:VCSCommandBufferInfo')
1066 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1072 " Section: Command definitions {{{1
1073 " Section: Primary commands {{{2
1074 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1075 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1076 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1077 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1078 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1079 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1080 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1081 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1082 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1083 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1084 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1085 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1086 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1087 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1088 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1090 " Section: VCS buffer management commands {{{2
1091 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1092 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1094 " Allow reloading VCSCommand.vim
1095 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
1097 " Section: Plugin command mappings {{{1
1098 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1099 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1100 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1101 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1102 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1103 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1104 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1105 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1106 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1107 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1108 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1109 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1110 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1111 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1112 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1113 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1115 " Section: Default mappings {{{1
1117 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1118 if !hasmapto('<Plug>VCSAdd')
1119 nmap <unique> <Leader>ca <Plug>VCSAdd
1121 if !hasmapto('<Plug>VCSAnnotate')
1122 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1124 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1125 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1127 if !hasmapto('<Plug>VCSCommit')
1128 nmap <unique> <Leader>cc <Plug>VCSCommit
1130 if !hasmapto('<Plug>VCSDelete')
1131 nmap <unique> <Leader>cD <Plug>VCSDelete
1133 if !hasmapto('<Plug>VCSDiff')
1134 nmap <unique> <Leader>cd <Plug>VCSDiff
1136 if !hasmapto('<Plug>VCSGotoOriginal')
1137 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1139 if !hasmapto('<Plug>VCSInfo')
1140 nmap <unique> <Leader>ci <Plug>VCSInfo
1142 if !hasmapto('<Plug>VCSLock')
1143 nmap <unique> <Leader>cL <Plug>VCSLock
1145 if !hasmapto('<Plug>VCSLog')
1146 nmap <unique> <Leader>cl <Plug>VCSLog
1148 if !hasmapto('<Plug>VCSRevert')
1149 nmap <unique> <Leader>cq <Plug>VCSRevert
1151 if !hasmapto('<Plug>VCSReview')
1152 nmap <unique> <Leader>cr <Plug>VCSReview
1154 if !hasmapto('<Plug>VCSStatus')
1155 nmap <unique> <Leader>cs <Plug>VCSStatus
1157 if !hasmapto('<Plug>VCSUnlock')
1158 nmap <unique> <Leader>cU <Plug>VCSUnlock
1160 if !hasmapto('<Plug>VCSUpdate')
1161 nmap <unique> <Leader>cu <Plug>VCSUpdate
1163 if !hasmapto('<Plug>VCSVimDiff')
1164 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1168 " Section: Menu items {{{1
1169 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1170 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1171 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1172 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1173 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1174 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1175 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1176 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1177 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1178 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1179 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1180 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1182 " Section: Autocommands to restore vimdiff state {{{1
1183 augroup VimDiffRestore
1185 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1188 " Section: Optional activation of buffer management {{{1
1190 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1191 call VCSCommandEnableBufferSetup()
1194 " Section: VIM shutdown hook {{{1
1196 " Close all result buffers when VIM exits, to prevent them from being restored
1199 " Function: s:CloseAllResultBuffers() {{{2
1200 " Closes all vcscommand result buffers.
1201 function! s:CloseAllResultBuffers()
1202 " This avoids using bufdo as that may load buffers already loaded in another
1203 " vim process, resulting in an error.
1205 let buffmaxnr = bufnr('$')
1206 while buffnr <= buffmaxnr
1207 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1210 let buffnr = buffnr + 1
1214 augroup VCSCommandVIMShutdown
1216 au VimLeavePre * call s:CloseAllResultBuffers()
1219 " Section: Plugin completion {{{1
1221 let loaded_VCSCommand = 2
1223 silent do VCSCommand User VCSPluginFinish
1225 let &cpo = s:save_cpo