startify.vim 29 KB

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