Respect 'no_plugin_maps'.
[vcscommand.git] / plugin / vcscommand.vim
blob92884d951846320f4f7731e3275826bcb1276499
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>
7 " License:
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
26 " IN THE SOFTWARE.
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
94 "                  new scratch buffer.
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
101 "                  scratch buffer.
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
120 "                  repository.
122 " VCSVimDiff       Uses vimdiff to display differences between versions of the
123 "                  current file.
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
134 "                  mode.
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
144 "                  buffers.
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:
155 "   <Leader>ca VCSAdd
156 "   <Leader>cn VCSAnnotate
157 "   <Leader>cN VCSAnnotate!
158 "   <Leader>cc VCSCommit
159 "   <Leader>cD VCSDelete
160 "   <Leader>cd VCSDiff
161 "   <Leader>cg VCSGotoOriginal
162 "   <Leader>cG VCSGotoOriginal!
163 "   <Leader>ci VCSInfo
164 "   <Leader>cl VCSLog
165 "   <Leader>cL VCSLock
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.
211 " VCSCommandEdit
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.
223 " VCSCommandMappings
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
231 "   shortcuts.
233 " VCSCommandMenuPriority
234 "   This variable, if set, overrides the default menu priority '' (empty)
236 " VCSCommandMenuRoot
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
249 "   'Diff').
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
256 "   numbers).
258 " VCSCommandSplit
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 not set, it defaults to 'horizontal' for all but
265 "   VCSVimDiff windows.
267 " VCSCommandVCSTypeOverride
268 "   This variable allows the VCS type detection to be overridden on a
269 "   path-by-path basis.  The value of this variable is expected to be a List
270 "   of Lists.  Each high-level List item is a List containing two elements.
271 "   The first element is a regular expression that will be matched against the
272 "   full file name of a given buffer.  If it matches, the second element will
273 "   be used as the VCS type.
275 " Event documentation {{{2
276 "   For additional customization, VCSCommand.vim uses User event autocommand
277 "   hooks.  Each event is in the VCSCommand group, and different patterns
278 "   match the various hooks.
280 "   For instance, the following could be added to the vimrc to provide a 'q'
281 "   mapping to quit a VCS scratch buffer:
283 "   augroup VCSCommand
284 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr>
285 "   augroup END
287 "   The following hooks are available:
289 "   VCSBufferCreated           This event is fired just after a VCS command
290 "                              output buffer is created.  It is executed
291 "                              within the context of the new buffer.
293 "   VCSBufferSetup             This event is fired just after VCS buffer setup
294 "                              occurs, if enabled.
296 "   VCSPluginInit              This event is fired when the VCSCommand plugin
297 "                              first loads.
299 "   VCSPluginFinish            This event is fired just after the VCSCommand
300 "                              plugin loads.
302 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
303 "                              command executes to allow customization of,
304 "                              for instance, window placement and focus.
306 " Section: Plugin header {{{1
308 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
309 " completes.  This allows various actions to only be taken by functions after
310 " system initialization.
312 if exists('VCSCommandDisableAll')
313         finish
314 endif
316 if exists('loaded_VCSCommand')
317         finish
318 endif
319 let loaded_VCSCommand = 1
321 if v:version < 700
322         echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
323         finish
324 endif
326 let s:save_cpo=&cpo
327 set cpo&vim
329 " Section: Event group setup {{{1
331 augroup VCSCommand
332 augroup END
334 augroup VCSCommandCommit
335 augroup END
337 " Section: Plugin initialization {{{1
338 silent do VCSCommand User VCSPluginInit
340 " Section: Constants declaration {{{1
342 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
343 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
345 " Section: Script variable initialization {{{1
347 " Hidden functions for use by extensions
348 let s:VCSCommandUtility = {}
350 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
351 let s:plugins = {}
353 " temporary values of overridden configuration variables
354 let s:optionOverrides = {}
356 " state flag used to vary behavior of certain automated actions
357 let s:isEditFileRunning = 0
359 " Section: Utility functions {{{1
361 " Function: s:ReportError(mapping) {{{2
362 " Displays the given error in a consistent faction.  This is intended to be
363 " invoked from a catch statement.
365 function! s:ReportError(error)
366         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
367 endfunction
369 " Function: s:VCSCommandUtility.system(...) {{{2
370 " Replacement for system() function.  This version protects the quoting in the
371 " command line on Windows systems.
373 function! s:VCSCommandUtility.system(...)
374         if (has("win32") || has("win64")) && &sxq !~ '"'
375                 let save_sxq = &sxq
376                 set sxq=\"
377         endif
378         try
379                 if exists('*iconv')
380                         return iconv(call('system', a:000), &tenc, &enc)
381                 endif
382                 return call('system', a:000)
383         finally
384                 if exists("save_sxq")
385                         let &sxq = save_sxq
386                 endif
387         endtry
388 endfunction
390 " Function: s:VCSCommandUtility.addMenuItem(shortcut, command) {{{2
391 " Adds the given menu item.
393 function! s:VCSCommandUtility.addMenuItem(shortcut, command)
394         if s:menuEnabled
395             exe 'amenu <silent> '.s:menuPriority.' '.s:menuRoot.'.'.a:shortcut.' '.a:command
396         endif
397 endfunction
399 " Function: s:ClearMenu() {{{2
400 " Removes all VCSCommand menu items
401 function! s:ClearMenu()
402         if s:menuEnabled
403                 execute 'aunmenu' s:menuRoot
404         endif
405 endfunction
407 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
408 " Creates the given mapping by prepending the contents of
409 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
410 " mapping it to the given plugin function.  If a mapping exists for the
411 " specified shortcut + prefix, emit an error but continue.  If a mapping
412 " exists for the specified function, do nothing.
414 function! s:CreateMapping(shortcut, expansion, display)
415         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
416         if !hasmapto(a:expansion)
417                 try
418                         execute 'nmap <silent> <unique>' lhs a:expansion
419                 catch /^Vim(.*):E227:/
420                         if(&verbose != 0)
421                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
422                         endif
423                 endtry
424         endif
425 endfunction
427 " Function: s:ExecuteExtensionMapping(mapping) {{{2
428 " Invokes the appropriate extension mapping depending on the type of the
429 " current buffer.
431 function! s:ExecuteExtensionMapping(mapping)
432         let buffer = bufnr('%')
433         let vcsType = VCSCommandGetVCSType(buffer)
434         if !has_key(s:plugins, vcsType)
435                 throw 'Unknown VCS type:  ' . vcsType
436         endif
437         if !has_key(s:plugins[vcsType][2], a:mapping)
438                 throw 'This extended mapping is not defined for ' . vcsType
439         endif
440         silent execute 'normal!' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
441 endfunction
443 " Function: s:ExecuteVCSCommand(command, argList) {{{2
444 " Calls the indicated plugin-specific VCS command on the current buffer.
445 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
446 " occurs.
448 function! s:ExecuteVCSCommand(command, argList)
449         try
450                 let buffer = bufnr('%')
452                 let vcsType = VCSCommandGetVCSType(buffer)
453                 if !has_key(s:plugins, vcsType)
454                         throw 'Unknown VCS type:  ' . vcsType
455                 endif
457                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
458                 let bufferName = bufname(originalBuffer)
460                 " It is already known that the directory is under VCS control.  No further
461                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
462                 " VCS-specific error messages from confusing things.
463                 if !isdirectory(bufferName)
464                         if !filereadable(bufferName)
465                                 throw 'No such file ' . bufferName
466                         endif
467                 endif
469                 let functionMap = s:plugins[vcsType][1]
470                 if !has_key(functionMap, a:command)
471                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
472                 endif
473                 return functionMap[a:command](a:argList)
474         catch
475                 call s:ReportError(v:exception)
476                 return -1
477         endtry
478 endfunction
480 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
481 " Default method of generating the name for VCS result buffers.  This can be
482 " overridden with the VCSResultBufferNameFunction variable.
484 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
485         let fileName = bufname(a:originalBuffer)
486         let bufferName = a:vcsType . ' ' . a:command
487         if strlen(a:statusText) > 0
488                 let bufferName .= ' ' . a:statusText
489         endif
490         let bufferName .= ' ' . fileName
491         let counter = 0
492         let versionedBufferName = bufferName
493         while bufexists(versionedBufferName)
494                 let counter += 1
495                 let versionedBufferName = bufferName . ' (' . counter . ')'
496         endwhile
497         return versionedBufferName
498 endfunction
500 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
501 " Method of generating the name for VCS result buffers that uses the original
502 " file name with the VCS type and command appended as extensions.
504 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
505         let fileName = bufname(a:originalBuffer)
506         let bufferName = a:vcsType . ' ' . a:command
507         if strlen(a:statusText) > 0
508                 let bufferName .= ' ' . a:statusText
509         endif
510         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
511         let counter = 0
512         let versionedBufferName = bufferName
513         while bufexists(versionedBufferName)
514                 let counter += 1
515                 let versionedBufferName = '(' . counter . ') ' . bufferName
516         endwhile
517         return versionedBufferName
518 endfunction
520 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
521 " Creates a new buffer of the given name and associates it with the given
522 " original buffer.
524 function! s:EditFile(command, originalBuffer, statusText)
525         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
527         " Protect against useless buffer set-up
528         let s:isEditFileRunning += 1
529         try
530                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
531                 if editCommand == 'split'
532                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
533                                 rightbelow split
534                         else
535                                 vert rightbelow split
536                         endif
537                 endif
539                 enew
541                 call s:SetupScratchBuffer(a:command, vcsType, a:originalBuffer, a:statusText)
543         finally
544                 let s:isEditFileRunning -= 1
545         endtry
546 endfunction
548 " Function: s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText) {{{2
549 " Creates convenience buffer variables and the name of a vcscommand result
550 " buffer.
552 function! s:SetupScratchBuffer(command, vcsType, originalBuffer, statusText)
553         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
554         if nameExtension == ''
555                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
556         else
557                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
558         endif
560         let name = call(nameFunction, [a:command, a:originalBuffer, a:vcsType, a:statusText])
562         let b:VCSCommandCommand = a:command
563         let b:VCSCommandOriginalBuffer = a:originalBuffer
564         let b:VCSCommandSourceFile = bufname(a:originalBuffer)
565         let b:VCSCommandVCSType = a:vcsType
566         if a:statusText != ''
567                 let b:VCSCommandStatusText = a:statusText
568         endif
570         setlocal buftype=nofile
571         setlocal noswapfile
572         let &filetype = tolower(a:vcsType . a:command)
574         if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
575                 setlocal bufhidden=delete
576         endif
577         silent noautocmd file `=name`
578 endfunction
580 " Function: s:SetupBuffer() {{{2
581 " Attempts to set the b:VCSCommandBufferInfo variable
583 function! s:SetupBuffer()
584         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
585                 " This buffer is already set up.
586                 return
587         endif
589         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
590                 " No special status for special buffers other than directory buffers.
591                 return
592         endif
594         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
595                 unlet! b:VCSCommandBufferSetup
596                 return
597         endif
599         try
600                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
601                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
602                 silent do VCSCommand User VCSBufferSetup
603         catch /No suitable plugin/
604                 " This is not a VCS-controlled file.
605                 let b:VCSCommandBufferInfo = []
606         endtry
608         let b:VCSCommandBufferSetup = 1
609 endfunction
611 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
612 " Resets the buffer setup state of the original buffer for a given VCS scratch
613 " buffer.
614 " Returns:  The VCS buffer number in a passthrough mode.
616 function! s:MarkOrigBufferForSetup(buffer)
617         checktime
618         if a:buffer > 0
619                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
620                 " This should never not work, but I'm paranoid
621                 if origBuffer != a:buffer
622                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
623                 endif
624         endif
625         return a:buffer
626 endfunction
628 " Function: s:OverrideOption(option, [value]) {{{2
629 " Provides a temporary override for the given VCS option.  If no value is
630 " passed, the override is disabled.
632 function! s:OverrideOption(option, ...)
633         if a:0 == 0
634                 call remove(s:optionOverrides[a:option], -1)
635         else
636                 if !has_key(s:optionOverrides, a:option)
637                         let s:optionOverrides[a:option] = []
638                 endif
639                 call add(s:optionOverrides[a:option], a:1)
640         endif
641 endfunction
643 " Function: s:WipeoutCommandBuffers() {{{2
644 " Clears all current VCS output buffers of the specified type for a given source.
646 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
647         let buffer = 1
648         while buffer <= bufnr('$')
649                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
650                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
651                                 execute 'bw' buffer
652                         endif
653                 endif
654                 let buffer = buffer + 1
655         endwhile
656 endfunction
658 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
659 " Checks whether the given buffer is one whose deletion should trigger
660 " restoration of an original buffer after it was diffed.  If so, it executes
661 " the appropriate setting command stored with that original buffer.
663 function! s:VimDiffRestore(vimDiffBuff)
664         let s:isEditFileRunning += 1
665         try
666                 if exists('t:vcsCommandVimDiffSourceBuffer')
667                         if a:vimDiffBuff == t:vcsCommandVimDiffSourceBuffer
668                                 " Original file is being removed.
669                                 unlet! t:vcsCommandVimDiffSourceBuffer
670                                 unlet! t:vcsCommandVimDiffRestoreCmd
671                                 unlet! t:vcsCommandVimDiffScratchList
672                         else
673                                 let index = index(t:vcsCommandVimDiffScratchList, a:vimDiffBuff)
674                                 if index >= 0
675                                         call remove(t:vcsCommandVimDiffScratchList, index)
676                                         if len(t:vcsCommandVimDiffScratchList) == 0
677                                                 if exists('t:vcsCommandVimDiffRestoreCmd')
678                                                         " All scratch buffers are gone, reset the original.
679                                                         " Only restore if the source buffer is still in Diff mode
681                                                         let sourceWinNR = bufwinnr(t:vcsCommandVimDiffSourceBuffer)
682                                                         if sourceWinNR != -1
683                                                                 " The buffer is visible in at least one window
684                                                                 let currentWinNR = winnr()
685                                                                 while winbufnr(sourceWinNR) != -1
686                                                                         if winbufnr(sourceWinNR) == t:vcsCommandVimDiffSourceBuffer
687                                                                                 execute sourceWinNR . 'wincmd w'
688                                                                                 if getwinvar(0, '&diff')
689                                                                                         execute t:vcsCommandVimDiffRestoreCmd
690                                                                                 endif
691                                                                         endif
692                                                                         let sourceWinNR = sourceWinNR + 1
693                                                                 endwhile
694                                                                 execute currentWinNR . 'wincmd w'
695                                                         else
696                                                                 " The buffer is hidden.  It must be visible in order to set the
697                                                                 " diff option.
698                                                                 let currentBufNR = bufnr('')
699                                                                 execute 'hide buffer' t:vcsCommandVimDiffSourceBuffer
700                                                                 if getwinvar(0, '&diff')
701                                                                         execute t:vcsCommandVimDiffRestoreCmd
702                                                                 endif
703                                                                 execute 'hide buffer' currentBufNR
704                                                         endif
706                                                         unlet t:vcsCommandVimDiffRestoreCmd
707                                                 endif
708                                                 " All buffers are gone.
709                                                 unlet t:vcsCommandVimDiffSourceBuffer
710                                                 unlet t:vcsCommandVimDiffScratchList
711                                         endif
712                                 endif
713                         endif
714                 endif
715         finally
716                 let s:isEditFileRunning -= 1
717         endtry
718 endfunction
720 " Section: Generic VCS command functions {{{1
722 " Function: s:VCSAnnotate(...) {{{2
723 function! s:VCSAnnotate(bang, ...)
724         try
725                 let line = line('.')
726                 let currentBuffer = bufnr('%')
727                 let originalBuffer = VCSCommandGetOriginalBuffer(currentBuffer)
729                 let annotateBuffer = s:ExecuteVCSCommand('Annotate', a:000)
730                 if annotateBuffer == -1
731                         return -1
732                 endif
733                 if a:bang == '!' && VCSCommandGetOption('VCSCommandDisableSplitAnnotate', 0) == 0
734                         let vcsType = VCSCommandGetVCSType(annotateBuffer)
735                         let functionMap = s:plugins[vcsType][1]
736                         let splitRegex = ''
737                         if has_key(s:plugins[vcsType][1], 'AnnotateSplitRegex')
738                                 let splitRegex = s:plugins[vcsType][1]['AnnotateSplitRegex']
739                         endif
740                         let splitRegex = VCSCommandGetOption('VCSCommand' . vcsType . 'AnnotateSplitRegex', splitRegex)
741                         if splitRegex == ''
742                                 return annotateBuffer
743                         endif
744                         let originalFileType = getbufvar(originalBuffer, '&ft')
745                         let annotateFileType = getbufvar(annotateBuffer, '&ft')
746                         execute "normal! 0zR\<c-v>G/" . splitRegex . "/e\<cr>d"
747                         call setbufvar('%', '&filetype', getbufvar(originalBuffer, '&filetype'))
748                         set scrollbind
749                         leftabove vert new
750                         normal! 0P
751                         execute "normal!" . (col('$') + (&number ? &numberwidth : 0)). "\<c-w>|"
752                         call s:SetupScratchBuffer('annotate', vcsType, originalBuffer, 'header')
753                         wincmd l
754                 endif
756                 if currentBuffer == originalBuffer
757                         " Starting from the original source buffer, so the
758                         " current line is relevant.
759                         if a:0 == 0
760                                 " No argument list means that we're annotating
761                                 " the current version, so jumping to the same
762                                 " line is the expected action.
763                                 execute "normal!" line . 'G'
764                                 if has('folding')
765                                         " The execution of the buffer created autocommand
766                                         " re-folds the buffer.  Display the current line
767                                         " unfolded.
768                                         normal! zv
769                                 endif
770                         endif
771                 endif
773                 return annotateBuffer
774         catch
775                 call s:ReportError(v:exception)
776                 return -1
777         endtry
778 endfunction
780 " Function: s:VCSCommit() {{{2
781 function! s:VCSCommit(bang, message)
782         try
783                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
784                 if !has_key(s:plugins, vcsType)
785                         throw 'Unknown VCS type:  ' . vcsType
786                 endif
788                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
790                 " Handle the commit message being specified.  If a message is supplied, it
791                 " is used; if bang is supplied, an empty message is used; otherwise, the
792                 " user is provided a buffer from which to edit the commit message.
794                 if strlen(a:message) > 0 || a:bang == '!'
795                         return s:VCSFinishCommit([a:message], originalBuffer)
796                 endif
798                 call s:EditFile('commitlog', originalBuffer, '')
799                 setlocal ft=vcscommit
801                 " Create a commit mapping.
803                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
805                 silent 0put ='VCS: ----------------------------------------------------------------------'
806                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
807                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
809                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
810                         setlocal buftype=acwrite
811                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
812                         silent put ='VCS: or write this buffer'
813                 endif
815                 silent put ='VCS: ----------------------------------------------------------------------'
816                 $
817                 setlocal nomodified
818                 silent do VCSCommand User VCSBufferCreated
819         catch
820                 call s:ReportError(v:exception)
821                 return -1
822         endtry
823 endfunction
825 " Function: s:VCSFinishCommitWithBuffer() {{{2
826 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
827 " which removes all lines starting with 'VCS:'.
829 function! s:VCSFinishCommitWithBuffer()
830         setlocal nomodified
831         let currentBuffer = bufnr('%')
832         let logMessageList = getbufline('%', 1, '$')
833         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
834         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
835         if resultBuffer >= 0
836                 execute 'bw' currentBuffer
837         endif
838         return resultBuffer
839 endfunction
841 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
842 function! s:VCSFinishCommit(logMessageList, originalBuffer)
843         let messageFileName = tempname()
844         call writefile(a:logMessageList, messageFileName)
845         try
846                 let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
847                 if resultBuffer < 0
848                         return resultBuffer
849                 endif
850                 return s:MarkOrigBufferForSetup(resultBuffer)
851         finally
852                 call delete(messageFileName)
853         endtry
854 endfunction
856 " Function: s:VCSGotoOriginal(bang) {{{2
857 function! s:VCSGotoOriginal(bang)
858         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
859         if originalBuffer > 0
860                 let origWinNR = bufwinnr(originalBuffer)
861                 if origWinNR == -1
862                         execute 'buffer' originalBuffer
863                 else
864                         execute origWinNR . 'wincmd w'
865                 endif
866                 if a:bang == '!'
867                         let buffnr = 1
868                         let buffmaxnr = bufnr('$')
869                         while buffnr <= buffmaxnr
870                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
871                                         execute 'bw' buffnr
872                                 endif
873                                 let buffnr = buffnr + 1
874                         endwhile
875                 endif
876         endif
877 endfunction
879 function! s:VCSDiff(...)  "{{{2
880         let resultBuffer = s:ExecuteVCSCommand('Diff', a:000)
881         if resultBuffer > 0
882                 let &filetype = 'diff'
883         elseif resultBuffer == 0
884                 echomsg 'No differences found'
885         endif
886         return resultBuffer
887 endfunction
889 function! s:VCSReview(...)  "{{{2
890         let resultBuffer = s:ExecuteVCSCommand('Review', a:000)
891         if resultBuffer > 0
892                 let &filetype = getbufvar(b:VCSCommandOriginalBuffer, '&filetype')
893         endif
894         return resultBuffer
895 endfunction
897 " Function: s:VCSVimDiff(...) {{{2
898 function! s:VCSVimDiff(...)
899         try
900                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
901                 if !has_key(s:plugins, vcsType)
902                         throw 'Unknown VCS type:  ' . vcsType
903                 endif
904                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
905                 let s:isEditFileRunning = s:isEditFileRunning + 1
906                 try
907                         " If there's already a VimDiff'ed window, restore it.
908                         " There may only be one VCSVimDiff original window at a time.
910                         if exists('t:vcsCommandVimDiffSourceBuffer') && t:vcsCommandVimDiffSourceBuffer != originalBuffer
911                                 " Clear the existing vimdiff setup by removing the result buffers.
912                                 call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
913                         endif
915                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
916                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
917                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
919                         " Split and diff
920                         if(a:0 == 2)
921                                 " Reset the vimdiff system, as 2 explicit versions were provided.
922                                 if exists('t:vcsCommandVimDiffSourceBuffer')
923                                         call s:WipeoutCommandBuffers(t:vcsCommandVimDiffSourceBuffer, 'vimdiff')
924                                 endif
925                                 let resultBuffer = s:VCSReview(a:1)
926                                 if resultBuffer < 0
927                                         echomsg 'Can''t open revision ' . a:1
928                                         return resultBuffer
929                                 endif
930                                 let b:VCSCommandCommand = 'vimdiff'
931                                 diffthis
932                                 let t:vcsCommandVimDiffScratchList = [resultBuffer]
933                                 " If no split method is defined, cheat, and set it to vertical.
934                                 try
935                                         call s:OverrideOption('VCSCommandSplit', orientation)
936                                         let resultBuffer = s:VCSReview(a:2)
937                                 finally
938                                         call s:OverrideOption('VCSCommandSplit')
939                                 endtry
940                                 if resultBuffer < 0
941                                         echomsg 'Can''t open revision ' . a:1
942                                         return resultBuffer
943                                 endif
944                                 let b:VCSCommandCommand = 'vimdiff'
945                                 diffthis
946                                 let t:vcsCommandVimDiffScratchList += [resultBuffer]
947                         else
948                                 " Add new buffer
949                                 call s:OverrideOption('VCSCommandEdit', 'split')
950                                 try
951                                         " Force splitting behavior, otherwise why use vimdiff?
952                                         call s:OverrideOption('VCSCommandSplit', orientation)
953                                         try
954                                                 if(a:0 == 0)
955                                                         let resultBuffer = s:VCSReview()
956                                                 else
957                                                         let resultBuffer = s:VCSReview(a:1)
958                                                 endif
959                                         finally
960                                                 call s:OverrideOption('VCSCommandSplit')
961                                         endtry
962                                 finally
963                                         call s:OverrideOption('VCSCommandEdit')
964                                 endtry
965                                 if resultBuffer < 0
966                                         echomsg 'Can''t open current revision'
967                                         return resultBuffer
968                                 endif
969                                 let b:VCSCommandCommand = 'vimdiff'
970                                 diffthis
972                                 if !exists('t:vcsCommandVimDiffSourceBuffer')
973                                         " New instance of vimdiff.
974                                         let t:vcsCommandVimDiffScratchList = [resultBuffer]
976                                         " This could have been invoked on a VCS result buffer, not the
977                                         " original buffer.
978                                         wincmd W
979                                         execute 'buffer' originalBuffer
980                                         " Store info for later original buffer restore
981                                         let t:vcsCommandVimDiffRestoreCmd =
982                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
983                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
984                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
985                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
986                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
987                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
988                                                                 \ . '|call setbufvar('.originalBuffer.', ''&cursorbind'', '.getbufvar(originalBuffer, '&cursorbind').')'
989                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
990                                                                 \ . '|if &foldmethod==''manual''|execute ''normal! zE''|endif'
991                                         diffthis
992                                         wincmd w
993                                 else
994                                         " Adding a window to an existing vimdiff
995                                         let t:vcsCommandVimDiffScratchList += [resultBuffer]
996                                 endif
997                         endif
999                         let t:vcsCommandVimDiffSourceBuffer = originalBuffer
1001                         " Avoid executing the modeline in the current buffer after the autocommand.
1003                         let currentBuffer = bufnr('%')
1004                         let saveModeline = getbufvar(currentBuffer, '&modeline')
1005                         try
1006                                 call setbufvar(currentBuffer, '&modeline', 0)
1007                                 silent do VCSCommand User VCSVimDiffFinish
1008                         finally
1009                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
1010                         endtry
1011                         return resultBuffer
1012                 finally
1013                         let s:isEditFileRunning = s:isEditFileRunning - 1
1014                 endtry
1015         catch
1016                 call s:ReportError(v:exception)
1017                 return -1
1018         endtry
1019 endfunction
1021 " Section: Public functions {{{1
1023 " Function: VCSCommandGetVCSType() {{{2
1024 " Sets the b:VCSCommandVCSType variable in the given buffer to the
1025 " appropriate source control system name.
1027 " This uses the Identify extension function to test the buffer.  If the
1028 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
1029 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
1030 " match is considered inexact, and is only applied if no exact match is found.
1031 " Multiple inexact matches is currently considered an error.
1033 function! VCSCommandGetVCSType(buffer)
1034         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
1035         if strlen(vcsType) > 0
1036                 return vcsType
1037         endif
1038         if exists("g:VCSCommandVCSTypeOverride")
1039                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
1040                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
1041                         if match(fullpath, path) > -1
1042                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
1043                                 return vcsType
1044                         endif
1045                 endfor
1046         endif
1047         let matches = []
1048         for vcsType in keys(s:plugins)
1049                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
1050                 if identified
1051                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
1052                                 let matches = [vcsType]
1053                                 break
1054                         else
1055                                 let matches += [vcsType]
1056                         endif
1057                 endif
1058         endfor
1059         if len(matches) == 1
1060                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
1061                 return matches[0]
1062         elseif len(matches) == 0
1063                 throw 'No suitable plugin'
1064         else
1065                 throw 'Too many matching VCS:  ' . join(matches)
1066         endif
1067 endfunction
1069 " Function: VCSCommandChdir(directory) {{{2
1070 " Changes the current directory, respecting :lcd changes.
1072 function! VCSCommandChdir(directory)
1073         let command = 'cd'
1074         if exists("*haslocaldir") && haslocaldir()
1075                 let command = 'lcd'
1076         endif
1077         execute command fnameescape(a:directory)
1078 endfunction
1080 " Function: VCSCommandChangeToCurrentFileDir() {{{2
1081 " Go to the directory in which the given file is located.
1083 function! VCSCommandChangeToCurrentFileDir(fileName)
1084         let oldCwd = getcwd()
1085         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
1086         if strlen(newCwd) > 0
1087                 call VCSCommandChdir(newCwd)
1088         endif
1089         return oldCwd
1090 endfunction
1092 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
1093 " Attempts to locate the original file to which VCS operations were applied
1094 " for a given buffer.
1096 function! VCSCommandGetOriginalBuffer(vcsBuffer)
1097         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
1098         if origBuffer
1099                 if bufexists(origBuffer)
1100                         return origBuffer
1101                 else
1102                         " Original buffer no longer exists.
1103                         throw 'Original buffer for this VCS buffer no longer exists.'
1104                 endif
1105         else
1106                 " No original buffer
1107                 return a:vcsBuffer
1108         endif
1109 endfunction
1111 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
1112 " Allows VCS modules to register themselves.
1114 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
1115         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
1116         if !empty(a:mappingMap)
1117                                 \ && !exists("g:no_plugin_maps")
1118                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1119                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
1120                 for shortcut in keys(a:mappingMap)
1121                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
1122                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
1123                 endfor
1124         endif
1125         return s:VCSCommandUtility
1126 endfunction
1128 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1129 " General skeleton for VCS function execution.  The given command is executed
1130 " after appending the current buffer name (or substituting it for
1131 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1132 " new buffer.
1134 " The optional 'options' Dictionary may contain the following options:
1135 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1136 "               non-zero exit status, the command is still considered
1137 "               successfuly.  This defaults to zero.
1138 " Returns: name of the new command buffer containing the command results
1140 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1141         let allowNonZeroExit = 0
1142         if has_key(a:options, 'allowNonZeroExit')
1143                 let allowNonZeroExit = a:options.allowNonZeroExit
1144         endif
1146         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1147         if originalBuffer == -1
1148                 throw 'Original buffer no longer exists, aborting.'
1149         endif
1151         let path = resolve(bufname(originalBuffer))
1153         " Work with netrw or other systems where a directory listing is displayed in
1154         " a buffer.
1156         if isdirectory(path)
1157                 let fileName = '.'
1158         else
1159                 let fileName = fnamemodify(path, ':t')
1160         endif
1162         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1163                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1164         else
1165                 let fullCmd = a:cmd . ' -- ' . shellescape(fileName)
1166         endif
1168         " Change to the directory of the current buffer.  This is done for CVS, but
1169         " is left in for other systems as it does not affect them negatively.
1171         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1172         try
1173                 let output = s:VCSCommandUtility.system(fullCmd)
1174         finally
1175                 call VCSCommandChdir(oldCwd)
1176         endtry
1178         " HACK:  if line endings in the repository have been corrupted, the output
1179         " of the command will be confused.
1180         let output = substitute(output, "\r", '', 'g')
1182         if v:shell_error && !allowNonZeroExit
1183                 if strlen(output) == 0
1184                         throw 'Version control command failed'
1185                 else
1186                         let output = substitute(output, '\n', '  ', 'g')
1187                         throw 'Version control command failed:  ' . output
1188                 endif
1189         endif
1191         if strlen(output) == 0
1192                 " Handle case of no output.  In this case, it is important to check the
1193                 " file status, especially since cvs edit/unedit may change the attributes
1194                 " of the file with no visible output.
1196                 checktime
1197                 return 0
1198         endif
1200         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1202         silent 0put=output
1204         " The last command left a blank line at the end of the buffer.  If the
1205         " last line is folded (a side effect of the 'put') then the attempt to
1206         " remove the blank line will kill the last fold.
1207         "
1208         " This could be fixed by explicitly detecting whether the last line is
1209         " within a fold, but I prefer to simply unfold the result buffer altogether.
1211         if has('folding')
1212                 normal! zR
1213         endif
1215         $d
1216         1
1218         " Define the environment and execute user-defined hooks.
1220         silent do VCSCommand User VCSBufferCreated
1221         return bufnr('%')
1222 endfunction
1224 " Function: VCSCommandGetOption(name, default) {{{2
1225 " Grab a user-specified option to override the default provided.  Options are
1226 " searched in the window, buffer, then global spaces.
1228 function! VCSCommandGetOption(name, default)
1229         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1230                 return s:optionOverrides[a:name][-1]
1231         elseif exists('w:' . a:name)
1232                 return w:{a:name}
1233         elseif exists('b:' . a:name)
1234                 return b:{a:name}
1235         elseif exists('g:' . a:name)
1236                 return g:{a:name}
1237         else
1238                 return a:default
1239         endif
1240 endfunction
1242 " Function: VCSCommandDisableBufferSetup() {{{2
1243 " Global function for deactivating the buffer autovariables.
1245 function! VCSCommandDisableBufferSetup()
1246         let g:VCSCommandEnableBufferSetup = 0
1247         silent! augroup! VCSCommandPlugin
1248 endfunction
1250 " Function: VCSCommandEnableBufferSetup() {{{2
1251 " Global function for activating the buffer autovariables.
1253 function! VCSCommandEnableBufferSetup()
1254         let g:VCSCommandEnableBufferSetup = 1
1255         augroup VCSCommandPlugin
1256                 au!
1257                 au BufEnter * call s:SetupBuffer()
1258         augroup END
1260         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1261         " chance to run.
1262         if g:loaded_VCSCommand == 2
1263                 call s:SetupBuffer()
1264         endif
1265 endfunction
1267 " Function: VCSCommandGetStatusLine() {{{2
1268 " Default (sample) status line entry for VCS-controlled files.  This is only
1269 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1270 " variable for how to do this).
1272 function! VCSCommandGetStatusLine()
1273         if exists('b:VCSCommandCommand')
1274                 " This is a result buffer.  Return nothing because the buffer name
1275                 " contains information already.
1276                 return ''
1277         endif
1279         if exists('b:VCSCommandVCSType')
1280                                 \ && exists('g:VCSCommandEnableBufferSetup')
1281                                 \ && g:VCSCommandEnableBufferSetup
1282                                 \ && exists('b:VCSCommandBufferInfo')
1283                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1284         else
1285                 return ''
1286         endif
1287 endfunction
1289 function! VCSCommandSetVCSType(type)
1290         if exists('b:VCSCommandBufferSetup')
1291                 unlet b:VCSCommandBufferSetup
1292         endif
1293         let b:VCSCommandVCSType = a:type
1294         call s:SetupBuffer()
1295 endfunction
1297 " Section: Command definitions {{{1
1298 " Section: Primary commands {{{2
1299 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1300 com! -nargs=* -bang VCSAnnotate call s:VCSAnnotate(<q-bang>, <f-args>)
1301 com! -nargs=* -bang VCSBlame call s:VCSAnnotate(<q-bang>, <f-args>)
1302 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1303 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1304 com! -nargs=* VCSDiff call s:VCSDiff(<f-args>)
1305 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1306 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1307 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1308 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1309 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1310 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1311 com! -nargs=? VCSReview call s:VCSReview(<f-args>)
1312 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1313 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1314 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1315 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1317 " Section: VCS buffer management commands {{{2
1318 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1319 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1321 " Allow reloading VCSCommand.vim
1322 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
1324 " Section: Plugin command mappings {{{1
1325 if !exists("no_plugin_maps")
1326         nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1327         nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1328         nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1329         nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1330         nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1331         nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1332         nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1333         nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1334         nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1335         nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1336         nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1337         nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1338         nnoremap <silent> <Plug>VCSSplitAnnotate :VCSAnnotate!<CR>
1339         nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1340         nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1341         nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1342         nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1343 endif
1345 " Section: Default mappings {{{1
1347 let s:defaultMappings = [
1348                         \['a', 'VCSAdd'],
1349                         \['c', 'VCSCommit'],
1350                         \['D', 'VCSDelete'],
1351                         \['d', 'VCSDiff'],
1352                         \['G', 'VCSClearAndGotoOriginal'],
1353                         \['g', 'VCSGotoOriginal'],
1354                         \['i', 'VCSInfo'],
1355                         \['L', 'VCSLock'],
1356                         \['l', 'VCSLog'],
1357                         \['N', 'VCSSplitAnnotate'],
1358                         \['n', 'VCSAnnotate'],
1359                         \['q', 'VCSRevert'],
1360                         \['r', 'VCSReview'],
1361                         \['s', 'VCSStatus'],
1362                         \['U', 'VCSUnlock'],
1363                         \['u', 'VCSUpdate'],
1364                         \['v', 'VCSVimDiff'],
1365                         \]
1367 if !exists("g:no_plugin_maps") && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1368         for [s:shortcut, s:vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1369                 call s:CreateMapping(s:shortcut, '<Plug>' . s:vcsFunction, '''' . s:vcsFunction . '''')
1370         endfor
1371         unlet s:shortcut s:vcsFunction
1372 endif
1373 unlet s:defaultMappings
1375 " Section: Menu items {{{1
1377 let s:menuEnabled = !VCSCommandGetOption('VCSCommandDisableMenu', 0)
1378 let s:menuRoot = VCSCommandGetOption('VCSCommandMenuRoot', '&Plugin.VCS')
1379 let s:menuPriority = VCSCommandGetOption('VCSCommandMenuPriority', '')
1381 for [s:shortcut, s:command] in [
1382                         \['&Add', '<Plug>VCSAdd'],
1383                         \['A&nnotate', '<Plug>VCSAnnotate'],
1384                         \['&Commit', '<Plug>VCSCommit'],
1385                         \['Delete', '<Plug>VCSDelete'],
1386                         \['&Diff', '<Plug>VCSDiff'],
1387                         \['&Info', '<Plug>VCSInfo'],
1388                         \['&Log', '<Plug>VCSLog'],
1389                         \['Revert', '<Plug>VCSRevert'],
1390                         \['&Review', '<Plug>VCSReview'],
1391                         \['&Status', '<Plug>VCSStatus'],
1392                         \['&Update', '<Plug>VCSUpdate'],
1393                         \['&VimDiff', '<Plug>VCSVimDiff']
1394                         \]
1395         call s:VCSCommandUtility.addMenuItem(s:shortcut, s:command)
1396 endfor
1397 unlet s:shortcut s:command
1399 " Section: Autocommands to restore vimdiff state {{{1
1400 augroup VimDiffRestore
1401         au!
1402         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1403 augroup END
1405 " Section: Optional activation of buffer management {{{1
1407 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1408         call VCSCommandEnableBufferSetup()
1409 endif
1411 " Section: VIM shutdown hook {{{1
1413 " Close all result buffers when VIM exits, to prevent them from being restored
1414 " via viminfo.
1416 " Function: s:CloseAllResultBuffers() {{{2
1417 " Closes all vcscommand result buffers.
1418 function! s:CloseAllResultBuffers()
1419         " This avoids using bufdo as that may load buffers already loaded in another
1420         " vim process, resulting in an error.
1421         let buffnr = 1
1422         let buffmaxnr = bufnr('$')
1423         while buffnr <= buffmaxnr
1424                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != ""
1425                         execute 'bw' buffnr
1426                 endif
1427                 let buffnr = buffnr + 1
1428         endwhile
1429 endfunction
1431 augroup VCSCommandVIMShutdown
1432         au!
1433         au VimLeavePre * call s:CloseAllResultBuffers()
1434 augroup END
1436 " Section: Plugin completion {{{1
1438 let loaded_VCSCommand = 2
1440 silent do VCSCommand User VCSPluginFinish
1442 let &cpo = s:save_cpo