plug.vim 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. " vim-plug: Vim plugin manager
  2. " ============================
  3. "
  4. " Download plug.vim and put it in ~/.vim/autoload
  5. "
  6. " curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
  7. " https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
  8. "
  9. " Edit your .vimrc
  10. "
  11. " call plug#begin('~/.vim/plugged')
  12. "
  13. " " Make sure you use single quotes
  14. "
  15. " " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
  16. " Plug 'junegunn/vim-easy-align'
  17. "
  18. " " Any valid git URL is allowed
  19. " Plug 'https://github.com/junegunn/vim-github-dashboard.git'
  20. "
  21. " " Group dependencies, vim-snippets depends on ultisnips
  22. " Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'
  23. "
  24. " " On-demand loading
  25. " Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
  26. " Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
  27. "
  28. " " Using a non-master branch
  29. " Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }
  30. "
  31. " " Plugin options
  32. " Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }
  33. "
  34. " " Plugin outside ~/.vim/plugged with post-update hook
  35. " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
  36. "
  37. " " Unmanaged plugin (manually installed and updated)
  38. " Plug '~/my-prototype-plugin'
  39. "
  40. " " Add plugins to &runtimepath
  41. " call plug#end()
  42. "
  43. " Then reload .vimrc and :PlugInstall to install plugins.
  44. "
  45. " Plug options:
  46. "
  47. "| Option | Description |
  48. "| ----------------------- | ------------------------------------------------ |
  49. "| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use |
  50. "| `rtp` | Subdirectory that contains Vim plugin |
  51. "| `dir` | Custom directory for the plugin |
  52. "| `as` | Use different name for the plugin |
  53. "| `do` | Post-update hook (string or funcref) |
  54. "| `on` | On-demand loading: Commands or `<Plug>`-mappings |
  55. "| `for` | On-demand loading: File types |
  56. "| `frozen` | Do not update unless explicitly specified |
  57. "
  58. " More information: https://github.com/junegunn/vim-plug
  59. "
  60. "
  61. " Copyright (c) 2015 Junegunn Choi
  62. "
  63. " MIT License
  64. "
  65. " Permission is hereby granted, free of charge, to any person obtaining
  66. " a copy of this software and associated documentation files (the
  67. " "Software"), to deal in the Software without restriction, including
  68. " without limitation the rights to use, copy, modify, merge, publish,
  69. " distribute, sublicense, and/or sell copies of the Software, and to
  70. " permit persons to whom the Software is furnished to do so, subject to
  71. " the following conditions:
  72. "
  73. " The above copyright notice and this permission notice shall be
  74. " included in all copies or substantial portions of the Software.
  75. "
  76. " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  77. " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  78. " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  79. " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  80. " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  81. " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  82. " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  83. if exists('g:loaded_plug')
  84. finish
  85. endif
  86. let g:loaded_plug = 1
  87. let s:cpo_save = &cpo
  88. set cpo&vim
  89. let s:plug_src = 'https://github.com/junegunn/vim-plug.git'
  90. let s:plug_tab = get(s:, 'plug_tab', -1)
  91. let s:plug_buf = get(s:, 'plug_buf', -1)
  92. let s:mac_gui = has('gui_macvim') && has('gui_running')
  93. let s:is_win = has('win32') || has('win64')
  94. let s:nvim = has('nvim') && exists('*jobwait') && !s:is_win
  95. let s:me = resolve(expand('<sfile>:p'))
  96. let s:base_spec = { 'branch': 'master', 'frozen': 0 }
  97. let s:TYPE = {
  98. \ 'string': type(''),
  99. \ 'list': type([]),
  100. \ 'dict': type({}),
  101. \ 'funcref': type(function('call'))
  102. \ }
  103. let s:loaded = get(s:, 'loaded', {})
  104. let s:triggers = get(s:, 'triggers', {})
  105. function! plug#begin(...)
  106. if a:0 > 0
  107. let s:plug_home_org = a:1
  108. let home = s:path(fnamemodify(expand(a:1), ':p'))
  109. elseif exists('g:plug_home')
  110. let home = s:path(g:plug_home)
  111. elseif !empty(&rtp)
  112. let home = s:path(split(&rtp, ',')[0]) . '/plugged'
  113. else
  114. return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
  115. endif
  116. let g:plug_home = home
  117. let g:plugs = {}
  118. let g:plugs_order = []
  119. let s:triggers = {}
  120. call s:define_commands()
  121. return 1
  122. endfunction
  123. function! s:define_commands()
  124. command! -nargs=+ -bar Plug call s:add(<args>)
  125. if !executable('git')
  126. return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.')
  127. endif
  128. command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(<bang>0, [<f-args>])
  129. command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(<bang>0, [<f-args>])
  130. command! -nargs=0 -bar -bang PlugClean call s:clean(<bang>0)
  131. command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif
  132. command! -nargs=0 -bar PlugStatus call s:status()
  133. command! -nargs=0 -bar PlugDiff call s:diff()
  134. command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(<bang>0, <f-args>)
  135. endfunction
  136. function! s:to_a(v)
  137. return type(a:v) == s:TYPE.list ? a:v : [a:v]
  138. endfunction
  139. function! s:to_s(v)
  140. return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
  141. endfunction
  142. function! s:source(from, ...)
  143. for pattern in a:000
  144. for vim in s:lines(globpath(a:from, pattern))
  145. execute 'source' s:esc(vim)
  146. endfor
  147. endfor
  148. endfunction
  149. function! s:assoc(dict, key, val)
  150. let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
  151. endfunction
  152. function! s:ask(message)
  153. call inputsave()
  154. echohl WarningMsg
  155. let proceed = input(a:message.' (y/N) ') =~? '^y'
  156. echohl None
  157. call inputrestore()
  158. echo "\r"
  159. return proceed
  160. endfunction
  161. function! plug#end()
  162. if !exists('g:plugs')
  163. return s:err('Call plug#begin() first')
  164. endif
  165. if exists('#PlugLOD')
  166. augroup PlugLOD
  167. autocmd!
  168. augroup END
  169. augroup! PlugLOD
  170. endif
  171. let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
  172. filetype off
  173. for name in g:plugs_order
  174. let plug = g:plugs[name]
  175. if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for')
  176. let s:loaded[name] = 1
  177. continue
  178. endif
  179. if has_key(plug, 'on')
  180. let s:triggers[name] = { 'map': [], 'cmd': [] }
  181. for cmd in s:to_a(plug.on)
  182. if cmd =~? '^<Plug>.\+'
  183. if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
  184. call s:assoc(lod.map, cmd, name)
  185. endif
  186. call add(s:triggers[name].map, cmd)
  187. elseif cmd =~# '^[A-Z]'
  188. if exists(':'.cmd) != 2
  189. call s:assoc(lod.cmd, cmd, name)
  190. endif
  191. call add(s:triggers[name].cmd, cmd)
  192. else
  193. call s:err('Invalid `on` option: '.cmd.
  194. \ '. Should start with an uppercase letter or `<Plug>`.')
  195. endif
  196. endfor
  197. endif
  198. if has_key(plug, 'for')
  199. let types = s:to_a(plug.for)
  200. if !empty(types)
  201. call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
  202. endif
  203. for type in types
  204. call s:assoc(lod.ft, type, name)
  205. endfor
  206. endif
  207. endfor
  208. for [cmd, names] in items(lod.cmd)
  209. execute printf(
  210. \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
  211. \ cmd, string(cmd), string(names))
  212. endfor
  213. for [map, names] in items(lod.map)
  214. for [mode, map_prefix, key_prefix] in
  215. \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
  216. execute printf(
  217. \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, "%s")<CR>',
  218. \ mode, map, map_prefix, string(map), string(names), key_prefix)
  219. endfor
  220. endfor
  221. for [ft, names] in items(lod.ft)
  222. augroup PlugLOD
  223. execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
  224. \ ft, string(ft), string(names))
  225. augroup END
  226. endfor
  227. call s:reorg_rtp()
  228. filetype plugin indent on
  229. if has('vim_starting')
  230. syntax enable
  231. else
  232. call s:reload()
  233. endif
  234. endfunction
  235. function! s:loaded_names()
  236. return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
  237. endfunction
  238. function! s:reload()
  239. for name in s:loaded_names()
  240. call s:source(s:rtp(g:plugs[name]), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
  241. endfor
  242. endfunction
  243. function! s:trim(str)
  244. return substitute(a:str, '[\/]\+$', '', '')
  245. endfunction
  246. function! s:version_requirement(val, min)
  247. for idx in range(0, len(a:min) - 1)
  248. let v = get(a:val, idx, 0)
  249. if v < a:min[idx] | return 0
  250. elseif v > a:min[idx] | return 1
  251. endif
  252. endfor
  253. return 1
  254. endfunction
  255. function! s:git_version_requirement(...)
  256. let s:git_version = get(s:, 'git_version',
  257. \ map(split(split(s:system('git --version'))[-1], '\.'), 'str2nr(v:val)'))
  258. return s:version_requirement(s:git_version, a:000)
  259. endfunction
  260. function! s:progress_opt(base)
  261. return a:base && !s:is_win &&
  262. \ s:git_version_requirement(1, 7, 1) ? '--progress' : ''
  263. endfunction
  264. if s:is_win
  265. function! s:rtp(spec)
  266. return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
  267. endfunction
  268. function! s:path(path)
  269. return s:trim(substitute(a:path, '/', '\', 'g'))
  270. endfunction
  271. function! s:dirpath(path)
  272. return s:path(a:path) . '\'
  273. endfunction
  274. function! s:is_local_plug(repo)
  275. return a:repo =~? '^[a-z]:\|^[%~]'
  276. endfunction
  277. else
  278. function! s:rtp(spec)
  279. return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
  280. endfunction
  281. function! s:path(path)
  282. return s:trim(a:path)
  283. endfunction
  284. function! s:dirpath(path)
  285. return substitute(a:path, '[/\\]*$', '/', '')
  286. endfunction
  287. function! s:is_local_plug(repo)
  288. return a:repo[0] =~ '[/$~]'
  289. endfunction
  290. endif
  291. function! s:err(msg)
  292. echohl ErrorMsg
  293. echom '[vim-plug] '.a:msg
  294. echohl None
  295. return 0
  296. endfunction
  297. function! s:esc(path)
  298. return escape(a:path, ' ')
  299. endfunction
  300. function! s:escrtp(path)
  301. return escape(a:path, ' ,')
  302. endfunction
  303. function! s:remove_rtp()
  304. for name in s:loaded_names()
  305. let rtp = s:rtp(g:plugs[name])
  306. execute 'set rtp-='.s:escrtp(rtp)
  307. let after = globpath(rtp, 'after')
  308. if isdirectory(after)
  309. execute 'set rtp-='.s:escrtp(after)
  310. endif
  311. endfor
  312. endfunction
  313. function! s:reorg_rtp()
  314. if !empty(s:first_rtp)
  315. execute 'set rtp-='.s:first_rtp
  316. execute 'set rtp-='.s:last_rtp
  317. endif
  318. " &rtp is modified from outside
  319. if exists('s:prtp') && s:prtp !=# &rtp
  320. call s:remove_rtp()
  321. unlet! s:middle
  322. endif
  323. let s:middle = get(s:, 'middle', &rtp)
  324. let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
  325. let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), 'isdirectory(v:val)')
  326. let rtp = join(map(rtps, 'escape(v:val, ",")'), ',')
  327. \ . ','.s:middle.','
  328. \ . join(map(afters, 'escape(v:val, ",")'), ',')
  329. let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
  330. let s:prtp = &rtp
  331. if !empty(s:first_rtp)
  332. execute 'set rtp^='.s:first_rtp
  333. execute 'set rtp+='.s:last_rtp
  334. endif
  335. endfunction
  336. function! plug#load(...)
  337. if a:0 == 0
  338. return s:err('Argument missing: plugin name(s) required')
  339. endif
  340. if !exists('g:plugs')
  341. return s:err('plug#begin was not called')
  342. endif
  343. let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)')
  344. if !empty(unknowns)
  345. let s = len(unknowns) > 1 ? 's' : ''
  346. return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
  347. end
  348. for name in a:000
  349. call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  350. endfor
  351. if exists('#BufRead')
  352. doautocmd BufRead
  353. endif
  354. return 1
  355. endfunction
  356. function! s:remove_triggers(name)
  357. if !has_key(s:triggers, a:name)
  358. return
  359. endif
  360. for cmd in s:triggers[a:name].cmd
  361. execute 'silent! delc' cmd
  362. endfor
  363. for map in s:triggers[a:name].map
  364. execute 'silent! unmap' map
  365. execute 'silent! iunmap' map
  366. endfor
  367. call remove(s:triggers, a:name)
  368. endfunction
  369. function! s:lod(names, types)
  370. for name in a:names
  371. call s:remove_triggers(name)
  372. let s:loaded[name] = 1
  373. endfor
  374. call s:reorg_rtp()
  375. for name in a:names
  376. let rtp = s:rtp(g:plugs[name])
  377. for dir in a:types
  378. call s:source(rtp, dir.'/**/*.vim')
  379. endfor
  380. if exists('#User#'.name)
  381. execute 'doautocmd User' name
  382. endif
  383. endfor
  384. endfunction
  385. function! s:lod_ft(pat, names)
  386. call s:lod(a:names, ['plugin', 'after/plugin', 'syntax', 'after/syntax'])
  387. execute 'autocmd! PlugLOD FileType' a:pat
  388. if exists('#filetypeplugin#FileType')
  389. doautocmd filetypeplugin FileType
  390. endif
  391. if exists('#filetypeindent#FileType')
  392. doautocmd filetypeindent FileType
  393. endif
  394. endfunction
  395. function! s:lod_cmd(cmd, bang, l1, l2, args, names)
  396. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  397. execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
  398. endfunction
  399. function! s:lod_map(map, names, prefix)
  400. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  401. let extra = ''
  402. while 1
  403. let c = getchar(0)
  404. if c == 0
  405. break
  406. endif
  407. let extra .= nr2char(c)
  408. endwhile
  409. call feedkeys(a:prefix . substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
  410. endfunction
  411. function! s:add(repo, ...)
  412. if a:0 > 1
  413. return s:err('Invalid number of arguments (1..2)')
  414. endif
  415. try
  416. let repo = s:trim(a:repo)
  417. let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec
  418. let name = get(opts, 'as', fnamemodify(repo, ':t:s?\.git$??'))
  419. let spec = extend(s:infer_properties(name, repo), opts)
  420. if !has_key(g:plugs, name)
  421. call add(g:plugs_order, name)
  422. endif
  423. let g:plugs[name] = spec
  424. let s:loaded[name] = get(s:loaded, name, 0)
  425. catch
  426. return s:err(v:exception)
  427. endtry
  428. endfunction
  429. function! s:parse_options(arg)
  430. let opts = copy(s:base_spec)
  431. let type = type(a:arg)
  432. if type == s:TYPE.string
  433. let opts.tag = a:arg
  434. elseif type == s:TYPE.dict
  435. call extend(opts, a:arg)
  436. if has_key(opts, 'dir')
  437. let opts.dir = s:dirpath(expand(opts.dir))
  438. endif
  439. else
  440. throw 'Invalid argument type (expected: string or dictionary)'
  441. endif
  442. return opts
  443. endfunction
  444. function! s:infer_properties(name, repo)
  445. let repo = a:repo
  446. if s:is_local_plug(repo)
  447. return { 'dir': s:dirpath(expand(repo)) }
  448. else
  449. if repo =~ ':'
  450. let uri = repo
  451. else
  452. if repo !~ '/'
  453. let repo = 'vim-scripts/'. repo
  454. endif
  455. let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
  456. let uri = printf(fmt, repo)
  457. endif
  458. let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') )
  459. return { 'dir': dir, 'uri': uri }
  460. endif
  461. endfunction
  462. function! s:install(force, names)
  463. call s:update_impl(0, a:force, a:names)
  464. endfunction
  465. function! s:update(force, names)
  466. call s:update_impl(1, a:force, a:names)
  467. endfunction
  468. function! plug#helptags()
  469. if !exists('g:plugs')
  470. return s:err('plug#begin was not called')
  471. endif
  472. for spec in values(g:plugs)
  473. let docd = join([spec.dir, 'doc'], '/')
  474. if isdirectory(docd)
  475. silent! execute 'helptags' s:esc(docd)
  476. endif
  477. endfor
  478. return 1
  479. endfunction
  480. function! s:syntax()
  481. syntax clear
  482. syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
  483. syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
  484. syn match plugNumber /[0-9]\+[0-9.]*/ contained
  485. syn match plugBracket /[[\]]/ contained
  486. syn match plugX /x/ contained
  487. syn match plugDash /^-/
  488. syn match plugPlus /^+/
  489. syn match plugStar /^*/
  490. syn match plugMessage /\(^- \)\@<=.*/
  491. syn match plugName /\(^- \)\@<=[^ ]*:/
  492. syn match plugSha /\%(: \)\@<=[0-9a-z]\{4,}$/
  493. syn match plugTag /(tag: [^)]\+)/
  494. syn match plugInstall /\(^+ \)\@<=[^:]*/
  495. syn match plugUpdate /\(^* \)\@<=[^:]*/
  496. syn match plugCommit /^ [0-9a-z]\{7} .*/ contains=plugRelDate,plugSha,plugTag
  497. syn match plugSha /\(^ \)\@<=[0-9a-z]\{7}/ contained
  498. syn match plugRelDate /([^)]*)$/ contained
  499. syn match plugNotLoaded /(not loaded)$/
  500. syn match plugError /^x.*/
  501. syn match plugH2 /^.*:\n-\+$/
  502. syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
  503. hi def link plug1 Title
  504. hi def link plug2 Repeat
  505. hi def link plugH2 Type
  506. hi def link plugX Exception
  507. hi def link plugBracket Structure
  508. hi def link plugNumber Number
  509. hi def link plugDash Special
  510. hi def link plugPlus Constant
  511. hi def link plugStar Boolean
  512. hi def link plugMessage Function
  513. hi def link plugName Label
  514. hi def link plugInstall Function
  515. hi def link plugUpdate Type
  516. hi def link plugError Error
  517. hi def link plugRelDate Comment
  518. hi def link plugSha Identifier
  519. hi def link plugTag Constant
  520. hi def link plugNotLoaded Comment
  521. endfunction
  522. function! s:lpad(str, len)
  523. return a:str . repeat(' ', a:len - len(a:str))
  524. endfunction
  525. function! s:lines(msg)
  526. return split(a:msg, "[\r\n]")
  527. endfunction
  528. function! s:lastline(msg)
  529. return get(s:lines(a:msg), -1, '')
  530. endfunction
  531. function! s:new_window()
  532. execute get(g:, 'plug_window', 'vertical topleft new')
  533. endfunction
  534. function! s:plug_window_exists()
  535. let buflist = tabpagebuflist(s:plug_tab)
  536. return !empty(buflist) && index(buflist, s:plug_buf) >= 0
  537. endfunction
  538. function! s:switch_in()
  539. if !s:plug_window_exists()
  540. return 0
  541. endif
  542. if winbufnr(0) != s:plug_buf
  543. let s:pos = [tabpagenr(), winnr(), winsaveview()]
  544. execute 'normal!' s:plug_tab.'gt'
  545. let winnr = bufwinnr(s:plug_buf)
  546. execute winnr.'wincmd w'
  547. call add(s:pos, winsaveview())
  548. else
  549. let s:pos = [winsaveview()]
  550. endif
  551. setlocal modifiable
  552. return 1
  553. endfunction
  554. function! s:switch_out(...)
  555. call winrestview(s:pos[-1])
  556. setlocal nomodifiable
  557. if a:0 > 0
  558. execute a:1
  559. endif
  560. if len(s:pos) > 1
  561. execute 'normal!' s:pos[0].'gt'
  562. execute s:pos[1] 'wincmd w'
  563. call winrestview(s:pos[2])
  564. endif
  565. endfunction
  566. function! s:finish_bindings()
  567. nnoremap <silent> <buffer> R :silent! call <SID>retry()<cr>
  568. nnoremap <silent> <buffer> D :PlugDiff<cr>
  569. nnoremap <silent> <buffer> S :PlugStatus<cr>
  570. nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  571. xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  572. nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
  573. nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
  574. endfunction
  575. function! s:prepare(...)
  576. call s:job_abort()
  577. if s:switch_in()
  578. normal q
  579. endif
  580. call s:new_window()
  581. nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>bd<cr>
  582. if a:0 == 0
  583. call s:finish_bindings()
  584. endif
  585. let b:plug_preview = -1
  586. let s:plug_tab = tabpagenr()
  587. let s:plug_buf = winbufnr(0)
  588. call s:assign_name()
  589. silent! unmap <buffer> <cr>
  590. silent! unmap <buffer> L
  591. silent! unmap <buffer> o
  592. silent! unmap <buffer> X
  593. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable
  594. setf vim-plug
  595. if exists('g:syntax_on')
  596. call s:syntax()
  597. endif
  598. endfunction
  599. function! s:assign_name()
  600. " Assign buffer name
  601. let prefix = '[Plugins]'
  602. let name = prefix
  603. let idx = 2
  604. while bufexists(name)
  605. let name = printf('%s (%s)', prefix, idx)
  606. let idx = idx + 1
  607. endwhile
  608. silent! execute 'f' fnameescape(name)
  609. endfunction
  610. function! s:do(pull, force, todo)
  611. for [name, spec] in items(a:todo)
  612. if !isdirectory(spec.dir)
  613. continue
  614. endif
  615. let installed = has_key(s:update.new, name)
  616. let updated = installed ? 0 :
  617. \ (a:pull && index(s:update.errors, name) < 0 && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  618. if a:force || installed || updated
  619. execute 'cd' s:esc(spec.dir)
  620. call append(3, '- Post-update hook for '. name .' ... ')
  621. let error = ''
  622. let type = type(spec.do)
  623. if type == s:TYPE.string
  624. try
  625. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  626. " but it won't work on Windows.
  627. let g:_plug_do = '!'.escape(spec.do, '#!%')
  628. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  629. finally
  630. if v:shell_error
  631. let error = 'Exit status: ' . v:shell_error
  632. endif
  633. unlet g:_plug_do
  634. endtry
  635. elseif type == s:TYPE.funcref
  636. try
  637. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  638. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  639. catch
  640. let error = v:exception
  641. endtry
  642. else
  643. let error = 'Invalid hook type'
  644. endif
  645. call setline(4, empty(error) ? (getline(4) . 'OK')
  646. \ : ('x' . getline(4)[1:] . error))
  647. cd -
  648. endif
  649. endfor
  650. endfunction
  651. function! s:hash_match(a, b)
  652. return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
  653. endfunction
  654. function! s:checkout(plugs)
  655. for [name, spec] in items(a:plugs)
  656. let sha = spec.commit
  657. call append(3, '- Checking out '.sha[:6].' of '.name.' ... ')
  658. redraw
  659. let error = []
  660. let output = s:lines(s:system('git rev-parse HEAD', spec.dir))
  661. if v:shell_error
  662. let error = output
  663. elseif !s:hash_match(sha, output[0])
  664. let output = s:lines(s:system(
  665. \ 'git fetch --depth 999999 && git checkout '.sha, spec.dir))
  666. if v:shell_error
  667. let error = output
  668. endif
  669. endif
  670. if empty(error)
  671. call setline(4, getline(4) . 'OK')
  672. else
  673. call setline(4, 'x'.getline(4)[1:] . 'Error')
  674. for line in reverse(error)
  675. call append(4, ' '.line)
  676. endfor
  677. endif
  678. endfor
  679. endfunction
  680. function! s:finish(pull)
  681. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  682. if new_frozen
  683. let s = new_frozen > 1 ? 's' : ''
  684. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  685. endif
  686. call append(3, '- Finishing ... ')
  687. redraw
  688. call plug#helptags()
  689. call plug#end()
  690. call setline(4, getline(4) . 'Done!')
  691. redraw
  692. let msgs = []
  693. if !empty(s:update.errors)
  694. call add(msgs, "Press 'R' to retry.")
  695. endif
  696. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  697. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  698. call add(msgs, "Press 'D' to see the updated changes.")
  699. endif
  700. echo join(msgs, ' ')
  701. call s:finish_bindings()
  702. endfunction
  703. function! s:retry()
  704. if empty(s:update.errors)
  705. return
  706. endif
  707. call s:update_impl(s:update.pull, s:update.force,
  708. \ extend(copy(s:update.errors), [s:update.threads]))
  709. endfunction
  710. function! s:is_managed(name)
  711. return has_key(g:plugs[a:name], 'uri')
  712. endfunction
  713. function! s:names(...)
  714. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  715. endfunction
  716. function! s:update_impl(pull, force, args) abort
  717. let args = copy(a:args)
  718. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  719. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  720. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  721. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  722. \ filter(managed, 'index(args, v:key) >= 0')
  723. if empty(todo)
  724. echohl WarningMsg
  725. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  726. echohl None
  727. return
  728. endif
  729. if !s:is_win && s:git_version_requirement(2, 3)
  730. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  731. let $GIT_TERMINAL_PROMPT = 0
  732. for plug in values(todo)
  733. let plug.uri = substitute(plug.uri,
  734. \ '^https://git::@github\.com', 'https://github.com', '')
  735. endfor
  736. endif
  737. if !isdirectory(g:plug_home)
  738. try
  739. call mkdir(g:plug_home, 'p')
  740. catch
  741. return s:err(printf('Invalid plug directory: %s. '.
  742. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  743. endtry
  744. endif
  745. if has('nvim') && !exists('*jobwait') && threads > 1
  746. echohl WarningMsg
  747. echomsg 'vim-plug: update Neovim for parallel installer'
  748. echohl None
  749. endif
  750. let python = (has('python') || has('python3')) && (!s:nvim || has('vim_starting'))
  751. let ruby = has('ruby') && !s:nvim && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running'))
  752. let s:update = {
  753. \ 'start': reltime(),
  754. \ 'all': todo,
  755. \ 'todo': copy(todo),
  756. \ 'errors': [],
  757. \ 'pull': a:pull,
  758. \ 'force': a:force,
  759. \ 'new': {},
  760. \ 'threads': (python || ruby || s:nvim) ? min([len(todo), threads]) : 1,
  761. \ 'bar': '',
  762. \ 'fin': 0
  763. \ }
  764. call s:prepare(1)
  765. call append(0, ['', ''])
  766. normal! 2G
  767. silent! redraw
  768. let s:clone_opt = get(g:, 'plug_shallow', 1) ?
  769. \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : ''
  770. " Python version requirement (>= 2.7)
  771. if python && !has('python3') && !ruby && !s:nvim && s:update.threads > 1
  772. redir => pyv
  773. silent python import platform; print platform.python_version()
  774. redir END
  775. let python = s:version_requirement(
  776. \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
  777. endif
  778. if (python || ruby) && s:update.threads > 1
  779. try
  780. let imd = &imd
  781. if s:mac_gui
  782. set noimd
  783. endif
  784. if ruby
  785. call s:update_ruby()
  786. else
  787. call s:update_python()
  788. endif
  789. catch
  790. let lines = getline(4, '$')
  791. let printed = {}
  792. silent! 4,$d _
  793. for line in lines
  794. let name = s:extract_name(line, '.', '')
  795. if empty(name) || !has_key(printed, name)
  796. call append('$', line)
  797. if !empty(name)
  798. let printed[name] = 1
  799. if line[0] == 'x' && index(s:update.errors, name) < 0
  800. call add(s:update.errors, name)
  801. end
  802. endif
  803. endif
  804. endfor
  805. finally
  806. let &imd = imd
  807. call s:update_finish()
  808. endtry
  809. else
  810. call s:update_vim()
  811. endif
  812. endfunction
  813. function! s:update_finish()
  814. if exists('s:git_terminal_prompt')
  815. let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
  816. endif
  817. if s:switch_in()
  818. call s:checkout(filter(copy(s:update.all), 'has_key(v:val, "commit")'))
  819. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  820. call s:finish(s:update.pull)
  821. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  822. call s:switch_out('normal! gg')
  823. endif
  824. endfunction
  825. function! s:job_abort()
  826. if !s:nvim || !exists('s:jobs')
  827. return
  828. endif
  829. for [name, j] in items(s:jobs)
  830. silent! call jobstop(j.jobid)
  831. if j.new
  832. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  833. endif
  834. endfor
  835. let s:jobs = {}
  836. endfunction
  837. " When a:event == 'stdout', data = list of strings
  838. " When a:event == 'exit', data = returncode
  839. function! s:job_handler(job_id, data, event) abort
  840. if !s:plug_window_exists() " plug window closed
  841. return s:job_abort()
  842. endif
  843. if a:event == 'stdout'
  844. let complete = empty(a:data[-1])
  845. let lines = map(filter(a:data, 'len(v:val) > 0'), 'split(v:val, "[\r\n]")[-1]')
  846. call extend(self.lines, lines)
  847. let self.result = join(self.lines, "\n")
  848. if !complete
  849. call remove(self.lines, -1)
  850. endif
  851. " To reduce the number of buffer updates
  852. let self.tick = get(self, 'tick', -1) + 1
  853. if self.tick % len(s:jobs) == 0
  854. call s:log(self.new ? '+' : '*', self.name, self.result)
  855. endif
  856. elseif a:event == 'exit'
  857. let self.running = 0
  858. if a:data != 0
  859. let self.error = 1
  860. endif
  861. call s:reap(self.name)
  862. call s:tick()
  863. endif
  864. endfunction
  865. function! s:spawn(name, cmd, opts)
  866. let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [], 'result': '',
  867. \ 'new': get(a:opts, 'new', 0),
  868. \ 'on_stdout': function('s:job_handler'),
  869. \ 'on_exit' : function('s:job_handler'),
  870. \ }
  871. let s:jobs[a:name] = job
  872. if s:nvim
  873. let argv = [ 'sh', '-c',
  874. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd) ]
  875. let jid = jobstart(argv, job)
  876. if jid > 0
  877. let job.jobid = jid
  878. else
  879. let job.running = 0
  880. let job.error = 1
  881. let job.result = jid < 0 ? 'sh is not executable' :
  882. \ 'Invalid arguments (or job table is full)'
  883. endif
  884. else
  885. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  886. let job.result = call('s:system', params)
  887. let job.error = v:shell_error != 0
  888. let job.running = 0
  889. endif
  890. endfunction
  891. function! s:reap(name)
  892. let job = s:jobs[a:name]
  893. if job.error
  894. call add(s:update.errors, a:name)
  895. elseif get(job, 'new', 0)
  896. let s:update.new[a:name] = 1
  897. endif
  898. let s:update.bar .= job.error ? 'x' : '='
  899. call s:log(job.error ? 'x' : '-', a:name, job.result)
  900. call s:bar()
  901. call remove(s:jobs, a:name)
  902. endfunction
  903. function! s:bar()
  904. if s:switch_in()
  905. let total = len(s:update.all)
  906. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  907. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  908. call s:progress_bar(2, s:update.bar, total)
  909. call s:switch_out()
  910. endif
  911. endfunction
  912. function! s:logpos(name)
  913. for i in range(1, line('$'))
  914. if getline(i) =~# '^[-+x*] '.a:name.':'
  915. return i
  916. endif
  917. endfor
  918. return 0
  919. endfunction
  920. function! s:log(bullet, name, lines)
  921. if s:switch_in()
  922. let pos = s:logpos(a:name)
  923. if pos > 0
  924. execute pos 'd _'
  925. if pos > winheight('.')
  926. let pos = 4
  927. endif
  928. else
  929. let pos = 4
  930. endif
  931. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  932. call s:switch_out()
  933. endif
  934. endfunction
  935. function! s:update_vim()
  936. let s:jobs = {}
  937. call s:bar()
  938. call s:tick()
  939. endfunction
  940. function! s:tick()
  941. let pull = s:update.pull
  942. let prog = s:progress_opt(s:nvim)
  943. while 1 " Without TCO, Vim stack is bound to explode
  944. if empty(s:update.todo)
  945. if empty(s:jobs) && !s:update.fin
  946. let s:update.fin = 1
  947. call s:update_finish()
  948. endif
  949. return
  950. endif
  951. let name = keys(s:update.todo)[0]
  952. let spec = remove(s:update.todo, name)
  953. let new = !isdirectory(spec.dir)
  954. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  955. redraw
  956. let has_tag = has_key(spec, 'tag')
  957. let checkout = s:shellesc(has_tag ? spec.tag : spec.branch)
  958. let merge = s:shellesc(has_tag ? spec.tag : 'origin/'.spec.branch)
  959. if !new
  960. let error = s:git_validate(spec, 0)
  961. if empty(error)
  962. if pull
  963. let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : ''
  964. call s:spawn(name,
  965. \ printf('(git fetch %s %s 2>&1 && git checkout -q %s 2>&1 && git merge --ff-only %s 2>&1 && git submodule update --init --recursive 2>&1)',
  966. \ fetch_opt, prog, checkout, merge), { 'dir': spec.dir })
  967. else
  968. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  969. endif
  970. else
  971. let s:jobs[name] = { 'running': 0, 'result': error, 'error': 1 }
  972. endif
  973. else
  974. call s:spawn(name,
  975. \ printf('git clone %s %s --recursive %s -b %s %s 2>&1',
  976. \ has_tag ? '' : s:clone_opt,
  977. \ prog,
  978. \ s:shellesc(spec.uri),
  979. \ checkout,
  980. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  981. endif
  982. if !s:jobs[name].running
  983. call s:reap(name)
  984. endif
  985. if len(s:jobs) >= s:update.threads
  986. break
  987. endif
  988. endwhile
  989. endfunction
  990. function! s:update_python()
  991. let py_exe = has('python') ? 'python' : 'python3'
  992. execute py_exe "<< EOF"
  993. import datetime
  994. import functools
  995. import os
  996. try:
  997. import queue
  998. except ImportError:
  999. import Queue as queue
  1000. import random
  1001. import re
  1002. import shutil
  1003. import signal
  1004. import subprocess
  1005. import tempfile
  1006. import threading as thr
  1007. import time
  1008. import traceback
  1009. import vim
  1010. G_NVIM = vim.eval("has('nvim')") == '1'
  1011. G_PULL = vim.eval('s:update.pull') == '1'
  1012. G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
  1013. G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
  1014. G_CLONE_OPT = vim.eval('s:clone_opt')
  1015. G_PROGRESS = vim.eval('s:progress_opt(1)')
  1016. G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
  1017. G_STOP = thr.Event()
  1018. G_IS_WIN = vim.eval('s:is_win') == '1'
  1019. class PlugError(Exception):
  1020. def __init__(self, msg):
  1021. self.msg = msg
  1022. class CmdTimedOut(PlugError):
  1023. pass
  1024. class CmdFailed(PlugError):
  1025. pass
  1026. class InvalidURI(PlugError):
  1027. pass
  1028. class Action(object):
  1029. INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
  1030. class Buffer(object):
  1031. def __init__(self, lock, num_plugs, is_pull):
  1032. self.bar = ''
  1033. self.event = 'Updating' if is_pull else 'Installing'
  1034. self.lock = lock
  1035. self.maxy = int(vim.eval('winheight(".")'))
  1036. self.num_plugs = num_plugs
  1037. def __where(self, name):
  1038. """ Find first line with name in current buffer. Return line num. """
  1039. found, lnum = False, 0
  1040. matcher = re.compile('^[-+x*] {0}:'.format(name))
  1041. for line in vim.current.buffer:
  1042. if matcher.search(line) is not None:
  1043. found = True
  1044. break
  1045. lnum += 1
  1046. if not found:
  1047. lnum = -1
  1048. return lnum
  1049. def header(self):
  1050. curbuf = vim.current.buffer
  1051. curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
  1052. num_spaces = self.num_plugs - len(self.bar)
  1053. curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
  1054. with self.lock:
  1055. vim.command('normal! 2G')
  1056. vim.command('redraw')
  1057. def write(self, action, name, lines):
  1058. first, rest = lines[0], lines[1:]
  1059. msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
  1060. msg.extend([' ' + line for line in rest])
  1061. try:
  1062. if action == Action.ERROR:
  1063. self.bar += 'x'
  1064. vim.command("call add(s:update.errors, '{0}')".format(name))
  1065. elif action == Action.DONE:
  1066. self.bar += '='
  1067. curbuf = vim.current.buffer
  1068. lnum = self.__where(name)
  1069. if lnum != -1: # Found matching line num
  1070. del curbuf[lnum]
  1071. if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
  1072. lnum = 3
  1073. else:
  1074. lnum = 3
  1075. curbuf.append(msg, lnum)
  1076. self.header()
  1077. except vim.error:
  1078. pass
  1079. class Command(object):
  1080. CD = 'cd /d' if G_IS_WIN else 'cd'
  1081. def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
  1082. self.cmd = cmd
  1083. if cmd_dir:
  1084. self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
  1085. self.timeout = timeout
  1086. self.callback = cb if cb else (lambda msg: None)
  1087. self.clean = clean if clean else (lambda: None)
  1088. self.proc = None
  1089. @property
  1090. def alive(self):
  1091. """ Returns true only if command still running. """
  1092. return self.proc and self.proc.poll() is None
  1093. def execute(self, ntries=3):
  1094. """ Execute the command with ntries if CmdTimedOut.
  1095. Returns the output of the command if no Exception.
  1096. """
  1097. attempt, finished, limit = 0, False, self.timeout
  1098. while not finished:
  1099. try:
  1100. attempt += 1
  1101. result = self.try_command()
  1102. finished = True
  1103. return result
  1104. except CmdTimedOut:
  1105. if attempt != ntries:
  1106. self.notify_retry()
  1107. self.timeout += limit
  1108. else:
  1109. raise
  1110. def notify_retry(self):
  1111. """ Retry required for command, notify user. """
  1112. for count in range(3, 0, -1):
  1113. if G_STOP.is_set():
  1114. raise KeyboardInterrupt
  1115. msg = 'Timeout. Will retry in {0} second{1} ...'.format(
  1116. count, 's' if count != 1 else '')
  1117. self.callback([msg])
  1118. time.sleep(1)
  1119. self.callback(['Retrying ...'])
  1120. def try_command(self):
  1121. """ Execute a cmd & poll for callback. Returns list of output.
  1122. Raises CmdFailed -> return code for Popen isn't 0
  1123. Raises CmdTimedOut -> command exceeded timeout without new output
  1124. """
  1125. first_line = True
  1126. try:
  1127. tfile = tempfile.NamedTemporaryFile(mode='w+b')
  1128. preexec_fn = not G_IS_WIN and os.setsid or None
  1129. self.proc = subprocess.Popen(self.cmd, stdout=tfile,
  1130. stderr=subprocess.STDOUT,
  1131. stdin=subprocess.PIPE, shell=True,
  1132. preexec_fn=preexec_fn)
  1133. thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
  1134. thrd.start()
  1135. thread_not_started = True
  1136. while thread_not_started:
  1137. try:
  1138. thrd.join(0.1)
  1139. thread_not_started = False
  1140. except RuntimeError:
  1141. pass
  1142. while self.alive:
  1143. if G_STOP.is_set():
  1144. raise KeyboardInterrupt
  1145. if first_line or random.random() < G_LOG_PROB:
  1146. first_line = False
  1147. line = '' if G_IS_WIN else nonblock_read(tfile.name)
  1148. if line:
  1149. self.callback([line])
  1150. time_diff = time.time() - os.path.getmtime(tfile.name)
  1151. if time_diff > self.timeout:
  1152. raise CmdTimedOut(['Timeout!'])
  1153. thrd.join(0.5)
  1154. tfile.seek(0)
  1155. result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
  1156. if self.proc.returncode != 0:
  1157. raise CmdFailed([''] + result)
  1158. return result
  1159. except:
  1160. self.terminate()
  1161. raise
  1162. def terminate(self):
  1163. """ Terminate process and cleanup. """
  1164. if self.alive:
  1165. if G_IS_WIN:
  1166. os.kill(self.proc.pid, signal.SIGINT)
  1167. else:
  1168. os.killpg(self.proc.pid, signal.SIGTERM)
  1169. self.clean()
  1170. class Plugin(object):
  1171. def __init__(self, name, args, buf_q, lock):
  1172. self.name = name
  1173. self.args = args
  1174. self.buf_q = buf_q
  1175. self.lock = lock
  1176. tag = args.get('tag', 0)
  1177. self.checkout = esc(tag if tag else args['branch'])
  1178. self.merge = esc(tag if tag else 'origin/' + args['branch'])
  1179. self.tag = tag
  1180. def manage(self):
  1181. try:
  1182. if os.path.exists(self.args['dir']):
  1183. self.update()
  1184. else:
  1185. self.install()
  1186. with self.lock:
  1187. thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
  1188. except PlugError as exc:
  1189. self.write(Action.ERROR, self.name, exc.msg)
  1190. except KeyboardInterrupt:
  1191. G_STOP.set()
  1192. self.write(Action.ERROR, self.name, ['Interrupted!'])
  1193. except:
  1194. # Any exception except those above print stack trace
  1195. msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
  1196. self.write(Action.ERROR, self.name, msg.split('\n'))
  1197. raise
  1198. def install(self):
  1199. target = self.args['dir']
  1200. if target[-1] == '\\':
  1201. target = target[0:-1]
  1202. def clean(target):
  1203. def _clean():
  1204. try:
  1205. shutil.rmtree(target)
  1206. except OSError:
  1207. pass
  1208. return _clean
  1209. self.write(Action.INSTALL, self.name, ['Installing ...'])
  1210. callback = functools.partial(self.write, Action.INSTALL, self.name)
  1211. cmd = 'git clone {0} {1} --recursive {2} -b {3} {4} 2>&1'.format(
  1212. '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
  1213. self.checkout, esc(target))
  1214. com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
  1215. result = com.execute(G_RETRIES)
  1216. self.write(Action.DONE, self.name, result[-1:])
  1217. def repo_uri(self):
  1218. cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url'
  1219. command = Command(cmd, self.args['dir'], G_TIMEOUT,)
  1220. result = command.execute(G_RETRIES)
  1221. return result[-1]
  1222. def update(self):
  1223. match = re.compile(r'git::?@')
  1224. actual_uri = re.sub(match, '', self.repo_uri())
  1225. expect_uri = re.sub(match, '', self.args['uri'])
  1226. if actual_uri != expect_uri:
  1227. msg = ['',
  1228. 'Invalid URI: {0}'.format(actual_uri),
  1229. 'Expected {0}'.format(expect_uri),
  1230. 'PlugClean required.']
  1231. raise InvalidURI(msg)
  1232. if G_PULL:
  1233. self.write(Action.UPDATE, self.name, ['Updating ...'])
  1234. callback = functools.partial(self.write, Action.UPDATE, self.name)
  1235. fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
  1236. cmds = ['git fetch {0} {1}'.format(fetch_opt, G_PROGRESS),
  1237. 'git checkout -q {0}'.format(self.checkout),
  1238. 'git merge --ff-only {0}'.format(self.merge),
  1239. 'git submodule update --init --recursive']
  1240. cmd = ' 2>&1 && '.join(cmds)
  1241. com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
  1242. result = com.execute(G_RETRIES)
  1243. self.write(Action.DONE, self.name, result[-1:])
  1244. else:
  1245. self.write(Action.DONE, self.name, ['Already installed'])
  1246. def write(self, action, name, msg):
  1247. self.buf_q.put((action, name, msg))
  1248. class PlugThread(thr.Thread):
  1249. def __init__(self, tname, args):
  1250. super(PlugThread, self).__init__()
  1251. self.tname = tname
  1252. self.args = args
  1253. def run(self):
  1254. thr.current_thread().name = self.tname
  1255. buf_q, work_q, lock = self.args
  1256. try:
  1257. while not G_STOP.is_set():
  1258. name, args = work_q.get_nowait()
  1259. plug = Plugin(name, args, buf_q, lock)
  1260. plug.manage()
  1261. work_q.task_done()
  1262. except queue.Empty:
  1263. pass
  1264. class RefreshThread(thr.Thread):
  1265. def __init__(self, lock):
  1266. super(RefreshThread, self).__init__()
  1267. self.lock = lock
  1268. self.running = True
  1269. def run(self):
  1270. while self.running:
  1271. with self.lock:
  1272. thread_vim_command('noautocmd normal! a')
  1273. time.sleep(0.33)
  1274. def stop(self):
  1275. self.running = False
  1276. if G_NVIM:
  1277. def thread_vim_command(cmd):
  1278. vim.session.threadsafe_call(lambda: vim.command(cmd))
  1279. else:
  1280. def thread_vim_command(cmd):
  1281. vim.command(cmd)
  1282. def esc(name):
  1283. return '"' + name.replace('"', '\"') + '"'
  1284. def nonblock_read(fname):
  1285. """ Read a file with nonblock flag. Return the last line. """
  1286. fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
  1287. buf = os.read(fread, 100000).decode('utf-8', 'replace')
  1288. os.close(fread)
  1289. line = buf.rstrip('\r\n')
  1290. left = max(line.rfind('\r'), line.rfind('\n'))
  1291. if left != -1:
  1292. left += 1
  1293. line = line[left:]
  1294. return line
  1295. def main():
  1296. thr.current_thread().name = 'main'
  1297. nthreads = int(vim.eval('s:update.threads'))
  1298. plugs = vim.eval('s:update.todo')
  1299. mac_gui = vim.eval('s:mac_gui') == '1'
  1300. lock = thr.Lock()
  1301. buf = Buffer(lock, len(plugs), G_PULL)
  1302. buf_q, work_q = queue.Queue(), queue.Queue()
  1303. for work in plugs.items():
  1304. work_q.put(work)
  1305. start_cnt = thr.active_count()
  1306. for num in range(nthreads):
  1307. tname = 'PlugT-{0:02}'.format(num)
  1308. thread = PlugThread(tname, (buf_q, work_q, lock))
  1309. thread.start()
  1310. if mac_gui:
  1311. rthread = RefreshThread(lock)
  1312. rthread.start()
  1313. while not buf_q.empty() or thr.active_count() != start_cnt:
  1314. try:
  1315. action, name, msg = buf_q.get(True, 0.25)
  1316. buf.write(action, name, msg)
  1317. buf_q.task_done()
  1318. except queue.Empty:
  1319. pass
  1320. except KeyboardInterrupt:
  1321. G_STOP.set()
  1322. if mac_gui:
  1323. rthread.stop()
  1324. rthread.join()
  1325. main()
  1326. EOF
  1327. endfunction
  1328. function! s:update_ruby()
  1329. ruby << EOF
  1330. module PlugStream
  1331. SEP = ["\r", "\n", nil]
  1332. def get_line
  1333. buffer = ''
  1334. loop do
  1335. char = readchar rescue return
  1336. if SEP.include? char.chr
  1337. buffer << $/
  1338. break
  1339. else
  1340. buffer << char
  1341. end
  1342. end
  1343. buffer
  1344. end
  1345. end unless defined?(PlugStream)
  1346. def esc arg
  1347. %["#{arg.gsub('"', '\"')}"]
  1348. end
  1349. def killall pid
  1350. pids = [pid]
  1351. if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
  1352. pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
  1353. else
  1354. unless `which pgrep 2> /dev/null`.empty?
  1355. children = pids
  1356. until children.empty?
  1357. children = children.map { |pid|
  1358. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  1359. }.flatten
  1360. pids += children
  1361. end
  1362. end
  1363. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  1364. end
  1365. end
  1366. require 'thread'
  1367. require 'fileutils'
  1368. require 'timeout'
  1369. running = true
  1370. iswin = VIM::evaluate('s:is_win').to_i == 1
  1371. pull = VIM::evaluate('s:update.pull').to_i == 1
  1372. base = VIM::evaluate('g:plug_home')
  1373. all = VIM::evaluate('s:update.todo')
  1374. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  1375. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  1376. nthr = VIM::evaluate('s:update.threads').to_i
  1377. maxy = VIM::evaluate('winheight(".")').to_i
  1378. cd = iswin ? 'cd /d' : 'cd'
  1379. tot = VIM::evaluate('len(s:update.todo)') || 0
  1380. bar = ''
  1381. skip = 'Already installed'
  1382. mtx = Mutex.new
  1383. take1 = proc { mtx.synchronize { running && all.shift } }
  1384. logh = proc {
  1385. cnt = bar.length
  1386. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  1387. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  1388. VIM::command('normal! 2G')
  1389. VIM::command('redraw')
  1390. }
  1391. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  1392. log = proc { |name, result, type|
  1393. mtx.synchronize do
  1394. ing = ![true, false].include?(type)
  1395. bar += type ? '=' : 'x' unless ing
  1396. b = case type
  1397. when :install then '+' when :update then '*'
  1398. when true, nil then '-' else
  1399. VIM::command("call add(s:update.errors, '#{name}')")
  1400. 'x'
  1401. end
  1402. result =
  1403. if type || type.nil?
  1404. ["#{b} #{name}: #{result.lines.to_a.last}"]
  1405. elsif result =~ /^Interrupted|^Timeout/
  1406. ["#{b} #{name}: #{result}"]
  1407. else
  1408. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  1409. end
  1410. if lnum = where.call(name)
  1411. $curbuf.delete lnum
  1412. lnum = 4 if ing && lnum > maxy
  1413. end
  1414. result.each_with_index do |line, offset|
  1415. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  1416. end
  1417. logh.call
  1418. end
  1419. }
  1420. bt = proc { |cmd, name, type, cleanup|
  1421. tried = timeout = 0
  1422. begin
  1423. tried += 1
  1424. timeout += limit
  1425. fd = nil
  1426. data = ''
  1427. if iswin
  1428. Timeout::timeout(timeout) do
  1429. tmp = VIM::evaluate('tempname()')
  1430. system("(#{cmd}) > #{tmp}")
  1431. data = File.read(tmp).chomp
  1432. File.unlink tmp rescue nil
  1433. end
  1434. else
  1435. fd = IO.popen(cmd).extend(PlugStream)
  1436. first_line = true
  1437. log_prob = 1.0 / nthr
  1438. while line = Timeout::timeout(timeout) { fd.get_line }
  1439. data << line
  1440. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  1441. first_line = false
  1442. end
  1443. fd.close
  1444. end
  1445. [$? == 0, data.chomp]
  1446. rescue Timeout::Error, Interrupt => e
  1447. if fd && !fd.closed?
  1448. killall fd.pid
  1449. fd.close
  1450. end
  1451. cleanup.call if cleanup
  1452. if e.is_a?(Timeout::Error) && tried < tries
  1453. 3.downto(1) do |countdown|
  1454. s = countdown > 1 ? 's' : ''
  1455. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1456. sleep 1
  1457. end
  1458. log.call name, 'Retrying ...', type
  1459. retry
  1460. end
  1461. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1462. end
  1463. }
  1464. main = Thread.current
  1465. threads = []
  1466. watcher = Thread.new {
  1467. while VIM::evaluate('getchar(1)')
  1468. sleep 0.1
  1469. end
  1470. mtx.synchronize do
  1471. running = false
  1472. threads.each { |t| t.raise Interrupt }
  1473. end
  1474. threads.each { |t| t.join rescue nil }
  1475. main.kill
  1476. }
  1477. refresh = Thread.new {
  1478. while true
  1479. mtx.synchronize do
  1480. break unless running
  1481. VIM::command('noautocmd normal! a')
  1482. end
  1483. sleep 0.2
  1484. end
  1485. } if VIM::evaluate('s:mac_gui') == 1
  1486. clone_opt = VIM::evaluate('s:clone_opt')
  1487. progress = VIM::evaluate('s:progress_opt(1)')
  1488. nthr.times do
  1489. mtx.synchronize do
  1490. threads << Thread.new {
  1491. while pair = take1.call
  1492. name = pair.first
  1493. dir, uri, branch, tag = pair.last.values_at *%w[dir uri branch tag]
  1494. checkout = esc(tag ? tag : branch)
  1495. merge = esc(tag ? tag : "origin/#{branch}")
  1496. subm = "git submodule update --init --recursive 2>&1"
  1497. exists = File.directory? dir
  1498. ok, result =
  1499. if exists
  1500. chdir = "#{cd} #{iswin ? dir : esc(dir)}"
  1501. ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1502. current_uri = data.lines.to_a.last
  1503. if !ret
  1504. if data =~ /^Interrupted|^Timeout/
  1505. [false, data]
  1506. else
  1507. [false, [data.chomp, "PlugClean required."].join($/)]
  1508. end
  1509. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1510. [false, ["Invalid URI: #{current_uri}",
  1511. "Expected: #{uri}",
  1512. "PlugClean required."].join($/)]
  1513. else
  1514. if pull
  1515. log.call name, 'Updating ...', :update
  1516. fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
  1517. bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1 && git checkout -q #{checkout} 2>&1 && git merge --ff-only #{merge} 2>&1 && #{subm}", name, :update, nil
  1518. else
  1519. [true, skip]
  1520. end
  1521. end
  1522. else
  1523. d = esc dir.sub(%r{[\\/]+$}, '')
  1524. log.call name, 'Installing ...', :install
  1525. bt.call "git clone #{clone_opt unless tag} #{progress} --recursive #{uri} -b #{checkout} #{d} 2>&1", name, :install, proc {
  1526. FileUtils.rm_rf dir
  1527. }
  1528. end
  1529. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1530. log.call name, result, ok
  1531. end
  1532. } if running
  1533. end
  1534. end
  1535. threads.each { |t| t.join rescue nil }
  1536. logh.call
  1537. refresh.kill if refresh
  1538. watcher.kill
  1539. EOF
  1540. endfunction
  1541. function! s:shellesc(arg)
  1542. return '"'.escape(a:arg, '"').'"'
  1543. endfunction
  1544. function! s:glob_dir(path)
  1545. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1546. endfunction
  1547. function! s:progress_bar(line, bar, total)
  1548. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1549. endfunction
  1550. function! s:compare_git_uri(a, b)
  1551. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1552. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1553. return a ==# b
  1554. endfunction
  1555. function! s:format_message(bullet, name, message)
  1556. if a:bullet != 'x'
  1557. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1558. else
  1559. let lines = map(s:lines(a:message), '" ".v:val')
  1560. return extend([printf('x %s:', a:name)], lines)
  1561. endif
  1562. endfunction
  1563. function! s:with_cd(cmd, dir)
  1564. return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
  1565. endfunction
  1566. function! s:system(cmd, ...)
  1567. try
  1568. let [sh, shrd] = [&shell, &shellredir]
  1569. if !s:is_win
  1570. set shell=sh shellredir=>%s\ 2>&1
  1571. endif
  1572. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1573. return system(s:is_win ? '('.cmd.')' : cmd)
  1574. finally
  1575. let [&shell, &shellredir] = [sh, shrd]
  1576. endtry
  1577. endfunction
  1578. function! s:system_chomp(...)
  1579. let ret = call('s:system', a:000)
  1580. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1581. endfunction
  1582. function! s:git_validate(spec, check_branch)
  1583. let err = ''
  1584. if isdirectory(a:spec.dir)
  1585. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1586. let remote = result[-1]
  1587. if v:shell_error
  1588. let err = join([remote, 'PlugClean required.'], "\n")
  1589. elseif !s:compare_git_uri(remote, a:spec.uri)
  1590. let err = join(['Invalid URI: '.remote,
  1591. \ 'Expected: '.a:spec.uri,
  1592. \ 'PlugClean required.'], "\n")
  1593. elseif a:check_branch && has_key(a:spec, 'commit')
  1594. let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir))
  1595. let sha = result[-1]
  1596. if v:shell_error
  1597. let err = join(add(result, 'PlugClean required.'), "\n")
  1598. elseif !s:hash_match(sha, a:spec.commit)
  1599. let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
  1600. \ a:spec.commit[:6], sha[:6]),
  1601. \ 'PlugUpdate required.'], "\n")
  1602. endif
  1603. elseif a:check_branch
  1604. let branch = result[0]
  1605. " Check tag
  1606. if has_key(a:spec, 'tag')
  1607. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1608. if a:spec.tag !=# tag
  1609. let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
  1610. \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
  1611. endif
  1612. " Check branch
  1613. elseif a:spec.branch !=# branch
  1614. let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
  1615. \ branch, a:spec.branch)
  1616. endif
  1617. endif
  1618. else
  1619. let err = 'Not found'
  1620. endif
  1621. return err
  1622. endfunction
  1623. function! s:rm_rf(dir)
  1624. if isdirectory(a:dir)
  1625. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
  1626. endif
  1627. endfunction
  1628. function! s:clean(force)
  1629. call s:prepare()
  1630. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1631. call append(1, '')
  1632. " List of valid directories
  1633. let dirs = []
  1634. let [cnt, total] = [0, len(g:plugs)]
  1635. for [name, spec] in items(g:plugs)
  1636. if !s:is_managed(name) || empty(s:git_validate(spec, 0))
  1637. call add(dirs, spec.dir)
  1638. endif
  1639. let cnt += 1
  1640. call s:progress_bar(2, repeat('=', cnt), total)
  1641. normal! 2G
  1642. redraw
  1643. endfor
  1644. let allowed = {}
  1645. for dir in dirs
  1646. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1647. let allowed[dir] = 1
  1648. for child in s:glob_dir(dir)
  1649. let allowed[child] = 1
  1650. endfor
  1651. endfor
  1652. let todo = []
  1653. let found = sort(s:glob_dir(g:plug_home))
  1654. while !empty(found)
  1655. let f = remove(found, 0)
  1656. if !has_key(allowed, f) && isdirectory(f)
  1657. call add(todo, f)
  1658. call append(line('$'), '- ' . f)
  1659. let found = filter(found, 'stridx(v:val, f) != 0')
  1660. end
  1661. endwhile
  1662. normal! G
  1663. redraw
  1664. if empty(todo)
  1665. call append(line('$'), 'Already clean.')
  1666. else
  1667. if a:force || s:ask('Proceed?')
  1668. for dir in todo
  1669. call s:rm_rf(dir)
  1670. endfor
  1671. call append(line('$'), 'Removed.')
  1672. else
  1673. call append(line('$'), 'Cancelled.')
  1674. endif
  1675. endif
  1676. normal! G
  1677. endfunction
  1678. function! s:upgrade()
  1679. echo 'Downloading the latest version of vim-plug'
  1680. redraw
  1681. let tmp = tempname()
  1682. let new = tmp . '/plug.vim'
  1683. try
  1684. let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
  1685. if v:shell_error
  1686. return s:err('Error upgrading vim-plug: '. out)
  1687. endif
  1688. if readfile(s:me) ==# readfile(new)
  1689. echo 'vim-plug is already up-to-date'
  1690. return 0
  1691. else
  1692. call rename(s:me, s:me . '.old')
  1693. call rename(new, s:me)
  1694. unlet g:loaded_plug
  1695. echo 'vim-plug has been upgraded'
  1696. return 1
  1697. endif
  1698. finally
  1699. silent! call s:rm_rf(tmp)
  1700. endtry
  1701. endfunction
  1702. function! s:upgrade_specs()
  1703. for spec in values(g:plugs)
  1704. let spec.frozen = get(spec, 'frozen', 0)
  1705. endfor
  1706. endfunction
  1707. function! s:status()
  1708. call s:prepare()
  1709. call append(0, 'Checking plugins')
  1710. call append(1, '')
  1711. let ecnt = 0
  1712. let unloaded = 0
  1713. let [cnt, total] = [0, len(g:plugs)]
  1714. for [name, spec] in items(g:plugs)
  1715. if has_key(spec, 'uri')
  1716. if isdirectory(spec.dir)
  1717. let err = s:git_validate(spec, 1)
  1718. let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
  1719. else
  1720. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1721. endif
  1722. else
  1723. if isdirectory(spec.dir)
  1724. let [valid, msg] = [1, 'OK']
  1725. else
  1726. let [valid, msg] = [0, 'Not found.']
  1727. endif
  1728. endif
  1729. let cnt += 1
  1730. let ecnt += !valid
  1731. " `s:loaded` entry can be missing if PlugUpgraded
  1732. if valid && get(s:loaded, name, -1) == 0
  1733. let unloaded = 1
  1734. let msg .= ' (not loaded)'
  1735. endif
  1736. call s:progress_bar(2, repeat('=', cnt), total)
  1737. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1738. normal! 2G
  1739. redraw
  1740. endfor
  1741. call setline(1, 'Finished. '.ecnt.' error(s).')
  1742. normal! gg
  1743. setlocal nomodifiable
  1744. if unloaded
  1745. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1746. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1747. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1748. end
  1749. endfunction
  1750. function! s:extract_name(str, prefix, suffix)
  1751. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1752. endfunction
  1753. function! s:status_load(lnum)
  1754. let line = getline(a:lnum)
  1755. let name = s:extract_name(line, '-', '(not loaded)')
  1756. if !empty(name)
  1757. call plug#load(name)
  1758. setlocal modifiable
  1759. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1760. setlocal nomodifiable
  1761. endif
  1762. endfunction
  1763. function! s:status_update() range
  1764. let lines = getline(a:firstline, a:lastline)
  1765. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1766. if !empty(names)
  1767. echo
  1768. execute 'PlugUpdate' join(names)
  1769. endif
  1770. endfunction
  1771. function! s:is_preview_window_open()
  1772. silent! wincmd P
  1773. if &previewwindow
  1774. wincmd p
  1775. return 1
  1776. endif
  1777. return 0
  1778. endfunction
  1779. function! s:find_name(lnum)
  1780. for lnum in reverse(range(1, a:lnum))
  1781. let line = getline(lnum)
  1782. if empty(line)
  1783. return ''
  1784. endif
  1785. let name = s:extract_name(line, '-', '')
  1786. if !empty(name)
  1787. return name
  1788. endif
  1789. endfor
  1790. return ''
  1791. endfunction
  1792. function! s:preview_commit()
  1793. if b:plug_preview < 0
  1794. let b:plug_preview = !s:is_preview_window_open()
  1795. endif
  1796. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1797. if empty(sha)
  1798. return
  1799. endif
  1800. let name = s:find_name(line('.'))
  1801. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1802. return
  1803. endif
  1804. execute 'pedit' sha
  1805. wincmd P
  1806. setlocal filetype=git buftype=nofile nobuflisted modifiable
  1807. execute 'silent read !cd' s:shellesc(g:plugs[name].dir) '&& git show --pretty=medium' sha
  1808. normal! gg"_dd
  1809. setlocal nomodifiable
  1810. nnoremap <silent> <buffer> q :q<cr>
  1811. wincmd p
  1812. endfunction
  1813. function! s:section(flags)
  1814. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1815. endfunction
  1816. function! s:format_git_log(line)
  1817. let [sha, refs, subject, date] = split(a:line, nr2char(1))
  1818. let tag = matchstr(refs, 'tag: [^,)]\+')
  1819. let tag = empty(tag) ? ' ' : ' ('.tag.') '
  1820. return printf(' %s%s%s (%s)', sha, tag, subject, date)
  1821. endfunction
  1822. function! s:append_ul(lnum, text)
  1823. call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
  1824. endfunction
  1825. function! s:diff()
  1826. call s:prepare()
  1827. call append(0, ['Collecting changes ...', ''])
  1828. let cnts = [0, 0]
  1829. let bar = ''
  1830. let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
  1831. call s:progress_bar(2, bar, len(total))
  1832. for origin in [1, 0]
  1833. let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
  1834. if empty(plugs)
  1835. continue
  1836. endif
  1837. call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
  1838. for [k, v] in plugs
  1839. let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..'
  1840. let diff = s:system_chomp('git log --pretty=format:"%h%x01%d%x01%s%x01%cr" '.s:shellesc(range), v.dir)
  1841. if !empty(diff)
  1842. let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
  1843. call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
  1844. let cnts[origin] += 1
  1845. endif
  1846. let bar .= '='
  1847. call s:progress_bar(2, bar, len(total))
  1848. normal! 2G
  1849. redraw
  1850. endfor
  1851. if !cnts[origin]
  1852. call append(5, ['', 'N/A'])
  1853. endif
  1854. endfor
  1855. call setline(1, printf('%d plugin(s) updated.', cnts[0])
  1856. \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
  1857. if cnts[0] || cnts[1]
  1858. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1859. nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
  1860. endif
  1861. if cnts[0]
  1862. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1863. echo "Press 'X' on each block to revert the update"
  1864. endif
  1865. normal! gg
  1866. setlocal nomodifiable
  1867. endfunction
  1868. function! s:revert()
  1869. if search('^Pending updates', 'bnW')
  1870. return
  1871. endif
  1872. let name = s:find_name(line('.'))
  1873. if empty(name) || !has_key(g:plugs, name) ||
  1874. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1875. return
  1876. endif
  1877. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1878. setlocal modifiable
  1879. normal! "_dap
  1880. setlocal nomodifiable
  1881. echo 'Reverted.'
  1882. endfunction
  1883. function! s:snapshot(force, ...) abort
  1884. call s:prepare()
  1885. setf vim
  1886. call append(0, ['" Generated by vim-plug',
  1887. \ '" '.strftime("%c"),
  1888. \ '" :source this file in vim to restore the snapshot',
  1889. \ '" or execute: vim -S snapshot.vim',
  1890. \ '', '', 'PlugUpdate!'])
  1891. 1
  1892. let anchor = line('$') - 3
  1893. let names = sort(keys(filter(copy(g:plugs),
  1894. \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)')))
  1895. for name in reverse(names)
  1896. let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir)
  1897. if !empty(sha)
  1898. call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
  1899. redraw
  1900. endif
  1901. endfor
  1902. if a:0 > 0
  1903. let fn = expand(a:1)
  1904. if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
  1905. return
  1906. endif
  1907. call writefile(getline(1, '$'), fn)
  1908. echo 'Saved as '.a:1
  1909. silent execute 'e' s:esc(fn)
  1910. setf vim
  1911. endif
  1912. endfunction
  1913. function! s:split_rtp()
  1914. return split(&rtp, '\\\@<!,')
  1915. endfunction
  1916. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1917. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1918. if exists('g:plugs')
  1919. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1920. call s:upgrade_specs()
  1921. call s:define_commands()
  1922. endif
  1923. let &cpo = s:cpo_save
  1924. unlet s:cpo_save