plug.vim 62 KB

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