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 " VCSBlame Alias for 'VCSAnnotate'.
56 " VCSCommit[!] Commits changes to the current file to source control.
58 " If called with arguments, the arguments are the log message.
60 " If '!' is used, an empty log message is committed.
62 " If called with no arguments, this is a two-step command.
63 " The first step opens a buffer to accept a log message.
64 " When that buffer is written, it is automatically closed and
65 " the file is committed using the information from that log
66 " message. The commit can be abandoned if the log message
67 " buffer is deleted or wiped before being written.
69 " VCSDelete Deletes the current file and removes it from source control.
71 " VCSDiff With no arguments, this displays the differences between
72 " the current file and its parent version under source
73 " control in a new scratch buffer.
75 " With one argument, the diff is performed on the
76 " current file against the specified revision.
78 " With two arguments, the diff is performed between the
79 " specified revisions of the current file.
81 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
82 " to specify diff options. If that variable does not exist,
83 " a plugin-specific default is used. If you wish to have no
84 " options, then set it to the empty string.
86 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
87 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
88 " VCS scratch buffers associated with the original file.
90 " VCSInfo Displays extended information about the current file in a
93 " VCSLock Locks the current file in order to prevent other users from
94 " concurrently modifying it. The exact semantics of this
95 " command depend on the underlying VCS.
97 " VCSLog Displays the version history of the current file in a new
100 " VCSRevert Replaces the modified version of the current file with the
101 " most recent version from the repository.
103 " VCSReview Displays a particular version of the current file in a new
104 " scratch buffer. If no argument is given, the most recent
105 " version of the file on the current branch is retrieved.
107 " VCSStatus Displays versioning information about the current file in a
108 " new scratch buffer.
110 " VCSUnlock Unlocks the current file in order to allow other users from
111 " concurrently modifying it. The exact semantics of this
112 " command depend on the underlying VCS.
114 " VCSUpdate Updates the current file with any relevant changes from the
117 " VCSVimDiff Uses vimdiff to display differences between versions of the
120 " If no revision is specified, the most recent version of the
121 " file on the current branch is used. With one argument,
122 " that argument is used as the revision as above. With two
123 " arguments, the differences between the two revisions is
124 " displayed using vimdiff.
126 " With either zero or one argument, the original buffer is
127 " used to perform the vimdiff. When the scratch buffer is
128 " closed, the original buffer will be returned to normal
131 " Once vimdiff mode is started using the above methods,
132 " additional vimdiff buffers may be added by passing a single
133 " version argument to the command. There may be up to 4
134 " vimdiff buffers total.
136 " Using the 2-argument form of the command resets the vimdiff
137 " to only those 2 versions. Additionally, invoking the
138 " command on a different file will close the previous vimdiff
141 " Mapping documentation: {{{2
143 " By default, a mapping is defined for each command. User-provided mappings
144 " can be used instead by mapping to <Plug>CommandName, for instance:
146 " nmap ,ca <Plug>VCSAdd
148 " The default mappings are as follow:
151 " <Leader>cn VCSAnnotate
152 " <Leader>cc VCSCommit
153 " <Leader>cD VCSDelete
155 " <Leader>cg VCSGotoOriginal
156 " <Leader>cG VCSGotoOriginal!
160 " <Leader>cr VCSReview
161 " <Leader>cs VCSStatus
162 " <Leader>cu VCSUpdate
163 " <Leader>cU VCSUnlock
164 " <Leader>cv VCSVimDiff
166 " Options documentation: {{{2
168 " Several variables are checked by the script to determine behavior as follow:
170 " VCSCommandCommitOnWrite
171 " This variable, if set to a non-zero value, causes the pending commit to
172 " take place immediately as soon as the log message buffer is written. If
173 " set to zero, only the VCSCommit mapping will cause the pending commit to
174 " occur. If not set, it defaults to 1.
176 " VCSCommandDeleteOnHide
177 " This variable, if set to a non-zero value, causes the temporary VCS result
178 " buffers to automatically delete themselves when hidden.
180 " VCSCommand{VCSType}DiffOpt
181 " This variable, if set, determines the options passed to the diff command
182 " of the underlying VCS. Each VCS plugin defines a default value.
184 " VCSCommandDiffSplit
185 " This variable overrides the VCSCommandSplit variable, but only for buffers
186 " created with VCSVimDiff.
188 " VCSCommandDisableMappings
189 " This variable, if set to a non-zero value, prevents the default command
190 " mappings from being set.
192 " VCSCommandDisableExtensionMappings
193 " This variable, if set to a non-zero value, prevents the default command
194 " mappings from being set for commands specific to an individual VCS.
197 " This variable controls whether to split the current window to display a
198 " scratch buffer ('split'), or to display it in the current buffer ('edit').
199 " If not set, it defaults to 'split'.
201 " VCSCommandEnableBufferSetup
202 " This variable, if set to a non-zero value, activates VCS buffer management
203 " mode. This mode means that the buffer variable 'VCSRevision' is set if
204 " the file is VCS-controlled. This is useful for displaying version
205 " information in the status bar. Additional options may be set by
206 " individual VCS plugins.
208 " VCSCommandResultBufferNameExtension
209 " This variable, if set to a non-blank value, is appended to the name of the
210 " VCS command output buffers. For example, '.vcs'. Using this option may
211 " help avoid problems caused by autocommands dependent on file extension.
213 " VCSCommandResultBufferNameFunction
214 " This variable, if set, specifies a custom function for naming VCS command
215 " output buffers. This function will be passed the following arguments:
217 " command - name of the VCS command being executed (such as 'Log' or
220 " originalBuffer - buffer number of the source file.
222 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
224 " statusText - extra text associated with the VCS action (such as version
228 " This variable controls the orientation of the various window splits that
229 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
230 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
231 " If set to 'horizontal', the resulting windows will be on stacked on top of
232 " one another. If set to 'vertical', the resulting windows will be
233 " side-by-side. If not set, it defaults to 'horizontal' for all but
234 " VCSVimDiff windows.
236 " Event documentation {{{2
237 " For additional customization, VCSCommand.vim uses User event autocommand
238 " hooks. Each event is in the VCSCommand group, and different patterns
239 " match the various hooks.
241 " For instance, the following could be added to the vimrc to provide a 'q'
242 " mapping to quit a VCS scratch buffer:
245 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
248 " The following hooks are available:
250 " VCSBufferCreated This event is fired just after a VCS command
251 " output buffer is created. It is executed
252 " within the context of the new buffer.
254 " VCSBufferSetup This event is fired just after VCS buffer setup
255 " occurs, if enabled.
257 " VCSPluginInit This event is fired when the VCSCommand plugin
260 " VCSPluginFinish This event is fired just after the VCSCommand
263 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
264 " command executes to allow customization of,
265 " for instance, window placement and focus.
267 " Section: Plugin header {{{1
269 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
270 " completes. This allows various actions to only be taken by functions after
271 " system initialization.
273 if exists('loaded_VCSCommand')
276 let loaded_VCSCommand = 1
279 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
286 " Section: Event group setup {{{1
291 augroup VCSCommandCommit
294 " Section: Plugin initialization {{{1
295 silent do VCSCommand User VCSPluginInit
297 " Section: Script variable initialization {{{1
300 let s:pluginFiles = []
301 let s:extendedMappings = {}
302 let s:optionOverrides = {}
303 let s:isEditFileRunning = 0
305 unlet! s:vimDiffRestoreCmd
306 unlet! s:vimDiffSourceBuffer
307 unlet! s:vimDiffScratchList
309 " Section: Utility functions {{{1
311 " Function: s:ReportError(mapping) {{{2
312 " Displays the given error in a consistent faction. This is intended to be
313 " invoked from a catch statement.
315 function! s:ReportError(error)
316 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
319 " Function: s:ExecuteExtensionMapping(mapping) {{{2
320 " Invokes the appropriate extension mapping depending on the type of the
323 function! s:ExecuteExtensionMapping(mapping)
324 let buffer = bufnr('%')
325 let vcsType = VCSCommandGetVCSType(buffer)
326 if !has_key(s:extendedMappings, vcsType)
327 throw 'Unknown VCS type: ' . vcsType
329 if !has_key(s:extendedMappings[vcsType], a:mapping)
330 throw 'This extended mapping is not defined for ' . vcsType
332 silent execute 'normal' ':' . s:extendedMappings[vcsType][a:mapping] . "\<CR>"
335 " Function: s:ExecuteVCSCommand(command, argList) {{{2
336 " Calls the indicated plugin-specific VCS command on the current buffer.
337 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
340 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
342 let buffer = bufnr('%')
344 let vcsType = VCSCommandGetVCSType(buffer)
345 if !has_key(s:plugins, vcsType)
346 throw 'Unknown VCS type: ' . vcsType
349 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
350 let bufferName = bufname(originalBuffer)
352 " It is already known that the directory is under VCS control. No further
353 " checks are needed. Otherwise, perform some basic sanity checks to avoid
354 " VCS-specific error messages from confusing things.
355 if !isdirectory(bufferName)
356 if !filereadable(bufferName)
357 throw 'No such file ' . bufferName
360 if isdirectory(bufferName)
362 let revision = VCSCommandGetRevision()
364 throw 'Unable to obtain version information.'
365 elseif revision == 'Unknown'
366 throw 'Item not under source control'
367 elseif revision == 'New'
368 throw 'Operation not available on newly-added item.'
373 let functionMap = s:plugins[vcsType]
374 if !has_key(functionMap, a:command)
375 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
377 return functionMap[a:command](a:argList)
379 call s:ReportError(v:exception)
384 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
385 " Default method of generating the name for VCS result buffers. This can be
386 " overridden with the VCSResultBufferNameFunction variable.
388 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
389 let fileName = bufname(a:originalBuffer)
390 let bufferName = a:vcsType . ' ' . a:command
391 if strlen(a:statusText) > 0
392 let bufferName .= ' ' . a:statusText
394 let bufferName .= ' ' . fileName
396 let versionedBufferName = bufferName
397 while buflisted(versionedBufferName)
399 let versionedBufferName = bufferName . ' (' . counter . ')'
401 return versionedBufferName
404 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
405 " Method of generating the name for VCS result buffers that uses the original
406 " file name with the VCS type and command appended as extensions.
408 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
409 let fileName = bufname(a:originalBuffer)
410 let bufferName = a:vcsType . ' ' . a:command
411 if strlen(a:statusText) > 0
412 let bufferName .= ' ' . a:statusText
414 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
416 let versionedBufferName = bufferName
417 while buflisted(versionedBufferName)
419 let versionedBufferName = '(' . counter . ') ' . bufferName
421 return versionedBufferName
424 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
425 " Creates a new buffer of the given name and associates it with the given
428 function! s:EditFile(command, originalBuffer, statusText)
429 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
431 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
432 if nameExtension == ''
433 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
435 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
438 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
440 " Protect against useless buffer set-up
441 let s:isEditFileRunning += 1
443 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
444 if editCommand == 'split'
445 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
448 vert rightbelow split
451 edit `=resultBufferName`
452 let b:VCSCommandCommand = a:command
453 let b:VCSCommandOriginalBuffer = a:originalBuffer
454 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
455 let b:VCSCommandVCSType = vcsType
459 let &filetype = vcsType . a:command
461 if a:statusText != ''
462 let b:VCSCommandStatusText = a:statusText
465 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
469 let s:isEditFileRunning -= 1
474 " Function: s:SetupBuffer() {{{2
475 " Attempts to set the b:VCSCommandBufferInfo variable
477 function! s:SetupBuffer()
478 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
479 " This buffer is already set up.
483 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
484 " No special status for special buffers other than directory buffers.
488 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
489 unlet! b:VCSCommandBufferSetup
494 let vcsType = VCSCommandGetVCSType(bufnr('%'))
495 let b:VCSCommandBufferInfo = s:plugins[vcsType].GetBufferInfo()
496 silent do VCSCommand User VCSBufferSetup
497 catch /No suitable plugin/
498 " This is not a VCS-controlled file.
499 let b:VCSCommandBufferInfo = []
502 let b:VCSCommandBufferSetup = 1
505 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
506 " Resets the buffer setup state of the original buffer for a given VCS scratch
508 " Returns: The VCS buffer number in a passthrough mode.
510 function! s:MarkOrigBufferForSetup(buffer)
513 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
514 " This should never not work, but I'm paranoid
515 if origBuffer != a:buffer
516 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
522 " Function: s:OverrideOption(option, [value]) {{{2
523 " Provides a temporary override for the given VCS option. If no value is
524 " passed, the override is disabled.
526 function! s:OverrideOption(option, ...)
528 call remove(s:optionOverrides[a:option], -1)
530 if !has_key(s:optionOverrides, a:option)
531 let s:optionOverrides[a:option] = []
533 call add(s:optionOverrides[a:option], a:1)
537 " Function: s:WipeoutCommandBuffers() {{{2
538 " Clears all current VCS output buffers of the specified type for a given source.
540 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
542 while buffer <= bufnr('$')
543 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
544 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
548 let buffer = buffer + 1
552 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
553 " Checks whether the given buffer is one whose deletion should trigger
554 " restoration of an original buffer after it was diffed. If so, it executes
555 " the appropriate setting command stored with that original buffer.
557 function! s:VimDiffRestore(vimDiffBuff)
558 let s:isEditFileRunning += 1
560 if exists('s:vimDiffSourceBuffer')
561 if a:vimDiffBuff == s:vimDiffSourceBuffer
562 " Original file is being removed.
563 unlet! s:vimDiffSourceBuffer
564 unlet! s:vimDiffRestoreCmd
565 unlet! s:vimDiffScratchList
567 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
569 call remove(s:vimDiffScratchList, index)
570 if len(s:vimDiffScratchList) == 0
571 if exists('s:vimDiffRestoreCmd')
572 " All scratch buffers are gone, reset the original.
573 " Only restore if the source buffer is still in Diff mode
575 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
577 " The buffer is visible in at least one window
578 let currentWinNR = winnr()
579 while winbufnr(sourceWinNR) != -1
580 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
581 execute sourceWinNR . 'wincmd w'
582 if getwinvar(0, '&diff')
583 execute s:vimDiffRestoreCmd
586 let sourceWinNR = sourceWinNR + 1
588 execute currentWinNR . 'wincmd w'
590 " The buffer is hidden. It must be visible in order to set the
592 let currentBufNR = bufnr('')
593 execute 'hide buffer' s:vimDiffSourceBuffer
594 if getwinvar(0, '&diff')
595 execute s:vimDiffRestoreCmd
597 execute 'hide buffer' currentBufNR
600 unlet s:vimDiffRestoreCmd
602 " All buffers are gone.
603 unlet s:vimDiffSourceBuffer
604 unlet s:vimDiffScratchList
610 let s:isEditFileRunning -= 1
614 " Section: Generic VCS command functions {{{1
616 " Function: s:VCSCommit() {{{2
617 function! s:VCSCommit(bang, message)
619 let vcsType = VCSCommandGetVCSType(bufnr('%'))
620 if !has_key(s:plugins, vcsType)
621 throw 'Unknown VCS type: ' . vcsType
624 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
626 " Handle the commit message being specified. If a message is supplied, it
627 " is used; if bang is supplied, an empty message is used; otherwise, the
628 " user is provided a buffer from which to edit the commit message.
630 if strlen(a:message) > 0 || a:bang == '!'
631 return s:VCSFinishCommit([a:message], originalBuffer)
634 call s:EditFile('commitlog', originalBuffer, '')
637 " Create a commit mapping.
639 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
641 silent 0put ='VCS: ----------------------------------------------------------------------'
642 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
643 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
645 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
647 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
648 silent put ='VCS: or write this buffer'
651 silent put ='VCS: ----------------------------------------------------------------------'
655 call s:ReportError(v:exception)
660 " Function: s:VCSFinishCommitWithBuffer() {{{2
661 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
662 " which removes all lines starting with 'VCS:'.
664 function! s:VCSFinishCommitWithBuffer()
666 let currentBuffer = bufnr('%')
667 let logMessageList = getbufline('%', 1, '$')
668 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
669 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
671 execute 'bw' currentBuffer
676 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
677 function! s:VCSFinishCommit(logMessageList, originalBuffer)
678 let shellSlashBak = &shellslash
681 let messageFileName = tempname()
682 call writefile(a:logMessageList, messageFileName)
684 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
688 return s:MarkOrigBufferForSetup(resultBuffer)
690 call delete(messageFileName)
693 let &shellslash = shellSlashBak
697 " Function: s:VCSGotoOriginal(bang) {{{2
698 function! s:VCSGotoOriginal(bang)
699 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
700 if originalBuffer > 0
701 let origWinNR = bufwinnr(originalBuffer)
703 execute 'buffer' originalBuffer
705 execute origWinNR . 'wincmd w'
709 let buffmaxnr = bufnr('$')
710 while buffnr <= buffmaxnr
711 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
714 let buffnr = buffnr + 1
720 " Function: s:VCSVimDiff(...) {{{2
721 function! s:VCSVimDiff(...)
723 let vcsType = VCSCommandGetVCSType(bufnr('%'))
724 if !has_key(s:plugins, vcsType)
725 throw 'Unknown VCS type: ' . vcsType
727 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
728 let s:isEditFileRunning = s:isEditFileRunning + 1
730 " If there's already a VimDiff'ed window, restore it.
731 " There may only be one VCSVimDiff original window at a time.
733 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
734 " Clear the existing vimdiff setup by removing the result buffers.
735 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
740 " Reset the vimdiff system, as 2 explicit versions were provided.
741 if exists('s:vimDiffSourceBuffer')
742 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
744 let resultBuffer = s:plugins[vcsType].Review([a:1])
746 echomsg 'Can''t open revision ' . a:1
749 let b:VCSCommandCommand = 'vimdiff'
751 let s:vimDiffScratchList = [resultBuffer]
752 " If no split method is defined, cheat, and set it to vertical.
754 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
755 let resultBuffer = s:plugins[vcsType].Review([a:2])
757 call s:OverrideOption('VCSCommandSplit')
760 echomsg 'Can''t open revision ' . a:1
763 let b:VCSCommandCommand = 'vimdiff'
765 let s:vimDiffScratchList += [resultBuffer]
768 call s:OverrideOption('VCSCommandEdit', 'split')
770 " Force splitting behavior, otherwise why use vimdiff?
771 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
774 let resultBuffer = s:plugins[vcsType].Review([])
776 let resultBuffer = s:plugins[vcsType].Review([a:1])
779 call s:OverrideOption('VCSCommandSplit')
782 call s:OverrideOption('VCSCommandEdit')
785 echomsg 'Can''t open current revision'
788 let b:VCSCommandCommand = 'vimdiff'
791 if !exists('s:vimDiffSourceBuffer')
792 " New instance of vimdiff.
793 let s:vimDiffScratchList = [resultBuffer]
795 " This could have been invoked on a VCS result buffer, not the
798 execute 'buffer' originalBuffer
799 " Store info for later original buffer restore
800 let s:vimDiffRestoreCmd =
801 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
802 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
803 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
804 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
805 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
806 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
807 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
808 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
812 " Adding a window to an existing vimdiff
813 let s:vimDiffScratchList += [resultBuffer]
817 let s:vimDiffSourceBuffer = originalBuffer
819 " Avoid executing the modeline in the current buffer after the autocommand.
821 let currentBuffer = bufnr('%')
822 let saveModeline = getbufvar(currentBuffer, '&modeline')
824 call setbufvar(currentBuffer, '&modeline', 0)
825 silent do VCSCommand User VCSVimDiffFinish
827 call setbufvar(currentBuffer, '&modeline', saveModeline)
831 let s:isEditFileRunning = s:isEditFileRunning - 1
834 call s:ReportError(v:exception)
839 " Section: Public functions {{{1
841 " Function: VCSCommandGetVCSType() {{{2
842 " Sets the b:VCSCommandVCSType variable in the given buffer to the
843 " appropriate source control system name.
845 function! VCSCommandGetVCSType(buffer)
846 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
847 if strlen(vcsType) > 0
850 for vcsType in keys(s:plugins)
851 if s:plugins[vcsType].Identify(a:buffer)
852 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
856 throw 'No suitable plugin'
859 " Function: VCSCommandChdir(directory) {{{2
860 " Changes the current directory, respecting :lcd changes.
862 function! VCSCommandChdir(directory)
864 if exists("*haslocaldir") && haslocaldir()
867 execute command escape(a:directory, ' ')
870 " Function: VCSCommandChangeToCurrentFileDir() {{{2
871 " Go to the directory in which the given file is located.
873 function! VCSCommandChangeToCurrentFileDir(fileName)
874 let oldCwd = getcwd()
875 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
876 if strlen(newCwd) > 0
877 call VCSCommandChdir(newCwd)
882 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
883 " Attempts to locate the original file to which VCS operations were applied
884 " for a given buffer.
886 function! VCSCommandGetOriginalBuffer(vcsBuffer)
887 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
889 if bufexists(origBuffer)
892 " Original buffer no longer exists.
893 throw 'Original buffer for this VCS buffer no longer exists.'
901 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
902 " Allows VCS modules to register themselves.
904 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
905 let s:plugins[a:name] = a:commandMap
906 call add(s:pluginFiles, a:file)
907 let s:extendedMappings[a:name] = a:mappingMap
908 if !empty(a:mappingMap)
909 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
910 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
911 for mapname in keys(a:mappingMap)
912 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
917 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
918 " General skeleton for VCS function execution.
919 " Returns: name of the new command buffer containing the command results
921 function! VCSCommandDoCommand(cmd, cmdName, statusText)
922 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
923 if originalBuffer == -1
924 throw 'Original buffer no longer exists, aborting.'
927 let fileName = resolve(bufname(originalBuffer))
929 " Work with netrw or other systems where a directory listing is displayed in
932 if isdirectory(fileName)
933 let realFileName = '.'
935 let realFileName = fnamemodify(fileName, ':t')
938 " Change to the directory of the current buffer. This is done for CVS, but
939 " is left in for other systems as it does not affect them negatively.
941 let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
943 let output = system(a:cmd . ' "' . realFileName . '"')
945 call VCSCommandChdir(oldCwd)
948 " HACK: if line endings in the repository have been corrupted, the output
949 " of the command will be confused.
950 let output = substitute(output, "\r", '', 'g')
952 " HACK: CVS diff command does not return proper error codes
953 if v:shell_error && (a:cmdName != 'diff' || getbufvar(originalBuffer, 'VCSCommandVCSType') != 'CVS')
954 if strlen(output) == 0
955 throw 'Version control command failed'
957 let output = substitute(output, '\n', ' ', 'g')
958 throw 'Version control command failed: ' . output
961 if strlen(output) == 0
962 " Handle case of no output. In this case, it is important to check the
963 " file status, especially since cvs edit/unedit may change the attributes
964 " of the file with no visible output.
970 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
974 " The last command left a blank line at the end of the buffer. If the
975 " last line is folded (a side effect of the 'put') then the attempt to
976 " remove the blank line will kill the last fold.
978 " This could be fixed by explicitly detecting whether the last line is
979 " within a fold, but I prefer to simply unfold the result buffer altogether.
988 " Define the environment and execute user-defined hooks.
990 silent do VCSCommand User VCSBufferCreated
994 " Function: VCSCommandGetOption(name, default) {{{2
995 " Grab a user-specified option to override the default provided. Options are
996 " searched in the window, buffer, then global spaces.
998 function! VCSCommandGetOption(name, default)
999 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1000 return s:optionOverrides[a:name][-1]
1001 elseif exists('w:' . a:name)
1003 elseif exists('b:' . a:name)
1005 elseif exists('g:' . a:name)
1012 " Function: VCSCommandGetRevision() {{{2
1013 " Global function for retrieving the current buffer's revision number.
1014 " Returns: Revision number or an empty string if an error occurs.
1016 function! VCSCommandGetRevision()
1017 if !exists('b:VCSCommandBufferInfo')
1018 let b:VCSCommandBufferInfo = s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1021 if len(b:VCSCommandBufferInfo) > 0
1022 return b:VCSCommandBufferInfo[0]
1028 " Function: VCSCommandDisableBufferSetup() {{{2
1029 " Global function for deactivating the buffer autovariables.
1031 function! VCSCommandDisableBufferSetup()
1032 let g:VCSCommandEnableBufferSetup = 0
1033 silent! augroup! VCSCommandPlugin
1036 " Function: VCSCommandEnableBufferSetup() {{{2
1037 " Global function for activating the buffer autovariables.
1039 function! VCSCommandEnableBufferSetup()
1040 let g:VCSCommandEnableBufferSetup = 1
1041 augroup VCSCommandPlugin
1043 au BufEnter * call s:SetupBuffer()
1046 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1048 if g:loaded_VCSCommand == 2
1049 call s:SetupBuffer()
1053 " Function: VCSCommandGetStatusLine() {{{2
1054 " Default (sample) status line entry for VCS-controlled files. This is only
1055 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1056 " variable for how to do this).
1058 function! VCSCommandGetStatusLine()
1059 if exists('b:VCSCommandCommand')
1060 " This is a result buffer. Return nothing because the buffer name
1061 " contains information already.
1065 if exists('b:VCSCommandVCSType')
1066 \ && exists('g:VCSCommandEnableBufferSetup')
1067 \ && g:VCSCommandEnableBufferSetup
1068 \ && exists('b:VCSCommandBufferInfo')
1069 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1075 " Section: Command definitions {{{1
1076 " Section: Primary commands {{{2
1077 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1078 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1079 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1080 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1081 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1082 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1083 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1084 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1085 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1086 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1087 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1088 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1089 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1090 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1091 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1092 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1094 " Section: VCS buffer management commands {{{2
1095 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1096 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1098 " Allow reloading VCSCommand.vim
1099 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
1101 " Section: Plugin command mappings {{{1
1102 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1103 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1104 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1105 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1106 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1107 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1108 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1109 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1110 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1111 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1112 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1113 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1114 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1115 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1116 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1117 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1119 " Section: Default mappings {{{1
1121 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1122 if !hasmapto('<Plug>VCSAdd')
1123 nmap <unique> <Leader>ca <Plug>VCSAdd
1125 if !hasmapto('<Plug>VCSAnnotate')
1126 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1128 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1129 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1131 if !hasmapto('<Plug>VCSCommit')
1132 nmap <unique> <Leader>cc <Plug>VCSCommit
1134 if !hasmapto('<Plug>VCSDelete')
1135 nmap <unique> <Leader>cD <Plug>VCSDelete
1137 if !hasmapto('<Plug>VCSDiff')
1138 nmap <unique> <Leader>cd <Plug>VCSDiff
1140 if !hasmapto('<Plug>VCSGotoOriginal')
1141 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1143 if !hasmapto('<Plug>VCSInfo')
1144 nmap <unique> <Leader>ci <Plug>VCSInfo
1146 if !hasmapto('<Plug>VCSLock')
1147 nmap <unique> <Leader>cL <Plug>VCSLock
1149 if !hasmapto('<Plug>VCSLog')
1150 nmap <unique> <Leader>cl <Plug>VCSLog
1152 if !hasmapto('<Plug>VCSRevert')
1153 nmap <unique> <Leader>cq <Plug>VCSRevert
1155 if !hasmapto('<Plug>VCSReview')
1156 nmap <unique> <Leader>cr <Plug>VCSReview
1158 if !hasmapto('<Plug>VCSStatus')
1159 nmap <unique> <Leader>cs <Plug>VCSStatus
1161 if !hasmapto('<Plug>VCSUnlock')
1162 nmap <unique> <Leader>cU <Plug>VCSUnlock
1164 if !hasmapto('<Plug>VCSUpdate')
1165 nmap <unique> <Leader>cu <Plug>VCSUpdate
1167 if !hasmapto('<Plug>VCSVimDiff')
1168 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1172 " Section: Menu items {{{1
1173 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1174 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1175 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1176 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1177 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1178 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1179 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1180 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1181 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1182 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1183 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1184 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1186 " Section: Autocommands to restore vimdiff state {{{1
1187 augroup VimDiffRestore
1189 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1192 " Section: Optional activation of buffer management {{{1
1194 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1195 call VCSCommandEnableBufferSetup()
1198 " Section: VIM shutdown hook {{{1
1200 " Close all result buffers when VIM exits, to prevent them from being restored
1203 " Function: s:CloseAllResultBuffers() {{{2
1204 " Closes all vcscommand result buffers.
1205 function! s:CloseAllResultBuffers()
1206 " This avoids using bufdo as that may load buffers already loaded in another
1207 " vim process, resulting in an error.
1209 let buffmaxnr = bufnr('$')
1210 while buffnr <= buffmaxnr
1211 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1214 let buffnr = buffnr + 1
1218 augroup VCSCommandVIMShutdown
1220 au VimLeavePre * call s:CloseAllResultBuffers()
1223 " Section: Plugin completion {{{1
1225 let loaded_VCSCommand = 2
1227 silent do VCSCommand User VCSPluginFinish
1229 let &cpo = s:save_cpo