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