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 " VCSRemove Alias for 'VCSDelete'.
102 " VCSRevert Replaces the modified version of the current file with the
103 " most recent version from the repository.
105 " VCSReview Displays a particular version of the current file in a new
106 " scratch buffer. If no argument is given, the most recent
107 " version of the file on the current branch is retrieved.
109 " VCSStatus Displays versioning information about the current file in a
110 " new scratch buffer.
112 " VCSUnlock Unlocks the current file in order to allow other users from
113 " concurrently modifying it. The exact semantics of this
114 " command depend on the underlying VCS.
116 " VCSUpdate Updates the current file with any relevant changes from the
119 " VCSVimDiff Uses vimdiff to display differences between versions of the
122 " If no revision is specified, the most recent version of the
123 " file on the current branch is used. With one argument,
124 " that argument is used as the revision as above. With two
125 " arguments, the differences between the two revisions is
126 " displayed using vimdiff.
128 " With either zero or one argument, the original buffer is
129 " used to perform the vimdiff. When the scratch buffer is
130 " closed, the original buffer will be returned to normal
133 " Once vimdiff mode is started using the above methods,
134 " additional vimdiff buffers may be added by passing a single
135 " version argument to the command. There may be up to 4
136 " vimdiff buffers total.
138 " Using the 2-argument form of the command resets the vimdiff
139 " to only those 2 versions. Additionally, invoking the
140 " command on a different file will close the previous vimdiff
143 " Mapping documentation: {{{2
145 " By default, a mapping is defined for each command. User-provided mappings
146 " can be used instead by mapping to <Plug>CommandName, for instance:
148 " nmap ,ca <Plug>VCSAdd
150 " The default mappings are as follow:
153 " <Leader>cn VCSAnnotate
154 " <Leader>cc VCSCommit
155 " <Leader>cD VCSDelete
157 " <Leader>cg VCSGotoOriginal
158 " <Leader>cG VCSGotoOriginal!
162 " <Leader>cr VCSReview
163 " <Leader>cs VCSStatus
164 " <Leader>cu VCSUpdate
165 " <Leader>cU VCSUnlock
166 " <Leader>cv VCSVimDiff
168 " Options documentation: {{{2
170 " Several variables are checked by the script to determine behavior as follow:
172 " VCSCommandCommitOnWrite
173 " This variable, if set to a non-zero value, causes the pending commit to
174 " take place immediately as soon as the log message buffer is written. If
175 " set to zero, only the VCSCommit mapping will cause the pending commit to
176 " occur. If not set, it defaults to 1.
178 " VCSCommandDeleteOnHide
179 " This variable, if set to a non-zero value, causes the temporary VCS result
180 " buffers to automatically delete themselves when hidden.
182 " VCSCommand{VCSType}DiffOpt
183 " This variable, if set, determines the options passed to the diff command
184 " of the underlying VCS. Each VCS plugin defines a default value.
186 " VCSCommandDiffSplit
187 " This variable overrides the VCSCommandSplit variable, but only for buffers
188 " created with VCSVimDiff.
190 " VCSCommandDisableMappings
191 " This variable, if set to a non-zero value, prevents the default command
192 " mappings from being set.
194 " VCSCommandDisableExtensionMappings
195 " This variable, if set to a non-zero value, prevents the default command
196 " mappings from being set for commands specific to an individual VCS.
199 " This variable controls whether to split the current window to display a
200 " scratch buffer ('split'), or to display it in the current buffer ('edit').
201 " If not set, it defaults to 'split'.
203 " VCSCommandEnableBufferSetup
204 " This variable, if set to a non-zero value, activates VCS buffer management
205 " mode. This mode means that the buffer variable 'VCSRevision' is set if
206 " the file is VCS-controlled. This is useful for displaying version
207 " information in the status bar. Additional options may be set by
208 " individual VCS plugins.
210 " VCSCommandResultBufferNameExtension
211 " This variable, if set to a non-blank value, is appended to the name of the
212 " VCS command output buffers. For example, '.vcs'. Using this option may
213 " help avoid problems caused by autocommands dependent on file extension.
215 " VCSCommandResultBufferNameFunction
216 " This variable, if set, specifies a custom function for naming VCS command
217 " output buffers. This function will be passed the following arguments:
219 " command - name of the VCS command being executed (such as 'Log' or
222 " originalBuffer - buffer number of the source file.
224 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
226 " statusText - extra text associated with the VCS action (such as version
230 " This variable controls the orientation of the various window splits that
231 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
232 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
233 " If set to 'horizontal', the resulting windows will be on stacked on top of
234 " one another. If set to 'vertical', the resulting windows will be
235 " side-by-side. If not set, it defaults to 'horizontal' for all but
236 " VCSVimDiff windows.
238 " Event documentation {{{2
239 " For additional customization, VCSCommand.vim uses User event autocommand
240 " hooks. Each event is in the VCSCommand group, and different patterns
241 " match the various hooks.
243 " For instance, the following could be added to the vimrc to provide a 'q'
244 " mapping to quit a VCS scratch buffer:
247 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
250 " The following hooks are available:
252 " VCSBufferCreated This event is fired just after a VCS command
253 " output buffer is created. It is executed
254 " within the context of the new buffer.
256 " VCSBufferSetup This event is fired just after VCS buffer setup
257 " occurs, if enabled.
259 " VCSPluginInit This event is fired when the VCSCommand plugin
262 " VCSPluginFinish This event is fired just after the VCSCommand
265 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
266 " command executes to allow customization of,
267 " for instance, window placement and focus.
269 " Section: Plugin header {{{1
271 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
272 " completes. This allows various actions to only be taken by functions after
273 " system initialization.
275 if exists('loaded_VCSCommand')
278 let loaded_VCSCommand = 1
281 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
288 " Section: Event group setup {{{1
293 augroup VCSCommandCommit
296 " Section: Plugin initialization {{{1
297 silent do VCSCommand User VCSPluginInit
299 " Section: Script variable initialization {{{1
302 let s:pluginFiles = []
303 let s:extendedMappings = {}
304 let s:optionOverrides = {}
305 let s:isEditFileRunning = 0
307 unlet! s:vimDiffRestoreCmd
308 unlet! s:vimDiffSourceBuffer
309 unlet! s:vimDiffScratchList
311 " Section: Utility functions {{{1
313 " Function: s:ReportError(mapping) {{{2
314 " Displays the given error in a consistent faction. This is intended to be
315 " invoked from a catch statement.
317 function! s:ReportError(error)
318 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
321 " Function: s:ExecuteExtensionMapping(mapping) {{{2
322 " Invokes the appropriate extension mapping depending on the type of the
325 function! s:ExecuteExtensionMapping(mapping)
326 let buffer = bufnr('%')
327 let vcsType = VCSCommandGetVCSType(buffer)
328 if !has_key(s:extendedMappings, vcsType)
329 throw 'Unknown VCS type: ' . vcsType
331 if !has_key(s:extendedMappings[vcsType], a:mapping)
332 throw 'This extended mapping is not defined for ' . vcsType
334 silent execute 'normal' ':' . s:extendedMappings[vcsType][a:mapping] . "\<CR>"
337 " Function: s:ExecuteVCSCommand(command, argList) {{{2
338 " Calls the indicated plugin-specific VCS command on the current buffer.
339 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
342 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
344 let buffer = bufnr('%')
346 let vcsType = VCSCommandGetVCSType(buffer)
347 if !has_key(s:plugins, vcsType)
348 throw 'Unknown VCS type: ' . vcsType
351 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
352 let bufferName = bufname(originalBuffer)
354 " It is already known that the directory is under VCS control. No further
355 " checks are needed. Otherwise, perform some basic sanity checks to avoid
356 " VCS-specific error messages from confusing things.
357 if !isdirectory(bufferName)
358 if !filereadable(bufferName)
359 throw 'No such file ' . bufferName
362 if isdirectory(bufferName)
364 let revision = VCSCommandGetRevision()
366 throw 'Unable to obtain version information.'
367 elseif revision == 'Unknown'
368 throw 'Item not under source control'
369 elseif revision == 'New'
370 throw 'Operation not available on newly-added item.'
375 let functionMap = s:plugins[vcsType]
376 if !has_key(functionMap, a:command)
377 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
379 return functionMap[a:command](a:argList)
381 call s:ReportError(v:exception)
386 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
387 " Default method of generating the name for VCS result buffers. This can be
388 " overridden with the VCSResultBufferNameFunction variable.
390 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
391 let fileName = bufname(a:originalBuffer)
392 let bufferName = a:vcsType . ' ' . a:command
393 if strlen(a:statusText) > 0
394 let bufferName .= ' ' . a:statusText
396 let bufferName .= ' ' . fileName
398 let versionedBufferName = bufferName
399 while buflisted(versionedBufferName)
401 let versionedBufferName = bufferName . ' (' . counter . ')'
403 return versionedBufferName
406 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
407 " Method of generating the name for VCS result buffers that uses the original
408 " file name with the VCS type and command appended as extensions.
410 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
411 let fileName = bufname(a:originalBuffer)
412 let bufferName = a:vcsType . ' ' . a:command
413 if strlen(a:statusText) > 0
414 let bufferName .= ' ' . a:statusText
416 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
418 let versionedBufferName = bufferName
419 while buflisted(versionedBufferName)
421 let versionedBufferName = '(' . counter . ') ' . bufferName
423 return versionedBufferName
426 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
427 " Creates a new buffer of the given name and associates it with the given
430 function! s:EditFile(command, originalBuffer, statusText)
431 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
433 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
434 if nameExtension == ''
435 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
437 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
440 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
442 " Protect against useless buffer set-up
443 let s:isEditFileRunning += 1
445 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
446 if editCommand == 'split'
447 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
450 vert rightbelow split
453 edit `=resultBufferName`
454 let b:VCSCommandCommand = a:command
455 let b:VCSCommandOriginalBuffer = a:originalBuffer
456 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
457 let b:VCSCommandVCSType = vcsType
461 let &filetype = vcsType . a:command
463 if a:statusText != ''
464 let b:VCSCommandStatusText = a:statusText
467 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
471 let s:isEditFileRunning -= 1
476 " Function: s:SetupBuffer() {{{2
477 " Attempts to set the b:VCSCommandBufferInfo variable
479 function! s:SetupBuffer()
480 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
481 " This buffer is already set up.
485 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
486 " No special status for special buffers other than directory buffers.
490 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
491 unlet! b:VCSCommandBufferSetup
496 let vcsType = VCSCommandGetVCSType(bufnr('%'))
497 let b:VCSCommandBufferInfo = s:plugins[vcsType].GetBufferInfo()
498 silent do VCSCommand User VCSBufferSetup
499 catch /No suitable plugin/
500 " This is not a VCS-controlled file.
501 let b:VCSCommandBufferInfo = []
504 let b:VCSCommandBufferSetup = 1
507 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
508 " Resets the buffer setup state of the original buffer for a given VCS scratch
510 " Returns: The VCS buffer number in a passthrough mode.
512 function! s:MarkOrigBufferForSetup(buffer)
515 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
516 " This should never not work, but I'm paranoid
517 if origBuffer != a:buffer
518 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
524 " Function: s:OverrideOption(option, [value]) {{{2
525 " Provides a temporary override for the given VCS option. If no value is
526 " passed, the override is disabled.
528 function! s:OverrideOption(option, ...)
530 call remove(s:optionOverrides[a:option], -1)
532 if !has_key(s:optionOverrides, a:option)
533 let s:optionOverrides[a:option] = []
535 call add(s:optionOverrides[a:option], a:1)
539 " Function: s:WipeoutCommandBuffers() {{{2
540 " Clears all current VCS output buffers of the specified type for a given source.
542 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
544 while buffer <= bufnr('$')
545 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
546 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
550 let buffer = buffer + 1
554 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
555 " Checks whether the given buffer is one whose deletion should trigger
556 " restoration of an original buffer after it was diffed. If so, it executes
557 " the appropriate setting command stored with that original buffer.
559 function! s:VimDiffRestore(vimDiffBuff)
560 let s:isEditFileRunning += 1
562 if exists('s:vimDiffSourceBuffer')
563 if a:vimDiffBuff == s:vimDiffSourceBuffer
564 " Original file is being removed.
565 unlet! s:vimDiffSourceBuffer
566 unlet! s:vimDiffRestoreCmd
567 unlet! s:vimDiffScratchList
569 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
571 call remove(s:vimDiffScratchList, index)
572 if len(s:vimDiffScratchList) == 0
573 if exists('s:vimDiffRestoreCmd')
574 " All scratch buffers are gone, reset the original.
575 " Only restore if the source buffer is still in Diff mode
577 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
579 " The buffer is visible in at least one window
580 let currentWinNR = winnr()
581 while winbufnr(sourceWinNR) != -1
582 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
583 execute sourceWinNR . 'wincmd w'
584 if getwinvar(0, '&diff')
585 execute s:vimDiffRestoreCmd
588 let sourceWinNR = sourceWinNR + 1
590 execute currentWinNR . 'wincmd w'
592 " The buffer is hidden. It must be visible in order to set the
594 let currentBufNR = bufnr('')
595 execute 'hide buffer' s:vimDiffSourceBuffer
596 if getwinvar(0, '&diff')
597 execute s:vimDiffRestoreCmd
599 execute 'hide buffer' currentBufNR
602 unlet s:vimDiffRestoreCmd
604 " All buffers are gone.
605 unlet s:vimDiffSourceBuffer
606 unlet s:vimDiffScratchList
612 let s:isEditFileRunning -= 1
616 " Section: Generic VCS command functions {{{1
618 " Function: s:VCSCommit() {{{2
619 function! s:VCSCommit(bang, message)
621 let vcsType = VCSCommandGetVCSType(bufnr('%'))
622 if !has_key(s:plugins, vcsType)
623 throw 'Unknown VCS type: ' . vcsType
626 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
628 " Handle the commit message being specified. If a message is supplied, it
629 " is used; if bang is supplied, an empty message is used; otherwise, the
630 " user is provided a buffer from which to edit the commit message.
632 if strlen(a:message) > 0 || a:bang == '!'
633 return s:VCSFinishCommit([a:message], originalBuffer)
636 call s:EditFile('commitlog', originalBuffer, '')
639 " Create a commit mapping.
641 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
643 silent 0put ='VCS: ----------------------------------------------------------------------'
644 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
645 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
647 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
649 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
650 silent put ='VCS: or write this buffer'
653 silent put ='VCS: ----------------------------------------------------------------------'
657 call s:ReportError(v:exception)
662 " Function: s:VCSFinishCommitWithBuffer() {{{2
663 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
664 " which removes all lines starting with 'VCS:'.
666 function! s:VCSFinishCommitWithBuffer()
668 let currentBuffer = bufnr('%')
669 let logMessageList = getbufline('%', 1, '$')
670 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
671 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
673 execute 'bw' currentBuffer
678 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
679 function! s:VCSFinishCommit(logMessageList, originalBuffer)
680 let shellSlashBak = &shellslash
683 let messageFileName = tempname()
684 call writefile(a:logMessageList, messageFileName)
686 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
690 return s:MarkOrigBufferForSetup(resultBuffer)
692 call delete(messageFileName)
695 let &shellslash = shellSlashBak
699 " Function: s:VCSGotoOriginal(bang) {{{2
700 function! s:VCSGotoOriginal(bang)
701 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
702 if originalBuffer > 0
703 let origWinNR = bufwinnr(originalBuffer)
705 execute 'buffer' originalBuffer
707 execute origWinNR . 'wincmd w'
711 let buffmaxnr = bufnr('$')
712 while buffnr <= buffmaxnr
713 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
716 let buffnr = buffnr + 1
722 " Function: s:VCSVimDiff(...) {{{2
723 function! s:VCSVimDiff(...)
725 let vcsType = VCSCommandGetVCSType(bufnr('%'))
726 if !has_key(s:plugins, vcsType)
727 throw 'Unknown VCS type: ' . vcsType
729 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
730 let s:isEditFileRunning = s:isEditFileRunning + 1
732 " If there's already a VimDiff'ed window, restore it.
733 " There may only be one VCSVimDiff original window at a time.
735 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
736 " Clear the existing vimdiff setup by removing the result buffers.
737 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
742 " Reset the vimdiff system, as 2 explicit versions were provided.
743 if exists('s:vimDiffSourceBuffer')
744 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
746 let resultBuffer = s:plugins[vcsType].Review([a:1])
748 echomsg 'Can''t open revision ' . a:1
751 let b:VCSCommandCommand = 'vimdiff'
753 let s:vimDiffScratchList = [resultBuffer]
754 " If no split method is defined, cheat, and set it to vertical.
756 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
757 let resultBuffer = s:plugins[vcsType].Review([a:2])
759 call s:OverrideOption('VCSCommandSplit')
762 echomsg 'Can''t open revision ' . a:1
765 let b:VCSCommandCommand = 'vimdiff'
767 let s:vimDiffScratchList += [resultBuffer]
770 call s:OverrideOption('VCSCommandEdit', 'split')
772 " Force splitting behavior, otherwise why use vimdiff?
773 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
776 let resultBuffer = s:plugins[vcsType].Review([])
778 let resultBuffer = s:plugins[vcsType].Review([a:1])
781 call s:OverrideOption('VCSCommandSplit')
784 call s:OverrideOption('VCSCommandEdit')
787 echomsg 'Can''t open current revision'
790 let b:VCSCommandCommand = 'vimdiff'
793 if !exists('s:vimDiffSourceBuffer')
794 " New instance of vimdiff.
795 let s:vimDiffScratchList = [resultBuffer]
797 " This could have been invoked on a VCS result buffer, not the
800 execute 'buffer' originalBuffer
801 " Store info for later original buffer restore
802 let s:vimDiffRestoreCmd =
803 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
804 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
805 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
806 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
807 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
808 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
809 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
810 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
814 " Adding a window to an existing vimdiff
815 let s:vimDiffScratchList += [resultBuffer]
819 let s:vimDiffSourceBuffer = originalBuffer
821 " Avoid executing the modeline in the current buffer after the autocommand.
823 let currentBuffer = bufnr('%')
824 let saveModeline = getbufvar(currentBuffer, '&modeline')
826 call setbufvar(currentBuffer, '&modeline', 0)
827 silent do VCSCommand User VCSVimDiffFinish
829 call setbufvar(currentBuffer, '&modeline', saveModeline)
833 let s:isEditFileRunning = s:isEditFileRunning - 1
836 call s:ReportError(v:exception)
841 " Section: Public functions {{{1
843 " Function: VCSCommandGetVCSType() {{{2
844 " Sets the b:VCSCommandVCSType variable in the given buffer to the
845 " appropriate source control system name.
847 function! VCSCommandGetVCSType(buffer)
848 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
849 if strlen(vcsType) > 0
852 for vcsType in keys(s:plugins)
853 if s:plugins[vcsType].Identify(a:buffer)
854 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
858 throw 'No suitable plugin'
861 " Function: VCSCommandChdir(directory) {{{2
862 " Changes the current directory, respecting :lcd changes.
864 function! VCSCommandChdir(directory)
866 if exists("*haslocaldir") && haslocaldir()
869 execute command escape(a:directory, ' ')
872 " Function: VCSCommandChangeToCurrentFileDir() {{{2
873 " Go to the directory in which the given file is located.
875 function! VCSCommandChangeToCurrentFileDir(fileName)
876 let oldCwd = getcwd()
877 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
878 if strlen(newCwd) > 0
879 call VCSCommandChdir(newCwd)
884 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
885 " Attempts to locate the original file to which VCS operations were applied
886 " for a given buffer.
888 function! VCSCommandGetOriginalBuffer(vcsBuffer)
889 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
891 if bufexists(origBuffer)
894 " Original buffer no longer exists.
895 throw 'Original buffer for this VCS buffer no longer exists.'
903 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
904 " Allows VCS modules to register themselves.
906 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
907 let s:plugins[a:name] = a:commandMap
908 call add(s:pluginFiles, a:file)
909 let s:extendedMappings[a:name] = a:mappingMap
910 if !empty(a:mappingMap)
911 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
912 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
913 for mapname in keys(a:mappingMap)
914 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
919 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
920 " General skeleton for VCS function execution.
921 " Returns: name of the new command buffer containing the command results
923 function! VCSCommandDoCommand(cmd, cmdName, statusText)
924 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
925 if originalBuffer == -1
926 throw 'Original buffer no longer exists, aborting.'
929 let fileName = resolve(bufname(originalBuffer))
931 " Work with netrw or other systems where a directory listing is displayed in
934 if isdirectory(fileName)
935 let realFileName = '.'
937 let realFileName = fnamemodify(fileName, ':t')
940 " Change to the directory of the current buffer. This is done for CVS, but
941 " is left in for other systems as it does not affect them negatively.
943 let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
945 let output = system(a:cmd . ' "' . realFileName . '"')
947 call VCSCommandChdir(oldCwd)
950 " HACK: if line endings in the repository have been corrupted, the output
951 " of the command will be confused.
952 let output = substitute(output, "\r", '', 'g')
954 " HACK: CVS diff command does not return proper error codes
955 if v:shell_error && (a:cmdName != 'diff' || getbufvar(originalBuffer, 'VCSCommandVCSType') != 'CVS')
956 if strlen(output) == 0
957 throw 'Version control command failed'
959 let output = substitute(output, '\n', ' ', 'g')
960 throw 'Version control command failed: ' . output
963 if strlen(output) == 0
964 " Handle case of no output. In this case, it is important to check the
965 " file status, especially since cvs edit/unedit may change the attributes
966 " of the file with no visible output.
972 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
976 " The last command left a blank line at the end of the buffer. If the
977 " last line is folded (a side effect of the 'put') then the attempt to
978 " remove the blank line will kill the last fold.
980 " This could be fixed by explicitly detecting whether the last line is
981 " within a fold, but I prefer to simply unfold the result buffer altogether.
990 " Define the environment and execute user-defined hooks.
992 silent do VCSCommand User VCSBufferCreated
996 " Function: VCSCommandGetOption(name, default) {{{2
997 " Grab a user-specified option to override the default provided. Options are
998 " searched in the window, buffer, then global spaces.
1000 function! VCSCommandGetOption(name, default)
1001 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1002 return s:optionOverrides[a:name][-1]
1003 elseif exists('w:' . a:name)
1005 elseif exists('b:' . a:name)
1007 elseif exists('g:' . a:name)
1014 " Function: VCSCommandGetRevision() {{{2
1015 " Global function for retrieving the current buffer's revision number.
1016 " Returns: Revision number or an empty string if an error occurs.
1018 function! VCSCommandGetRevision()
1019 if !exists('b:VCSCommandBufferInfo')
1020 let b:VCSCommandBufferInfo = s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1023 if len(b:VCSCommandBufferInfo) > 0
1024 return b:VCSCommandBufferInfo[0]
1030 " Function: VCSCommandDisableBufferSetup() {{{2
1031 " Global function for deactivating the buffer autovariables.
1033 function! VCSCommandDisableBufferSetup()
1034 let g:VCSCommandEnableBufferSetup = 0
1035 silent! augroup! VCSCommandPlugin
1038 " Function: VCSCommandEnableBufferSetup() {{{2
1039 " Global function for activating the buffer autovariables.
1041 function! VCSCommandEnableBufferSetup()
1042 let g:VCSCommandEnableBufferSetup = 1
1043 augroup VCSCommandPlugin
1045 au BufEnter * call s:SetupBuffer()
1048 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1050 if g:loaded_VCSCommand == 2
1051 call s:SetupBuffer()
1055 " Function: VCSCommandGetStatusLine() {{{2
1056 " Default (sample) status line entry for VCS-controlled files. This is only
1057 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1058 " variable for how to do this).
1060 function! VCSCommandGetStatusLine()
1061 if exists('b:VCSCommandCommand')
1062 " This is a result buffer. Return nothing because the buffer name
1063 " contains information already.
1067 if exists('b:VCSCommandVCSType')
1068 \ && exists('g:VCSCommandEnableBufferSetup')
1069 \ && g:VCSCommandEnableBufferSetup
1070 \ && exists('b:VCSCommandBufferInfo')
1071 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1077 " Section: Command definitions {{{1
1078 " Section: Primary commands {{{2
1079 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1080 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1081 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1082 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1083 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1084 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1085 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1086 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1087 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1088 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1089 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1090 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1091 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1092 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1093 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1094 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1095 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1097 " Section: VCS buffer management commands {{{2
1098 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1099 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1101 " Allow reloading VCSCommand.vim
1102 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
1104 " Section: Plugin command mappings {{{1
1105 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1106 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1107 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1108 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1109 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1110 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1111 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1112 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1113 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1114 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1115 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1116 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1117 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1118 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1119 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1120 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1122 " Section: Default mappings {{{1
1124 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1125 if !hasmapto('<Plug>VCSAdd')
1126 nmap <unique> <Leader>ca <Plug>VCSAdd
1128 if !hasmapto('<Plug>VCSAnnotate')
1129 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1131 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1132 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1134 if !hasmapto('<Plug>VCSCommit')
1135 nmap <unique> <Leader>cc <Plug>VCSCommit
1137 if !hasmapto('<Plug>VCSDelete')
1138 nmap <unique> <Leader>cD <Plug>VCSDelete
1140 if !hasmapto('<Plug>VCSDiff')
1141 nmap <unique> <Leader>cd <Plug>VCSDiff
1143 if !hasmapto('<Plug>VCSGotoOriginal')
1144 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1146 if !hasmapto('<Plug>VCSInfo')
1147 nmap <unique> <Leader>ci <Plug>VCSInfo
1149 if !hasmapto('<Plug>VCSLock')
1150 nmap <unique> <Leader>cL <Plug>VCSLock
1152 if !hasmapto('<Plug>VCSLog')
1153 nmap <unique> <Leader>cl <Plug>VCSLog
1155 if !hasmapto('<Plug>VCSRevert')
1156 nmap <unique> <Leader>cq <Plug>VCSRevert
1158 if !hasmapto('<Plug>VCSReview')
1159 nmap <unique> <Leader>cr <Plug>VCSReview
1161 if !hasmapto('<Plug>VCSStatus')
1162 nmap <unique> <Leader>cs <Plug>VCSStatus
1164 if !hasmapto('<Plug>VCSUnlock')
1165 nmap <unique> <Leader>cU <Plug>VCSUnlock
1167 if !hasmapto('<Plug>VCSUpdate')
1168 nmap <unique> <Leader>cu <Plug>VCSUpdate
1170 if !hasmapto('<Plug>VCSVimDiff')
1171 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1175 " Section: Menu items {{{1
1176 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1177 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1178 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1179 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1180 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1181 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1182 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1183 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1184 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1185 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1186 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1187 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1189 " Section: Autocommands to restore vimdiff state {{{1
1190 augroup VimDiffRestore
1192 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1195 " Section: Optional activation of buffer management {{{1
1197 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1198 call VCSCommandEnableBufferSetup()
1201 " Section: VIM shutdown hook {{{1
1203 " Close all result buffers when VIM exits, to prevent them from being restored
1206 " Function: s:CloseAllResultBuffers() {{{2
1207 " Closes all vcscommand result buffers.
1208 function! s:CloseAllResultBuffers()
1209 " This avoids using bufdo as that may load buffers already loaded in another
1210 " vim process, resulting in an error.
1212 let buffmaxnr = bufnr('$')
1213 while buffnr <= buffmaxnr
1214 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1217 let buffnr = buffnr + 1
1221 augroup VCSCommandVIMShutdown
1223 au VimLeavePre * call s:CloseAllResultBuffers()
1226 " Section: Plugin completion {{{1
1228 let loaded_VCSCommand = 2
1230 silent do VCSCommand User VCSPluginFinish
1232 let &cpo = s:save_cpo