/vim/plugin/vcscommand.vim

https://bitbucket.org/vertespain/config · Vim Script · 1344 lines · 718 code · 149 blank · 477 comment · 142 complexity · bb6bb1fbde0b62f5634cb355d5294f0c MD5 · raw file

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