plug.vim 56 KB

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