1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
6 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
8 " Copyright (c) 2007 Bob Hiestand
10 " Permission is hereby granted, free of charge, to any person obtaining a copy
11 " of this software and associated documentation files (the "Software"), to
12 " deal in the Software without restriction, including without limitation the
13 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
14 " sell copies of the Software, and to permit persons to whom the Software is
15 " furnished to do so, subject to the following conditions:
17 " The above copyright notice and this permission notice shall be included in
18 " all copies or substantial portions of the Software.
20 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 " Section: Documentation {{{1
30 " Provides functions to invoke various source control commands on the current
31 " file (either the current buffer, or, in the case of an directory buffer, the
32 " directory and all subdirectories associated with the current buffer). The
33 " output of the commands is captured in a new scratch window.
35 " This plugin needs additional extension plugins, each specific to a source
36 " control system, to function. Those plugins should be placed in a
37 " subdirectory of the standard plugin directory named 'vcscommand'. Several
38 " options include the name of the version control system in the option name.
39 " Such options use the placeholder text '{VCSType}', which would be replaced
40 " in actual usage with 'CVS' or 'SVN', for instance.
42 " Command documentation {{{2
44 " VCSAdd Adds the current file to source control.
46 " VCSAnnotate Displays the current file with each line annotated with the
47 " version in which it was most recently changed. If an
48 " argument is given, the argument is used as a revision
49 " number to display. If not given an argument, it uses the
50 " most recent version of the file on the current branch.
51 " Additionally, if the current buffer is a VCSAnnotate buffer
52 " already, the version number on the current line is used.
54 " VCSCommit[!] Commits changes to the current file to source control.
56 " If called with arguments, the arguments are the log message.
58 " If '!' is used, an empty log message is committed.
60 " If called with no arguments, this is a two-step command.
61 " The first step opens a buffer to accept a log message.
62 " When that buffer is written, it is automatically closed and
63 " the file is committed using the information from that log
64 " message. The commit can be abandoned if the log message
65 " buffer is deleted or wiped before being written.
67 " VCSDelete Deletes the current file and removes it from source control.
69 " VCSDiff With no arguments, this displays the differences between
70 " the current file and its parent version under source
71 " control in a new scratch buffer.
73 " With one argument, the diff is performed on the
74 " current file against the specified revision.
76 " With two arguments, the diff is performed between the
77 " specified revisions of the current file.
79 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
80 " to specify diff options. If that variable does not exist,
81 " a plugin-specific default is used. If you wish to have no
82 " options, then set it to the empty string.
84 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
85 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
86 " VCS scratch buffers associated with the original file.
88 " VCSInfo Displays extended information about the current file in a
91 " VCSLock Locks the current file in order to prevent other users from
92 " concurrently modifying it. The exact semantics of this
93 " command depend on the underlying VCS.
95 " VCSLog Displays the version history of the current file in a new
98 " VCSRevert Replaces the modified version of the current file with the
99 " most recent version from the repository.
101 " VCSReview Displays a particular version of the current file in a new
102 " scratch buffer. If no argument is given, the most recent
103 " version of the file on the current branch is retrieved.
105 " VCSStatus Displays versioning information about the current file in a
106 " new scratch buffer.
108 " VCSUnlock Unlocks the current file in order to allow other users from
109 " concurrently modifying it. The exact semantics of this
110 " command depend on the underlying VCS.
112 " VCSUpdate Updates the current file with any relevant changes from the
115 " VCSVimDiff Uses vimdiff to display differences between versions of the
118 " If no revision is specified, the most recent version of the
119 " file on the current branch is used. With one argument,
120 " that argument is used as the revision as above. With two
121 " arguments, the differences between the two revisions is
122 " displayed using vimdiff.
124 " With either zero or one argument, the original buffer is
125 " used to perform the vimdiff. When the scratch buffer is
126 " closed, the original buffer will be returned to normal
129 " Once vimdiff mode is started using the above methods,
130 " additional vimdiff buffers may be added by passing a single
131 " version argument to the command. There may be up to 4
132 " vimdiff buffers total.
134 " Using the 2-argument form of the command resets the vimdiff
135 " to only those 2 versions. Additionally, invoking the
136 " command on a different file will close the previous vimdiff
139 " Mapping documentation: {{{2
141 " By default, a mapping is defined for each command. User-provided mappings
142 " can be used instead by mapping to <Plug>CommandName, for instance:
144 " nmap ,ca <Plug>VCSAdd
146 " The default mappings are as follow:
149 " <Leader>cn VCSAnnotate
150 " <Leader>cc VCSCommit
151 " <Leader>cD VCSDelete
153 " <Leader>cg VCSGotoOriginal
154 " <Leader>cG VCSGotoOriginal!
158 " <Leader>cr VCSReview
159 " <Leader>cs VCSStatus
160 " <Leader>cu VCSUpdate
161 " <Leader>cU VCSUnlock
162 " <Leader>cv VCSVimDiff
164 " Options documentation: {{{2
166 " Several variables are checked by the script to determine behavior as follow:
168 " VCSCommandCommitOnWrite
169 " This variable, if set to a non-zero value, causes the pending commit to
170 " take place immediately as soon as the log message buffer is written. If
171 " set to zero, only the VCSCommit mapping will cause the pending commit to
172 " occur. If not set, it defaults to 1.
174 " VCSCommandDeleteOnHide
175 " This variable, if set to a non-zero value, causes the temporary VCS result
176 " buffers to automatically delete themselves when hidden.
178 " VCSCommand{VCSType}DiffOpt
179 " This variable, if set, determines the options passed to the diff command
180 " of the underlying VCS. Each VCS plugin defines a default value.
182 " VCSCommandDiffSplit
183 " This variable overrides the VCSCommandSplit variable, but only for buffers
184 " created with VCSVimDiff.
186 " VCSCommandDisableMappings
187 " This variable, if set to a non-zero value, prevents the default command
188 " mappings from being set.
190 " VCSCommandDisableExtensionMappings
191 " This variable, if set to a non-zero value, prevents the default command
192 " mappings from being set for commands specific to an individual VCS.
195 " This variable controls whether to split the current window to display a
196 " scratch buffer ('split'), or to display it in the current buffer ('edit').
197 " If not set, it defaults to 'split'.
199 " VCSCommandEnableBufferSetup
200 " This variable, if set to a non-zero value, activates VCS buffer management
201 " mode. This mode means that the buffer variable 'VCSRevision' is set if
202 " the file is VCS-controlled. This is useful for displaying version
203 " information in the status bar. Additional options may be set by
204 " individual VCS plugins.
206 " VCSCommandResultBufferNameExtension
207 " This variable, if set to a non-blank value, is appended to the name of the
208 " VCS command output buffers. For example, '.vcs'. Using this option may
209 " help avoid problems caused by autocommands dependent on file extension.
211 " VCSCommandResultBufferNameFunction
212 " This variable, if set, specifies a custom function for naming VCS command
213 " output buffers. This function will be passed the following arguments:
215 " command - name of the VCS command being executed (such as 'Log' or
218 " originalBuffer - buffer number of the source file.
220 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
222 " statusText - extra text associated with the VCS action (such as version
226 " This variable controls the orientation of the various window splits that
227 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
228 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
229 " If set to 'horizontal', the resulting windows will be on stacked on top of
230 " one another. If set to 'vertical', the resulting windows will be
231 " side-by-side. If not set, it defaults to 'horizontal' for all but
232 " VCSVimDiff windows.
234 " Event documentation {{{2
235 " For additional customization, VCSCommand.vim uses User event autocommand
236 " hooks. Each event is in the VCSCommand group, and different patterns
237 " match the various hooks.
239 " For instance, the following could be added to the vimrc to provide a 'q'
240 " mapping to quit a VCS scratch buffer:
243 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
246 " The following hooks are available:
248 " VCSBufferCreated This event is fired just after a VCS command
249 " output buffer is created. It is executed
250 " within the context of the new buffer.
252 " VCSBufferSetup This event is fired just after VCS buffer setup
253 " occurs, if enabled.
255 " VCSPluginInit This event is fired when the VCSCommand plugin
258 " VCSPluginFinish This event is fired just after the VCSCommand
261 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
262 " command executes to allow customization of,
263 " for instance, window placement and focus.
265 " Section: Plugin header {{{1
267 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
268 " completes. This allows various actions to only be taken by functions after
269 " system initialization.
271 if exists('loaded_VCSCommand')
274 let loaded_VCSCommand = 1
277 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
281 " Section: Event group setup {{{1
286 augroup VCSCommandCommit
289 " Section: Plugin initialization {{{1
290 silent do VCSCommand User VCSPluginInit
292 " Section: Script variable initialization {{{1
295 let s:pluginFiles = []
296 let s:extendedMappings = {}
297 let s:optionOverrides = {}
298 let s:isEditFileRunning = 0
300 unlet! s:vimDiffRestoreCmd
301 unlet! s:vimDiffSourceBuffer
302 unlet! s:vimDiffScratchList
304 " Section: Utility functions {{{1
306 " Function: s:ReportError(mapping) {{{2
307 " Displays the given error in a consistent faction. This is intended to be
308 " invoked from a catch statement.
310 function! s:ReportError(error)
311 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
314 " Function: s:ExecuteExtensionMapping(mapping) {{{2
315 " Invokes the appropriate extension mapping depending on the type of the
318 function! s:ExecuteExtensionMapping(mapping)
319 let buffer = bufnr('%')
320 let vcsType = VCSCommandGetVCSType(buffer)
321 if !has_key(s:extendedMappings, vcsType)
322 throw 'Unknown VCS type: ' . vcsType
324 if !has_key(s:extendedMappings[vcsType], a:mapping)
325 throw 'This extended mapping is not defined for ' . vcsType
327 silent execute 'normal' ':' . s:extendedMappings[vcsType][a:mapping] . "\<CR>"
330 " Function: s:ExecuteVCSCommand(command, argList) {{{2
331 " Calls the indicated plugin-specific VCS command on the current buffer.
332 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
335 function! s:ExecuteVCSCommand(command, argList, verifyBuffer)
337 let buffer = bufnr('%')
339 let vcsType = VCSCommandGetVCSType(buffer)
340 if !has_key(s:plugins, vcsType)
341 throw 'Unknown VCS type: ' . vcsType
344 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
345 let bufferName = bufname(originalBuffer)
347 " It is already known that the directory is under VCS control. No further
348 " checks are needed. Otherwise, perform some basic sanity checks to avoid
349 " VCS-specific error messages from confusing things.
350 if !isdirectory(bufferName)
351 if !filereadable(bufferName)
352 throw 'No such file ' . bufferName
355 if isdirectory(bufferName)
357 let revision = VCSCommandGetRevision()
359 throw 'Unable to obtain version information.'
360 elseif revision == 'Unknown'
361 throw 'Item not under source control'
362 elseif revision == 'New'
363 throw 'Operation not available on newly-added item.'
368 let functionMap = s:plugins[vcsType]
369 if !has_key(functionMap, a:command)
370 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
372 return functionMap[a:command](a:argList)
374 call s:ReportError(v:exception)
379 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
380 " Default method of generating the name for VCS result buffers. This can be
381 " overridden with the VCSResultBufferNameFunction variable.
383 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
384 let fileName = bufname(a:originalBuffer)
385 let bufferName = a:vcsType . ' ' . a:command
386 if strlen(a:statusText) > 0
387 let bufferName .= ' ' . a:statusText
389 let bufferName .= ' ' . fileName
391 let versionedBufferName = bufferName
392 while buflisted(versionedBufferName)
394 let versionedBufferName = bufferName . ' (' . counter . ')'
396 return versionedBufferName
399 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
400 " Method of generating the name for VCS result buffers that uses the original
401 " file name with the VCS type and command appended as extensions.
403 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
404 let fileName = bufname(a:originalBuffer)
405 let bufferName = a:vcsType . ' ' . a:command
406 if strlen(a:statusText) > 0
407 let bufferName .= ' ' . a:statusText
409 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
411 let versionedBufferName = bufferName
412 while buflisted(versionedBufferName)
414 let versionedBufferName = '(' . counter . ') ' . bufferName
416 return versionedBufferName
419 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
420 " Creates a new buffer of the given name and associates it with the given
423 function! s:EditFile(command, originalBuffer, statusText)
424 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
426 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
427 if nameExtension == ''
428 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
430 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
433 let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
435 " Protect against useless buffer set-up
436 let s:isEditFileRunning += 1
438 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
439 if editCommand == 'split'
440 if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
443 vert rightbelow split
446 edit `=resultBufferName`
447 let b:VCSCommandCommand = a:command
448 let b:VCSCommandOriginalBuffer = a:originalBuffer
449 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
450 let b:VCSCommandVCSType = vcsType
454 let &filetype = vcsType . a:command
456 if a:statusText != ''
457 let b:VCSCommandStatusText = a:statusText
460 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
464 let s:isEditFileRunning -= 1
469 " Function: s:SetupBuffer() {{{2
470 " Attempts to set the b:VCSCommandBufferInfo variable
472 function! s:SetupBuffer()
473 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
474 " This buffer is already set up.
478 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
479 " No special status for special buffers other than directory buffers.
483 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
484 unlet! b:VCSCommandBufferSetup
489 let vcsType = VCSCommandGetVCSType(bufnr('%'))
490 let b:VCSCommandBufferInfo = s:plugins[vcsType].GetBufferInfo()
491 silent do VCSCommand User VCSBufferSetup
492 catch /No suitable plugin/
493 " This is not a VCS-controlled file.
494 let b:VCSCommandBufferInfo = []
497 let b:VCSCommandBufferSetup = 1
500 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
501 " Resets the buffer setup state of the original buffer for a given VCS scratch
503 " Returns: The VCS buffer number in a passthrough mode.
505 function! s:MarkOrigBufferForSetup(buffer)
508 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
509 " This should never not work, but I'm paranoid
510 if origBuffer != a:buffer
511 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
517 " Function: s:OverrideOption(option, [value]) {{{2
518 " Provides a temporary override for the given VCS option. If no value is
519 " passed, the override is disabled.
521 function! s:OverrideOption(option, ...)
523 call remove(s:optionOverrides[a:option], -1)
525 if !has_key(s:optionOverrides, a:option)
526 let s:optionOverrides[a:option] = []
528 call add(s:optionOverrides[a:option], a:1)
532 " Function: s:WipeoutCommandBuffers() {{{2
533 " Clears all current VCS output buffers of the specified type for a given source.
535 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
537 while buffer <= bufnr('$')
538 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
539 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
543 let buffer = buffer + 1
547 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
548 " Checks whether the given buffer is one whose deletion should trigger
549 " restoration of an original buffer after it was diffed. If so, it executes
550 " the appropriate setting command stored with that original buffer.
552 function! s:VimDiffRestore(vimDiffBuff)
553 let s:isEditFileRunning += 1
555 if exists('s:vimDiffSourceBuffer')
556 if a:vimDiffBuff == s:vimDiffSourceBuffer
557 " Original file is being removed.
558 unlet! s:vimDiffSourceBuffer
559 unlet! s:vimDiffRestoreCmd
560 unlet! s:vimDiffScratchList
562 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
564 call remove(s:vimDiffScratchList, index)
565 if len(s:vimDiffScratchList) == 0
566 if exists('s:vimDiffRestoreCmd')
567 " All scratch buffers are gone, reset the original.
568 " Only restore if the source buffer is still in Diff mode
570 let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
572 " The buffer is visible in at least one window
573 let currentWinNR = winnr()
574 while winbufnr(sourceWinNR) != -1
575 if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
576 execute sourceWinNR . 'wincmd w'
577 if getwinvar(0, '&diff')
578 execute s:vimDiffRestoreCmd
581 let sourceWinNR = sourceWinNR + 1
583 execute currentWinNR . 'wincmd w'
585 " The buffer is hidden. It must be visible in order to set the
587 let currentBufNR = bufnr('')
588 execute 'hide buffer' s:vimDiffSourceBuffer
589 if getwinvar(0, '&diff')
590 execute s:vimDiffRestoreCmd
592 execute 'hide buffer' currentBufNR
595 unlet s:vimDiffRestoreCmd
597 " All buffers are gone.
598 unlet s:vimDiffSourceBuffer
599 unlet s:vimDiffScratchList
605 let s:isEditFileRunning -= 1
609 " Section: Generic VCS command functions {{{1
611 " Function: s:VCSCommit() {{{2
612 function! s:VCSCommit(bang, message)
614 let vcsType = VCSCommandGetVCSType(bufnr('%'))
615 if !has_key(s:plugins, vcsType)
616 throw 'Unknown VCS type: ' . vcsType
619 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
621 " Handle the commit message being specified. If a message is supplied, it
622 " is used; if bang is supplied, an empty message is used; otherwise, the
623 " user is provided a buffer from which to edit the commit message.
625 if strlen(a:message) > 0 || a:bang == '!'
626 return s:VCSFinishCommit([a:message], originalBuffer)
629 call s:EditFile('commitlog', originalBuffer, '')
632 " Create a commit mapping.
634 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
636 silent 0put ='VCS: ----------------------------------------------------------------------'
637 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
638 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
640 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
642 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
643 silent put ='VCS: or write this buffer'
646 silent put ='VCS: ----------------------------------------------------------------------'
650 call s:ReportError(v:exception)
655 " Function: s:VCSFinishCommitWithBuffer() {{{2
656 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
657 " which removes all lines starting with 'VCS:'.
659 function! s:VCSFinishCommitWithBuffer()
661 let currentBuffer = bufnr('%')
662 let logMessageList = getbufline('%', 1, '$')
663 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
664 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
666 execute 'bw' currentBuffer
671 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
672 function! s:VCSFinishCommit(logMessageList, originalBuffer)
673 let shellSlashBak = &shellslash
676 let messageFileName = tempname()
677 call writefile(a:logMessageList, messageFileName)
679 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName], 0)
683 return s:MarkOrigBufferForSetup(resultBuffer)
685 call delete(messageFileName)
688 let &shellslash = shellSlashBak
692 " Function: s:VCSGotoOriginal(bang) {{{2
693 function! s:VCSGotoOriginal(bang)
694 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
695 if originalBuffer > 0
696 let origWinNR = bufwinnr(originalBuffer)
698 execute 'buffer' originalBuffer
700 execute origWinNR . 'wincmd w'
704 let buffmaxnr = bufnr('$')
705 while buffnr <= buffmaxnr
706 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
709 let buffnr = buffnr + 1
715 " Function: s:VCSVimDiff(...) {{{2
716 function! s:VCSVimDiff(...)
718 let vcsType = VCSCommandGetVCSType(bufnr('%'))
719 if !has_key(s:plugins, vcsType)
720 throw 'Unknown VCS type: ' . vcsType
722 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
723 let s:isEditFileRunning = s:isEditFileRunning + 1
725 " If there's already a VimDiff'ed window, restore it.
726 " There may only be one VCSVimDiff original window at a time.
728 if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
729 " Clear the existing vimdiff setup by removing the result buffers.
730 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
735 " Reset the vimdiff system, as 2 explicit versions were provided.
736 if exists('s:vimDiffSourceBuffer')
737 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
739 let resultBuffer = s:plugins[vcsType].Review([a:1])
741 echomsg 'Can''t open revision ' . a:1
744 let b:VCSCommandCommand = 'vimdiff'
746 let s:vimDiffScratchList = [resultBuffer]
747 " If no split method is defined, cheat, and set it to vertical.
749 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
750 let resultBuffer = s:plugins[vcsType].Review([a:2])
752 call s:OverrideOption('VCSCommandSplit')
755 echomsg 'Can''t open revision ' . a:1
758 let b:VCSCommandCommand = 'vimdiff'
760 let s:vimDiffScratchList += [resultBuffer]
763 call s:OverrideOption('VCSCommandEdit', 'split')
765 " Force splitting behavior, otherwise why use vimdiff?
766 call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
769 let resultBuffer = s:plugins[vcsType].Review([])
771 let resultBuffer = s:plugins[vcsType].Review([a:1])
774 call s:OverrideOption('VCSCommandSplit')
777 call s:OverrideOption('VCSCommandEdit')
780 echomsg 'Can''t open current revision'
783 let b:VCSCommandCommand = 'vimdiff'
786 if !exists('s:vimDiffSourceBuffer')
787 " New instance of vimdiff.
788 let s:vimDiffScratchList = [resultBuffer]
790 " This could have been invoked on a VCS result buffer, not the
793 execute 'buffer' originalBuffer
794 " Store info for later original buffer restore
795 let s:vimDiffRestoreCmd =
796 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
797 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
798 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
799 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
800 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
801 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
802 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
806 " Adding a window to an existing vimdiff
807 let s:vimDiffScratchList += [resultBuffer]
811 let s:vimDiffSourceBuffer = originalBuffer
813 " Avoid executing the modeline in the current buffer after the autocommand.
815 let currentBuffer = bufnr('%')
816 let saveModeline = getbufvar(currentBuffer, '&modeline')
818 call setbufvar(currentBuffer, '&modeline', 0)
819 silent do VCSCommand User VCSVimDiffFinish
821 call setbufvar(currentBuffer, '&modeline', saveModeline)
825 let s:isEditFileRunning = s:isEditFileRunning - 1
828 call s:ReportError(v:exception)
833 " Section: Public functions {{{1
835 " Function: VCSCommandGetVCSType() {{{2
836 " Sets the b:VCSCommandVCSType variable in the given buffer to the
837 " appropriate source control system name.
839 function! VCSCommandGetVCSType(buffer)
840 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
841 if strlen(vcsType) > 0
844 for vcsType in keys(s:plugins)
845 if s:plugins[vcsType].Identify(a:buffer)
846 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
850 throw 'No suitable plugin'
853 " Function: VCSCommandChdir(directory) {{{2
854 " Changes the current directory, respecting :lcd changes.
856 function! VCSCommandChdir(directory)
858 if exists("*haslocaldir") && haslocaldir()
861 execute command escape(a:directory, ' ')
864 " Function: VCSCommandChangeToCurrentFileDir() {{{2
865 " Go to the directory in which the given file is located.
867 function! VCSCommandChangeToCurrentFileDir(fileName)
868 let oldCwd = getcwd()
869 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
870 if strlen(newCwd) > 0
871 call VCSCommandChdir(newCwd)
876 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
877 " Attempts to locate the original file to which VCS operations were applied
878 " for a given buffer.
880 function! VCSCommandGetOriginalBuffer(vcsBuffer)
881 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
883 if bufexists(origBuffer)
886 " Original buffer no longer exists.
887 throw 'Original buffer for this VCS buffer no longer exists.'
895 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
896 " Allows VCS modules to register themselves.
898 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
899 let s:plugins[a:name] = a:commandMap
900 call add(s:pluginFiles, a:file)
901 let s:extendedMappings[a:name] = a:mappingMap
902 if !empty(a:mappingMap)
903 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
904 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
905 for mapname in keys(a:mappingMap)
906 execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
911 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
912 " General skeleton for VCS function execution.
913 " Returns: name of the new command buffer containing the command results
915 function! VCSCommandDoCommand(cmd, cmdName, statusText)
916 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
917 if originalBuffer == -1
918 throw 'Original buffer no longer exists, aborting.'
921 let fileName = resolve(bufname(originalBuffer))
923 " Work with netrw or other systems where a directory listing is displayed in
926 if isdirectory(fileName)
927 let realFileName = '.'
929 let realFileName = fnamemodify(fileName, ':t')
932 " Change to the directory of the current buffer. This is done for CVS, but
933 " is left in for other systems as it does not affect them negatively.
935 let oldCwd = VCSCommandChangeToCurrentFileDir(fileName)
937 let output = system(a:cmd . ' "' . realFileName . '"')
939 call VCSCommandChdir(oldCwd)
942 " HACK: if line endings in the repository have been corrupted, the output
943 " of the command will be confused.
944 let output = substitute(output, "\r", '', 'g')
946 " HACK: CVS diff command does not return proper error codes
947 if v:shell_error && (a:cmdName != 'diff' || getbufvar(originalBuffer, 'VCSCommandVCSType') != 'CVS')
948 if strlen(output) == 0
949 throw 'Version control command failed'
951 let output = substitute(output, '\n', ' ', 'g')
952 throw 'Version control command failed: ' . output
955 if strlen(output) == 0
956 " Handle case of no output. In this case, it is important to check the
957 " file status, especially since cvs edit/unedit may change the attributes
958 " of the file with no visible output.
964 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
968 " The last command left a blank line at the end of the buffer. If the
969 " last line is folded (a side effect of the 'put') then the attempt to
970 " remove the blank line will kill the last fold.
972 " This could be fixed by explicitly detecting whether the last line is
973 " within a fold, but I prefer to simply unfold the result buffer altogether.
982 " Define the environment and execute user-defined hooks.
984 silent do VCSCommand User VCSBufferCreated
988 " Function: VCSCommandGetOption(name, default) {{{2
989 " Grab a user-specified option to override the default provided. Options are
990 " searched in the window, buffer, then global spaces.
992 function! VCSCommandGetOption(name, default)
993 if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
994 return s:optionOverrides[a:name][-1]
995 elseif exists('w:' . a:name)
997 elseif exists('b:' . a:name)
999 elseif exists('g:' . a:name)
1006 " Function: VCSCommandGetRevision() {{{2
1007 " Global function for retrieving the current buffer's revision number.
1008 " Returns: Revision number or an empty string if an error occurs.
1010 function! VCSCommandGetRevision()
1011 if !exists('b:VCSCommandBufferInfo')
1012 let b:VCSCommandBufferInfo = s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
1015 if len(b:VCSCommandBufferInfo) > 0
1016 return b:VCSCommandBufferInfo[0]
1022 " Function: VCSCommandDisableBufferSetup() {{{2
1023 " Global function for deactivating the buffer autovariables.
1025 function! VCSCommandDisableBufferSetup()
1026 let g:VCSCommandEnableBufferSetup = 0
1027 silent! augroup! VCSCommandPlugin
1030 " Function: VCSCommandEnableBufferSetup() {{{2
1031 " Global function for activating the buffer autovariables.
1033 function! VCSCommandEnableBufferSetup()
1034 let g:VCSCommandEnableBufferSetup = 1
1035 augroup VCSCommandPlugin
1037 au BufEnter * call s:SetupBuffer()
1040 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1042 if g:loaded_VCSCommand == 2
1043 call s:SetupBuffer()
1047 " Function: VCSCommandGetStatusLine() {{{2
1048 " Default (sample) status line entry for VCS-controlled files. This is only
1049 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1050 " variable for how to do this).
1052 function! VCSCommandGetStatusLine()
1053 if exists('b:VCSCommandCommand')
1054 " This is a result buffer. Return nothing because the buffer name
1055 " contains information already.
1059 if exists('b:VCSCommandVCSType')
1060 \ && exists('g:VCSCommandEnableBufferSetup')
1061 \ && g:VCSCommandEnableBufferSetup
1062 \ && exists('b:VCSCommandBufferInfo')
1063 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1069 " Section: Command definitions {{{1
1070 " Section: Primary commands {{{2
1071 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>], 0))
1072 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>], 1)
1073 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1074 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>], 1)
1075 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>], 1)
1076 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1077 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>], 1)
1078 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>], 1))
1079 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>], 1)
1080 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', [], 1))
1081 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>], 1)
1082 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>], 1)
1083 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>], 1))
1084 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', [], 1))
1085 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1087 " Section: VCS buffer management commands {{{2
1088 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1089 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1091 " Allow reloading VCSCommand.vim
1092 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
1094 " Section: Plugin command mappings {{{1
1095 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1096 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1097 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1098 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1099 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1100 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1101 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1102 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1103 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1104 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1105 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1106 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1107 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1108 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1109 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1110 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1112 " Section: Default mappings {{{1
1114 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1115 if !hasmapto('<Plug>VCSAdd')
1116 nmap <unique> <Leader>ca <Plug>VCSAdd
1118 if !hasmapto('<Plug>VCSAnnotate')
1119 nmap <unique> <Leader>cn <Plug>VCSAnnotate
1121 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1122 nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1124 if !hasmapto('<Plug>VCSCommit')
1125 nmap <unique> <Leader>cc <Plug>VCSCommit
1127 if !hasmapto('<Plug>VCSDelete')
1128 nmap <unique> <Leader>cD <Plug>VCSDelete
1130 if !hasmapto('<Plug>VCSDiff')
1131 nmap <unique> <Leader>cd <Plug>VCSDiff
1133 if !hasmapto('<Plug>VCSGotoOriginal')
1134 nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1136 if !hasmapto('<Plug>VCSInfo')
1137 nmap <unique> <Leader>ci <Plug>VCSInfo
1139 if !hasmapto('<Plug>VCSLock')
1140 nmap <unique> <Leader>cL <Plug>VCSLock
1142 if !hasmapto('<Plug>VCSLog')
1143 nmap <unique> <Leader>cl <Plug>VCSLog
1145 if !hasmapto('<Plug>VCSRevert')
1146 nmap <unique> <Leader>cq <Plug>VCSRevert
1148 if !hasmapto('<Plug>VCSReview')
1149 nmap <unique> <Leader>cr <Plug>VCSReview
1151 if !hasmapto('<Plug>VCSStatus')
1152 nmap <unique> <Leader>cs <Plug>VCSStatus
1154 if !hasmapto('<Plug>VCSUnlock')
1155 nmap <unique> <Leader>cU <Plug>VCSUnlock
1157 if !hasmapto('<Plug>VCSUpdate')
1158 nmap <unique> <Leader>cu <Plug>VCSUpdate
1160 if !hasmapto('<Plug>VCSVimDiff')
1161 nmap <unique> <Leader>cv <Plug>VCSVimDiff
1165 " Section: Menu items {{{1
1166 amenu <silent> &Plugin.VCS.&Add <Plug>VCSAdd
1167 amenu <silent> &Plugin.VCS.A&nnotate <Plug>VCSAnnotate
1168 amenu <silent> &Plugin.VCS.&Commit <Plug>VCSCommit
1169 amenu <silent> &Plugin.VCS.Delete <Plug>VCSDelete
1170 amenu <silent> &Plugin.VCS.&Diff <Plug>VCSDiff
1171 amenu <silent> &Plugin.VCS.&Info <Plug>VCSInfo
1172 amenu <silent> &Plugin.VCS.&Log <Plug>VCSLog
1173 amenu <silent> &Plugin.VCS.Revert <Plug>VCSRevert
1174 amenu <silent> &Plugin.VCS.&Review <Plug>VCSReview
1175 amenu <silent> &Plugin.VCS.&Status <Plug>VCSStatus
1176 amenu <silent> &Plugin.VCS.&Update <Plug>VCSUpdate
1177 amenu <silent> &Plugin.VCS.&VimDiff <Plug>VCSVimDiff
1179 " Section: Autocommands to restore vimdiff state {{{1
1180 augroup VimDiffRestore
1182 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1185 " Section: Optional activation of buffer management {{{1
1187 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1188 call VCSCommandEnableBufferSetup()
1191 " Section: VIM shutdown hook {{{1
1193 " Close all result buffers when VIM exits, to prevent them from being restored
1196 " Function: s:CloseAllResultBuffers() {{{2
1197 " Closes all vcscommand result buffers.
1198 function! s:CloseAllResultBuffers()
1199 " This avoids using bufdo as that may load buffers already loaded in another
1200 " vim process, resulting in an error.
1202 let buffmaxnr = bufnr('$')
1203 while buffnr <= buffmaxnr
1204 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1207 let buffnr = buffnr + 1
1211 augroup VCSCommandVIMShutdown
1213 au VimLeavePre * call s:CloseAllResultBuffers()
1216 " Section: Plugin completion {{{1
1218 let loaded_VCSCommand = 2
1220 silent do VCSCommand User VCSPluginFinish