plug.vim 56 KB

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