PYENV prompt.
[profile.git] / .vim / plugin / vcscommand.vim
1 " vim600: set foldmethod=marker:
2 "
3 " Vim plugin to assist in working with files under control of various Version
4 " Control Systems, such as CVS, SVN, SVK, and git.
5 "
6 " Maintainer:    Bob Hiestand <bob.hiestand@gmail.com>
7 " Version:       Beta 29
8 " License:
9 " Copyright (c) 2008 Bob Hiestand
10 "
11 " Permission is hereby granted, free of charge, to any person obtaining a copy
12 " of this software and associated documentation files (the "Software"), to
13 " deal in the Software without restriction, including without limitation the
14 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
15 " sell copies of the Software, and to permit persons to whom the Software is
16 " furnished to do so, subject to the following conditions:
17 "
18 " The above copyright notice and this permission notice shall be included in
19 " all copies or substantial portions of the Software.
20 "
21 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
27 " IN THE SOFTWARE.
28 "
29 " Section: Documentation {{{1
30 "
31 " Provides functions to invoke various source control commands on the current
32 " file (either the current buffer, or, in the case of an directory buffer, the
33 " directory and all subdirectories associated with the current buffer).  The
34 " output of the commands is captured in a new scratch window.
35 "
36 " This plugin needs additional extension plugins, each  specific to a source
37 " control system, to function.  Those plugins should be placed in a
38 " subdirectory of the standard plugin directory named 'vcscommand'.  Several
39 " options include the name of the version control system in the option name.
40 " Such options use the placeholder text '{VCSType}', which would be replaced
41 " in actual usage with 'CVS' or 'SVN', for instance.
42 "
43 " Command documentation {{{2
44 "
45 " VCSAdd           Adds the current file to source control.
46 "
47 " VCSAnnotate      Displays the current file with each line annotated with the
48 "                  version in which it was most recently changed.  If an
49 "                  argument is given, the argument is used as a revision
50 "                  number to display.  If not given an argument, it uses the
51 "                  most recent version of the file on the current branch.
52 "                  Additionally, if the current buffer is a VCSAnnotate buffer
53 "                  already, the version number on the current line is used.
54 "
55 " VCSBlame         Alias for 'VCSAnnotate'.
56 "
57 " VCSCommit[!]     Commits changes to the current file to source control.
58 "
59 "                  If called with arguments, the arguments are the log message.
60 "
61 "                  If '!' is used, an empty log message is committed.
62 "
63 "                  If called with no arguments, this is a two-step command.
64 "                  The first step opens a buffer to accept a log message.
65 "                  When that buffer is written, it is automatically closed and
66 "                  the file is committed using the information from that log
67 "                  message.  The commit can be abandoned if the log message
68 "                  buffer is deleted or wiped before being written.
69 "
70 " VCSDelete        Deletes the current file and removes it from source control.
71 "
72 " VCSDiff          With no arguments, this displays the differences between
73 "                  the current file and its parent version under source
74 "                  control in a new scratch buffer.
75 "
76 "                  With one argument, the diff is performed on the
77 "                  current file against the specified revision.
78 "
79 "                  With two arguments, the diff is performed between the
80 "                  specified revisions of the current file.
81 "
82 "                  This command uses the 'VCSCommand{VCSType}DiffOpt' variable
83 "                  to specify diff options.  If that variable does not exist,
84 "                  a plugin-specific default is used.  If you wish to have no
85 "                  options, then set it to the empty string.
86 "
87 " VCSGotoOriginal  Jumps to the source buffer if the current buffer is a VCS
88 "                  scratch buffer.  If VCSGotoOriginal[!] is used, remove all
89 "                  VCS scratch buffers associated with the original file.
90 "
91 " VCSInfo          Displays extended information about the current file in a
92 "                  new scratch buffer. 
93 "
94 " VCSLock          Locks the current file in order to prevent other users from
95 "                  concurrently modifying it.  The exact semantics of this
96 "                  command depend on the underlying VCS.
97 "
98 " VCSLog           Displays the version history of the current file in a new
99 "                  scratch buffer.
100 "
101 " VCSRemove        Alias for 'VCSDelete'.
102 "
103 " VCSRevert        Replaces the modified version of the current file with the
104 "                  most recent version from the repository.
105 "
106 " VCSReview        Displays a particular version of the current file in a new
107 "                  scratch buffer.  If no argument is given, the most recent
108 "                  version of the file on the current branch is retrieved.
109 "
110 " VCSStatus        Displays versioning information about the current file in a
111 "                  new scratch buffer.
112 "
113 " VCSUnlock        Unlocks the current file in order to allow other users from
114 "                  concurrently modifying it.  The exact semantics of this
115 "                  command depend on the underlying VCS.
116 "
117 " VCSUpdate        Updates the current file with any relevant changes from the
118 "                  repository.
119 "
120 " VCSVimDiff       Uses vimdiff to display differences between versions of the
121 "                  current file.
122 "
123 "                  If no revision is specified, the most recent version of the
124 "                  file on the current branch is used.  With one argument,
125 "                  that argument is used as the revision as above.  With two
126 "                  arguments, the differences between the two revisions is
127 "                  displayed using vimdiff.
128 "
129 "                  With either zero or one argument, the original buffer is
130 "                  used to perform the vimdiff.  When the scratch buffer is
131 "                  closed, the original buffer will be returned to normal
132 "                  mode.
133 "
134 "                  Once vimdiff mode is started using the above methods,
135 "                  additional vimdiff buffers may be added by passing a single
136 "                  version argument to the command.  There may be up to 4
137 "                  vimdiff buffers total.
138 "
139 "                  Using the 2-argument form of the command resets the vimdiff
140 "                  to only those 2 versions.  Additionally, invoking the
141 "                  command on a different file will close the previous vimdiff
142 "                  buffers.
143 "
144 " Mapping documentation: {{{2
145 "
146 " By default, a mapping is defined for each command.  User-provided mappings
147 " can be used instead by mapping to <Plug>CommandName, for instance:
148 "
149 " nmap ,ca <Plug>VCSAdd
150 "
151 " The default mappings are as follow:
152 "
153 "   <Leader>ca VCSAdd
154 "   <Leader>cn VCSAnnotate
155 "   <Leader>cc VCSCommit
156 "   <Leader>cD VCSDelete
157 "   <Leader>cd VCSDiff
158 "   <Leader>cg VCSGotoOriginal
159 "   <Leader>cG VCSGotoOriginal!
160 "   <Leader>ci VCSInfo
161 "   <Leader>cl VCSLog
162 "   <Leader>cL VCSLock
163 "   <Leader>cr VCSReview
164 "   <Leader>cs VCSStatus
165 "   <Leader>cu VCSUpdate
166 "   <Leader>cU VCSUnlock
167 "   <Leader>cv VCSVimDiff
168 "
169 " Options documentation: {{{2
170 "
171 " Several variables are checked by the script to determine behavior as follow:
172 "
173 " VCSCommandCommitOnWrite
174 "   This variable, if set to a non-zero value, causes the pending commit to
175 "   take place immediately as soon as the log message buffer is written.  If
176 "   set to zero, only the VCSCommit mapping will cause the pending commit to
177 "   occur.  If not set, it defaults to 1.
178 "
179 " VCSCommandDeleteOnHide
180 "   This variable, if set to a non-zero value, causes the temporary VCS result
181 "   buffers to automatically delete themselves when hidden.
182 "
183 " VCSCommand{VCSType}DiffOpt
184 "   This variable, if set, determines the options passed to the diff command
185 "   of the underlying VCS.  Each VCS plugin defines a default value.
186 "
187 " VCSCommandDiffSplit
188 "   This variable overrides the VCSCommandSplit variable, but only for buffers
189 "   created with VCSVimDiff.
190 "
191 " VCSCommandDisableAll
192 "   This variable, if set, prevents the plugin or any extensions from loading
193 "   at all.  This is useful when a single runtime distribution is used on
194 "   multiple systems with varying versions.
195 "
196 " VCSCommandDisableMappings
197 "   This variable, if set to a non-zero value, prevents the default command
198 "   mappings from being set.
199 "
200 " VCSCommandDisableExtensionMappings
201 "   This variable, if set to a non-zero value, prevents the default command
202 "   mappings from being set for commands specific to an individual VCS.
203 "
204 " VCSCommandEdit
205 "   This variable controls whether to split the current window to display a
206 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
207 "   If not set, it defaults to 'split'.
208 "
209 " VCSCommandEnableBufferSetup
210 "   This variable, if set to a non-zero value, activates VCS buffer management
211 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
212 "   the file is VCS-controlled.  This is useful for displaying version
213 "   information in the status bar.  Additional options may be set by
214 "   individual VCS plugins.
215 "
216 " VCSCommandMappings
217 "   This variable, if set, overrides the default mappings used for shortcuts.
218 "   It should be a List of 2-element Lists, each containing a shortcut and
219 "   function name pair.
220 "
221 " VCSCommandMapPrefix
222 "   This variable, if set, overrides the default mapping prefix ('<Leader>c').
223 "   This allows customization of the mapping space used by the vcscommand
224 "   shortcuts.
225 "
226 " VCSCommandResultBufferNameExtension
227 "   This variable, if set to a non-blank value, is appended to the name of the
228 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
229 "   help avoid problems caused by autocommands dependent on file extension.
230 "
231 " VCSCommandResultBufferNameFunction
232 "   This variable, if set, specifies a custom function for naming VCS command
233 "   output buffers.  This function will be passed the following arguments:
234 "
235 "   command - name of the VCS command being executed (such as 'Log' or
236 "   'Diff').
237 "
238 "   originalBuffer - buffer number of the source file.
239 "
240 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
241 "
242 "   statusText - extra text associated with the VCS action (such as version
243 "   numbers).
244 "
245 " VCSCommandSplit
246 "   This variable controls the orientation of the various window splits that
247 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
248 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
249 "   If set to 'horizontal', the resulting windows will be on stacked on top of
250 "   one another.  If set to 'vertical', the resulting windows will be
251 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
252 "   VCSVimDiff windows.
253 "
254 " VCSCommandVCSTypeOverride
255 "   This variable allows the VCS type detection to be overridden on a
256 "   path-by-path basis.  The value of this variable is expected to be a List
257 "   of Lists.  Each high-level List item is a List containing two elements.
258 "   The first element is a regular expression that will be matched against the
259 "   full file name of a given buffer.  If it matches, the second element will
260 "   be used as the VCS type.
261 "
262 " Event documentation {{{2
263 "   For additional customization, VCSCommand.vim uses User event autocommand
264 "   hooks.  Each event is in the VCSCommand group, and different patterns
265 "   match the various hooks.
266 "
267 "   For instance, the following could be added to the vimrc to provide a 'q'
268 "   mapping to quit a VCS scratch buffer:
269 "
270 "   augroup VCSCommand
271 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr> 
272 "   augroup END
273 "
274 "   The following hooks are available:
275 "
276 "   VCSBufferCreated           This event is fired just after a VCS command
277 "                              output buffer is created.  It is executed
278 "                              within the context of the new buffer.
279 "
280 "   VCSBufferSetup             This event is fired just after VCS buffer setup
281 "                              occurs, if enabled.
282 "
283 "   VCSPluginInit              This event is fired when the VCSCommand plugin
284 "                              first loads.
285 "
286 "   VCSPluginFinish            This event is fired just after the VCSCommand
287 "                              plugin loads.
288 "
289 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
290 "                              command executes to allow customization of,
291 "                              for instance, window placement and focus.
292 "
293 " Section: Plugin header {{{1
294
295 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
296 " completes.  This allows various actions to only be taken by functions after
297 " system initialization.
298
299 if exists('VCSCommandDisableAll')
300         finish
301 endif
302
303 if exists('loaded_VCSCommand')
304         finish
305 endif
306 let loaded_VCSCommand = 1
307
308 if v:version < 700
309         "echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
310         finish
311 endif
312
313 let s:save_cpo=&cpo
314 set cpo&vim
315
316 " Section: Event group setup {{{1
317
318 augroup VCSCommand
319 augroup END
320
321 augroup VCSCommandCommit
322 augroup END
323
324 " Section: Plugin initialization {{{1
325 silent do VCSCommand User VCSPluginInit
326
327 " Section: Constants declaration {{{1
328
329 let g:VCSCOMMAND_IDENTIFY_EXACT = 1
330 let g:VCSCOMMAND_IDENTIFY_INEXACT = -1
331
332 " Section: Script variable initialization {{{1
333
334 " plugin-specific information:  {vcs -> [script, {command -> function}, {key -> mapping}]}
335 let s:plugins = {}
336
337 " temporary values of overridden configuration variables
338 let s:optionOverrides = {}
339
340 " state flag used to vary behavior of certain automated actions
341 let s:isEditFileRunning = 0
342
343 " commands needed to restore diff buffers to their original state
344 unlet! s:vimDiffRestoreCmd
345
346 " original buffer currently reflected in vimdiff windows
347 unlet! s:vimDiffSourceBuffer
348
349
350 unlet! s:vimDiffScratchList
351
352 " Section: Utility functions {{{1
353
354 " Function: s:ReportError(mapping) {{{2
355 " Displays the given error in a consistent faction.  This is intended to be
356 " invoked from a catch statement.
357
358 function! s:ReportError(error)
359         echohl WarningMsg|echomsg 'VCSCommand:  ' . a:error|echohl None
360 endfunction
361
362
363 " Function: s:CreateMapping(shortcut, expansion, display) {{{2
364 " Creates the given mapping by prepending the contents of
365 " 'VCSCommandMapPrefix' (by default '<Leader>c') to the given shortcut and
366 " mapping it to the given plugin function.  If a mapping exists for the
367 " specified shortcut + prefix, emit an error but continue.  If a mapping
368 " exists for the specified function, do nothing.
369
370 function! s:CreateMapping(shortcut, expansion, display)
371         let lhs = VCSCommandGetOption('VCSCommandMapPrefix', '<Leader>c') . a:shortcut
372         if !hasmapto(a:expansion)
373                 try
374                         execute 'nmap <silent> <unique>' lhs a:expansion
375                 catch /^Vim(.*):E227:/
376                         if(&verbose != 0)
377                                 echohl WarningMsg|echomsg 'VCSCommand:  mapping ''' . lhs . ''' already exists, refusing to overwrite.  The mapping for ' . a:display . ' will not be available.'|echohl None
378                         endif
379                 endtry
380         endif
381 endfunction
382
383 " Function: s:ExecuteExtensionMapping(mapping) {{{2
384 " Invokes the appropriate extension mapping depending on the type of the
385 " current buffer.
386
387 function! s:ExecuteExtensionMapping(mapping)
388         let buffer = bufnr('%')
389         let vcsType = VCSCommandGetVCSType(buffer)
390         if !has_key(s:plugins, vcsType)
391                 throw 'Unknown VCS type:  ' . vcsType
392         endif
393         if !has_key(s:plugins[vcsType][2], a:mapping)
394                 throw 'This extended mapping is not defined for ' . vcsType
395         endif
396         silent execute 'normal' ':' .  s:plugins[vcsType][2][a:mapping] . "\<CR>"
397 endfunction
398
399 " Function: s:ExecuteVCSCommand(command, argList) {{{2
400 " Calls the indicated plugin-specific VCS command on the current buffer.
401 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
402 " occurs.
403
404 function! s:ExecuteVCSCommand(command, argList)
405         try
406                 let buffer = bufnr('%')
407
408                 let vcsType = VCSCommandGetVCSType(buffer)
409                 if !has_key(s:plugins, vcsType)
410                         throw 'Unknown VCS type:  ' . vcsType
411                 endif
412
413                 let originalBuffer = VCSCommandGetOriginalBuffer(buffer)
414                 let bufferName = bufname(originalBuffer)
415
416                 " It is already known that the directory is under VCS control.  No further
417                 " checks are needed.  Otherwise, perform some basic sanity checks to avoid
418                 " VCS-specific error messages from confusing things.
419                 if !isdirectory(bufferName)
420                         if !filereadable(bufferName)
421                                 throw 'No such file ' . bufferName
422                         endif
423                 endif
424
425                 let functionMap = s:plugins[vcsType][1]
426                 if !has_key(functionMap, a:command)
427                         throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
428                 endif
429                 return functionMap[a:command](a:argList)
430         catch
431                 call s:ReportError(v:exception)
432                 return -1
433         endtry
434 endfunction
435
436 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
437 " Default method of generating the name for VCS result buffers.  This can be
438 " overridden with the VCSResultBufferNameFunction variable.
439
440 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
441         let fileName = bufname(a:originalBuffer)
442         let bufferName = a:vcsType . ' ' . a:command
443         if strlen(a:statusText) > 0
444                 let bufferName .= ' ' . a:statusText
445         endif
446         let bufferName .= ' ' . fileName
447         let counter = 0
448         let versionedBufferName = bufferName
449         while buflisted(versionedBufferName)
450                 let counter += 1
451                 let versionedBufferName = bufferName . ' (' . counter . ')'
452         endwhile
453         return versionedBufferName
454 endfunction
455
456 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
457 " Method of generating the name for VCS result buffers that uses the original
458 " file name with the VCS type and command appended as extensions.
459
460 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
461         let fileName = bufname(a:originalBuffer)
462         let bufferName = a:vcsType . ' ' . a:command
463         if strlen(a:statusText) > 0
464                 let bufferName .= ' ' . a:statusText
465         endif
466         let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
467         let counter = 0
468         let versionedBufferName = bufferName
469         while buflisted(versionedBufferName)
470                 let counter += 1
471                 let versionedBufferName = '(' . counter . ') ' . bufferName
472         endwhile
473         return versionedBufferName
474 endfunction
475
476 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
477 " Creates a new buffer of the given name and associates it with the given
478 " original buffer.
479
480 function! s:EditFile(command, originalBuffer, statusText)
481         let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
482
483         let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
484         if nameExtension == ''
485                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
486         else
487                 let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
488         endif
489
490         let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
491
492         " Protect against useless buffer set-up
493         let s:isEditFileRunning += 1
494         try
495                 let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
496                 if editCommand == 'split'
497                         if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
498                                 rightbelow split
499                         else
500                                 vert rightbelow split
501                         endif
502                 endif
503
504                 enew
505
506                 let b:VCSCommandCommand = a:command
507                 let b:VCSCommandOriginalBuffer = a:originalBuffer
508                 let b:VCSCommandSourceFile = bufname(a:originalBuffer)
509                 let b:VCSCommandVCSType = vcsType
510
511                 setlocal buftype=nofile
512                 setlocal noswapfile
513                 let &filetype = vcsType . a:command
514
515                 if a:statusText != ''
516                         let b:VCSCommandStatusText = a:statusText
517                 endif
518
519                 if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
520                         setlocal bufhidden=delete
521                 endif
522                 silent noautocmd file `=resultBufferName`
523         finally
524                 let s:isEditFileRunning -= 1
525         endtry
526 endfunction
527
528 " Function: s:SetupBuffer() {{{2
529 " Attempts to set the b:VCSCommandBufferInfo variable
530
531 function! s:SetupBuffer()
532         if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
533                 " This buffer is already set up.
534                 return
535         endif
536
537         if !isdirectory(@%) && (strlen(&buftype) > 0 || !filereadable(@%))
538                 " No special status for special buffers other than directory buffers.
539                 return
540         endif
541
542         if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
543                 unlet! b:VCSCommandBufferSetup
544                 return
545         endif
546
547         try
548                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
549                 let b:VCSCommandBufferInfo = s:plugins[vcsType][1].GetBufferInfo()
550                 silent do VCSCommand User VCSBufferSetup
551         catch /No suitable plugin/
552                 " This is not a VCS-controlled file.
553                 let b:VCSCommandBufferInfo = []
554         endtry
555
556         let b:VCSCommandBufferSetup = 1
557 endfunction
558
559 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
560 " Resets the buffer setup state of the original buffer for a given VCS scratch
561 " buffer.
562 " Returns:  The VCS buffer number in a passthrough mode.
563
564 function! s:MarkOrigBufferForSetup(buffer)
565         checktime
566         if a:buffer > 0 
567                 let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
568                 " This should never not work, but I'm paranoid
569                 if origBuffer != a:buffer
570                         call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
571                 endif
572         endif
573         return a:buffer
574 endfunction
575
576 " Function: s:OverrideOption(option, [value]) {{{2
577 " Provides a temporary override for the given VCS option.  If no value is
578 " passed, the override is disabled.
579
580 function! s:OverrideOption(option, ...)
581         if a:0 == 0
582                 call remove(s:optionOverrides[a:option], -1)
583         else
584                 if !has_key(s:optionOverrides, a:option)
585                         let s:optionOverrides[a:option] = []
586                 endif
587                 call add(s:optionOverrides[a:option], a:1)
588         endif
589 endfunction
590
591 " Function: s:WipeoutCommandBuffers() {{{2
592 " Clears all current VCS output buffers of the specified type for a given source.
593
594 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
595         let buffer = 1
596         while buffer <= bufnr('$')
597                 if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
598                         if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
599                                 execute 'bw' buffer
600                         endif
601                 endif
602                 let buffer = buffer + 1
603         endwhile
604 endfunction
605
606 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
607 " Checks whether the given buffer is one whose deletion should trigger
608 " restoration of an original buffer after it was diffed.  If so, it executes
609 " the appropriate setting command stored with that original buffer.
610
611 function! s:VimDiffRestore(vimDiffBuff)
612         let s:isEditFileRunning += 1
613         try
614                 if exists('s:vimDiffSourceBuffer')
615                         if a:vimDiffBuff == s:vimDiffSourceBuffer
616                                 " Original file is being removed.
617                                 unlet! s:vimDiffSourceBuffer
618                                 unlet! s:vimDiffRestoreCmd
619                                 unlet! s:vimDiffScratchList
620                         else
621                                 let index = index(s:vimDiffScratchList, a:vimDiffBuff)
622                                 if index >= 0
623                                         call remove(s:vimDiffScratchList, index)
624                                         if len(s:vimDiffScratchList) == 0
625                                                 if exists('s:vimDiffRestoreCmd')
626                                                         " All scratch buffers are gone, reset the original.
627                                                         " Only restore if the source buffer is still in Diff mode
628
629                                                         let sourceWinNR = bufwinnr(s:vimDiffSourceBuffer)
630                                                         if sourceWinNR != -1
631                                                                 " The buffer is visible in at least one window
632                                                                 let currentWinNR = winnr()
633                                                                 while winbufnr(sourceWinNR) != -1
634                                                                         if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
635                                                                                 execute sourceWinNR . 'wincmd w'
636                                                                                 if getwinvar(0, '&diff')
637                                                                                         execute s:vimDiffRestoreCmd
638                                                                                 endif
639                                                                         endif
640                                                                         let sourceWinNR = sourceWinNR + 1
641                                                                 endwhile
642                                                                 execute currentWinNR . 'wincmd w'
643                                                         else
644                                                                 " The buffer is hidden.  It must be visible in order to set the
645                                                                 " diff option.
646                                                                 let currentBufNR = bufnr('')
647                                                                 execute 'hide buffer' s:vimDiffSourceBuffer
648                                                                 if getwinvar(0, '&diff')
649                                                                         execute s:vimDiffRestoreCmd
650                                                                 endif
651                                                                 execute 'hide buffer' currentBufNR
652                                                         endif
653
654                                                         unlet s:vimDiffRestoreCmd
655                                                 endif 
656                                                 " All buffers are gone.
657                                                 unlet s:vimDiffSourceBuffer
658                                                 unlet s:vimDiffScratchList
659                                         endif
660                                 endif
661                         endif
662                 endif
663         finally
664                 let s:isEditFileRunning -= 1
665         endtry
666 endfunction
667
668 " Section: Generic VCS command functions {{{1
669
670 " Function: s:VCSCommit() {{{2
671 function! s:VCSCommit(bang, message)
672         try
673                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
674                 if !has_key(s:plugins, vcsType)
675                         throw 'Unknown VCS type:  ' . vcsType
676                 endif
677
678                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
679
680                 " Handle the commit message being specified.  If a message is supplied, it
681                 " is used; if bang is supplied, an empty message is used; otherwise, the
682                 " user is provided a buffer from which to edit the commit message.
683
684                 if strlen(a:message) > 0 || a:bang == '!'
685                         return s:VCSFinishCommit([a:message], originalBuffer)
686                 endif
687
688                 call s:EditFile('commitlog', originalBuffer, '')
689                 setlocal ft=vcscommit
690
691                 " Create a commit mapping.
692
693                 nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
694
695                 silent 0put ='VCS: ----------------------------------------------------------------------'
696                 silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
697                 silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
698
699                 if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
700                         setlocal buftype=acwrite
701                         au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
702                         silent put ='VCS: or write this buffer'
703                 endif
704
705                 silent put ='VCS: ----------------------------------------------------------------------'
706                 $
707                 setlocal nomodified
708         catch
709                 call s:ReportError(v:exception)
710                 return -1
711         endtry
712 endfunction
713
714 " Function: s:VCSFinishCommitWithBuffer() {{{2
715 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
716 " which removes all lines starting with 'VCS:'.
717
718 function! s:VCSFinishCommitWithBuffer()
719         setlocal nomodified
720         let currentBuffer = bufnr('%') 
721         let logMessageList = getbufline('%', 1, '$')
722         call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
723         let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
724         if resultBuffer >= 0
725                 execute 'bw' currentBuffer
726         endif
727         return resultBuffer
728 endfunction
729
730 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
731 function! s:VCSFinishCommit(logMessageList, originalBuffer)
732         let shellSlashBak = &shellslash
733         try
734                 set shellslash
735                 let messageFileName = tempname()
736                 call writefile(a:logMessageList, messageFileName)
737                 try
738                         let resultBuffer = s:ExecuteVCSCommand('Commit', [messageFileName])
739                         if resultBuffer < 0
740                                 return resultBuffer
741                         endif
742                         return s:MarkOrigBufferForSetup(resultBuffer)
743                 finally
744                         call delete(messageFileName)
745                 endtry
746         finally
747                 let &shellslash = shellSlashBak
748         endtry
749 endfunction
750
751 " Function: s:VCSGotoOriginal(bang) {{{2
752 function! s:VCSGotoOriginal(bang)
753         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
754         if originalBuffer > 0
755                 let origWinNR = bufwinnr(originalBuffer)
756                 if origWinNR == -1
757                         execute 'buffer' originalBuffer
758                 else
759                         execute origWinNR . 'wincmd w'
760                 endif
761                 if a:bang == '!'
762                         let buffnr = 1
763                         let buffmaxnr = bufnr('$')
764                         while buffnr <= buffmaxnr
765                                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
766                                         execute 'bw' buffnr
767                                 endif
768                                 let buffnr = buffnr + 1
769                         endwhile
770                 endif
771         endif
772 endfunction
773
774 " Function: s:VCSVimDiff(...) {{{2
775 function! s:VCSVimDiff(...)
776         try
777                 let vcsType = VCSCommandGetVCSType(bufnr('%'))
778                 if !has_key(s:plugins, vcsType)
779                         throw 'Unknown VCS type:  ' . vcsType
780                 endif
781                 let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
782                 let s:isEditFileRunning = s:isEditFileRunning + 1
783                 try
784                         " If there's already a VimDiff'ed window, restore it.
785                         " There may only be one VCSVimDiff original window at a time.
786
787                         if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
788                                 " Clear the existing vimdiff setup by removing the result buffers.
789                                 call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
790                         endif
791
792                         let orientation = &diffopt =~ 'horizontal' ? 'horizontal' : 'vertical'
793                         let orientation = VCSCommandGetOption('VCSCommandSplit', orientation)
794                         let orientation = VCSCommandGetOption('VCSCommandDiffSplit', orientation)
795
796                         " Split and diff
797                         if(a:0 == 2)
798                                 " Reset the vimdiff system, as 2 explicit versions were provided.
799                                 if exists('s:vimDiffSourceBuffer')
800                                         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
801                                 endif
802                                 let resultBuffer = s:plugins[vcsType][1].Review([a:1])
803                                 if resultBuffer < 0
804                                         echomsg 'Can''t open revision ' . a:1
805                                         return resultBuffer
806                                 endif
807                                 let b:VCSCommandCommand = 'vimdiff'
808                                 diffthis
809                                 let s:vimDiffScratchList = [resultBuffer]
810                                 " If no split method is defined, cheat, and set it to vertical.
811                                 try
812                                         call s:OverrideOption('VCSCommandSplit', orientation)
813                                         let resultBuffer = s:plugins[vcsType][1].Review([a:2])
814                                 finally
815                                         call s:OverrideOption('VCSCommandSplit')
816                                 endtry
817                                 if resultBuffer < 0
818                                         echomsg 'Can''t open revision ' . a:1
819                                         return resultBuffer
820                                 endif
821                                 let b:VCSCommandCommand = 'vimdiff'
822                                 diffthis
823                                 let s:vimDiffScratchList += [resultBuffer]
824                         else
825                                 " Add new buffer
826                                 call s:OverrideOption('VCSCommandEdit', 'split')
827                                 try
828                                         " Force splitting behavior, otherwise why use vimdiff?
829                                         call s:OverrideOption('VCSCommandSplit', orientation)
830                                         try
831                                                 if(a:0 == 0)
832                                                         let resultBuffer = s:plugins[vcsType][1].Review([])
833                                                 else
834                                                         let resultBuffer = s:plugins[vcsType][1].Review([a:1])
835                                                 endif
836                                         finally
837                                                 call s:OverrideOption('VCSCommandSplit')
838                                         endtry
839                                 finally
840                                         call s:OverrideOption('VCSCommandEdit')
841                                 endtry
842                                 if resultBuffer < 0
843                                         echomsg 'Can''t open current revision'
844                                         return resultBuffer
845                                 endif
846                                 let b:VCSCommandCommand = 'vimdiff'
847                                 diffthis
848
849                                 if !exists('s:vimDiffSourceBuffer')
850                                         " New instance of vimdiff.
851                                         let s:vimDiffScratchList = [resultBuffer]
852
853                                         " This could have been invoked on a VCS result buffer, not the
854                                         " original buffer.
855                                         wincmd W
856                                         execute 'buffer' originalBuffer
857                                         " Store info for later original buffer restore
858                                         let s:vimDiffRestoreCmd = 
859                                                                 \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
860                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
861                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
862                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
863                                                                 \ . '|call setbufvar('.originalBuffer.', ''&foldlevel'', '''.getbufvar(originalBuffer, '&foldlevel').''')'
864                                                                 \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
865                                                                 \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
866                                                                 \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
867                                         diffthis
868                                         wincmd w
869                                 else
870                                         " Adding a window to an existing vimdiff
871                                         let s:vimDiffScratchList += [resultBuffer]
872                                 endif
873                         endif
874
875                         let s:vimDiffSourceBuffer = originalBuffer
876
877                         " Avoid executing the modeline in the current buffer after the autocommand.
878
879                         let currentBuffer = bufnr('%')
880                         let saveModeline = getbufvar(currentBuffer, '&modeline')
881                         try
882                                 call setbufvar(currentBuffer, '&modeline', 0)
883                                 silent do VCSCommand User VCSVimDiffFinish
884                         finally
885                                 call setbufvar(currentBuffer, '&modeline', saveModeline)
886                         endtry
887                         return resultBuffer
888                 finally
889                         let s:isEditFileRunning = s:isEditFileRunning - 1
890                 endtry
891         catch
892                 call s:ReportError(v:exception)
893                 return -1
894         endtry
895 endfunction
896
897 " Section: Public functions {{{1
898
899 " Function: VCSCommandGetVCSType() {{{2
900 " Sets the b:VCSCommandVCSType variable in the given buffer to the
901 " appropriate source control system name.
902 "
903 " This uses the Identify extension function to test the buffer.  If the
904 " Identify function returns VCSCOMMAND_IDENTIFY_EXACT, the match is considered
905 " exact.  If the Identify function returns VCSCOMMAND_IDENTIFY_INEXACT, the
906 " match is considered inexact, and is only applied if no exact match is found.
907 " Multiple inexact matches is currently considered an error.
908
909 function! VCSCommandGetVCSType(buffer)
910         let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
911         if strlen(vcsType) > 0
912                 return vcsType
913         endif
914         if exists("g:VCSCommandVCSTypeOverride")
915                 let fullpath = fnamemodify(bufname(a:buffer), ':p')
916                 for [path, vcsType] in g:VCSCommandVCSTypeOverride
917                         if match(fullpath, path) > -1
918                                 call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
919                                 return vcsType
920                         endif
921                 endfor
922         endif
923         let matches = []
924         for vcsType in keys(s:plugins)
925                 let identified = s:plugins[vcsType][1].Identify(a:buffer)
926                 if identified
927                         if identified == g:VCSCOMMAND_IDENTIFY_EXACT
928                                 let matches = [vcsType]
929                                 break
930                         else
931                                 let matches += [vcsType]
932                         endif
933                 endif
934         endfor
935         if len(matches) == 1
936                 call setbufvar(a:buffer, 'VCSCommandVCSType', matches[0])
937                 return matches[0]
938         elseif len(matches) == 0
939                 throw 'No suitable plugin'
940         else
941                 throw 'Too many matching VCS:  ' . join(matches)
942         endif
943 endfunction
944
945 " Function: VCSCommandChdir(directory) {{{2
946 " Changes the current directory, respecting :lcd changes.
947
948 function! VCSCommandChdir(directory)
949         let command = 'cd'
950         if exists("*haslocaldir") && haslocaldir()
951                 let command = 'lcd'
952         endif
953         execute command escape(a:directory, ' ')
954 endfunction
955
956 " Function: VCSCommandChangeToCurrentFileDir() {{{2
957 " Go to the directory in which the given file is located.
958
959 function! VCSCommandChangeToCurrentFileDir(fileName)
960         let oldCwd = getcwd()
961         let newCwd = fnamemodify(resolve(a:fileName), ':p:h')
962         if strlen(newCwd) > 0
963                 call VCSCommandChdir(newCwd)
964         endif
965         return oldCwd
966 endfunction
967
968 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
969 " Attempts to locate the original file to which VCS operations were applied
970 " for a given buffer.
971
972 function! VCSCommandGetOriginalBuffer(vcsBuffer)
973         let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
974         if origBuffer
975                 if bufexists(origBuffer)
976                         return origBuffer
977                 else
978                         " Original buffer no longer exists.
979                         throw 'Original buffer for this VCS buffer no longer exists.'
980                 endif
981         else
982                 " No original buffer
983                 return a:vcsBuffer
984         endif
985 endfunction
986
987 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
988 " Allows VCS modules to register themselves.
989
990 function! VCSCommandRegisterModule(name, path, commandMap, mappingMap)
991         let s:plugins[a:name] = [a:path, a:commandMap, a:mappingMap]
992         if !empty(a:mappingMap)
993                                 \ && !VCSCommandGetOption('VCSCommandDisableMappings', 0)
994                                 \ && !VCSCommandGetOption('VCSCommandDisableExtensionMappings', 0)
995                 for shortcut in keys(a:mappingMap)
996                         let expansion = ":call <SID>ExecuteExtensionMapping('" . shortcut . "')<CR>"
997                         call s:CreateMapping(shortcut, expansion, a:name . " extension mapping " . shortcut)
998                 endfor
999         endif
1000 endfunction
1001
1002 " Function: VCSCommandDoCommand(cmd, cmdName, statusText, [options]) {{{2
1003 " General skeleton for VCS function execution.  The given command is executed
1004 " after appending the current buffer name (or substituting it for
1005 " <VCSCOMMANDFILE>, if such a token is present).  The output is captured in a
1006 " new buffer.
1007 "
1008 " The optional 'options' Dictionary may contain the following options:
1009 "       allowNonZeroExit:  if non-zero, if the underlying VCS command has a
1010 "               non-zero exit status, the command is still considered
1011 "               successfuly.  This defaults to zero.
1012 " Returns: name of the new command buffer containing the command results
1013
1014 function! VCSCommandDoCommand(cmd, cmdName, statusText, options)
1015         let allowNonZeroExit = 0
1016         if has_key(a:options, 'allowNonZeroExit')
1017                 let allowNonZeroExit = a:options.allowNonZeroExit
1018         endif
1019
1020         let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
1021         if originalBuffer == -1 
1022                 throw 'Original buffer no longer exists, aborting.'
1023         endif
1024
1025         let path = resolve(bufname(originalBuffer))
1026
1027         " Work with netrw or other systems where a directory listing is displayed in
1028         " a buffer.
1029
1030         if isdirectory(path)
1031                 let fileName = '.'
1032         else
1033                 let fileName = fnamemodify(path, ':t')
1034         endif
1035
1036         if match(a:cmd, '<VCSCOMMANDFILE>') > 0
1037                 let fullCmd = substitute(a:cmd, '<VCSCOMMANDFILE>', fileName, 'g')
1038         else
1039                 let fullCmd = a:cmd . ' "' . fileName . '"'
1040         endif
1041
1042         " Change to the directory of the current buffer.  This is done for CVS, but
1043         " is left in for other systems as it does not affect them negatively.
1044
1045         let oldCwd = VCSCommandChangeToCurrentFileDir(path)
1046         try
1047                 let output = system(fullCmd)
1048         finally
1049                 call VCSCommandChdir(oldCwd)
1050         endtry
1051
1052         " HACK:  if line endings in the repository have been corrupted, the output
1053         " of the command will be confused.
1054         let output = substitute(output, "\r", '', 'g')
1055
1056         if v:shell_error && !allowNonZeroExit
1057                 if strlen(output) == 0
1058                         throw 'Version control command failed'
1059                 else
1060                         let output = substitute(output, '\n', '  ', 'g')
1061                         throw 'Version control command failed:  ' . output
1062                 endif
1063         endif
1064
1065         if strlen(output) == 0
1066                 " Handle case of no output.  In this case, it is important to check the
1067                 " file status, especially since cvs edit/unedit may change the attributes
1068                 " of the file with no visible output.
1069
1070                 checktime
1071                 return 0
1072         endif
1073
1074         call s:EditFile(a:cmdName, originalBuffer, a:statusText)
1075
1076         silent 0put=output
1077
1078         " The last command left a blank line at the end of the buffer.  If the
1079         " last line is folded (a side effect of the 'put') then the attempt to
1080         " remove the blank line will kill the last fold.
1081         "
1082         " This could be fixed by explicitly detecting whether the last line is
1083         " within a fold, but I prefer to simply unfold the result buffer altogether.
1084
1085         if has('folding')
1086                 normal zR
1087         endif
1088
1089         $d
1090         1
1091
1092         " Define the environment and execute user-defined hooks.
1093
1094         silent do VCSCommand User VCSBufferCreated
1095         return bufnr('%')
1096 endfunction
1097
1098 " Function: VCSCommandGetOption(name, default) {{{2
1099 " Grab a user-specified option to override the default provided.  Options are
1100 " searched in the window, buffer, then global spaces.
1101
1102 function! VCSCommandGetOption(name, default)
1103         if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
1104                 return s:optionOverrides[a:name][-1]
1105         elseif exists('w:' . a:name)
1106                 return w:{a:name}
1107         elseif exists('b:' . a:name)
1108                 return b:{a:name}
1109         elseif exists('g:' . a:name)
1110                 return g:{a:name}
1111         else
1112                 return a:default
1113         endif
1114 endfunction
1115
1116 " Function: VCSCommandDisableBufferSetup() {{{2
1117 " Global function for deactivating the buffer autovariables.
1118
1119 function! VCSCommandDisableBufferSetup()
1120         let g:VCSCommandEnableBufferSetup = 0
1121         silent! augroup! VCSCommandPlugin
1122 endfunction
1123
1124 " Function: VCSCommandEnableBufferSetup() {{{2
1125 " Global function for activating the buffer autovariables.
1126
1127 function! VCSCommandEnableBufferSetup()
1128         let g:VCSCommandEnableBufferSetup = 1
1129         augroup VCSCommandPlugin
1130                 au!
1131                 au BufEnter * call s:SetupBuffer()
1132         augroup END
1133
1134         " Only auto-load if the plugin is fully loaded.  This gives other plugins a
1135         " chance to run.
1136         if g:loaded_VCSCommand == 2
1137                 call s:SetupBuffer()
1138         endif
1139 endfunction
1140
1141 " Function: VCSCommandGetStatusLine() {{{2
1142 " Default (sample) status line entry for VCS-controlled files.  This is only
1143 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
1144 " variable for how to do this).
1145
1146 function! VCSCommandGetStatusLine()
1147         if exists('b:VCSCommandCommand')
1148                 " This is a result buffer.  Return nothing because the buffer name
1149                 " contains information already.
1150                 return ''
1151         endif
1152
1153         if exists('b:VCSCommandVCSType')
1154                                 \ && exists('g:VCSCommandEnableBufferSetup')
1155                                 \ && g:VCSCommandEnableBufferSetup
1156                                 \ && exists('b:VCSCommandBufferInfo')
1157                 return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1158         else
1159                 return ''
1160         endif
1161 endfunction
1162
1163 " Section: Command definitions {{{1
1164 " Section: Primary commands {{{2
1165 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', [<f-args>]))
1166 com! -nargs=* VCSAnnotate call s:ExecuteVCSCommand('Annotate', [<f-args>])
1167 com! -nargs=* VCSBlame call s:ExecuteVCSCommand('Annotate', [<f-args>])
1168 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1169 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', [<f-args>])
1170 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', [<f-args>])
1171 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1172 com! -nargs=* VCSInfo call s:ExecuteVCSCommand('Info', [<f-args>])
1173 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', [<f-args>]))
1174 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', [<f-args>])
1175 com! -nargs=* VCSRemove call s:ExecuteVCSCommand('Delete', [<f-args>])
1176 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', []))
1177 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', [<f-args>])
1178 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', [<f-args>])
1179 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', [<f-args>]))
1180 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', []))
1181 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1182
1183 " Section: VCS buffer management commands {{{2
1184 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1185 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1186
1187 " Allow reloading VCSCommand.vim
1188 com! VCSReload let savedPlugins = s:plugins|let s:plugins = {}|aunmenu Plugin.VCS|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for plugin in values(savedPlugins)|execute 'source' plugin[0]|endfor|unlet savedPlugins
1189
1190 " Section: Plugin command mappings {{{1
1191 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1192 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1193 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1194 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1195 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1196 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1197 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1198 nnoremap <silent> <Plug>VCSInfo :VCSInfo<CR>
1199 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1200 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1201 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1202 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1203 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1204 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1205 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1206 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1207
1208 " Section: Default mappings {{{1
1209
1210 let s:defaultMappings = [
1211                         \['a', 'VCSAdd'],
1212                         \['c', 'VCSCommit'],
1213                         \['D', 'VCSDelete'],
1214                         \['d', 'VCSDiff'],
1215                         \['G', 'VCSClearAndGotoOriginal'],
1216                         \['g', 'VCSGotoOriginal'],
1217                         \['i', 'VCSInfo'],
1218                         \['L', 'VCSLock'],
1219                         \['l', 'VCSLog'],
1220                         \['n', 'VCSAnnotate'],
1221                         \['q', 'VCSRevert'],
1222                         \['r', 'VCSReview'],
1223                         \['s', 'VCSStatus'],
1224                         \['U', 'VCSUnlock'],
1225                         \['u', 'VCSUpdate'],
1226                         \['v', 'VCSVimDiff'],
1227                         \]
1228
1229 if !VCSCommandGetOption('VCSCommandDisableMappings', 0)
1230         for [shortcut, vcsFunction] in VCSCommandGetOption('VCSCommandMappings', s:defaultMappings)
1231                 call s:CreateMapping(shortcut, '<Plug>' . vcsFunction, '''' . vcsFunction . '''')
1232         endfor
1233 endif
1234
1235 " Section: Menu items {{{1
1236 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1237 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1238 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1239 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1240 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1241 amenu <silent> &Plugin.VCS.&Info       <Plug>VCSInfo
1242 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1243 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1244 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1245 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1246 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1247 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1248
1249 " Section: Autocommands to restore vimdiff state {{{1
1250 augroup VimDiffRestore
1251         au!
1252         au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1253 augroup END
1254
1255 " Section: Optional activation of buffer management {{{1
1256
1257 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1258         call VCSCommandEnableBufferSetup()
1259 endif
1260
1261 " Section: VIM shutdown hook {{{1
1262
1263 " Close all result buffers when VIM exits, to prevent them from being restored
1264 " via viminfo.
1265
1266 " Function: s:CloseAllResultBuffers() {{{2
1267 " Closes all vcscommand result buffers.
1268 function! s:CloseAllResultBuffers()
1269         " This avoids using bufdo as that may load buffers already loaded in another
1270         " vim process, resulting in an error.
1271         let buffnr = 1
1272         let buffmaxnr = bufnr('$')
1273         while buffnr <= buffmaxnr
1274                 if getbufvar(buffnr, 'VCSCommandOriginalBuffer') != "" 
1275                         execute 'bw' buffnr
1276                 endif
1277                 let buffnr = buffnr + 1
1278         endwhile
1279 endfunction
1280
1281 augroup VCSCommandVIMShutdown
1282         au!
1283         au VimLeavePre * call s:CloseAllResultBuffers()
1284 augroup END
1285
1286 " Section: Plugin completion {{{1
1287
1288 let loaded_VCSCommand = 2
1289
1290 silent do VCSCommand User VCSPluginFinish
1291
1292 let &cpo = s:save_cpo