startify.vim 29 KB

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