1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of various Version
4 " Control Systems, such as CVS, SVN, SVK, and git.
6 " Maintainer: Bob Hiestand <bob.hiestand@gmail.com>
8 " Copyright (c) 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. Several options include the name of the
37 " version control system in the option name. Such options use the placeholder
38 " text '{VCSType}', which would be replaced in actual usage with 'CVS' or
39 " 'SVN', for instance.
41 " Command documentation {{{2
43 " VCSAdd Adds the current file to source control.
45 " VCSAnnotate[!] Displays the current file with each line annotated with the
46 " version in which it was most recently changed. If an
47 " argument is given, the argument is used as a revision
48 " number to display. If not given an argument, it uses the
49 " most recent version of the file on the current branch.
50 " Additionally, if the current buffer is a VCSAnnotate buffer
51 " already, the version number on the current line is used.
53 " If '!' is used, the view of the annotated buffer is split
54 " so that the annotation is in a separate window from the
55 " content, and each is highlighted separately.
57 " VCSBlame Alias for 'VCSAnnotate'.
59 " VCSCommit[!] Commits changes to the current file to source control.
61 " If called with arguments, the arguments are the log message.
63 " If '!' is used, an empty log message is committed.
65 " If called with no arguments, this is a two-step command.
66 " The first step opens a buffer to accept a log message.
67 " When that buffer is written, it is automatically closed and
68 " the file is committed using the information from that log
69 " message. The commit can be abandoned if the log message
70 " buffer is deleted or wiped before being written.
72 " VCSDelete Deletes the current file and removes it from source control.
74 " VCSDiff With no arguments, this displays the differences between
75 " the current file and its parent version under source
76 " control in a new scratch buffer.
78 " With one argument, the diff is performed on the
79 " current file against the specified revision.
81 " With two arguments, the diff is performed between the
82 " specified revisions of the current file.
84 " This command uses the 'VCSCommand{VCSType}DiffOpt' variable
85 " to specify diff options. If that variable does not exist,
86 " a plugin-specific default is used. If you wish to have no
87 " options, then set it to the empty string.
89 " VCSGotoOriginal Jumps to the source buffer if the current buffer is a VCS
90 " scratch buffer. If VCSGotoOriginal[!] is used, remove all
91 " VCS scratch buffers associated with the original file.
93 " VCSInfo Displays extended information about the current file in a
96 " VCSLock Locks the current file in order to prevent other users from
97 " concurrently modifying it. The exact semantics of this
98 " command depend on the underlying VCS.
100 " VCSLog Displays the version history of the current file in a new
103 " VCSRemove Alias for 'VCSDelete'.
105 " VCSRevert Replaces the modified version of the current file with the
106 " most recent version from the repository.
108 " VCSReview Displays a particular version of the current file in a new
109 " scratch buffer. If no argument is given, the most recent
110 " version of the file on the current branch is retrieved.
112 " VCSStatus Displays versioning information about the current file in a
113 " new scratch buffer.
115 " VCSUnlock Unlocks the current file in order to allow other users from
116 " concurrently modifying it. The exact semantics of this
117 " command depend on the underlying VCS.
119 " VCSUpdate Updates the current file with any relevant changes from the
122 " VCSVimDiff Uses vimdiff to display differences between versions of the
125 " If no revision is specified, the most recent version of the
126 " file on the current branch is used. With one argument,
127 " that argument is used as the revision as above. With two
128 " arguments, the differences between the two revisions is
129 " displayed using vimdiff.
131 " With either zero or one argument, the original buffer is
132 " used to perform the vimdiff. When the scratch buffer is
133 " closed, the original buffer will be returned to normal
136 " Once vimdiff mode is started using the above methods,
137 " additional vimdiff buffers may be added by passing a single
138 " version argument to the command. There may be up to 4
139 " vimdiff buffers total.
141 " Using the 2-argument form of the command resets the vimdiff
142 " to only those 2 versions. Additionally, invoking the
143 " command on a different file will close the previous vimdiff
146 " Mapping documentation: {{{2
148 " By default, a mapping is defined for each command. User-provided mappings
149 " can be used instead by mapping to <Plug>CommandName, for instance:
151 " nmap ,ca <Plug>VCSAdd
153 " The default mappings are as follow:
156 " <Leader>cn VCSAnnotate
157 " <Leader>cN VCSAnnotate!
158 " <Leader>cc VCSCommit
159 " <Leader>cD VCSDelete
161 " <Leader>cg VCSGotoOriginal
162 " <Leader>cG VCSGotoOriginal!
166 " <Leader>cr VCSReview
167 " <Leader>cs VCSStatus
168 " <Leader>cu VCSUpdate
169 " <Leader>cU VCSUnlock
170 " <Leader>cv VCSVimDiff
172 " Options documentation: {{{2
174 " Several variables are checked by the script to determine behavior as follow:
176 " VCSCommandCommitOnWrite
177 " This variable, if set to a non-zero value, causes the pending commit to
178 " take place immediately as soon as the log message buffer is written. If
179 " set to zero, only the VCSCommit mapping will cause the pending commit to
180 " occur. If not set, it defaults to 1.
182 " VCSCommandDeleteOnHide
183 " This variable, if set to a non-zero value, causes the temporary VCS result
184 " buffers to automatically delete themselves when hidden.
186 " VCSCommand{VCSType}DiffOpt
187 " This variable, if set, determines the options passed to the diff command
188 " of the underlying VCS. Each VCS plugin defines a default value.
190 " VCSCommandDiffSplit
191 " This variable overrides the VCSCommandSplit variable, but only for buffers
192 " created with VCSVimDiff.
194 " VCSCommandDisableAll
195 " This variable, if set, prevents the plugin or any extensions from loading
196 " at all. This is useful when a single runtime distribution is used on
197 " multiple systems with varying versions.
199 " VCSCommandDisableMappings
200 " This variable, if set to a non-zero value, prevents the default command
201 " mappings from being set.
203 " VCSCommandDisableExtensionMappings
204 " This variable, if set to a non-zero value, prevents the default command
205 " mappings from being set for commands specific to an individual VCS.
207 " VCSCommandDisableMenu
208 " This variable, if set to a non-zero value, prevents the default command
209 " menu from being set.
212 " This variable controls whether to split the current window to display a
213 " scratch buffer ('split'), or to display it in the current buffer ('edit').
214 " If not set, it defaults to 'split'.
216 " VCSCommandEnableBufferSetup
217 " This variable, if set to a non-zero value, activates VCS buffer management
218 " mode. This mode means that the buffer variable 'VCSRevision' is set if
219 " the file is VCS-controlled. This is useful for displaying version
220 " information in the status bar. Additional options may be set by
221 " individual VCS plugins.
224 " This variable, if set, overrides the default mappings used for shortcuts.
225 " It should be a List of 2-element Lists, each containing a shortcut and
226 " function name pair.
228 " VCSCommandMapPrefix
229 " This variable, if set, overrides the default mapping prefix ('<Leader>c').
230 " This allows customization of the mapping space used by the vcscommand
233 " VCSCommandMenuPriority
234 " This variable, if set, overrides the default menu priority '' (empty)
237 " This variable, if set, overrides the default menu root 'Plugin.VCS'
239 " VCSCommandResultBufferNameExtension
240 " This variable, if set to a non-blank value, is appended to the name of the
241 " VCS command output buffers. For example, '.vcs'. Using this option may
242 " help avoid problems caused by autocommands dependent on file extension.
244 " VCSCommandResultBufferNameFunction
245 " This variable, if set, specifies a custom function for naming VCS command
246 " output buffers. This function will be passed the following arguments:
248 " command - name of the VCS command being executed (such as 'Log' or
251 " originalBuffer - buffer number of the source file.
253 " vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
255 " statusText - extra text associated with the VCS action (such as version
259 " This variable controls the orientation of the various window splits that
260 " may occur (such as with VCSVimDiff, when using a VCS command on a VCS
261 " command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
262 " If set to 'horizontal', the resulting windows will be on stacked on top of
263 " one another. If set to 'vertical', the resulting windows will be
264 " side-by-side. If set to 'bottom', the resulting windows will be shown
266 " If not set, it defaults to 'horizontal' for all but
267 " VCSVimDiff windows.
269 " VCSCommandVCSTypeOverride
270 " This variable allows the VCS type detection to be overridden on a
271 " path-by-path basis. The value of this variable is expected to be a List
272 " of Lists. Each high-level List item is a List containing two elements.
273 " The first element is a regular expression that will be matched against the
274 " full file name of a given buffer. If it matches, the second element will
275 " be used as the VCS type.
277 " VCSCommandVCSTypePreference
278 " This variable allows the VCS type detection to be weighted towards a
279 " specific VCS, in case more than one potential VCS is detected as useable.
280 " The format of the variable is either a list or a space-separated string
281 " containing the ordered-by-preference abbreviations of the preferred VCS
284 " Event documentation {{{2
285 " For additional customization, VCSCommand.vim uses User event autocommand
286 " hooks. Each event is in the VCSCommand group, and different patterns
287 " match the various hooks.
289 " For instance, the following could be added to the vimrc to provide a 'q'
290 " mapping to quit a VCS scratch buffer:
293 " au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
296 " The following hooks are available:
298 " VCSBufferCreated This event is fired just after a VCS command
299 " output buffer is created. It is executed
300 " within the context of the new buffer.
302 " VCSBufferSetup This event is fired just after VCS buffer setup
303 " occurs, if enabled.
305 " VCSPluginInit This event is fired when the VCSCommand plugin
308 " VCSPluginFinish This event is fired just after the VCSCommand
311 " VCSVimDiffFinish This event is fired just after the VCSVimDiff
312 " command executes to allow customization of,
313 " for instance, window placement and focus.
315 " Section: Plugin header {{{1
317 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
318 " completes. This allows various actions to only be taken by functions after
319 " system initialization.
321 if exists('VCSCommandDisableAll')
325 if exists('loaded_VCSCommand')
328 let loaded_VCSCommand = 1
331 echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
338 " Section: Event group setup {{{1
343 augroup VCSCommandCommit
346 " Section: Plugin initialization {{{1
347 silent do VCSCommand User VCSPluginInit
349 " Section: Constants declaration {{{1
351 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
352 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
354 " Section: Script variable initialization {{{1
356 " Hidden functions for use by extensions
357 let s:VCSCommandUtility = {}
359 " plugin-specific information: {vcs -> [script, {command -> function}, {key -> mapping}]}
362 " Stack of dictionaries representing nested options
363 let s:executionContext = []
365 " state flag used to vary behavior of certain automated actions
366 let s:isEditFileRunning = 0
368 " Section: Utility functions {{{1
370 " Function: s:ReportError(mapping) {{{2
371 " Displays the given error in a consistent faction. This is intended to be
372 " invoked from a catch statement.
374 function! s:ReportError(error)
375 echohl WarningMsg|echomsg 'VCSCommand: ' . a:error|echohl None
378 " Function: s:VCSCommandUtility.system(...) {{{2
379 " Replacement for system() function. This version protects the quoting in the
380 " command line on Windows systems.
382 function! s:VCSCommandUtility.system(...)
383 if (has("win32") || has("win64")) && &sxq !~ '"'
388 let output = call('system', a:000)
389 if exists('*iconv') && has('multi_byte')
390 if(strlen(&tenc) && &tenc != &enc)
391 let output = iconv(output, &tenc, &enc)
393 let originalBuffer = VCSCommandGetOriginalBuffer(VCSCommandGetOption('VCSCommandEncodeAsFile', 0))
395 let fenc = getbufvar(originalBuffer, '&fenc')
397 let output = iconv(output, fenc, &enc)
404 if exists("save_sxq")
411 " Function: s:VCSCommandUtility.addMenuItem(shortcut, command) {{{2
412 " Adds the given menu item.
414 function! s:VCSCommandUtility.addMenuItem(shortcut, command)
416 exe 'amenu <silent> '.s:menuPriority.' '.s:menuRoot.'.'.a:shortcut.' '.a:command
420 " Function: s:VCSCommandUtility.pushContext(context) {{{2
421 " Adds a dictionary containing current options to the stack.
423 function! s:VCSCommandUtility.pushContext(context)
424 call insert(s:executionContext, a:context)
427 " Function: s:VCSCommandUtility.popContext() {{{2
428 " Removes a dictionary containing current options from the stack.
430 function! s:VCSCommandUtility.popContext()
431 call remove(s:executionContext, 0)
434 " Function: s:ClearMenu() {{{2
435 " Removes all VCSCommand menu items
436 function! s:ClearMenu()
438 execute 'aunmenu' s:menuRoot
442 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
443 " Creates the given mapping by prepending the contents of
444 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
445 " mapping it to the given plugin function. If a mapping exists for the
446 " specified shortcut + prefix, emit an error but continue. If a mapping
447 " exists for the specified function, do nothing.
449 function! s:CreateMapping(shortcut, expansion, display)
450 let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
451 if !hasmapto(a:expansion)
453 execute 'nmap <silent> <unique>' lhs a:expansion
454 catch /^Vim(.*):E227:/
456 echohl WarningMsg|echomsg 'VCSCommand: mapping ''' . lhs . ''' already exists, refusing to overwrite. The mapping for ' . a:display . ' will not be available.'|echohl None
462 " Function: s:ExecuteExtensionMapping(mapping) {{{2
463 " Invokes the appropriate extension mapping depending on the type of the
466 function! s:ExecuteExtensionMapping(mapping)
467 let buffer = bufnr('%')
468 let vcsType = VCSCommandGetVCSType(buffer)
469 if !has_key(s:plugins, vcsType)
470 throw 'Unknown VCS type: ' . vcsType
472 if !has_key(s:plugins[vcsType][2], a:mapping)
473 throw 'This extended mapping is not defined for ' . vcsType
475 silent execute 'normal!' ':' . s:plugins[vcsType][2][a:mapping] . "\<CR>"
478 function! VCSIsNERDTreeBuffer(originalBuffer)
479 return getbufvar(a:originalBuffer, "&filetype") == "nerdtree"
482 function! VCSGetNERDTreeBufferName(buffer)
483 return getbufvar(a:buffer, 'NERDTreeRoot').path.str()
486 " Function: s:ExecuteVCSCommand(command, argList) {{{2
487 " Calls the indicated plugin-specific VCS command on the current buffer.
488 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
491 function! s:ExecuteVCSCommand(command, argList)
493 let buffer = bufnr('%')
495 let vcsType = VCSCommandGetVCSType(buffer)
496 if !has_key(s:plugins, vcsType)
497 throw 'Unknown VCS type: ' . vcsType
500 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
501 let bufferName = bufname(originalBuffer)
502 if VCSIsNERDTreeBuffer(originalBuffer)
503 let bufferName = VCSGetNERDTreeBufferName(originalBuffer)
506 " It is already known that the directory is under VCS control. No further
507 " checks are needed. Otherwise, perform some basic sanity checks to avoid
508 " VCS-specific error messages from confusing things.
509 if !isdirectory(bufferName)
510 if !filereadable(bufferName)
511 throw 'No such file ' . bufferName
515 let functionMap = s:plugins[vcsType][1]
516 if !has_key(functionMap, a:command)
517 throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
519 return functionMap[a:command](a:argList)
521 call s:ReportError(v:exception)
526 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
527 " Default method of generating the name for VCS result buffers. This can be
528 " overridden with the VCSResultBufferNameFunction variable.
530 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
531 let fileName = bufname(a:originalBuffer)
533 if VCSIsNERDTreeBuffer(a:originalBuffer)
534 let fileName = VCSGetNERDTreeBufferName(a:originalBuffer)
537 let bufferName = a:vcsType . ' ' . a:command
538 if strlen(a:statusText) > 0
539 let bufferName .= ' ' . a:statusText
541 let bufferName .= ' ' . fileName
543 let versionedBufferName = bufferName
544 while bufexists(versionedBufferName)
546 let versionedBufferName = bufferName . ' (' . counter . ')'
548 return versionedBufferName
551 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
552 " Method of generating the name for VCS result buffers that uses the original
553 " file name with the VCS type and command appended as extensions.
555 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
556 let fileName = bufname(a:originalBuffer)
558 if VCSIsNERDTreeBuffer(a:originalBuffer)
559 let fileName = VCSGetNERDTreeBufferName(a:originalBuffer)
562 let bufferName = a:vcsType . ' ' . a:command
563 if strlen(a:statusText) > 0
564 let bufferName .= ' ' . a:statusText
566 let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
568 let versionedBufferName = bufferName
569 while bufexists(versionedBufferName)
571 let versionedBufferName = '(' . counter . ') ' . bufferName
573 return versionedBufferName
576 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
577 " Creates a new buffer of the given name and associates it with the given
580 function! s:EditFile(command, originalBuffer, statusText)
581 let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
583 " Protect against useless buffer set-up
584 let s:isEditFileRunning += 1
586 if winnr('$') > 1 && VCSIsNERDTreeBuffer(bufnr('%'))
587 let width = winwidth(0)
590 execute winnr('#') 'wincmd w'
592 execute "vert resize" width
593 execute winnr('#') 'wincmd w'
595 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
596 if editCommand == 'split'
597 let splitType = VCSCommandGetOption('VCSCommandSplit', 'horizontal')
598 if splitType == 'horizontal'
600 elseif splitType == 'bottom'
604 vert rightbelow split
611 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
614 let s:isEditFileRunning -= 1
618 " Function: s:IdentifyVCSType() {{{2
619 " This function implements the non-cached identification strategy for
620 " VcsCommandGetVCSType().
622 " Returns: VCS type name identified for the given buffer; an exception is
623 " thrown in case no type can be identified.
625 function! s:IdentifyVCSType(buffer)
626 let fullPath = bufname(a:buffer)
627 if VCSIsNERDTreeBuffer(a:buffer)
628 let fullPath = VCSGetNERDTreeBufferName(a:buffer)
630 let fullPath = resolve(fullPath)
631 if exists("g:VCSCommandVCSTypeOverride")
632 let dirpath = fnamemodify(fullPath), ':p')
633 for [path, vcsType] in g:VCSCommandVCSTypeOverride
634 if match(dirpath, path) > -1
641 let exactMatchCount = 0
642 for vcsType in keys(s:plugins)
643 let identified = s:plugins[vcsType][1].Identify(fullPath)
645 if identified == g:VCSCOMMAND_IDENTIFY_EXACT
646 let exactMatch = vcsType
647 let exactMatchCount += 1
649 call add(matches, [vcsType, identified])
654 elseif len(matches) == 0
655 throw 'No suitable plugin'
657 let preferences = VCSCommandGetOption("VCSCommandVCSTypePreference", [])
658 if len(preferences) > 0
659 if type(preferences) == 1
660 let listPreferences = split(preferences, '\W\+')
662 let preferences = listPreferences
664 for preferred in preferences
665 for [vcsType, identified] in matches
666 if vcsType ==? preferred
673 if exactMatchCount == 1
677 throw 'can''t identify VCS type for current buffer due to too many matching VCS: ' . join(map(matches, 'v:val[0]'))
681 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
682 " Creates convenience buffer variables and the name of a vcscommand result
685 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
686 let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
687 if nameExtension == ''
688 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
690 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
693 let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
695 let b:VCSCommandCommand = a:command
696 let b:VCSCommandOriginalBuffer = a:originalBuffer
697 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
698 let b:VCSCommandVCSType = a:vcsType
699 if a:statusText != ''
700 let b:VCSCommandStatusText = a:statusText
703 setlocal buftype=nofile
705 let &filetype = tolower(a:vcsType . a:command)
707 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
708 setlocal bufhidden=delete
710 silent noautocmd file `=name`
713 " Function: s:SetupBuffer() {{{2
714 " Attempts to set the b:VCSCommandBufferInfo variable
716 function! s:SetupBuffer()
717 if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
718 " This buffer is already set up.
722 if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
723 " No special status for special buffers other than directory buffers.
727 if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
728 unlet! b:VCSCommandBufferSetup
733 let vcsType = VCSCommandGetVCSType(bufnr('%'))
734 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
735 silent do VCSCommand User VCSBufferSetup
736 catch /No suitable plugin/
737 " This is not a VCS-controlled file.
738 let b:VCSCommandBufferInfo = []
741 let b:VCSCommandBufferSetup = 1
744 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
745 " Resets the buffer setup state of the original buffer for a given VCS scratch
747 " Returns: The VCS buffer number in a passthrough mode.
749 function! s:MarkOrigBufferForSetup(buffer)
752 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
753 " This should never not work, but I'm paranoid
754 if origBuffer != a:buffer
755 call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
761 " Function: s:WipeoutCommandBuffers() {{{2
762 " Clears all current VCS output buffers of the specified type for a given source.
764 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
766 while buffer <= bufnr('$')
767 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
768 if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
772 let buffer = buffer + 1
776 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
777 " Checks whether the given buffer is one whose deletion should trigger
778 " restoration of an original buffer after it was diffed. If so, it executes
779 " the appropriate setting command stored with that original buffer.
781 function! s:VimDiffRestore(vimDiffBuff)
782 let s:isEditFileRunning += 1
784 if exists('t:vcsCommandVimDiffSourceBuffer')
785 if a:vimDiffBuff == t:vcsCommandVimDiffSourceBuffer
786 " Original file is being removed.
787 unlet! t:vcsCommandVimDiffSourceBuffer
788 unlet! t:vcsCommandVimDiffRestoreCmd
789 unlet! t:vcsCommandVimDiffScratchList
791 let index = index(t:vcsCommandVimDiffScratchList, a:vimDiffBuff)
793 call remove(t:vcsCommandVimDiffScratchList, index)
794 if len(t:vcsCommandVimDiffScratchList) == 0
795 if exists('t:vcsCommandVimDiffRestoreCmd')
796 " All scratch buffers are gone, reset the original.
797 " Only restore if the source buffer is still in Diff mode
799 let sourceWinNR = bufwinnr(t:vcsCommandVimDiffSourceBuffer)
801 " The buffer is visible in at least one window
802 let currentWinNR = winnr()
803 while winbufnr(sourceWinNR) != -1
804 if winbufnr(sourceWinNR) == t:vcsCommandVimDiffSourceBuffer
805 execute sourceWinNR . 'wincmd w'
806 if getwinvar(0, '&diff')
807 execute t:vcsCommandVimDiffRestoreCmd
810 let sourceWinNR = sourceWinNR + 1
812 execute currentWinNR . 'wincmd w'
814 " The buffer is hidden. It must be visible in order to set the
816 let currentBufNR = bufnr('')
817 execute 'hide buffer' t:vcsCommandVimDiffSourceBuffer
818 if getwinvar(0, '&diff')
819 execute t:vcsCommandVimDiffRestoreCmd
821 execute 'hide buffer' currentBufNR
824 unlet t:vcsCommandVimDiffRestoreCmd
826 " All buffers are gone.
827 unlet t:vcsCommandVimDiffSourceBuffer
828 unlet t:vcsCommandVimDiffScratchList
834 let s:isEditFileRunning -= 1
838 " Section: Generic VCS command functions {{{1
840 " Function: s:VCSAnnotate(...) {{{2
841 function! s:VCSAnnotate(bang, ...)
842 call s:VCSCommandUtility.pushContext({'VCSCommandEncodeAsFile': bufnr('%')})
845 let currentBuffer = bufnr('%')
846 let originalBuffer = VCSCommandGetOriginalBuffer(currentBuffer)
848 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
849 if annotateBuffer == -1
852 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
853 let vcsType = VCSCommandGetVCSType(annotateBuffer)
854 let functionMap = s:plugins[vcsType][1]
856 if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
857 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
859 let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
861 return annotateBuffer
864 let originalFileType = getbufvar(originalBuffer, '&ft')
865 let annotateFileType = getbufvar(annotateBuffer, '&ft')
867 let saveselection = &selection
868 set selection=inclusive
870 execute "normal! 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
872 let &selection = saveselection
875 call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
879 execute "normal!" . (col('$') + (&number ? &numberwidth : 0)). "\<c-w>|"
880 call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
884 if currentBuffer == originalBuffer
885 " Starting from the original source buffer, so the
886 " current line is relevant.
888 " No argument list means that we're annotating
889 " the current version, so jumping to the same
890 " line is the expected action.
891 execute "normal!" line . 'G'
893 " The execution of the buffer created autocommand
894 " re-folds the buffer. Display the current line
901 return annotateBuffer
903 call s:ReportError(v:exception)
906 call s:VCSCommandUtility.popContext()
910 " Function: s:VCSCommit() {{{2
911 function! s:VCSCommit(bang, message)
913 let vcsType = VCSCommandGetVCSType(bufnr('%'))
914 if !has_key(s:plugins, vcsType)
915 throw 'Unknown VCS type: ' . vcsType
918 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
920 " Handle the commit message being specified. If a message is supplied, it
921 " is used; if bang is supplied, an empty message is used; otherwise, the
922 " user is provided a buffer from which to edit the commit message.
924 if strlen(a:message) > 0 || a:bang == '!'
925 return s:VCSFinishCommit([a:message], originalBuffer)
928 call s:EditFile('commitlog', originalBuffer, '')
929 setlocal ft=vcscommit
931 " Create a commit mapping.
933 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
935 silent 0put ='VCS: ----------------------------------------------------------------------'
936 silent put ='VCS: Please enter log message. Lines beginning with ''VCS:'' are removed automatically.'
937 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
939 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
940 setlocal buftype=acwrite
941 au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
942 silent put ='VCS: or write this buffer'
945 silent put ='VCS: ----------------------------------------------------------------------'
948 silent do VCSCommand User VCSBufferCreated
950 call s:ReportError(v:exception)
955 " Function: s:VCSFinishCommitWithBuffer() {{{2
956 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
957 " which removes all lines starting with 'VCS:'.
959 function! s:VCSFinishCommitWithBuffer()
961 let currentBuffer = bufnr('%')
962 let logMessageList = getbufline('%', 1, '$')
963 call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
964 let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
966 execute 'bw' currentBuffer
971 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
972 function! s:VCSFinishCommit(logMessageList, originalBuffer)
973 let messageFileName = tempname()
974 if exists('*iconv') && has('multi_byte')
975 if(strlen(&tenc) && &tenc != &enc)
976 call map(a:logMessageList, 'iconv(v:val, &enc, &tenc)')
979 call writefile(a:logMessageList, messageFileName)
981 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
985 return s:MarkOrigBufferForSetup(resultBuffer)
987 call delete(messageFileName)
991 " Function: s:VCSGotoOriginal(bang) {{{2
992 function! s:VCSGotoOriginal(bang)
993 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
994 if originalBuffer > 0
995 let origWinNR = bufwinnr(originalBuffer)
997 execute 'buffer' originalBuffer
999 execute origWinNR . 'wincmd w'
1003 let buffmaxnr = bufnr('$')
1004 while buffnr <= buffmaxnr
1005 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
1008 let buffnr = buffnr + 1
1014 function! s:VCSDiff(...) "{{{2
1015 call s:VCSCommandUtility.pushContext({'VCSCommandEncodeAsFile': bufnr('%')})
1017 let resultBuffer = s:ExecuteVCSCommand('Diff', a:000)
1019 let &filetype = 'diff'
1020 elseif resultBuffer == 0
1021 echomsg 'No differences found'
1025 call s:VCSCommandUtility.popContext()
1029 function! s:VCSReview(...) "{{{2
1030 call s:VCSCommandUtility.pushContext({'VCSCommandEncodeAsFile': bufnr('%')})
1032 let resultBuffer = s:ExecuteVCSCommand('Review', a:000)
1034 let &filetype = getbufvar(b:VCSCommandOriginalBuffer, '&filetype')
1038 call s:VCSCommandUtility.popContext()
1042 " Function: s:VCSVimDiff(...) {{{2
1043 function! s:VCSVimDiff(...)
1045 let vcsType = VCSCommandGetVCSType(bufnr('%'))
1046 if !has_key(s:plugins, vcsType)
1047 throw 'Unknown VCS type: ' . vcsType
1049 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1050 let s:isEditFileRunning = s:isEditFileRunning + 1
1052 " If there's already a VimDiff'ed window, restore it.
1053 " There may only be one VCSVimDiff original window at a time.
1055 if exists('t:vcsCommandVimDiffSourceBuffer') && t:vcsCommandVimDiffSourceBuffer != originalBuffer
1056 " Clear the existing vimdiff setup by removing the result buffers.
1057 call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
1060 let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
1061 let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
1062 let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
1066 " Reset the vimdiff system, as 2 explicit versions were provided.
1067 if exists('t:vcsCommandVimDiffSourceBuffer')
1068 call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
1070 let resultBuffer = s:VCSReview(a:1)
1072 echomsg 'Can''t open revision ' . a:1
1075 let b:VCSCommandCommand = 'vimdiff'
1077 let t:vcsCommandVimDiffScratchList = [resultBuffer]
1078 " If no split method is defined, cheat, and set it to vertical.
1079 call s:VCSCommandUtility.pushContext({'VCSCommandSplit': orientation})
1081 let resultBuffer = s:VCSReview(a:2)
1083 call s:VCSCommandUtility.popContext()
1086 echomsg 'Can''t open revision ' . a:1
1089 let b:VCSCommandCommand = 'vimdiff'
1091 let t:vcsCommandVimDiffScratchList += [resultBuffer]
1093 " Add new buffer. Force splitting behavior, otherwise why use vimdiff?
1094 call s:VCSCommandUtility.pushContext({'VCSCommandEdit': 'split', 'VCSCommandSplit': orientation})
1097 let resultBuffer = s:VCSReview()
1099 let resultBuffer = s:VCSReview(a:1)
1102 call s:VCSCommandUtility.popContext()
1105 echomsg 'Can''t open current revision'
1108 let b:VCSCommandCommand = 'vimdiff'
1111 if !exists('t:vcsCommandVimDiffSourceBuffer')
1112 " New instance of vimdiff.
1113 let t:vcsCommandVimDiffScratchList = [resultBuffer]
1115 " This could have been invoked on a VCS result buffer, not the
1118 execute 'buffer' originalBuffer
1119 " Store info for later original buffer restore
1120 let t:vcsCommandVimDiffRestoreCmd =
1121 \ 'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
1122 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
1123 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
1124 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
1125 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
1126 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
1127 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
1128 if has('cursorbind')
1129 let t:vcsCommandVimDiffRestoreCmd .= '|call setbufvar('.originalBuffer.', ''&cursorbind'', '.getbufvar(originalBuffer, '&cursorbind').')'
1131 let t:vcsCommandVimDiffRestoreCmd .= '|if &foldmethod==''manual''|execute ''normal! zE''|endif'
1135 " Adding a window to an existing vimdiff
1136 let t:vcsCommandVimDiffScratchList += [resultBuffer]
1140 let t:vcsCommandVimDiffSourceBuffer = originalBuffer
1142 " Avoid executing the modeline in the current buffer after the autocommand.
1144 let currentBuffer = bufnr('%')
1145 let saveModeline = getbufvar(currentBuffer, '&modeline')
1147 call setbufvar(currentBuffer, '&modeline', 0)
1148 silent do VCSCommand User VCSVimDiffFinish
1150 call setbufvar(currentBuffer, '&modeline', saveModeline)
1154 let s:isEditFileRunning = s:isEditFileRunning - 1
1157 call s:ReportError(v:exception)
1162 " Section: Public functions {{{1
1164 " Function: VCSCommandGetVCSType() {{{2
1165 " This function sets the b:VCSCommandVCSType variable in the given buffer to the
1166 " appropriate source control system name and returns the same name.
1168 " Returns: VCS type name identified for the given buffer. An exception is
1169 " thrown if no type can be identified.
1171 " Rules for determining type:
1172 " 1. use previously-cached value
1173 " 2. use value from 'VCSCommandVCSTypeOverride'
1174 " 3. use single match
1175 " 4. use first matching value from 'VCSCommandTypePreference'
1176 " 5. use single exact match
1177 " 6. error if multiple matching types
1178 " 7. error if no matching types
1180 function! VCSCommandGetVCSType(buffer)
1181 let vcsType = VCSCommandGetOption('VCSCommandVCSTypeExplicitOverride', '')
1182 if len(vcsType) == 0
1183 let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
1184 if strlen(vcsType) == 0
1185 let vcsType = s:IdentifyVCSType(a:buffer)
1186 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1192 " Function: VCSCommandChdir(directory) {{{2
1193 " Changes the current directory, respecting :lcd changes.
1195 function! VCSCommandChdir(directory)
1197 if exists("*haslocaldir") && haslocaldir()
1200 if exists("*fnameescape")
1201 execute command fnameescape(a:directory)
1203 execute command escape(a:directory, ' ')
1207 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1208 " Go to the directory in which the given file is located.
1210 function! VCSCommandChangeToCurrentFileDir(fileName)
1211 let oldCwd = getcwd()
1212 let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1213 if strlen(newCwd) > 0
1214 call VCSCommandChdir(newCwd)
1219 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1220 " Attempts to locate the original file to which VCS operations were applied
1221 " for a given buffer.
1223 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1224 let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1226 if bufexists(origBuffer)
1229 " Original buffer no longer exists.
1230 throw 'Original buffer for this VCS buffer no longer exists.'
1233 " No original buffer
1238 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1239 " Allows VCS modules to register themselves.
1241 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1242 let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1243 if !empty(a:mappingMap)
1244 \ && !exists("g:no_plugin_maps")
1245 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1246 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1247 for shortcut in keys(a:mappingMap)
1248 let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1249 call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1252 return s:VCSCommandUtility
1255 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1256 " General skeleton for VCS function execution. The given command is executed
1257 " after appending the current buffer name (or substituting it for
1258 " <VCSCOMMANDFILE>, if such a token is present). The output is captured in a
1261 " The optional 'options' Dictionary may contain the following options:
1262 " allowNonZeroExit: if non-zero, if the underlying VCS command has a
1263 " non-zero exit status, the command is still considered
1264 " successfuly. This defaults to zero.
1265 " Returns: name of the new command buffer containing the command results
1267 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1268 let allowNonZeroExit = 0
1269 if has_key(a:options, 'allowNonZeroExit')
1270 let allowNonZeroExit = a:options.allowNonZeroExit
1273 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1274 if originalBuffer == -1
1275 throw 'Original buffer no longer exists, aborting.'
1278 let path = resolve(bufname(originalBuffer))
1280 " Work with netrw or other systems where a directory listing is displayed in
1283 if isdirectory(path)
1285 elseif VCSIsNERDTreeBuffer(originalBuffer)
1286 let nerdTreeRoot = VCSGetNERDTreeBufferName(originalBuffer)
1287 let path = resolve(nerdTreeRoot)
1288 let fileName = nerdTreeRoot
1290 let fileName = fnamemodify(path, ':t')
1293 if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1294 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1296 let fullCmd = a:cmd . ' -- ' . shellescape(fileName)
1299 " Change to the directory of the current buffer. This is done for CVS, but
1300 " is left in for other systems as it does not affect them negatively.
1302 let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1304 let output = s:VCSCommandUtility.system(fullCmd)
1306 call VCSCommandChdir(oldCwd)
1309 " HACK: if line endings in the repository have been corrupted, the output
1310 " of the command will be confused.
1311 let output = substitute(output, "\r", '', 'g')
1313 if v:shell_error && !allowNonZeroExit
1314 if strlen(output) == 0
1315 throw 'Version control command failed'
1317 let output = substitute(output, '\n', ' ', 'g')
1318 throw 'Version control command failed: ' . output
1322 if strlen(output) == 0
1323 " Handle case of no output. In this case, it is important to check the
1324 " file status, especially since cvs edit/unedit may change the attributes
1325 " of the file with no visible output.
1331 call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1335 " The last command left a blank line at the end of the buffer. If the
1336 " last line is folded (a side effect of the 'put') then the attempt to
1337 " remove the blank line will kill the last fold.
1339 " This could be fixed by explicitly detecting whether the last line is
1340 " within a fold, but I prefer to simply unfold the result buffer altogether.
1349 " Define the environment and execute user-defined hooks.
1351 silent do VCSCommand User VCSBufferCreated
1355 " Function: VCSCommandGetOption(name, default) {{{2
1356 " Grab a user-specified option to override the default provided. Options are
1357 " searched in the window, buffer, then global spaces.
1359 function! VCSCommandGetOption(name, default)
1360 for context in s:executionContext
1361 if has_key(context, a:name)
1362 return context[a:name]
1365 if exists('w:' . a:name)
1367 elseif exists('b:' . a:name)
1369 elseif exists('g:' . a:name)
1376 " Function: VCSCommandDisableBufferSetup() {{{2
1377 " Global function for deactivating the buffer autovariables.
1379 function! VCSCommandDisableBufferSetup()
1380 let g:VCSCommandEnableBufferSetup = 0
1381 silent! augroup! VCSCommandPlugin
1384 " Function: VCSCommandEnableBufferSetup() {{{2
1385 " Global function for activating the buffer autovariables.
1387 function! VCSCommandEnableBufferSetup()
1388 let g:VCSCommandEnableBufferSetup = 1
1389 augroup VCSCommandPlugin
1391 au BufEnter * call s:SetupBuffer()
1394 " Only auto-load if the plugin is fully loaded. This gives other plugins a
1396 if g:loaded_VCSCommand == 2
1397 call s:SetupBuffer()
1401 " Function: VCSCommandGetStatusLine() {{{2
1402 " Default (sample) status line entry for VCS-controlled files. This is only
1403 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1404 " variable for how to do this).
1406 function! VCSCommandGetStatusLine()
1407 if exists('b:VCSCommandCommand')
1408 " This is a result buffer. Return nothing because the buffer name
1409 " contains information already.
1413 if exists('b:VCSCommandVCSType')
1414 \ && exists('g:VCSCommandEnableBufferSetup')
1415 \ && g:VCSCommandEnableBufferSetup
1416 \ && exists('b:VCSCommandBufferInfo')
1417 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1423 function! VCSCommandSetVCSType(type)
1424 if exists('b:VCSCommandBufferSetup')
1425 unlet b:VCSCommandBufferSetup
1427 let b:VCSCommandVCSType = a:type
1428 call s:SetupBuffer()
1431 " Section: Command definitions {{{1
1432 " Section: Primary commands {{{2
1433 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1434 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1435 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1436 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1437 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1438 com! -nargs=* VCSDiff call s:VCSDiff(<f-args>)
1439 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1440 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1441 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1442 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1443 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1444 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1445 com! -nargs=? VCSReview call s:VCSReview(<f-args>)
1446 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1447 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1448 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1449 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1451 " Section: VCS buffer management commands {{{2
1452 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1453 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1455 " Allow reloading VCSCommand.vim
1456 com! VCSReload let savedPlugins = s:plugins|let s:plugins = {}|call s:ClearMenu()|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for plugin in values(savedPlugins)|execute 'source' plugin[0]|endfor|unlet savedPlugins
1458 " Section: Plugin command mappings {{{1
1459 if !exists("no_plugin_maps")
1460 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1461 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1462 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1463 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1464 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1465 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1466 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1467 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1468 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1469 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1470 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1471 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1472 nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1473 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1474 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1475 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1476 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1479 " Section: Default mappings {{{1
1481 let s:defaultMappings = [
1483 \['c', 'VCSCommit'],
1484 \['D', 'VCSDelete'],
1486 \['G', 'VCSClearAndGotoOriginal'],
1487 \['g', 'VCSGotoOriginal'],
1491 \['N', 'VCSSplitAnnotate'],
1492 \['n', 'VCSAnnotate'],
1493 \['q', 'VCSRevert'],
1494 \['r', 'VCSReview'],
1495 \['s', 'VCSStatus'],
1496 \['U', 'VCSUnlock'],
1497 \['u', 'VCSUpdate'],
1498 \['v', 'VCSVimDiff'],
1501 if !exists("g:no_plugin_maps") && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1502 for [s:shortcut, s:vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1503 call s:CreateMapping(s:shortcut, '<Plug>' . s:vcsFunction, '''' . s:vcsFunction . '''')
1505 unlet s:shortcut s:vcsFunction
1507 unlet s:defaultMappings
1509 " Section: Menu items {{{1
1511 let s:menuEnabled = !VCSCommandGetOption('VCSCommandDisableMenu', 0)
1512 let s:menuRoot = VCSCommandGetOption('VCSCommandMenuRoot', '&Plugin.VCS')
1513 let s:menuPriority = VCSCommandGetOption('VCSCommandMenuPriority', '')
1515 for [s:shortcut, s:command] in [
1516 \['&Add', '<Plug>VCSAdd'],
1517 \['A&nnotate', '<Plug>VCSAnnotate'],
1518 \['&Commit', '<Plug>VCSCommit'],
1519 \['Delete', '<Plug>VCSDelete'],
1520 \['&Diff', '<Plug>VCSDiff'],
1521 \['&Info', '<Plug>VCSInfo'],
1522 \['&Log', '<Plug>VCSLog'],
1523 \['Revert', '<Plug>VCSRevert'],
1524 \['&Review', '<Plug>VCSReview'],
1525 \['&Status', '<Plug>VCSStatus'],
1526 \['&Update', '<Plug>VCSUpdate'],
1527 \['&VimDiff', '<Plug>VCSVimDiff']
1529 call s:VCSCommandUtility.addMenuItem(s:shortcut, s:command)
1531 unlet s:shortcut s:command
1533 " Section: Autocommands to restore vimdiff state {{{1
1534 augroup VimDiffRestore
1536 au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1539 " Section: Optional activation of buffer management {{{1
1541 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1542 call VCSCommandEnableBufferSetup()
1545 " Section: VIM shutdown hook {{{1
1547 " Close all result buffers when VIM exits, to prevent them from being restored
1550 " Function: s:CloseAllResultBuffers() {{{2
1551 " Closes all vcscommand result buffers.
1552 function! s:CloseAllResultBuffers()
1553 " This avoids using bufdo as that may load buffers already loaded in another
1554 " vim process, resulting in an error.
1556 let buffmaxnr = bufnr('$')
1557 while buffnr <= buffmaxnr
1558 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1561 let buffnr = buffnr + 1
1565 augroup VCSCommandVIMShutdown
1567 au VimLeavePre * call s:CloseAllResultBuffers()
1570 " Section: Plugin completion {{{1
1572 let loaded_VCSCommand = 2
1574 silent do VCSCommand User VCSPluginFinish
1576 let &cpo = s:save_cpo