1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
6 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
8 " Copyright (c) 2007 Bob Hiestand
10 " Permission is hereby granted, free of charge, to any person obtaining a copy
11 " of this software and associated documentation files (the "Software"), to
12 " deal in the Software without restriction, including without limitation the
13 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
14 " sell copies of the Software, and to permit persons to whom the Software is
15 " furnished to do so, subject to the following conditions:
17 " The above copyright notice and this permission notice shall be included in
18 " all copies or substantial portions of the Software.
20 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 " Section: Documentation {{{1
30 " Provides functions to invoke various source control commands on the current
31 " file (either the current buffer, or, in the case of an directory buffer, the
32 " directory and all subdirectories associated with the current buffer). The
33 " output of the commands is captured in a new scratch window.
35 " This plugin needs additional extension plugins, each specific to a source
36 " control system, to function. Those plugins should be placed in a
37 " subdirectory of the standard plugin directory named 'vcscommand'. Several
38 " options include the name of the version control system in the option name.
39 " Such options use the placeholder text '{VCSType}', which would be replaced
40 " in actual usage with 'CVS' or 'SVN', for instance.
42 " Command documentation {{{2
44 " VCSAdd Adds the current file to source control.
46 " VCSAnnotate Displays the current file with each line annotated with the
47 " version in which it was most recently changed. If an
48 " argument is given, the argument is used as a revision
49 " number to display. If not given an argument, it uses the
50 " most recent version of the file on the current branch.
51 " Additionally, if the current buffer is a VCSAnnotate buffer
52 " already, the version number on the current line is used.
54 " VCSCommit[!] Commits changes to the current file to source control.
56 " If called with arguments, the arguments are the log message.
58 " If '!' is used, an empty log message is committed.
60 " If called with no arguments, this is a two-step command.
61 " The first step opens a buffer to accept a log message.
62 " When that buffer is written, it is automatically closed and
63 " the file is committed using the information from that log
64 " message. The commit can be abandoned if the log message
65 " buffer is deleted or wiped before being written.
67 " VCSDelete Deletes the current file and removes it from source control.
69 " VCSDiff With no arguments, this displays the differences between
70 " the current file and its parent version under source
71 " control in a new scratch buffer.
73 " With one argument, the diff is performed on the
74 " current file against the specified revision.
76 " With two arguments, the diff is performed between the
77 " specified revisions of the current file.
79 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
80 " to specify diff options. If that variable does not exist,
81 " a plugin-specific default is used. If you wish to have no
82 " options, then set it to the empty string.
84 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
85 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
86 " VCS scratch buffers associated with the original file.
88 " VCSInfo Displays extended information about the current file in a
91 " VCSLock Locks the current file in order to prevent other users from
92 " concurrently modifying it. The exact semantics of this
93 " command depend on the underlying VCS.
95 " VCSLog Displays the version history of the current file in a new
98 " VCSRevert Replaces the modified version of the current file with the
99 " most recent version from the repository.
101 " VCSReview Displays a particular version of the current file in a new
102 " scratch buffer. If no argument is given, the most recent
103 " version of the file on the current branch is retrieved.
105 " VCSStatus Displays versioning information about the current file in a
106 " new scratch buffer.
108 " VCSUnlock Unlocks the current file in order to allow other users from
109 " concurrently modifying it. The exact semantics of this
110 " command depend on the underlying VCS.
112 " VCSUpdate Updates the current file with any relevant changes from the
115 " VCSVimDiff Uses vimdiff to display differences between versions of the
118 " If no revision is specified, the most recent version of the
119 " file on the current branch is used. With one argument,
120 " that argument is used as the revision as above. With two
121 " arguments, the differences between the two revisions is
122 " displayed using vimdiff.
124 " With either zero or one argument, the original buffer is
125 " used to perform the vimdiff. When the scratch buffer is
126 " closed, the original buffer will be returned to normal
129 " Once vimdiff mode is started using the above methods,
130 " additional vimdiff buffers may be added by passing a single
131 " version argument to the command. There may be up to 4
132 " vimdiff buffers total.
134 " Using the 2-argument form of the command resets the vimdiff
135 " to only those 2 versions. Additionally, invoking the
136 " command on a different file will close the previous vimdiff
139 " Mapping documentation: {{{2
141 " By default, a mapping is defined for each command. User-provided mappings
142 " can be used instead by mapping to <Plug>CommandName, for instance:
144 " nmap ,ca <Plug>VCSAdd
146 " The default mappings are as follow:
149 " <Leader>cn VCSAnnotate
150 " <Leader>cc VCSCommit
151 " <Leader>cD VCSDelete
153 " <Leader>cg VCSGotoOriginal
154 " <Leader>cG VCSGotoOriginal!
158 " <Leader>cr VCSReview
159 " <Leader>cs VCSStatus
160 " <Leader>cu VCSUpdate
161 " <Leader>cU VCSUnlock
162 " <Leader>cv VCSVimDiff
164 " Options documentation: {{{2
166 " Several variables are checked by the script to determine behavior as follow:
168 " VCSCommandCommitOnWrite
169 " This variable, if set to a non-zero value, causes the pending commit to
170 " take place immediately as soon as the log message buffer is written. If
171 " set to zero, only the VCSCommit mapping will cause the pending commit to
172 " occur. If not set, it defaults to 1.
174 " VCSCommandDeleteOnHide
175 " This variable, if set to a non-zero value, causes the temporary VCS result
176 " buffers to automatically delete themselves when hidden.
178 " VCSCommand{VCSType}DiffOpt
179 " This variable, if set, determines the options passed to the diff command
180 " of the underlying VCS. Each VCS plugin defines a default value.
182 " VCSCommandDiffSplit
183 " This variable overrides the VCSCommandSplit variable, but only for buffers
184 " created with VCSVimDiff.
187 " This variable controls whether to split the current window to display a
188 " scratch buffer ('split'), or to display it in the current buffer ('edit').
189 " If not set, it defaults to 'split'.
191 " VCSCommandEnableBufferSetup
192 " This variable, if set to a non-zero value, activates VCS buffer management
193 " mode. This mode means that the buffer variable 'VCSRevision' is set if
194 " the file is VCS-controlled. This is useful for displaying version
195 " information in the status bar. Additional options may be set by
196 " individual VCS plugins.
198 " VCSCommandResultBufferNameExtension
199 " This variable, if set to a non-blank value, is appended to the name of the
200 " VCS command output buffers. For example, '.vcs'. Using this option may
201 " help avoid problems caused by autocommands dependent on file extension.
203 " VCSCommandResultBufferNameFunction
204 " This variable, if set, specifies a custom function for naming VCS command
205 " output buffers. This function will be passed the following arguments:
207 " command - name of the VCS command being executed (such as 'Log' or
210 " originalBuffer - buffer number of the source file.
212 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
214 " statusText - extra text associated with the VCS action (such as version
218 " This variable controls the orientation of the various window splits that
219 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
220 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
221 " If set to 'horizontal', the resulting windows will be on stacked on top of
222 " one another. If set to 'vertical', the resulting windows will be
223 " side-by-side. If not set, it defaults to 'horizontal' for all but
224 " VCSVimDiff windows.
226 " Event documentation {{{2
227 " For additional customization, VCSCommand.vim uses User event autocommand
228 " hooks. Each event is in the VCSCommand group, and different patterns
229 " match the various hooks.
231 " For instance, the following could be added to the vimrc to provide a 'q'
232 " mapping to quit a VCS scratch buffer:
235 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
238 " The following hooks are available:
240 " VCSBufferCreated This event is fired just after a VCS command
241 " output buffer is created. It is executed
242 " within the context of the new buffer.
244 " VCSBufferSetup This event is fired just after VCS buffer setup
245 " occurs, if enabled.
247 " VCSPluginInit This event is fired when the VCSCommand plugin
250 " VCSPluginFinish This event is fired just after the VCSCommand
253 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
254 " command executes to allow customization of,
255 " for instance, window placement and focus.
257 " Section: Plugin header {{{1
259 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
260 " completes. This allows various actions to only be taken by functions after
261 " system initialization.
263 if exists('loaded_VCSCommand')
266 let loaded_VCSCommand = 1
269 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
273 " Section: Event group setup {{{1
278 augroup VCSCommandCommit
281 " Section: Plugin initialization {{{1
282 silent do VCSCommand User VCSPluginInit
284 " Section: Script variable initialization {{{1
287 let s:pluginFiles = []
288 let s:extendedMappings = {}
289 let s:optionOverrides = {}
290 let s:isEditFileRunning = 0
292 unlet! s:vimDiffRestoreCmd
293 unlet! s:vimDiffSourceBuffer
294 unlet! s:vimDiffScratchList
296 " Section: Utility functions {{{1
298 " Function: s:ReportError(mapping) {{{2
299 " Displays the given error in a consistent faction. This is intended to be
300 " invoked from a catch statement.
302 function! s:ReportError(error)
303 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
306 " Function: s:ExecuteExtensionMapping(mapping) {{{2
307 " Invokes the appropriate extension mapping depending on the type of the
310 function! s:ExecuteExtensionMapping(mapping)
311 let buffer = bufnr('%')
312 let vcsType = VCSCommandGetVCSType(buffer)
313 if !has_key(s:extendedMappings, vcsType)
314 throw 'Unknown VCS type: ' . vcsType
316 if !has_key(s:extendedMappings[vcsType], a:mapping)
317 throw 'This extended mapping is not defined for ' . vcsType
319 silent execute 'normal' ':' . s:extendedMappings[vcsType][a:mapping] . "\<CR>"
322 " Function: s:ExecuteVCSCommand(command, argList) {{{2
323 " Calls the indicated plugin-specific VCS command on the current buffer.
324 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
327 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
329 let buffer = bufnr('%')
331 let vcsType = VCSCommandGetVCSType(buffer)
332 if !has_key(s:plugins, vcsType)
333 throw 'Unknown VCS type: ' . vcsType
336 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
337 let bufferName = bufname(originalBuffer)
339 " It is already known that the directory is under VCS control. No further
340 " checks are needed. Otherwise, perform some basic sanity checks to avoid
341 " VCS-specific error messages from confusing things.
342 if !isdirectory(bufferName)
343 if !filereadable(bufferName)
344 throw 'No such file ' . bufferName
347 if isdirectory(bufferName)
349 let revision = VCSCommandGetRevision()
351 throw 'Unable to obtain version information.'
352 elseif revision == 'Unknown'
353 throw 'Item not under source control'
354 elseif revision == 'New'
355 throw 'Operation not available on newly-added item.'
360 let functionMap = s:plugins[vcsType]
361 if !has_key(functionMap, a:command)
362 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
364 return functionMap[a:command](a:argList)
366 call s:ReportError(v:exception)
371 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
372 " Default method of generating the name for VCS result buffers. This can be
373 " overridden with the VCSResultBufferNameFunction variable.
375 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
376 let fileName = bufname(a:originalBuffer)
377 let bufferName = a:vcsType . ' ' . a:command
378 if strlen(a:statusText) > 0
379 let bufferName .= ' ' . a:statusText
381 let bufferName .= ' ' . fileName
383 let versionedBufferName = bufferName
384 while buflisted(versionedBufferName)
386 let versionedBufferName = bufferName . ' (' . counter . ')'
388 return versionedBufferName
391 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
392 " Method of generating the name for VCS result buffers that uses the original
393 " file name with the VCS type and command appended as extensions.
395 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
396 let fileName = bufname(a:originalBuffer)
397 let bufferName = a:vcsType . ' ' . a:command
398 if strlen(a:statusText) > 0
399 let bufferName .= ' ' . a:statusText
401 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
403 let versionedBufferName = bufferName
404 while buflisted(versionedBufferName)
406 let versionedBufferName = '(' . counter . ') ' . bufferName
408 return versionedBufferName
411 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
412 " Creates a new buffer of the given name and associates it with the given
415 function! s:EditFile(command, originalBuffer, statusText)
416 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
418 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
419 if nameExtension == ''
420 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
422 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
425 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
427 " Protect against useless buffer set-up
428 let s:isEditFileRunning += 1
430 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
431 if editCommand == 'split'
432 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
435 vert rightbelow split
438 edit `=resultBufferName`
439 let b:VCSCommandCommand = a:command
440 let b:VCSCommandOriginalBuffer = a:originalBuffer
441 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
442 let b:VCSCommandVCSType = vcsType
446 let &filetype = vcsType . a:command
448 if a:statusText != ''
449 let b:VCSCommandStatusText = a:statusText
452 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
456 let s:isEditFileRunning -= 1
461 " Function: s:SetupBuffer() {{{2
462 " Attempts to set the b:VCSCommandBufferInfo variable
464 function! s:SetupBuffer()
465 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
466 " This buffer is already set up.
470 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
471 " No special status for special buffers other than directory buffers.
475 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
476 unlet! b:VCSCommandBufferSetup
481 let vcsType = VCSCommandGetVCSType(bufnr('%'))
482 let b:VCSCommandBufferInfo = s:plugins[vcsType].GetBufferInfo()
483 silent do VCSCommand User VCSBufferSetup
484 catch /No suitable plugin/
485 " This is not a VCS-controlled file.
486 let b:VCSCommandBufferInfo = []
489 let b:VCSCommandBufferSetup = 1
492 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
493 " Resets the buffer setup state of the original buffer for a given VCS scratch
495 " Returns: The VCS buffer number in a passthrough mode.
497 function! s:MarkOrigBufferForSetup(buffer)
500 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
501 " This should never not work, but I'm paranoid
502 if origBuffer != a:buffer
503 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
509 " Function: s:OverrideOption(option, [value]) {{{2
510 " Provides a temporary override for the given VCS option. If no value is
511 " passed, the override is disabled.
513 function! s:OverrideOption(option, ...)
515 call remove(s:optionOverrides[a:option], -1)
517 if !has_key(s:optionOverrides, a:option)
518 let s:optionOverrides[a:option] = []
520 call add(s:optionOverrides[a:option], a:1)
524 " Function: s:WipeoutCommandBuffers() {{{2
525 " Clears all current VCS output buffers of the specified type for a given source.
527 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
529 while buffer <= bufnr('$')
530 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
531 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
535 let buffer = buffer + 1
539 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
540 " Checks whether the given buffer is one whose deletion should trigger
541 " restoration of an original buffer after it was diffed. If so, it executes
542 " the appropriate setting command stored with that original buffer.
544 function! s:VimDiffRestore(vimDiffBuff)
545 let s:isEditFileRunning += 1
547 if exists('s:vimDiffSourceBuffer')
548 if a:vimDiffBuff == s:vimDiffSourceBuffer
549 " Original file is being removed.
550 unlet! s:vimDiffSourceBuffer
551 unlet! s:vimDiffRestoreCmd
552 unlet! s:vimDiffScratchList
554 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
556 call remove(s:vimDiffScratchList, index)
557 if len(s:vimDiffScratchList) == 0
558 if exists('s:vimDiffRestoreCmd')
559 " All scratch buffers are gone, reset the original.
560 " Only restore if the source buffer is still in Diff mode
562 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
564 " The buffer is visible in at least one window
565 let currentWinNR = winnr()
566 while winbufnr(sourceWinNR) != -1
567 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
568 execute sourceWinNR . 'wincmd w'
569 if getwinvar(0, '&diff')
570 execute s:vimDiffRestoreCmd
573 let sourceWinNR = sourceWinNR + 1
575 execute currentWinNR . 'wincmd w'
577 " The buffer is hidden. It must be visible in order to set the
579 let currentBufNR = bufnr('')
580 execute 'hide buffer' s:vimDiffSourceBuffer
581 if getwinvar(0, '&diff')
582 execute s:vimDiffRestoreCmd
584 execute 'hide buffer' currentBufNR
587 unlet s:vimDiffRestoreCmd
589 " All buffers are gone.
590 unlet s:vimDiffSourceBuffer
591 unlet s:vimDiffScratchList
597 let s:isEditFileRunning -= 1
601 " Section: Generic VCS command functions {{{1
603 " Function: s:VCSCommit() {{{2
604 function! s:VCSCommit(bang, message)
606 let vcsType = VCSCommandGetVCSType(bufnr('%'))
607 if !has_key(s:plugins, vcsType)
608 throw 'Unknown VCS type: ' . vcsType
611 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
613 " Handle the commit message being specified. If a message is supplied, it
614 " is used; if bang is supplied, an empty message is used; otherwise, the
615 " user is provided a buffer from which to edit the commit message.
617 if strlen(a:message) > 0 || a:bang == '!'
618 return s:VCSFinishCommit([a:message], originalBuffer)
621 call s:EditFile('commitlog', originalBuffer, '')
624 " Create a commit mapping.
626 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
628 silent 0put ='VCS: ----------------------------------------------------------------------'
629 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
630 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
632 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
634 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
635 silent put ='VCS: or write this buffer'
638 silent put ='VCS: ----------------------------------------------------------------------'
642 call s:ReportError(v:exception)
647 " Function: s:VCSFinishCommitWithBuffer() {{{2
648 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
649 " which removes all lines starting with 'VCS:'.
651 function! s:VCSFinishCommitWithBuffer()
653 let currentBuffer = bufnr('%')
654 let logMessageList = getbufline('%', 1, '$')
655 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
656 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
658 execute 'bw' currentBuffer
663 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
664 function! s:VCSFinishCommit(logMessageList, originalBuffer)
665 let shellSlashBak = &shellslash
668 let messageFileName = tempname()
669 call writefile(a:logMessageList, messageFileName)
671 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
675 return s:MarkOrigBufferForSetup(resultBuffer)
677 call delete(messageFileName)
680 let &shellslash = shellSlashBak
684 " Function: s:VCSGotoOriginal(bang) {{{2
685 function! s:VCSGotoOriginal(bang)
686 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
687 if originalBuffer > 0
688 let origWinNR = bufwinnr(originalBuffer)
690 execute 'buffer' originalBuffer
692 execute origWinNR . 'wincmd w'
696 let buffmaxnr = bufnr('$')
697 while buffnr <= buffmaxnr
698 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
701 let buffnr = buffnr + 1
707 " Function: s:VCSVimDiff(...) {{{2
708 function! s:VCSVimDiff(...)
710 let vcsType = VCSCommandGetVCSType(bufnr('%'))
711 if !has_key(s:plugins, vcsType)
712 throw 'Unknown VCS type: ' . vcsType
714 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
715 let s:isEditFileRunning = s:isEditFileRunning + 1
717 " If there's already a VimDiff'ed window, restore it.
718 " There may only be one VCSVimDiff original window at a time.
720 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
721 " Clear the existing vimdiff setup by removing the result buffers.
722 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
727 " Reset the vimdiff system, as 2 explicit versions were provided.
728 if exists('s:vimDiffSourceBuffer')
729 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
731 let resultBuffer = s:plugins[vcsType].Review([a:1])
733 echomsg 'Can''t open revision ' . a:1
736 let b:VCSCommandCommand = 'vimdiff'
738 let s:vimDiffScratchList = [resultBuffer]
739 " If no split method is defined, cheat, and set it to vertical.
741 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
742 let resultBuffer = s:plugins[vcsType].Review([a:2])
744 call s:OverrideOption('VCSCommandSplit')
747 echomsg 'Can''t open revision ' . a:1
750 let b:VCSCommandCommand = 'vimdiff'
752 let s:vimDiffScratchList += [resultBuffer]
755 call s:OverrideOption('VCSCommandEdit', 'split')
757 " Force splitting behavior, otherwise why use vimdiff?
758 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
761 let resultBuffer = s:plugins[vcsType].Review([])
763 let resultBuffer = s:plugins[vcsType].Review([a:1])
766 call s:OverrideOption('VCSCommandSplit')
769 call s:OverrideOption('VCSCommandEdit')
772 echomsg 'Can''t open current revision'
775 let b:VCSCommandCommand = 'vimdiff'
778 if !exists('s:vimDiffSourceBuffer')
779 " New instance of vimdiff.
780 let s:vimDiffScratchList = [resultBuffer]
782 " This could have been invoked on a VCS result buffer, not the
785 execute 'buffer' originalBuffer
786 " Store info for later original buffer restore
787 let s:vimDiffRestoreCmd =
788 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
789 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
790 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
791 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
792 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
793 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
794 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
798 " Adding a window to an existing vimdiff
799 let s:vimDiffScratchList += [resultBuffer]
803 let s:vimDiffSourceBuffer = originalBuffer
805 " Avoid executing the modeline in the current buffer after the autocommand.
807 let currentBuffer = bufnr('%')
808 let saveModeline = getbufvar(currentBuffer, '&modeline')
810 call setbufvar(currentBuffer, '&modeline', 0)
811 silent do VCSCommand User VCSVimDiffFinish
813 call setbufvar(currentBuffer, '&modeline', saveModeline)
817 let s:isEditFileRunning = s:isEditFileRunning - 1
820 call s:ReportError(v:exception)
825 " Section: Public functions {{{1
827 " Function: VCSCommandGetVCSType() {{{2
828 " Sets the b:VCSCommandVCSType variable in the given buffer to the
829 " appropriate source control system name.
831 function! VCSCommandGetVCSType(buffer)
832 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
833 if strlen(vcsType) > 0
836 for vcsType in keys(s:plugins)
837 if s:plugins[vcsType].Identify(a:buffer)
838 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
842 throw 'No suitable plugin'
845 " Function: VCSCommandChdir(directory) {{{2
846 " Changes the current directory, respecting :lcd changes.
848 function! VCSCommandChdir(directory)
850 if exists("*haslocaldir") && haslocaldir()
853 execute command escape(a:directory, ' ')
856 " Function: VCSCommandChangeToCurrentFileDir() {{{2
857 " Go to the directory in which the given file is located.
859 function! VCSCommandChangeToCurrentFileDir(fileName)
860 let oldCwd = getcwd()
861 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
862 if strlen(newCwd) > 0
863 call VCSCommandChdir(newCwd)
868 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
869 " Attempts to locate the original file to which VCS operations were applied
870 " for a given buffer.
872 function! VCSCommandGetOriginalBuffer(vcsBuffer)
873 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
875 if bufexists(origBuffer)
878 " Original buffer no longer exists.
879 throw 'Original buffer for this VCS buffer no longer exists.'
887 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
888 " Allows VCS modules to register themselves.
890 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
891 let s:plugins[a:name] = a:commandMap
892 call add(s:pluginFiles, a:file)
893 let s:extendedMappings[a:name] = a:mappingMap
894 if(!empty(a:mappingMap))
895 for mapname in keys(a:mappingMap)
896 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
901 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
902 " General skeleton for VCS function execution.
903 " Returns: name of the new command buffer containing the command results
905 function! VCSCommandDoCommand(cmd, cmdName, statusText)
906 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
907 if originalBuffer == -1
908 throw 'Original buffer no longer exists, aborting.'
911 let fileName = resolve(bufname(originalBuffer))
913 " Work with netrw or other systems where a directory listing is displayed in
916 if isdirectory(fileName)
917 let realFileName = '.'
919 let realFileName = fnamemodify(fileName, ':t')
922 " Change to the directory of the current buffer. This is done for CVS, but
923 " is left in for other systems as it does not affect them negatively.
925 let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
927 let output = system(a:cmd . ' "' . realFileName . '"')
929 call VCSCommandChdir(oldCwd)
932 " HACK: if line endings in the repository have been corrupted, the output
933 " of the command will be confused.
934 let output = substitute(output, "\r", '', 'g')
936 " HACK: CVS diff command does not return proper error codes
937 if v:shell_error && (a:cmdName != 'diff' || getbufvar(originalBuffer, 'VCSCommandVCSType') != 'CVS')
938 if strlen(output) == 0
939 throw 'Version control command failed'
941 let output = substitute(output, '\n', ' ', 'g')
942 throw 'Version control command failed: ' . output
945 if strlen(output) == 0
946 " Handle case of no output. In this case, it is important to check the
947 " file status, especially since cvs edit/unedit may change the attributes
948 " of the file with no visible output.
954 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
958 " The last command left a blank line at the end of the buffer. If the
959 " last line is folded (a side effect of the 'put') then the attempt to
960 " remove the blank line will kill the last fold.
962 " This could be fixed by explicitly detecting whether the last line is
963 " within a fold, but I prefer to simply unfold the result buffer altogether.
972 " Define the environment and execute user-defined hooks.
974 silent do VCSCommand User VCSBufferCreated
978 " Function: VCSCommandGetOption(name, default) {{{2
979 " Grab a user-specified option to override the default provided. Options are
980 " searched in the window, buffer, then global spaces.
982 function! VCSCommandGetOption(name, default)
983 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
984 return s:optionOverrides[a:name][-1]
985 elseif exists('w:' . a:name)
987 elseif exists('b:' . a:name)
989 elseif exists('g:' . a:name)
996 " Function: VCSCommandGetRevision() {{{2
997 " Global function for retrieving the current buffer's revision number.
998 " Returns: Revision number or an empty string if an error occurs.
1000 function! VCSCommandGetRevision()
1001 if !exists('b:VCSCommandBufferInfo')
1002 let b:VCSCommandBufferInfo = s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1005 if len(b:VCSCommandBufferInfo) > 0
1006 return b:VCSCommandBufferInfo[0]
1012 " Function: VCSCommandDisableBufferSetup() {{{2
1013 " Global function for deactivating the buffer autovariables.
1015 function! VCSCommandDisableBufferSetup()
1016 let g:VCSCommandEnableBufferSetup = 0
1017 silent! augroup! VCSCommandPlugin
1020 " Function: VCSCommandEnableBufferSetup() {{{2
1021 " Global function for activating the buffer autovariables.
1023 function! VCSCommandEnableBufferSetup()
1024 let g:VCSCommandEnableBufferSetup = 1
1025 augroup VCSCommandPlugin
1027 au BufEnter * call s:SetupBuffer()
1030 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1032 if g:loaded_VCSCommand == 2
1033 call s:SetupBuffer()
1037 " Function: VCSCommandGetStatusLine() {{{2
1038 " Default (sample) status line entry for VCS-controlled files. This is only
1039 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1040 " variable for how to do this).
1042 function! VCSCommandGetStatusLine()
1043 if exists('b:VCSCommandCommand')
1044 " This is a result buffer. Return nothing because the buffer name
1045 " contains information already.
1049 if exists('b:VCSCommandVCSType')
1050 \ && exists('g:VCSCommandEnableBufferSetup')
1051 \ && g:VCSCommandEnableBufferSetup
1052 \ && exists('b:VCSCommandBufferInfo')
1053 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1059 " Section: Command definitions {{{1
1060 " Section: Primary commands {{{2
1061 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1062 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1063 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1064 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1065 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1066 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1067 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1068 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1069 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1070 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1071 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1072 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1073 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1074 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1075 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1077 " Section: VCS buffer management commands {{{2
1078 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1079 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1081 " Allow reloading VCSCommand.vim
1082 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
1084 " Section: Plugin command mappings {{{1
1085 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1086 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1087 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1088 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1089 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1090 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1091 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1092 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1093 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1094 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1095 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1096 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1097 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1098 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1099 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1100 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1102 " Section: Default mappings {{{1
1103 if !hasmapto('<Plug>VCSAdd')
1104 nmap <unique> <Leader>ca <Plug>VCSAdd
1106 if !hasmapto('<Plug>VCSAnnotate')
1107 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1109 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1110 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1112 if !hasmapto('<Plug>VCSCommit')
1113 nmap <unique> <Leader>cc <Plug>VCSCommit
1115 if !hasmapto('<Plug>VCSDelete')
1116 nmap <unique> <Leader>cD <Plug>VCSDelete
1118 if !hasmapto('<Plug>VCSDiff')
1119 nmap <unique> <Leader>cd <Plug>VCSDiff
1121 if !hasmapto('<Plug>VCSGotoOriginal')
1122 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1124 if !hasmapto('<Plug>VCSInfo')
1125 nmap <unique> <Leader>ci <Plug>VCSInfo
1127 if !hasmapto('<Plug>VCSLock')
1128 nmap <unique> <Leader>cL <Plug>VCSLock
1130 if !hasmapto('<Plug>VCSLog')
1131 nmap <unique> <Leader>cl <Plug>VCSLog
1133 if !hasmapto('<Plug>VCSRevert')
1134 nmap <unique> <Leader>cq <Plug>VCSRevert
1136 if !hasmapto('<Plug>VCSReview')
1137 nmap <unique> <Leader>cr <Plug>VCSReview
1139 if !hasmapto('<Plug>VCSStatus')
1140 nmap <unique> <Leader>cs <Plug>VCSStatus
1142 if !hasmapto('<Plug>VCSUnlock')
1143 nmap <unique> <Leader>cU <Plug>VCSUnlock
1145 if !hasmapto('<Plug>VCSUpdate')
1146 nmap <unique> <Leader>cu <Plug>VCSUpdate
1148 if !hasmapto('<Plug>VCSVimDiff')
1149 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1152 " Section: Menu items {{{1
1153 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1154 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1155 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1156 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1157 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1158 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1159 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1160 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1161 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1162 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1163 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1164 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1166 " Section: Autocommands to restore vimdiff state {{{1
1167 augroup VimDiffRestore
1169 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1172 " Section: Optional activation of buffer management {{{1
1174 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1175 call VCSCommandEnableBufferSetup()
1178 " Section: VIM shutdown hook {{{1
1180 " Close all result buffers when VIM exits, to prevent them from being restored
1183 " Function: s:CloseAllResultBuffers() {{{2
1184 " Closes all vcscommand result buffers.
1185 function! s:CloseAllResultBuffers()
1186 " This avoids using bufdo as that may load buffers already loaded in another
1187 " vim process, resulting in an error.
1189 let buffmaxnr = bufnr('$')
1190 while buffnr <= buffmaxnr
1191 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1194 let buffnr = buffnr + 1
1198 augroup VCSCommandVIMShutdown
1200 au VimLeavePre * call s:CloseAllResultBuffers()
1203 " Section: Plugin completion {{{1
1205 let loaded_VCSCommand = 2
1207 silent do VCSCommand User VCSPluginFinish