plug.vim 65 KB

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