plug.vim 56 KB

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