startify.vim 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. " vim: et sw=2 sts=2
  2. " Plugin: https://github.com/mhinz/vim-startify
  3. " Description: A fancy start screen for Vim.
  4. " Maintainer: Marco Hinz <http://github.com/mhinz>
  5. if exists('g:autoloaded_startify') || &compatible
  6. finish
  7. endif
  8. let g:autoloaded_startify = 1
  9. " Function: #get_lastline {{{1
  10. function! startify#get_lastline() abort
  11. return b:startify.lastline + 1
  12. endfunction
  13. " Function: #get_separator {{{1
  14. function! startify#get_separator() abort
  15. return !exists('+shellslash') || &shellslash ? '/' : '\'
  16. endfunction
  17. " Function: #get_session_path {{{1
  18. function! startify#get_session_path() abort
  19. if exists('g:startify_session_dir')
  20. let path = g:startify_session_dir
  21. elseif has('nvim')
  22. let path = has('nvim-0.3.1')
  23. \ ? stdpath('data').'/session'
  24. \ : has('win32')
  25. \ ? '~/AppData/Local/nvim-data/session'
  26. \ : '~/.local/share/nvim/session'
  27. else " Vim
  28. let path = has('win32')
  29. \ ? '~/vimfiles/session'
  30. \ : '~/.vim/session'
  31. endif
  32. return resolve(expand(path))
  33. endfunction
  34. " Function: #insane_in_the_membrane {{{1
  35. function! startify#insane_in_the_membrane(on_vimenter) abort
  36. " Handle vim -y, vim -M.
  37. if a:on_vimenter && (&insertmode || !&modifiable)
  38. return
  39. endif
  40. if !&hidden && &modified
  41. call s:warn('Save your changes first.')
  42. return
  43. endif
  44. if !empty(v:servername) && exists('g:startify_skiplist_server')
  45. for servname in g:startify_skiplist_server
  46. if servname == v:servername
  47. return
  48. endif
  49. endfor
  50. endif
  51. if line2byte('$') != -1
  52. noautocmd enew
  53. endif
  54. silent! setlocal
  55. \ bufhidden=wipe
  56. \ colorcolumn=
  57. \ foldcolumn=0
  58. \ matchpairs=
  59. \ nobuflisted
  60. \ nocursorcolumn
  61. \ nocursorline
  62. \ nolist
  63. \ nonumber
  64. \ norelativenumber
  65. \ nospell
  66. \ noswapfile
  67. \ signcolumn=no
  68. if empty(&statusline)
  69. setlocal statusline=\ startify
  70. endif
  71. " Must be global so that it can be read by syntax/startify.vim.
  72. let g:startify_header = exists('g:startify_custom_header')
  73. \ ? s:set_custom_section(g:startify_custom_header)
  74. \ : (exists('*strwidth') ? startify#fortune#cowsay() : [])
  75. if !empty(g:startify_header)
  76. let g:startify_header += [''] " add blank line
  77. endif
  78. call append('$', g:startify_header)
  79. let b:startify = { 'tick': 0, 'entries': {}, 'indices': [] }
  80. if s:show_special
  81. call append('$', [s:padding_left .'[e] <empty buffer>', ''])
  82. endif
  83. call s:register(line('$')-1, 'e', 'special', 'enew', '')
  84. let b:startify.entry_number = 0
  85. if filereadable('Session.vim')
  86. call append('$', [s:padding_left .'[0] '. getcwd() . s:sep .'Session.vim', ''])
  87. call s:register(line('$')-1, '0', 'session',
  88. \ 'call startify#session_delete_buffers() | source', 'Session.vim')
  89. let b:startify.entry_number = 1
  90. let l:show_session = 1
  91. endif
  92. if empty(v:oldfiles)
  93. call s:warn("Can't read viminfo file. Read :help startify-faq-02")
  94. endif
  95. let b:startify.section_header_lines = []
  96. let lists = s:get_lists()
  97. call s:show_lists(lists)
  98. silent $delete _
  99. if s:show_special
  100. call append('$', ['', s:padding_left .'[q] <quit>'])
  101. call s:register(line('$'), 'q', 'special', 'call s:close()', '')
  102. else
  103. " Don't overwrite the last regular entry, thus +1
  104. call s:register(line('$')+1, 'q', 'special', 'call s:close()', '')
  105. endif
  106. " compute first line offset
  107. let b:startify.firstline = 2
  108. let b:startify.firstline += len(g:startify_header)
  109. " no special, no local Session.vim, but a section header
  110. if !s:show_special && !exists('l:show_session') && has_key(lists[0], 'header')
  111. let b:startify.firstline += len(lists[0].header) + 1
  112. endif
  113. let b:startify.lastline = line('$')
  114. let footer = exists('g:startify_custom_footer')
  115. \ ? s:set_custom_section(g:startify_custom_footer)
  116. \ : []
  117. if !empty(footer)
  118. let footer = [''] + footer
  119. endif
  120. call append('$', footer)
  121. setlocal nomodifiable nomodified
  122. call s:set_mappings()
  123. call cursor(b:startify.firstline, 5)
  124. autocmd startify CursorMoved <buffer> call s:set_cursor()
  125. silent! %foldopen!
  126. set filetype=startify
  127. if exists('##DirChanged')
  128. let b:startify.cwd = getcwd()
  129. autocmd startify DirChanged <buffer> if getcwd() !=# get(get(b:, 'startify', {}), 'cwd') | Startify | endif
  130. endif
  131. if exists('#User#Startified')
  132. doautocmd <nomodeline> User Startified
  133. endif
  134. if exists('#User#StartifyReady')
  135. doautocmd <nomodeline> User StartifyReady
  136. endif
  137. endfunction
  138. " Function: #session_load {{{1
  139. function! startify#session_load(source_last_session, ...) abort
  140. if !isdirectory(s:session_dir)
  141. echomsg 'The session directory does not exist: '. s:session_dir
  142. return
  143. elseif empty(startify#session_list_as_string(''))
  144. echomsg 'There are no sessions...'
  145. return
  146. endif
  147. let session_path = s:session_dir . s:sep
  148. if a:0
  149. let session_path .= a:1
  150. elseif a:source_last_session && !has('win32')
  151. let session_path .= '__LAST__'
  152. else
  153. call inputsave()
  154. let session_path .= input(
  155. \ 'Load this session: ',
  156. \ fnamemodify(v:this_session, ':t'),
  157. \ 'custom,startify#session_list_as_string') | redraw
  158. call inputrestore()
  159. endif
  160. if filereadable(session_path)
  161. if get(g:, 'startify_session_persistence') && filewritable(v:this_session)
  162. call startify#session_write(fnameescape(v:this_session))
  163. endif
  164. call startify#session_delete_buffers()
  165. execute 'source '. fnameescape(session_path)
  166. call s:create_last_session_link(session_path)
  167. else
  168. echo 'No such file: '. session_path
  169. endif
  170. endfunction
  171. " Function: #session_save {{{1
  172. function! startify#session_save(bang, ...) abort
  173. if !isdirectory(s:session_dir)
  174. if exists('*mkdir')
  175. echo 'The session directory does not exist: '. s:session_dir .'. Create it? [y/n]'
  176. if (nr2char(getchar()) == 'y')
  177. call mkdir(s:session_dir, 'p')
  178. else
  179. echo
  180. return
  181. endif
  182. else
  183. echo 'The session directory does not exist: '. s:session_dir
  184. return
  185. endif
  186. endif
  187. call inputsave()
  188. let this_session = fnamemodify(v:this_session, ':t')
  189. if this_session ==# '__LAST__'
  190. let this_session = ''
  191. endif
  192. let session_name = exists('a:1')
  193. \ ? a:1
  194. \ : input('Save under this session name: ', this_session, 'custom,startify#session_list_as_string') | redraw
  195. call inputrestore()
  196. if empty(session_name)
  197. echo 'You gave an empty name!'
  198. return
  199. endif
  200. let session_path = s:session_dir . s:sep . session_name
  201. if !filereadable(session_path)
  202. call startify#session_write(fnameescape(session_path))
  203. echo 'Session saved under: '. session_path
  204. return
  205. endif
  206. echo 'Session already exists. Overwrite? [y/n]' | redraw
  207. if a:bang || nr2char(getchar()) == 'y'
  208. call startify#session_write(fnameescape(session_path))
  209. echo 'Session saved under: '. session_path
  210. else
  211. echo 'Did NOT save the session!'
  212. endif
  213. endfunction
  214. " Function: #session_close {{{1
  215. function! startify#session_close() abort
  216. if exists('v:this_session') && filewritable(v:this_session)
  217. call startify#session_write(fnameescape(v:this_session))
  218. let v:this_session = ''
  219. endif
  220. call startify#session_delete_buffers()
  221. Startify
  222. endfunction
  223. " Function: #session_write {{{1
  224. function! startify#session_write(session_path)
  225. " preserve existing variables from savevars
  226. if exists('g:startify_session_savevars')
  227. let savevars = map(filter(copy(g:startify_session_savevars), 'exists(v:val)'), '"let ". v:val ." = ". strtrans(string(eval(v:val)))')
  228. endif
  229. " if this function is called while being in the Startify buffer
  230. " (by loading another session or running :SSave/:SLoad directly)
  231. " switch back to the previous buffer before saving the session
  232. if &filetype == 'startify'
  233. let callingbuffer = bufnr('#')
  234. if callingbuffer > 0
  235. execute 'buffer' callingbuffer
  236. endif
  237. endif
  238. " prevent saving already deleted buffers that were in the arglist
  239. for arg in argv()
  240. if !buflisted(arg)
  241. execute 'silent! argdelete' fnameescape(arg)
  242. endif
  243. endfor
  244. " clean up session before saving it
  245. for cmd in get(g:, 'startify_session_before_save', [])
  246. execute cmd
  247. endfor
  248. let ssop = &sessionoptions
  249. set sessionoptions-=options
  250. try
  251. execute 'mksession!' a:session_path
  252. catch
  253. echohl ErrorMsg
  254. echomsg v:exception
  255. echohl NONE
  256. return
  257. finally
  258. let &sessionoptions = ssop
  259. endtry
  260. if exists('g:startify_session_remove_lines')
  261. \ || exists('g:startify_session_savevars')
  262. \ || exists('g:startify_session_savecmds')
  263. silent execute 'split' a:session_path
  264. " remove lines from the session file
  265. if exists('g:startify_session_remove_lines')
  266. for pattern in g:startify_session_remove_lines
  267. execute 'silent global/'. pattern .'/delete _'
  268. endfor
  269. endif
  270. " put variables from savevars into session file
  271. if exists('savevars') && !empty(savevars)
  272. call append(line('$')-3, savevars)
  273. endif
  274. " put commands from savecmds into session file
  275. if exists('g:startify_session_savecmds')
  276. call append(line('$')-3, g:startify_session_savecmds)
  277. endif
  278. setlocal bufhidden=delete
  279. silent update
  280. silent hide
  281. endif
  282. call s:create_last_session_link(a:session_path)
  283. endfunction
  284. " Function: #session_delete {{{1
  285. function! startify#session_delete(bang, ...) abort
  286. if !isdirectory(s:session_dir)
  287. echo 'The session directory does not exist: '. s:session_dir
  288. return
  289. elseif empty(startify#session_list_as_string(''))
  290. echo 'There are no sessions...'
  291. return
  292. endif
  293. call inputsave()
  294. let session_path = s:session_dir . s:sep . (exists('a:1')
  295. \ ? a:1
  296. \ : input('Delete this session: ', fnamemodify(v:this_session, ':t'), 'custom,startify#session_list_as_string'))
  297. call inputrestore()
  298. if !filereadable(session_path)
  299. echomsg 'No such session: '. session_path
  300. return
  301. endif
  302. echo 'Really delete '. session_path .'? [y/n]'
  303. if a:bang || nr2char(getchar()) == 'y'
  304. if delete(session_path) == 0
  305. echo 'Deleted session '. session_path .'!'
  306. else
  307. echo 'Deletion failed!'
  308. endif
  309. else
  310. echo 'Deletion aborted!'
  311. endif
  312. endfunction
  313. " Function: #session_delete_buffers {{{1
  314. function! startify#session_delete_buffers()
  315. if get(g:, 'startify_session_delete_buffers', 1)
  316. silent! %bdelete!
  317. endif
  318. endfunction
  319. " Function: #session_list {{{1
  320. function! startify#session_list(lead, ...) abort
  321. return filter(map(split(globpath(s:session_dir, '*'.a:lead.'*'), '\n'), 'fnamemodify(v:val, ":t")'), 'v:val !=# "__LAST__"')
  322. endfunction
  323. " Function: #session_list_as_string {{{1
  324. function! startify#session_list_as_string(lead, ...) abort
  325. return join(filter(map(split(globpath(s:session_dir, '*'.a:lead.'*'), '\n'), 'fnamemodify(v:val, ":t")'), 'v:val !=# "__LAST__"'), "\n")
  326. endfunction
  327. " Function: #debug {{{1
  328. function! startify#debug()
  329. if exists('b:startify.entries')
  330. for k in sort(keys(b:startify.entries))
  331. echomsg '['. k .'] = '. string(b:startify.entries[k])
  332. endfor
  333. else
  334. call s:warn('This is no Startify buffer!')
  335. endif
  336. endfunction
  337. " Function: #open_buffers {{{1
  338. function! startify#open_buffers(...) abort
  339. if exists('a:1') " used in mappings
  340. let entry = b:startify.entries[a:1]
  341. if !empty(s:batchmode) && entry.type == 'file'
  342. call s:set_mark(s:batchmode, a:1)
  343. else
  344. call s:open_buffer(entry)
  345. endif
  346. return
  347. endif
  348. let marked = filter(copy(b:startify.entries), 'v:val.marked')
  349. if empty(marked) " open current entry
  350. call s:open_buffer(b:startify.entries[line('.')])
  351. return
  352. endif
  353. enew
  354. setlocal nobuflisted
  355. " Open all marked entries.
  356. for entry in sort(values(marked), 's:sort_by_tick')
  357. call s:open_buffer(entry)
  358. endfor
  359. wincmd =
  360. if exists('#User#StartifyAllBuffersOpened')
  361. doautocmd <nomodeline> User StartifyAllBuffersOpened
  362. endif
  363. endfunction
  364. " Function: s:get_lists {{{1
  365. function! s:get_lists() abort
  366. if exists('g:startify_lists')
  367. return g:startify_lists
  368. elseif exists('g:startify_list_order')
  369. " Convert old g:startify_list_order format to newer g:startify_lists format.
  370. let lists = []
  371. for item in g:startify_list_order
  372. if type(item) == type([])
  373. let header = item
  374. else
  375. if exists('header')
  376. let lists += [{ 'type': item, 'header': header }]
  377. unlet header
  378. else
  379. let lists += [{ 'type': item }]
  380. endif
  381. endif
  382. unlet item
  383. endfor
  384. return lists
  385. else
  386. return [
  387. \ { 'header': [s:padding_left .'MRU'], 'type': 'files' },
  388. \ { 'header': [s:padding_left .'MRU '. getcwd()], 'type': 'dir' },
  389. \ { 'header': [s:padding_left .'Sessions'], 'type': 'sessions' },
  390. \ { 'header': [s:padding_left .'Bookmarks'], 'type': 'bookmarks' },
  391. \ { 'header': [s:padding_left .'Commands'], 'type': 'commands' },
  392. \ ]
  393. endif
  394. endfunction
  395. " Function: s:show_lists {{{1
  396. function! s:show_lists(lists) abort
  397. for list in a:lists
  398. if !has_key(list, 'type')
  399. continue
  400. endif
  401. let b:startify.indices = copy(get(list, 'indices', []))
  402. if type(list.type) == type('')
  403. if has_key(list, 'header')
  404. let s:last_message = list.header
  405. endif
  406. call s:show_{list.type}()
  407. elseif type(list.type) == type(function('tr'))
  408. try
  409. let entries = list.type()
  410. catch
  411. call s:warn(v:exception)
  412. continue
  413. endtry
  414. if empty(entries)
  415. unlet! s:last_message
  416. continue
  417. endif
  418. if has_key(list, 'header')
  419. let s:last_message = list.header
  420. call s:print_section_header()
  421. endif
  422. for entry in entries
  423. let cmd = get(entry, 'cmd', 'edit')
  424. let path = get(entry, 'path', '')
  425. let type = get(entry, 'type', empty(path) ? 'special' : 'file')
  426. let index = s:get_index_as_string()
  427. call append('$', s:padding_left .'['. index .']'. repeat(' ', (3 - strlen(index))) . entry.line)
  428. call s:register(line('$'), index, type, cmd, path)
  429. endfor
  430. call append('$', '')
  431. else
  432. call s:warn('Wrong format for g:startify_lists: '. string(list))
  433. endif
  434. endfor
  435. endfunction
  436. " Function: s:open_buffer {{{1
  437. function! s:open_buffer(entry)
  438. if a:entry.type == 'special'
  439. execute a:entry.cmd
  440. elseif a:entry.type == 'session'
  441. execute a:entry.cmd a:entry.path
  442. elseif a:entry.type == 'file'
  443. if line2byte('$') == -1
  444. execute 'edit' a:entry.path
  445. else
  446. if a:entry.cmd == 'tabnew'
  447. wincmd =
  448. endif
  449. execute a:entry.cmd a:entry.path
  450. endif
  451. call s:check_user_options(a:entry.path)
  452. endif
  453. if exists('#User#StartifyBufferOpened')
  454. doautocmd <nomodeline> User StartifyBufferOpened
  455. endif
  456. endfunction
  457. " Function: s:set_custom_section {{{1
  458. function! s:set_custom_section(section) abort
  459. if type(a:section) == type([])
  460. return copy(a:section)
  461. elseif type(a:section) == type('')
  462. return empty(a:section) ? [] : eval(a:section)
  463. endif
  464. return []
  465. endfunction
  466. " Function: s:display_by_path {{{1
  467. function! s:display_by_path(path_prefix, path_format, use_env) abort
  468. let oldfiles = call(get(g:, 'startify_enable_unsafe') ? 's:filter_oldfiles_unsafe' : 's:filter_oldfiles',
  469. \ [a:path_prefix, a:path_format, a:use_env])
  470. let entry_format = "s:padding_left .'['. index .']'. repeat(' ', (3 - strlen(index))) ."
  471. if exists('*StartifyEntryFormat')
  472. let entry_format .= StartifyEntryFormat()
  473. else
  474. let entry_format .= 'entry_path'
  475. endif
  476. if !empty(oldfiles)
  477. if exists('s:last_message')
  478. call s:print_section_header()
  479. endif
  480. for [absolute_path, entry_path] in oldfiles
  481. let index = s:get_index_as_string()
  482. call append('$', eval(entry_format))
  483. if has('win32')
  484. let absolute_path = substitute(absolute_path, '\[', '\[[]', 'g')
  485. endif
  486. call s:register(line('$'), index, 'file', 'edit', absolute_path)
  487. endfor
  488. call append('$', '')
  489. endif
  490. endfunction
  491. " Function: s:filter_oldfiles {{{1
  492. function! s:filter_oldfiles(path_prefix, path_format, use_env) abort
  493. let path_prefix = '\V'. escape(a:path_prefix, '\')
  494. let counter = s:numfiles
  495. let entries = {}
  496. let oldfiles = []
  497. for fname in v:oldfiles
  498. if counter <= 0
  499. break
  500. endif
  501. if s:is_in_skiplist(fname)
  502. " https://github.com/mhinz/vim-startify/issues/353
  503. continue
  504. endif
  505. let absolute_path = fnamemodify(resolve(fname), ":p")
  506. " filter duplicates, bookmarks and entries from the skiplist
  507. if has_key(entries, absolute_path)
  508. \ || !filereadable(absolute_path)
  509. \ || s:is_in_skiplist(absolute_path)
  510. \ || match(absolute_path, path_prefix)
  511. continue
  512. endif
  513. let entry_path = ''
  514. if s:tf
  515. let entry_path = s:transform(absolute_path)
  516. endif
  517. if empty(entry_path)
  518. let entry_path = fnamemodify(absolute_path, a:path_format)
  519. endif
  520. let entries[absolute_path] = 1
  521. let counter -= 1
  522. let oldfiles += [[fnameescape(absolute_path), entry_path]]
  523. endfor
  524. if a:use_env
  525. call s:init_env()
  526. for i in range(len(oldfiles))
  527. for [k,v] in s:env
  528. let p = oldfiles[i][0]
  529. if !stridx(tolower(p), tolower(v))
  530. let oldfiles[i][1] = printf('$%s%s', k, p[len(v):])
  531. break
  532. endif
  533. endfor
  534. endfor
  535. endif
  536. return oldfiles
  537. endfunction
  538. " Function: s:filter_oldfiles_unsafe {{{1
  539. function! s:filter_oldfiles_unsafe(path_prefix, path_format, use_env) abort
  540. let path_prefix = '\V'. escape(a:path_prefix, '\')
  541. let counter = s:numfiles
  542. let entries = {}
  543. let oldfiles = []
  544. let is_dir = escape(s:sep, '\') . '$'
  545. for fname in v:oldfiles
  546. if counter <= 0
  547. break
  548. endif
  549. if s:is_in_skiplist(fname)
  550. " https://github.com/mhinz/vim-startify/issues/353
  551. continue
  552. endif
  553. let absolute_path = glob(fnamemodify(fname, ":p"))
  554. if empty(absolute_path)
  555. \ || has_key(entries, absolute_path)
  556. \ || (absolute_path =~ is_dir)
  557. \ || match(absolute_path, path_prefix)
  558. \ || s:is_in_skiplist(absolute_path)
  559. continue
  560. endif
  561. let entry_path = fnamemodify(absolute_path, a:path_format)
  562. let entries[absolute_path] = 1
  563. let counter -= 1
  564. let oldfiles += [[fnameescape(absolute_path), entry_path]]
  565. endfor
  566. return oldfiles
  567. endfunction
  568. " Function: s:show_dir {{{1
  569. function! s:show_dir() abort
  570. return s:display_by_path(getcwd() . s:sep, ':.', 0)
  571. endfunction
  572. " Function: s:show_files {{{1
  573. function! s:show_files() abort
  574. return s:display_by_path('', s:relative_path, get(g:, 'startify_use_env'))
  575. endfunction
  576. " Function: s:show_sessions {{{1
  577. function! s:show_sessions() abort
  578. let limit = get(g:, 'startify_session_number', 999) - 1
  579. if limit <= -1
  580. return
  581. endif
  582. let sfiles = split(globpath(s:session_dir, '*'), '\n')
  583. let sfiles = filter(sfiles, 'v:val !~# "__LAST__$"')
  584. let sfiles = filter(sfiles,
  585. \ '!(v:val =~# "x\.vim$" && index(sfiles, v:val[:-6].".vim") >= 0)')
  586. if empty(sfiles)
  587. if exists('s:last_message')
  588. unlet s:last_message
  589. endif
  590. return
  591. endif
  592. if exists('s:last_message')
  593. call s:print_section_header()
  594. endif
  595. if get(g:, 'startify_session_sort')
  596. function! s:sort_by_mtime(foo, bar)
  597. let foo = getftime(a:foo)
  598. let bar = getftime(a:bar)
  599. return foo == bar ? 0 : (foo < bar ? 1 : -1)
  600. endfunction
  601. call sort(sfiles, 's:sort_by_mtime')
  602. endif
  603. for i in range(len(sfiles))
  604. let index = s:get_index_as_string()
  605. let fname = fnamemodify(sfiles[i], ':t')
  606. let dname = sfiles[i] ==# v:this_session ? fname.' (*)' : fname
  607. call append('$', s:padding_left .'['. index .']'. repeat(' ', (3 - strlen(index))) . dname)
  608. if has('win32')
  609. let fname = substitute(fname, '\[', '\[[]', 'g')
  610. endif
  611. call s:register(line('$'), index, 'session', 'SLoad', fname)
  612. if i == limit
  613. break
  614. endif
  615. endfor
  616. call append('$', '')
  617. endfunction
  618. " Function: s:show_bookmarks {{{1
  619. function! s:show_bookmarks() abort
  620. if !exists('g:startify_bookmarks') || empty(g:startify_bookmarks)
  621. return
  622. endif
  623. if exists('s:last_message')
  624. call s:print_section_header()
  625. endif
  626. for bookmark in g:startify_bookmarks
  627. if type(bookmark) == type({})
  628. let [index, path] = items(bookmark)[0]
  629. else " string
  630. let [index, path] = [s:get_index_as_string(), bookmark]
  631. endif
  632. let entry_path = ''
  633. if s:tf
  634. let entry_path = s:transform(fnamemodify(resolve(expand(path)), ':p'))
  635. endif
  636. if empty(entry_path)
  637. let entry_path = path
  638. endif
  639. call append('$', s:padding_left .'['. index .']'. repeat(' ', (3 - strlen(index))) . entry_path)
  640. if has('win32')
  641. let path = substitute(path, '\[', '\[[]', 'g')
  642. endif
  643. call s:register(line('$'), index, 'file', 'edit', fnameescape(expand(path)))
  644. unlet bookmark " avoid type mismatch for heterogeneous lists
  645. endfor
  646. call append('$', '')
  647. endfunction
  648. " Function: s:show_commands {{{1
  649. function! s:show_commands() abort
  650. if !exists('g:startify_commands') || empty(g:startify_commands)
  651. return
  652. endif
  653. if exists('s:last_message')
  654. call s:print_section_header()
  655. endif
  656. for entry in g:startify_commands
  657. if type(entry) == type({}) " with custom index
  658. let [index, command] = items(entry)[0]
  659. else
  660. let command = entry
  661. let index = s:get_index_as_string()
  662. endif
  663. " If no list is given, the description is the command itself.
  664. let [desc, cmd] = type(command) == type([]) ? command : [command, command]
  665. call append('$', s:padding_left .'['. index .']'. repeat(' ', (3 - strlen(index))) . desc)
  666. call s:register(line('$'), index, 'special', cmd, '')
  667. unlet entry command
  668. endfor
  669. call append('$', '')
  670. endfunction
  671. " Function: s:is_in_skiplist {{{1
  672. function! s:is_in_skiplist(arg) abort
  673. for regexp in s:skiplist
  674. try
  675. if a:arg =~# regexp
  676. return 1
  677. endif
  678. catch
  679. call s:warn('Pattern '. string(regexp) .' threw an exception. Read :help g:startify_skiplist')
  680. endtry
  681. endfor
  682. endfunction
  683. " Function: s:set_cursor {{{1
  684. function! s:set_cursor() abort
  685. let b:startify.oldline = exists('b:startify.newline') ? b:startify.newline : 2 + len(s:padding_left)
  686. let b:startify.newline = line('.')
  687. " going up (-1) or down (1)
  688. if b:startify.oldline == b:startify.newline
  689. \ && col('.') != s:fixed_column
  690. \ && !b:startify.leftmouse
  691. let movement = 2 * (col('.') > s:fixed_column) - 1
  692. let b:startify.newline += movement
  693. else
  694. let movement = 2 * (b:startify.newline > b:startify.oldline) - 1
  695. let b:startify.leftmouse = 0
  696. endif
  697. " skip section headers lines until an entry is found
  698. while index(b:startify.section_header_lines, b:startify.newline) != -1
  699. let b:startify.newline += movement
  700. endwhile
  701. " skip blank lines between lists
  702. if empty(getline(b:startify.newline))
  703. let b:startify.newline += movement
  704. endif
  705. " don't go beyond first or last entry
  706. let b:startify.newline = max([b:startify.firstline, min([b:startify.lastline, b:startify.newline])])
  707. call cursor(b:startify.newline, s:fixed_column)
  708. endfunction
  709. " Function: s:set_mappings {{{1
  710. function! s:set_mappings() abort
  711. nnoremap <buffer><nowait><silent> i :enew <bar> startinsert<cr>
  712. nnoremap <buffer><nowait><silent> <insert> :enew <bar> startinsert<cr>
  713. nnoremap <buffer><nowait><silent> b :call <sid>set_mark('B')<cr>
  714. nnoremap <buffer><nowait><silent> s :call <sid>set_mark('S')<cr>
  715. nnoremap <buffer><nowait><silent> t :call <sid>set_mark('T')<cr>
  716. nnoremap <buffer><nowait><silent> v :call <sid>set_mark('V')<cr>
  717. nnoremap <buffer><nowait><silent> B :call startify#set_batchmode('B')<cr>
  718. nnoremap <buffer><nowait><silent> S :call startify#set_batchmode('S')<cr>
  719. nnoremap <buffer><nowait><silent> T :call startify#set_batchmode('T')<cr>
  720. nnoremap <buffer><nowait><silent> V :call startify#set_batchmode('V')<cr>
  721. nnoremap <buffer><nowait><silent> <cr> :call startify#open_buffers()<cr>
  722. nnoremap <buffer><nowait><silent> <LeftMouse> :call <sid>leftmouse()<cr>
  723. nnoremap <buffer><nowait><silent> <2-LeftMouse> :call startify#open_buffers()<cr>
  724. nnoremap <buffer><nowait><silent> <MiddleMouse> :enew <bar> execute 'normal! "'.(v:register=='"'?'*':v:register).'gp'<cr>
  725. " Without these mappings n/N wouldn't work properly, since autocmds always
  726. " force the cursor back on the index.
  727. nnoremap <buffer><expr> n ' j'[v:searchforward].'n'
  728. nnoremap <buffer><expr> N 'j '[v:searchforward].'N'
  729. function! s:leftmouse()
  730. " feedkeys() triggers CursorMoved which calls s:set_cursor() which checks
  731. " .leftmouse.
  732. let b:startify.leftmouse = 1
  733. call feedkeys("\<LeftMouse>", 'nt')
  734. endfunction
  735. function! s:compare_by_index(foo, bar)
  736. return a:foo.index - a:bar.index
  737. endfunction
  738. for entry in sort(values(b:startify.entries), 's:compare_by_index')
  739. execute 'nnoremap <buffer><silent><nowait>' entry.index
  740. \ ':call startify#open_buffers('. string(entry.line) .')<cr>'
  741. endfor
  742. endfunction
  743. " Function: #set_batchmode {{{1
  744. function! startify#set_batchmode(batchmode) abort
  745. let s:batchmode = (a:batchmode == s:batchmode) ? '' : a:batchmode
  746. echo empty(s:batchmode) ? 'Batchmode off' : 'Batchmode: '. s:batchmode
  747. endfunction
  748. " Function: s:set_mark {{{1
  749. function! s:set_mark(type, ...) abort
  750. if a:0
  751. let entryline = a:1
  752. else
  753. call startify#set_batchmode('')
  754. let entryline = line('.')
  755. endif
  756. let entry = b:startify.entries[entryline]
  757. if entry.type != 'file'
  758. return
  759. endif
  760. let default_cmds = {
  761. \ 'B': 'edit',
  762. \ 'S': 'split',
  763. \ 'V': 'vsplit',
  764. \ 'T': 'tabnew',
  765. \ }
  766. let origline = line('.')
  767. execute entryline
  768. let index = expand('<cword>')
  769. setlocal modifiable
  770. if entry.marked && index[0] == a:type
  771. let entry.cmd = 'edit'
  772. let entry.marked = 0
  773. execute 'normal! ci]'. entry.index
  774. else
  775. let entry.cmd = default_cmds[a:type]
  776. let entry.marked = 1
  777. let entry.tick = b:startify.tick
  778. let b:startify.tick += 1
  779. execute 'normal! ci]'. repeat(a:type, len(index))
  780. endif
  781. setlocal nomodifiable nomodified
  782. " Reset cursor to fixed column, which is important for s:set_cursor().
  783. call cursor(origline, s:fixed_column)
  784. endfunction
  785. " Function: s:sort_by_tick {{{1
  786. function! s:sort_by_tick(one, two)
  787. return a:one.tick - a:two.tick
  788. endfunction
  789. " Function: s:check_user_options {{{1
  790. function! s:check_user_options(path) abort
  791. let session = a:path . s:sep .'Session.vim'
  792. if get(g:, 'startify_session_autoload') && filereadable(glob(session))
  793. execute 'silent bwipeout' a:path
  794. call startify#session_delete_buffers()
  795. execute 'source' session
  796. return
  797. endif
  798. if get(g:, 'startify_change_to_vcs_root') && s:cd_to_vcs_root(a:path)
  799. return
  800. endif
  801. if get(g:, 'startify_change_to_dir', 1)
  802. if isdirectory(a:path)
  803. execute 'lcd' a:path
  804. else
  805. let dir = fnamemodify(a:path, ':h')
  806. if isdirectory(dir)
  807. execute 'lcd' dir
  808. else
  809. " Do nothing. E.g. a:path == `scp://foo/bar`
  810. endif
  811. endif
  812. endif
  813. endfunction
  814. " Function: s:cd_to_vcs_root {{{1
  815. function! s:cd_to_vcs_root(path) abort
  816. let dir = fnamemodify(a:path, ':p:h')
  817. for vcs in [ '.git', '.hg', '.bzr', '.svn' ]
  818. let root = finddir(vcs, dir .';')
  819. if !empty(root)
  820. execute 'lcd' fnameescape(fnamemodify(root, ':h'))
  821. return 1
  822. endif
  823. endfor
  824. return 0
  825. endfunction
  826. " Function: s:close {{{1
  827. function! s:close() abort
  828. if len(filter(range(0, bufnr('$')), 'buflisted(v:val)')) - &buflisted
  829. if bufloaded(bufnr('#')) && bufnr('#') != bufnr('%')
  830. buffer #
  831. else
  832. bnext
  833. endif
  834. else
  835. quit
  836. endif
  837. endfunction
  838. " Function: s:get_index_as_string {{{1
  839. function! s:get_index_as_string() abort
  840. if !empty(b:startify.indices)
  841. return remove(b:startify.indices, 0)
  842. elseif exists('g:startify_custom_indices')
  843. let listlen = len(g:startify_custom_indices)
  844. if b:startify.entry_number < listlen
  845. let idx = g:startify_custom_indices[b:startify.entry_number]
  846. else
  847. let idx = string(b:startify.entry_number - listlen)
  848. endif
  849. else
  850. let idx = string(b:startify.entry_number)
  851. endif
  852. let b:startify.entry_number += 1
  853. return idx
  854. endfunction
  855. " Function: s:print_section_header {{{1
  856. function! s:print_section_header() abort
  857. $
  858. let curline = line('.')
  859. for lnum in range(curline, curline + len(s:last_message) + 1)
  860. call add(b:startify.section_header_lines, lnum)
  861. endfor
  862. call append('$', s:last_message + [''])
  863. unlet s:last_message
  864. endfunction
  865. " Function: s:register {{{1
  866. function! s:register(line, index, type, cmd, path)
  867. let b:startify.entries[a:line] = {
  868. \ 'index': a:index,
  869. \ 'type': a:type,
  870. \ 'line': a:line,
  871. \ 'cmd': a:cmd,
  872. \ 'path': a:path,
  873. \ 'marked': 0,
  874. \ }
  875. endfunction
  876. " Function: s:create_last_session_link {{{1
  877. function! s:create_last_session_link(session_path)
  878. if !has('win32') && a:session_path !~# '__LAST__$'
  879. let cmd = printf('ln -sf %s %s',
  880. \ shellescape(fnamemodify(a:session_path, ':t')),
  881. \ shellescape(s:session_dir .'/__LAST__'))
  882. call system(cmd)
  883. if v:shell_error
  884. call s:warn("Can't create 'last used session' symlink.")
  885. endif
  886. endif
  887. endfunction
  888. " Function: s:init_env {{{1
  889. function! s:init_env()
  890. let s:env = []
  891. let ignore = {
  892. \ 'HOME': 1,
  893. \ 'OLDPWD': 1,
  894. \ 'PWD': 1,
  895. \ }
  896. function! s:get_env()
  897. redir => s
  898. silent! execute "norm!:ec$\<c-a>'\<c-b>\<right>\<right>\<del>'\<cr>"
  899. redir END
  900. redraw
  901. return split(s)
  902. endfunction
  903. function! s:compare_by_key_len(foo, bar)
  904. return len(a:foo[0]) - len(a:bar[0])
  905. endfunction
  906. function! s:compare_by_val_len(foo, bar)
  907. return len(a:bar[1]) - len(a:foo[1])
  908. endfunction
  909. for k in s:get_env()
  910. silent! execute "let v = eval('$'.k)"
  911. if has('win32') ? (v[1] != ':') : (v[0] != '/')
  912. \ || has_key(ignore, k)
  913. \ || len(k) > len(v)
  914. continue
  915. endif
  916. call insert(s:env, [k,v], 0)
  917. endfor
  918. let s:env = sort(s:env, 's:compare_by_key_len')
  919. let s:env = sort(s:env, 's:compare_by_val_len')
  920. endfunction
  921. " Function: s:transform {{{1
  922. function s:transform(absolute_path)
  923. for [k,V] in g:startify_transformations
  924. if a:absolute_path =~ k
  925. return type(V) == type('') ? V : V(a:absolute_path)
  926. endif
  927. unlet V
  928. endfor
  929. return ''
  930. endfunction
  931. " Function: s:warn {{{1
  932. function! s:warn(msg) abort
  933. echohl WarningMsg
  934. echomsg 'startify: '. a:msg
  935. echohl NONE
  936. endfunction
  937. " Init: values {{{1
  938. let s:sep = startify#get_separator()
  939. let s:numfiles = get(g:, 'startify_files_number', 10)
  940. let s:show_special = get(g:, 'startify_enable_special', 1)
  941. let s:relative_path = get(g:, 'startify_relative_path') ? ':~:.' : ':p:~'
  942. let s:tf = exists('g:startify_transformations')
  943. let s:session_dir = startify#get_session_path()
  944. let s:skiplist = get(g:, 'startify_skiplist', [
  945. \ 'runtime/doc/.*\.txt',
  946. \ 'bundle/.*/doc/.*\.txt',
  947. \ 'plugged/.*/doc/.*\.txt',
  948. \ '/.git/',
  949. \ 'fugitiveblame$',
  950. \ escape(fnamemodify(resolve($VIMRUNTIME), ':p'), '\') .'doc/.*\.txt',
  951. \ ])
  952. let s:padding_left = repeat(' ', get(g:, 'startify_padding_left', 3))
  953. let s:fixed_column = len(s:padding_left) + 2
  954. let s:batchmode = ''