plug.vim 56 KB

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