r8@localhost: bob | 2007-02-08 11:02:13 -0600
[vcscommand.git] / plugin / vcscommand.vim
blob553bd68703ac642f84b1ae84a3d8c715785c3b9c
1 " vim600: set foldmethod=marker:
3 " Vim plugin to assist in working with files under control of CVS or SVN.
5 " Version:       Beta 10
6 " Maintainer:    Bob Hiestand <bob.hiestand@gmail.com>
7 " License:
8 " Copyright (c) 2007 Bob Hiestand
10 " Permission is hereby granted, free of charge, to any person obtaining a copy
11 " of this software and associated documentation files (the "Software"), to
12 " deal in the Software without restriction, including without limitation the
13 " rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
14 " sell copies of the Software, and to permit persons to whom the Software is
15 " furnished to do so, subject to the following conditions:
17 " The above copyright notice and this permission notice shall be included in
18 " all copies or substantial portions of the Software.
20 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 " FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
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.  Those plugins should be placed in a
37 " subdirectory of the standard plugin directory named 'vcscommand'.  Several
38 " options include the name of the version control system in the option name.
39 " Such options use the placeholder text '{VCSType}', which would be replaced
40 " in actual usage with 'CVS' or 'SVN', for instance.
42 " Command documentation {{{2
44 " VCSAdd           Adds the current file to source control.
46 " VCSAnnotate      Displays the current file with each line annotated with the
47 "                  version in which it was most recently changed.  If an
48 "                  argument is given, the argument is used as a revision
49 "                  number to display.  If not given an argument, it uses the
50 "                  most recent version of the file on the current branch.
51 "                  Additionally, if the current buffer is a VCSAnnotate buffer
52 "                  already, the version number on the current line is used.
54 " VCSCommit[!]     Commits changes to the current file to source control.
56 "                  If called with arguments, the arguments are the log message.
58 "                  If '!' is used, an empty log message is committed.
60 "                  If called with no arguments, this is a two-step command.
61 "                  The first step opens a buffer to accept a log message.
62 "                  When that buffer is written, it is automatically closed and
63 "                  the file is committed using the information from that log
64 "                  message.  The commit can be abandoned if the log message
65 "                  buffer is deleted or wiped before being written.
67 " VCSDelete        Deletes the current file and removes it from source control.
69 " VCSDiff          With no arguments, this displays the differences between
70 "                  the current file and its parent version under source
71 "                  control in a new scratch buffer.
73 "                  With one argument, the diff is performed on the
74 "                  current file against the specified revision.
76 "                  With two arguments, the diff is performed between the
77 "                  specified revisions of the current file.
79 "                  This command uses the 'VCSCommand{VCSType}DiffOpt' variable
80 "                  to specify diff options.  If that variable does not exist,
81 "                  a plugin-specific default is used.  If you wish to have no
82 "                  options, then set it to the empty string.
84 " VCSGotoOriginal  Jumps to the source buffer if the current buffer is a VCS
85 "                  scratch buffer.  If VCSGotoOriginal[!] is used, remove all
86 "                  VCS scratch buffers associated with the original file.
88 " VCSLock          Locks the current file in order to prevent other users from
89 "                  concurrently modifying it.  The exact semantics of this
90 "                  command depend on the underlying VCS.
92 " VCSLog           Displays the version history of the current file in a new
93 "                  scratch buffer.
95 " VCSRevert        Replaces the modified version of the current file with the
96 "                  most recent version from the repository.
98 " VCSReview        Displays a particular version of the current file in a new
99 "                  scratch buffer.  If no argument is given, the most recent
100 "                  version of the file on the current branch is retrieved.
102 " VCSStatus        Displays versioning information about the current file in a
103 "                  new scratch buffer.
105 " VCSUnlock        Unlocks the current file in order to allow other users from
106 "                  concurrently modifying it.  The exact semantics of this
107 "                  command depend on the underlying VCS.
109 " VCSUpdate        Updates the current file with any relevant changes from the
110 "                  repository.
112 " VCSVimDiff       Uses vimdiff to display differences between versions of the
113 "                  current file.
115 "                  If no revision is specified, the most recent version of the
116 "                  file on the current branch is used.  With one argument,
117 "                  that argument is used as the revision as above.  With two
118 "                  arguments, the differences between the two revisions is
119 "                  displayed using vimdiff.
121 "                  With either zero or one argument, the original buffer is
122 "                  used to perform the vimdiff.  When the scratch buffer is
123 "                  closed, the original buffer will be returned to normal
124 "                  mode.
126 "                  Once vimdiff mode is started using the above methods,
127 "                  additional vimdiff buffers may be added by passing a single
128 "                  version argument to the command.  There may be up to 4
129 "                  vimdiff buffers total.
131 "                  Using the 2-argument form of the command resets the vimdiff
132 "                  to only those 2 versions.  Additionally, invoking the
133 "                  command on a different file will close the previous vimdiff
134 "                  buffers.
136 " Mapping documentation: {{{2
138 " By default, a mapping is defined for each command.  User-provided mappings
139 " can be used instead by mapping to <Plug>CommandName, for instance:
141 " nmap ,ca <Plug>VCSAdd
143 " The default mappings are as follow:
145 "   <Leader>ca VCSAdd
146 "   <Leader>cn VCSAnnotate
147 "   <Leader>cc VCSCommit
148 "   <Leader>cD VCSDelete
149 "   <Leader>cd VCSDiff
150 "   <Leader>cg VCSGotoOriginal
151 "   <Leader>cG VCSGotoOriginal!
152 "   <Leader>cl VCSLog
153 "   <Leader>cL VCSLock
154 "   <Leader>cr VCSReview
155 "   <Leader>cs VCSStatus
156 "   <Leader>cu VCSUpdate
157 "   <Leader>cU VCSUnlock
158 "   <Leader>cv VCSVimDiff
160 " Options documentation: {{{2
162 " Several variables are checked by the script to determine behavior as follow:
164 " VCSCommandCommitOnWrite
165 "   This variable, if set to a non-zero value, causes the pending commit to
166 "   take place immediately as soon as the log message buffer is written.  If
167 "   set to zero, only the VCSCommit mapping will cause the pending commit to
168 "   occur.  If not set, it defaults to 1.
170 " VCSCommandDeleteOnHide
171 "   This variable, if set to a non-zero value, causes the temporary VCS result
172 "   buffers to automatically delete themselves when hidden.
174 " VCSCommand{VCSType}DiffOpt
175 "   This variable, if set, determines the options passed to the diff command
176 "   of the underlying VCS.  Each VCS plugin defines a default value.
178 " VCSCommandDiffSplit
179 "   This variable overrides the VCSCommandSplit variable, but only for buffers
180 "   created with VCSVimDiff.
182 " VCSCommandEdit
183 "   This variable controls whether to split the current window to display a
184 "   scratch buffer ('split'), or to display it in the current buffer ('edit').
185 "   If not set, it defaults to 'split'.
187 " VCSCommandEnableBufferSetup
188 "   This variable, if set to a non-zero value, activates VCS buffer management
189 "   mode.  This mode means that the buffer variable 'VCSRevision' is set if
190 "   the file is VCS-controlled.  This is useful for displaying version
191 "   information in the status bar.  Additional options may be set by
192 "   individual VCS plugins.
194 " VCSCommandResultBufferNameExtension
195 "   This variable, if set to a non-blank value, is appended to the name of the
196 "   VCS command output buffers.  For example, '.vcs'.  Using this option may
197 "   help avoid problems caused by autocommands dependent on file extension.
199 " VCSCommandResultBufferNameFunction
200 "   This variable, if set, specifies a custom function for naming VCS command
201 "   output buffers.  This function will be passed the following arguments:
203 "   command - name of the VCS command being executed (such as 'Log' or
204 "   'Diff').
206 "   originalBuffer - buffer number of the source file.
208 "   vcsType - type of VCS controlling this file (such as 'CVS' or 'SVN').
210 "   statusText - extra text associated with the VCS action (such as version
211 "   numbers).
213 " VCSCommandSplit
214 "   This variable controls the orientation of the various window splits that
215 "   may occur (such as with VCSVimDiff, when using a VCS command on a VCS
216 "   command buffer, or when the 'VCSCommandEdit' variable is set to 'split'.
217 "   If set to 'horizontal', the resulting windows will be on stacked on top of
218 "   one another.  If set to 'vertical', the resulting windows will be
219 "   side-by-side.  If not set, it defaults to 'horizontal' for all but
220 "   VCSVimDiff windows.
222 " Event documentation {{{2
223 "   For additional customization, VCSCommand.vim uses User event autocommand
224 "   hooks.  Each event is in the VCSCommand group, and different patterns
225 "   match the various hooks.
227 "   For instance, the following could be added to the vimrc to provide a 'q'
228 "   mapping to quit a VCS scratch buffer:
230 "   augroup VCSCommand
231 "     au VCSCommand User VCSBufferCreated silent! nmap <unique> <buffer> q :bwipeout<cr> 
232 "   augroup END
234 "   The following hooks are available:
236 "   VCSBufferCreated           This event is fired just after a VCS command
237 "                              output buffer is created.  It is executed
238 "                              within the context of the new buffer.
240 "   VCSBufferSetup             This event is fired just after VCS buffer setup
241 "                              occurs, if enabled.
243 "   VCSLoadExtensions          This event is fired just before the
244 "                              VCSPluginFinish event.  It is intended to be
245 "                              used only by VCS extensions to register
246 "                              themselves with VCSCommand if they are sourced
247 "                              first.
249 "   VCSPluginInit              This event is fired when the VCSCommand plugin
250 "                              first loads.
252 "   VCSPluginFinish            This event is fired just after the VCSCommand
253 "                              plugin loads.
255 "   VCSVimDiffFinish           This event is fired just after the VCSVimDiff
256 "                              command executes to allow customization of,
257 "                              for instance, window placement and focus.
259 " Section: Plugin header {{{1
261 " loaded_VCSCommand is set to 1 when the initialization begins, and 2 when it
262 " completes.  This allows various actions to only be taken by functions after
263 " system initialization.
265 if exists('loaded_VCSCommand')
266    finish
267 endif
268 let loaded_VCSCommand = 1
270 if v:version < 700
271   echohl WarningMsg|echomsg 'VCSCommand requires at least VIM 7.0'|echohl None
272   finish
273 endif
275 " Section: Event group setup {{{1
277 augroup VCSCommand
278 augroup END
280 augroup VCSCommandCommit
281 augroup END
283 " Section: Plugin initialization {{{1
284 silent do VCSCommand User VCSPluginInit
286 " Section: Script variable initialization {{{1
288 let s:plugins = {}
289 let s:pluginFiles = []
290 let s:extendedMappings = {}
291 let s:optionOverrides = {}
292 let s:isEditFileRunning = 0
294 unlet! s:vimDiffRestoreCmd
295 unlet! s:vimDiffSourceBuffer
296 unlet! s:vimDiffScratchList
298 " Section: Utility functions {{{1
300 " Function: s:ExecuteExtensionMapping(mapping) {{{2
301 " Invokes the appropriate extension mapping depending on the type of the
302 " current buffer.
304 function! s:ExecuteExtensionMapping(mapping)
305   let buffer = bufnr('%')
306   let vcsType = VCSCommandGetVCSType(buffer)
307   if !has_key(s:extendedMappings, vcsType)
308     throw 'Unknown VCS type:  ' . vcsType
309   endif
310   if !has_key(s:extendedMappings[vcsType], a:mapping)
311     throw 'This extended mapping is not defined for ' . vcsType
312   endif
313   silent execute 'normal' ':' .  s:extendedMappings[vcsType][a:mapping] . "\<CR>"
314 endfunction
316 " Function: s:ExecuteVCSCommand(command, buffer, argList) {{{2
317 " Calls the indicated plugin-specific VCS command on the indicated buffer.
318 " Returns: buffer number of resulting output scratch buffer, or -1 if an error
319 " occurs.
321 function! s:ExecuteVCSCommand(command, buffer, argList)
322   try
323     let vcsType = VCSCommandGetVCSType(a:buffer)
324     if !has_key(s:plugins, vcsType)
325       throw 'Unknown VCS type:  ' . vcsType
326     endif
327     let functionMap = s:plugins[vcsType]
328     if !has_key(functionMap, a:command)
329       throw 'Command ''' . a:command . ''' not implemented for ' . vcsType
330     endif
331     return functionMap[a:command](a:argList)
332   catch
333     echohl WarningMsg|echomsg v:exception|echohl None
334     return -1
335   endtry
336 endfunction
338 " Function: s:CreateCommandBuffer(cmd, cmdName, originalBuffer, statusText) {{{2
339 " Creates a new scratch buffer and captures the output from execution of the
340 " given command.  The name of the scratch buffer is returned.
342 function! s:CreateCommandBuffer(cmd, cmdName, originalBuffer, statusText)
343   let output = system(a:cmd)
345   " HACK:  if line endings in the repository have been corrupted, the output
346   " of the command will be confused.
347   let output = substitute(output, "\r", '', 'g')
349   " HACK:  CVS diff command does not return proper error codes
350   if v:shell_error && (a:cmdName != 'diff' || getbufvar(a:originalBuffer, 'VCSCommandVCSType') != 'CVS')
351     if strlen(output) == 0
352       throw 'Version control command failed'
353     else
354       let output = substitute(output, '\n', '  ', 'g')
355       throw 'Version control command failed:  ' . output
356     endif
357   endif
358   if strlen(output) == 0
359     " Handle case of no output.  In this case, it is important to check the
360     " file status, especially since cvs edit/unedit may change the attributes
361     " of the file with no visible output.
363     checktime
364     return 0
365   endif
367   call s:EditFile(a:cmdName, a:originalBuffer, a:statusText)
369   silent 0put=output
371   " The last command left a blank line at the end of the buffer.  If the
372   " last line is folded (a side effect of the 'put') then the attempt to
373   " remove the blank line will kill the last fold.
374   "
375   " This could be fixed by explicitly detecting whether the last line is
376   " within a fold, but I prefer to simply unfold the result buffer altogether.
378   if has('folding')
379     normal zR
380   endif
382   $d
383   1
385   " Define the environment and execute user-defined hooks.
387   silent do VCSCommand User VCSBufferCreated
388   return bufnr('%')
389 endfunction
391 " Function: s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText) {{{2
392 " Default method of generating the name for VCS result buffers.  This can be
393 " overridden with the VCSResultBufferNameFunction variable.
395 function! s:GenerateResultBufferName(command, originalBuffer, vcsType, statusText)
396   let fileName=bufname(a:originalBuffer)
397   let bufferName = a:vcsType . ' ' . a:command
398   if strlen(a:statusText) > 0
399     let bufferName .= ' ' . a:statusText
400   endif
401   let bufferName .= ' ' . fileName
402   let counter = 0
403   let versionedBufferName = bufferName
404   while buflisted(versionedBufferName)
405     let counter += 1
406     let versionedBufferName = bufferName . ' (' . counter . ')'
407   endwhile
408   return versionedBufferName
409 endfunction
411 " Function: s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText) {{{2
412 " Method of generating the name for VCS result buffers that uses the original
413 " file name with the VCS type and command appended as extensions.
415 function! s:GenerateResultBufferNameWithExtension(command, originalBuffer, vcsType, statusText)
416   let fileName=bufname(a:originalBuffer)
417   let bufferName = a:vcsType . ' ' . a:command
418   if strlen(a:statusText) > 0
419     let bufferName .= ' ' . a:statusText
420   endif
421   let bufferName .= ' ' . fileName . VCSCommandGetOption('VCSCommandResultBufferNameExtension', '.vcs')
422   let counter = 0
423   let versionedBufferName = bufferName
424   while buflisted(versionedBufferName)
425     let counter += 1
426     let versionedBufferName = '(' . counter . ') ' . bufferName
427   endwhile
428   return versionedBufferName
429 endfunction
431 " Function: s:EditFile(command, originalBuffer, statusText) {{{2
432 " Creates a new buffer of the given name and associates it with the given
433 " original buffer.
435 function! s:EditFile(command, originalBuffer, statusText)
436   let vcsType = getbufvar(a:originalBuffer, 'VCSCommandVCSType')
438   let nameExtension = VCSCommandGetOption('VCSCommandResultBufferNameExtension', '')
439   if nameExtension == ''
440     let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferName')
441   else
442     let nameFunction = VCSCommandGetOption('VCSCommandResultBufferNameFunction', 's:GenerateResultBufferNameWithExtension')
443   endif
445   let resultBufferName = call(nameFunction, [a:command, a:originalBuffer, vcsType, a:statusText])
447   " Protect against useless buffer set-up
448   let s:isEditFileRunning += 1
449   try
450     let editCommand = VCSCommandGetOption('VCSCommandEdit', 'split')
451     if editCommand == 'split'
452       if VCSCommandGetOption('VCSCommandSplit', 'horizontal') == 'horizontal'
453         rightbelow split
454       else
455         vert rightbelow split
456       endif
457     endif
458     edit `=resultBufferName`
459     let b:VCSCommandCommand = a:command
460     let b:VCSCommandOriginalBuffer = a:originalBuffer
461     let b:VCSCommandSourceFile = bufname(a:originalBuffer)
462     let b:VCSCommandVCSType = vcsType
464     set buftype=nofile
465     set noswapfile
466     let &filetype=vcsType . a:command
468     if a:statusText != ''
469       let b:VCSCommandStatusText = a:statusText
470     endif
472     if VCSCommandGetOption('VCSCommandDeleteOnHide', 0)
473       set bufhidden=delete
474     endif
475   finally
476     let s:isEditFileRunning -= 1
477   endtry
479 endfunction
481 " Function: s:SetupBuffer() {{{2
482 " Attempts to set the b:VCSCommandBufferInfo variable
484 function! s:SetupBuffer()
485   if (exists('b:VCSCommandBufferSetup') && b:VCSCommandBufferSetup)
486     " This buffer is already set up.
487     return
488   endif
490   if strlen(&buftype) > 0 || !filereadable(@%)
491     " No special status for special buffers.
492     return
493   endif
495   if !VCSCommandGetOption('VCSCommandEnableBufferSetup', 0) || s:isEditFileRunning > 0
496     unlet! b:VCSCommandBufferSetup
497     return
498   endif
500   try
501     let vcsType = VCSCommandGetVCSType(bufnr('%'))
502     let b:VCSCommandBufferInfo =  s:plugins[vcsType].GetBufferInfo()
503     silent do VCSCommand User VCSBufferSetup
504   catch /No suitable plugin/
505     " This is not a VCS-controlled file.
506     let b:VCSCommandBufferInfo = []
507   endtry
509   let b:VCSCommandBufferSetup=1
510 endfunction
512 " Function: s:MarkOrigBufferForSetup(buffer) {{{2
513 " Resets the buffer setup state of the original buffer for a given VCS scratch
514 " buffer.
515 " Returns:  The VCS buffer number in a passthrough mode.
517 function! s:MarkOrigBufferForSetup(buffer)
518   checktime
519   if a:buffer > 0 
520     let origBuffer = VCSCommandGetOriginalBuffer(a:buffer)
521     " This should never not work, but I'm paranoid
522     if origBuffer != a:buffer
523       call setbufvar(origBuffer, 'VCSCommandBufferSetup', 0)
524     endif
525   endif
526   return a:buffer
527 endfunction
529 " Function: s:OverrideOption(option, [value]) {{{2
530 " Provides a temporary override for the given VCS option.  If no value is
531 " passed, the override is disabled.
533 function! s:OverrideOption(option, ...)
534   if a:0 == 0
535     call remove(s:optionOverrides[a:option], -1)
536   else
537     if !has_key(s:optionOverrides, a:option)
538       let s:optionOverrides[a:option] = []
539     endif
540     call add(s:optionOverrides[a:option], a:1)
541   endif
542 endfunction
544 " Function: s:WipeoutCommandBuffers() {{{2
545 " Clears all current VCS output buffers of the specified type for a given source.
547 function! s:WipeoutCommandBuffers(originalBuffer, VCSCommand)
548   let buffer = 1
549   while buffer <= bufnr('$')
550     if getbufvar(buffer, 'VCSCommandOriginalBuffer') == a:originalBuffer
551       if getbufvar(buffer, 'VCSCommandCommand') == a:VCSCommand
552         execute 'bw' buffer
553       endif
554     endif
555     let buffer = buffer + 1
556   endwhile
557 endfunction
559 " Function: s:VimDiffRestore(vimDiffBuff) {{{2
560 " Checks whether the given buffer is one whose deletion should trigger
561 " restoration of an original buffer after it was diffed.  If so, it executes
562 " the appropriate setting command stored with that original buffer.
564 function! s:VimDiffRestore(vimDiffBuff)
565   let s:isEditFileRunning += 1
566   try
567     if exists('s:vimDiffSourceBuffer')
568       if a:vimDiffBuff == s:vimDiffSourceBuffer
569         " Original file is being removed.
570         unlet! s:vimDiffSourceBuffer
571         unlet! s:vimDiffRestoreCmd
572         unlet! s:vimDiffScratchList
573       else
574         let index = index(s:vimDiffScratchList, a:vimDiffBuff)
575         if index >= 0
576           call remove(s:vimDiffScratchList, index)
577           if len(s:vimDiffScratchList) == 0
578             if exists('s:vimDiffRestoreCmd')
579               " All scratch buffers are gone, reset the original.
580               " Only restore if the source buffer is still in Diff mode
582               let sourceWinNR=bufwinnr(s:vimDiffSourceBuffer)
583               if sourceWinNR != -1
584                 " The buffer is visible in at least one window
585                 let currentWinNR = winnr()
586                 while winbufnr(sourceWinNR) != -1
587                   if winbufnr(sourceWinNR) == s:vimDiffSourceBuffer
588                     execute sourceWinNR . 'wincmd w'
589                     if getwinvar(0, '&diff')
590                       execute s:vimDiffRestoreCmd
591                     endif
592                   endif
593                   let sourceWinNR = sourceWinNR + 1
594                 endwhile
595                 execute currentWinNR . 'wincmd w'
596               else
597                 " The buffer is hidden.  It must be visible in order to set the
598                 " diff option.
599                 let currentBufNR = bufnr('')
600                 execute 'hide buffer' s:vimDiffSourceBuffer
601                 if getwinvar(0, '&diff')
602                   execute s:vimDiffRestoreCmd
603                 endif
604                 execute 'hide buffer' currentBufNR
605               endif
607               unlet s:vimDiffRestoreCmd
608             endif 
609             " All buffers are gone.
610             unlet s:vimDiffSourceBuffer
611             unlet s:vimDiffScratchList
612           endif
613         endif
614       endif
615     endif
616   finally
617     let s:isEditFileRunning -= 1
618   endtry
619 endfunction
622 " Section: Generic VCS command functions {{{1
624 " Function: s:VCSCommit() {{{2
625 function! s:VCSCommit(bang, message)
626   let vcsType = VCSCommandGetVCSType(bufnr('%'))
627   if !has_key(s:plugins, vcsType)
628     throw 'Unknown VCS type:  ' . vcsType
629   endif
631   let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
633   " Handle the commit message being specified.  If a message is supplied, it
634   " is used; if bang is supplied, an empty message is used; otherwise, the
635   " user is provided a buffer from which to edit the commit message.
637   if strlen(a:message) > 0 || a:bang == '!'
638     return s:VCSFinishCommit([a:message], originalBuffer)
639   endif
641   call s:EditFile('commitlog', originalBuffer, '')
642   set ft=vcscommit
644   " Create a commit mapping.
646   nnoremap <silent> <buffer> <Plug>VCSCommit :call <SID>VCSFinishCommitWithBuffer()<CR>
648   silent 0put ='VCS: ----------------------------------------------------------------------'
649   silent put ='VCS: Please enter log message.  Lines beginning with ''VCS:'' are removed automatically.'
650   silent put ='VCS: To finish the commit, Type <leader>cc (or your own <Plug>VCSCommit mapping)'
652   if VCSCommandGetOption('VCSCommandCommitOnWrite', 1) == 1
653     set buftype=acwrite
654     au VCSCommandCommit BufWriteCmd <buffer> call s:VCSFinishCommitWithBuffer()
655     silent put ='VCS: or write this buffer'
656   endif
658   silent put ='VCS: ----------------------------------------------------------------------'
659   $
660   set nomodified
661 endfunction
663 " Function: s:VCSFinishCommitWithBuffer() {{{2
664 " Wrapper for s:VCSFinishCommit which is called only from a commit log buffer
665 " which removes all lines starting with 'VCS:'.
667 function! s:VCSFinishCommitWithBuffer()
668   set nomodified
669   let currentBuffer = bufnr('%') 
670   let logMessageList = getbufline('%', 1, '$')
671   call filter(logMessageList, 'v:val !~ ''^\s*VCS:''')
672   let resultBuffer = s:VCSFinishCommit(logMessageList, b:VCSCommandOriginalBuffer)
673   if resultBuffer >= 0
674     execute 'bw' currentBuffer
675   endif
676   return resultBuffer
677 endfunction
679 " Function: s:VCSFinishCommit(logMessageList, originalBuffer) {{{2
680 function! s:VCSFinishCommit(logMessageList, originalBuffer)
681   let shellSlashBak = &shellslash
682   try
683     set shellslash
684     let messageFileName = tempname()
685     call writefile(a:logMessageList, messageFileName)
686     try
687       let resultBuffer = s:ExecuteVCSCommand('Commit', a:originalBuffer, [messageFileName])
688       if resultBuffer < 0
689         return resultBuffer
690       endif
691       return s:MarkOrigBufferForSetup(resultBuffer)
692     finally
693       call delete(messageFileName)
694     endtry
695   finally
696     let &shellslash = shellSlashBak
697   endtry
698 endfunction
700 " Function: s:VCSGotoOriginal(bang) {{{2
701 function! s:VCSGotoOriginal(bang)
702   let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
703   if originalBuffer > 0
704     let origWinNR = bufwinnr(originalBuffer)
705     if origWinNR == -1
706       execute 'buffer' originalBuffer
707     else
708       execute origWinNR . 'wincmd w'
709     endif
710     if a:bang == '!'
711       let buffnr = 1
712       let buffmaxnr = bufnr('$')
713       while buffnr <= buffmaxnr
714         if getbufvar(buffnr, 'VCSCommandOriginalBuffer') == originalBuffer
715           execute 'bw' buffnr
716         endif
717         let buffnr = buffnr + 1
718       endwhile
719     endif
720   endif
721 endfunction
723 " Function: s:VCSVimDiff(...) {{{2
724 function! s:VCSVimDiff(...)
725   let vcsType = VCSCommandGetVCSType(bufnr('%'))
726   if !has_key(s:plugins, vcsType)
727     throw 'Unknown VCS type:  ' . vcsType
728   endif
729   let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
730   let s:isEditFileRunning = s:isEditFileRunning + 1
731   try
732     " If there's already a VimDiff'ed window, restore it.
733     " There may only be one VCSVimDiff original window at a time.
735     if exists('s:vimDiffSourceBuffer') && s:vimDiffSourceBuffer != originalBuffer
736       " Clear the existing vimdiff setup by removing the result buffers.
737       call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
738     endif
740     " Split and diff
741     if(a:0 == 2)
742       " Reset the vimdiff system, as 2 explicit versions were provided.
743       if exists('s:vimDiffSourceBuffer')
744         call s:WipeoutCommandBuffers(s:vimDiffSourceBuffer, 'vimdiff')
745       endif
746       let resultBuffer = s:plugins[vcsType].Review([a:1])
747       if resultBuffer < 0
748         echomsg 'Can''t open revision ' . a:1
749         return resultBuffer
750       endif
751       let b:VCSCommandCommand = 'vimdiff'
752       diffthis
753       let s:vimDiffScratchList = [resultBuffer]
754       " If no split method is defined, cheat, and set it to vertical.
755       try
756         call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
757         let resultBuffer=s:plugins[vcsType].Review([a:2])
758       finally
759         call s:OverrideOption('VCSCommandSplit')
760       endtry
761       if resultBuffer < 0
762         echomsg 'Can''t open revision ' . a:1
763         return resultBuffer
764       endif
765       let b:VCSCommandCommand = 'vimdiff'
766       diffthis
767       let s:vimDiffScratchList += [resultBuffer]
768     else
769       " Add new buffer
770       call s:OverrideOption('VCSCommandEdit', 'split')
771       try
772         " Force splitting behavior, otherwise why use vimdiff?
773         call s:OverrideOption('VCSCommandSplit', VCSCommandGetOption('VCSCommandDiffSplit', VCSCommandGetOption('VCSCommandSplit', 'vertical')))
774         try
775           if(a:0 == 0)
776             let resultBuffer=s:plugins[vcsType].Review([])
777           else
778             let resultBuffer=s:plugins[vcsType].Review([a:1])
779           endif
780         finally
781           call s:OverrideOption('VCSCommandSplit')
782         endtry
783       finally
784         call s:OverrideOption('VCSCommandEdit')
785       endtry
786       if resultBuffer < 0
787         echomsg 'Can''t open current revision'
788         return resultBuffer
789       endif
790       let b:VCSCommandCommand = 'vimdiff'
791       diffthis
793       if !exists('s:vimDiffSourceBuffer')
794         " New instance of vimdiff.
795         let s:vimDiffScratchList = [resultBuffer]
797         " This could have been invoked on a VCS result buffer, not the
798         " original buffer.
799         wincmd W
800         execute 'buffer' originalBuffer
801         " Store info for later original buffer restore
802         let s:vimDiffRestoreCmd = 
803               \    'call setbufvar('.originalBuffer.', ''&diff'', '.getbufvar(originalBuffer, '&diff').')'
804               \ . '|call setbufvar('.originalBuffer.', ''&foldcolumn'', '.getbufvar(originalBuffer, '&foldcolumn').')'
805               \ . '|call setbufvar('.originalBuffer.', ''&foldenable'', '.getbufvar(originalBuffer, '&foldenable').')'
806               \ . '|call setbufvar('.originalBuffer.', ''&foldmethod'', '''.getbufvar(originalBuffer, '&foldmethod').''')'
807               \ . '|call setbufvar('.originalBuffer.', ''&scrollbind'', '.getbufvar(originalBuffer, '&scrollbind').')'
808               \ . '|call setbufvar('.originalBuffer.', ''&wrap'', '.getbufvar(originalBuffer, '&wrap').')'
809               \ . '|if &foldmethod==''manual''|execute ''normal zE''|endif'
810         diffthis
811         wincmd w
812       else
813         " Adding a window to an existing vimdiff
814         let s:vimDiffScratchList += [resultBuffer]
815       endif
816     endif
818     let s:vimDiffSourceBuffer = originalBuffer
820     " Avoid executing the modeline in the current buffer after the autocommand.
822     let currentBuffer = bufnr('%')
823     let saveModeline = getbufvar(currentBuffer, '&modeline')
824     try
825       call setbufvar(currentBuffer, '&modeline', 0)
826       silent do VCSCommand User VCSVimDiffFinish
827     finally
828       call setbufvar(currentBuffer, '&modeline', saveModeline)
829     endtry
830     return resultBuffer
831   finally
832     let s:isEditFileRunning = s:isEditFileRunning - 1
833   endtry
834 endfunction
836 " Section: Public functions {{{1
838 " Function: VCSCommandGetVCSType(buffer) {{{2
839 " Sets the b:VCSCommandVCSType variable in the current buffer to the
840 " appropriate source control system name.
842 function! VCSCommandGetVCSType(buffer)
843   let vcsType = getbufvar(a:buffer, 'VCSCommandVCSType')
844   if strlen(vcsType) > 0
845     return vcsType
846   endif
847   for vcsType in keys(s:plugins)
848     if s:plugins[vcsType].Identify(a:buffer)
849       call setbufvar(a:buffer, 'VCSCommandVCSType', vcsType)
850       return vcsType
851     endif
852   endfor
853   throw 'No suitable plugin'
854 endfunction
856 " Function: VCSCommandChangeToCurrentFileDir() {{{2
857 " Go to the directory in which the given file is located.
859 function! VCSCommandChangeToCurrentFileDir(fileName)
860   let oldCwd=getcwd()
861   let newCwd=fnamemodify(resolve(a:fileName), ':p:h')
862   if strlen(newCwd) > 0
863     execute 'cd' escape(newCwd, ' ')
864   endif
865   return oldCwd
866 endfunction
868 " Function: VCSCommandGetOriginalBuffer(vcsBuffer) {{{2
869 " Attempts to locate the original file to which VCS operations were applied
870 " for a given buffer.
872 function! VCSCommandGetOriginalBuffer(vcsBuffer)
873   let origBuffer = getbufvar(a:vcsBuffer, 'VCSCommandOriginalBuffer')
874   if origBuffer
875     if bufexists(origBuffer)
876       return origBuffer
877     else
878       " Original buffer no longer exists.
879       throw 'Original buffer for this VCS buffer no longer exists.'
880     endif
881   else
882     " No original buffer
883     return a:vcsBuffer
884   endif
885 endfunction
887 " Function: VCSCommandRegisterModule(name, file, commandMap) {{{2
888 " Allows VCS modules to register themselves.
890 function! VCSCommandRegisterModule(name, file, commandMap, mappingMap)
891   let s:plugins[a:name] = a:commandMap
892   call add(s:pluginFiles, a:file)
893   let s:extendedMappings[a:name] = a:mappingMap
894   if(!empty(a:mappingMap))
895     for mapname in keys(a:mappingMap)
896       execute 'noremap <silent> <Leader>' . mapname ':call <SID>ExecuteExtensionMapping(''' . mapname . ''')<CR>'
897     endfor
898   endif
899 endfunction
901 " Function: VCSCommandDoCommand(cmd, cmdName, statusText) {{{2
902 " General skeleton for VCS function execution.
903 " Returns: name of the new command buffer containing the command results
905 function! VCSCommandDoCommand(cmd, cmdName, statusText)
906   let originalBuffer = VCSCommandGetOriginalBuffer(bufnr('%'))
907   if originalBuffer == -1 
908     throw 'Original buffer no longer exists, aborting.'
909   endif
911   let fileName=bufname(originalBuffer)
913   " Work with netrw or other systems where a directory listing is displayed in
914   " a buffer.
916   if isdirectory(fileName)
917     let realFileName = '.'
918   else
919     let realFileName = fnamemodify(resolve(fileName), ':t')
920   endif
922   let oldCwd=VCSCommandChangeToCurrentFileDir(fileName)
923   try
924     let fullCmd = a:cmd . ' "' . realFileName . '"'
925     let resultBuffer=s:CreateCommandBuffer(fullCmd, a:cmdName, originalBuffer, a:statusText)
926     return resultBuffer
927   finally
928     execute 'cd' escape(oldCwd, ' ')
929   endtry
930 endfunction
932 " Function: VCSCommandGetOption(name, default) {{{2
933 " Grab a user-specified option to override the default provided.  Options are
934 " searched in the window, buffer, then global spaces.
936 function! VCSCommandGetOption(name, default)
937   if has_key(s:optionOverrides, a:name) && len(s:optionOverrides[a:name]) > 0
938     return s:optionOverrides[a:name][-1]
939   elseif exists('w:' . a:name)
940     return w:{a:name}
941   elseif exists('b:' . a:name)
942     return b:{a:name}
943   elseif exists('g:' . a:name)
944     return g:{a:name}
945   else
946     return a:default
947   endif
948 endfunction
950 " Function: VCSCommandGetRevision() {{{2
951 " Global function for retrieving the current buffer's revision number.
952 " Returns: Revision number or an empty string if an error occurs.
954 function! VCSCommandGetRevision()
955   if !exists('b:VCSCommandBufferInfo')
956     let b:VCSCommandBufferInfo =  s:plugins[VCSCommandGetVCSType(bufnr('%'))].GetBufferInfo()
957   endif
959   if len(b:VCSCommandBufferInfo) > 0
960     return b:VCSCommandBufferInfo[0]
961   else
962     return ''
963   endif
964 endfunction
966 " Function: VCSCommandDisableBufferSetup() {{{2
967 " Global function for deactivating the buffer autovariables.
969 function! VCSCommandDisableBufferSetup()
970   let g:VCSCommandEnableBufferSetup = 0
971   silent! augroup! VCSCommandPlugin
972 endfunction
974 " Function: VCSCommandEnableBufferSetup() {{{2
975 " Global function for activating the buffer autovariables.
977 function! VCSCommandEnableBufferSetup()
978   let g:VCSCommandEnableBufferSetup = 1
979   augroup VCSCommandPlugin
980     au!
981     au BufEnter * call s:SetupBuffer()
982   augroup END
984   " Only auto-load if the plugin is fully loaded.  This gives other plugins a
985   " chance to run.
986   if g:loaded_VCSCommand == 2
987     call s:SetupBuffer()
988   endif
989 endfunction
991 " Function: VCSCommandGetStatusLine() {{{2
992 " Default (sample) status line entry for VCS-controlled files.  This is only
993 " useful if VCS-managed buffer mode is on (see the VCSCommandEnableBufferSetup
994 " variable for how to do this).
996 function! VCSCommandGetStatusLine()
997   if exists('b:VCSCommandCommand')
998     " This is a result buffer.  Return nothing because the buffer name
999     " contains information already.
1000     return ''
1001   endif
1003   if exists('b:VCSCommandVCSType')
1004         \ && exists('g:VCSCommandEnableBufferSetup')
1005         \ && g:VCSCommandEnableBufferSetup
1006         \ && exists('b:VCSCommandBufferInfo')
1007     return '[' . join(extend([b:VCSCommandVCSType], b:VCSCommandBufferInfo), ' ') . ']'
1008   else
1009     return ''
1010   endif
1011 endfunction
1013 " Section: Command definitions {{{1
1014 " Section: Primary commands {{{2
1015 com! -nargs=* VCSAdd call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Add', bufnr('%'), [<f-args>]))
1016 com! -nargs=? VCSAnnotate call s:ExecuteVCSCommand('Annotate', bufnr('%'), [<f-args>])
1017 com! -nargs=? -bang VCSCommit call s:VCSCommit(<q-bang>, <q-args>)
1018 com! -nargs=* VCSDelete call s:ExecuteVCSCommand('Delete', bufnr('%'), [<f-args>])
1019 com! -nargs=* VCSDiff call s:ExecuteVCSCommand('Diff', bufnr('%'), [<f-args>])
1020 com! -nargs=0 -bang VCSGotoOriginal call s:VCSGotoOriginal(<q-bang>)
1021 com! -nargs=* VCSLock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Lock', bufnr('%'), [<f-args>]))
1022 com! -nargs=* VCSLog call s:ExecuteVCSCommand('Log', bufnr('%'), [<f-args>])
1023 com! -nargs=0 VCSRevert call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Revert', bufnr('%'), []))
1024 com! -nargs=? VCSReview call s:ExecuteVCSCommand('Review', bufnr('%'), [<f-args>])
1025 com! -nargs=* VCSStatus call s:ExecuteVCSCommand('Status', bufnr('%'), [<f-args>])
1026 com! -nargs=* VCSUnlock call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Unlock', bufnr('%'), [<f-args>]))
1027 com! -nargs=0 VCSUpdate call s:MarkOrigBufferForSetup(s:ExecuteVCSCommand('Update', bufnr('%'), []))
1028 com! -nargs=* VCSVimDiff call s:VCSVimDiff(<f-args>)
1030 " Section: VCS buffer management commands {{{2
1031 com! VCSCommandDisableBufferSetup call VCSCommandDisableBufferSetup()
1032 com! VCSCommandEnableBufferSetup call VCSCommandEnableBufferSetup()
1034 " Allow reloading VCSCommand.vim
1035 com! VCSReload let savedPluginFiles = s:pluginFiles|aunmenu Plugin.VCS|unlet! g:loaded_VCSCommand|runtime plugin/vcscommand.vim|for file in savedPluginFiles|execute 'source' file|endfor
1037 " Section: Plugin command mappings {{{1
1038 nnoremap <silent> <Plug>VCSAdd :VCSAdd<CR>
1039 nnoremap <silent> <Plug>VCSAnnotate :VCSAnnotate<CR>
1040 nnoremap <silent> <Plug>VCSCommit :VCSCommit<CR>
1041 nnoremap <silent> <Plug>VCSDelete :VCSDelete<CR>
1042 nnoremap <silent> <Plug>VCSDiff :VCSDiff<CR>
1043 nnoremap <silent> <Plug>VCSGotoOriginal :VCSGotoOriginal<CR>
1044 nnoremap <silent> <Plug>VCSClearAndGotoOriginal :VCSGotoOriginal!<CR>
1045 nnoremap <silent> <Plug>VCSLock :VCSLock<CR>
1046 nnoremap <silent> <Plug>VCSLog :VCSLog<CR>
1047 nnoremap <silent> <Plug>VCSRevert :VCSRevert<CR>
1048 nnoremap <silent> <Plug>VCSReview :VCSReview<CR>
1049 nnoremap <silent> <Plug>VCSStatus :VCSStatus<CR>
1050 nnoremap <silent> <Plug>VCSUnlock :VCSUnlock<CR>
1051 nnoremap <silent> <Plug>VCSUpdate :VCSUpdate<CR>
1052 nnoremap <silent> <Plug>VCSVimDiff :VCSVimDiff<CR>
1054 " Section: Default mappings {{{1
1055 if !hasmapto('<Plug>VCSAdd')
1056   nmap <unique> <Leader>ca <Plug>VCSAdd
1057 endif
1058 if !hasmapto('<Plug>VCSAnnotate')
1059   nmap <unique> <Leader>cn <Plug>VCSAnnotate
1060 endif
1061 if !hasmapto('<Plug>VCSClearAndGotoOriginal')
1062   nmap <unique> <Leader>cG <Plug>VCSClearAndGotoOriginal
1063 endif
1064 if !hasmapto('<Plug>VCSCommit')
1065   nmap <unique> <Leader>cc <Plug>VCSCommit
1066 endif
1067 if !hasmapto('<Plug>VCSDelete')
1068   nmap <unique> <Leader>cD <Plug>VCSDelete
1069 endif
1070 if !hasmapto('<Plug>VCSDiff')
1071   nmap <unique> <Leader>cd <Plug>VCSDiff
1072 endif
1073 if !hasmapto('<Plug>VCSGotoOriginal')
1074   nmap <unique> <Leader>cg <Plug>VCSGotoOriginal
1075 endif
1076 if !hasmapto('<Plug>VCSLock')
1077   nmap <unique> <Leader>cL <Plug>VCSLock
1078 endif
1079 if !hasmapto('<Plug>VCSLog')
1080   nmap <unique> <Leader>cl <Plug>VCSLog
1081 endif
1082 if !hasmapto('<Plug>VCSRevert')
1083   nmap <unique> <Leader>cq <Plug>VCSRevert
1084 endif
1085 if !hasmapto('<Plug>VCSReview')
1086   nmap <unique> <Leader>cr <Plug>VCSReview
1087 endif
1088 if !hasmapto('<Plug>VCSStatus')
1089   nmap <unique> <Leader>cs <Plug>VCSStatus
1090 endif
1091 if !hasmapto('<Plug>VCSUnlock')
1092   nmap <unique> <Leader>cU <Plug>VCSUnlock
1093 endif
1094 if !hasmapto('<Plug>VCSUpdate')
1095   nmap <unique> <Leader>cu <Plug>VCSUpdate
1096 endif
1097 if !hasmapto('<Plug>VCSVimDiff')
1098   nmap <unique> <Leader>cv <Plug>VCSVimDiff
1099 endif
1101 " Section: Menu items {{{1
1102 amenu <silent> &Plugin.VCS.&Add        <Plug>VCSAdd
1103 amenu <silent> &Plugin.VCS.A&nnotate   <Plug>VCSAnnotate
1104 amenu <silent> &Plugin.VCS.&Commit     <Plug>VCSCommit
1105 amenu <silent> &Plugin.VCS.Delete      <Plug>VCSDelete
1106 amenu <silent> &Plugin.VCS.&Diff       <Plug>VCSDiff
1107 amenu <silent> &Plugin.VCS.&Log        <Plug>VCSLog
1108 amenu <silent> &Plugin.VCS.Revert      <Plug>VCSRevert
1109 amenu <silent> &Plugin.VCS.&Review     <Plug>VCSReview
1110 amenu <silent> &Plugin.VCS.&Status     <Plug>VCSStatus
1111 amenu <silent> &Plugin.VCS.&Update     <Plug>VCSUpdate
1112 amenu <silent> &Plugin.VCS.&VimDiff    <Plug>VCSVimDiff
1114 " Section: Autocommands to restore vimdiff state {{{1
1115 augroup VimDiffRestore
1116   au!
1117   au BufUnload * call s:VimDiffRestore(str2nr(expand('<abuf>')))
1118 augroup END
1120 " Section: Optional activation of buffer management {{{1
1122 if VCSCommandGetOption('VCSCommandEnableBufferSetup', 0)
1123   call VCSCommandEnableBufferSetup()
1124 endif
1126 " Section: Plugin completion {{{1
1128 let loaded_VCSCommand=2
1130 " Load delayed extension plugin registration.
1131 silent do VCSCommand User VCSLoadExtensions
1132 au! VCSCommand User VCSLoadExtensions
1134 silent do VCSCommand User VCSPluginFinish