plug.vim 55 KB

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