plug.vim 63 KB

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