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