bufexplorer.vim 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. "============================================================================
  2. " Copyright: Copyright (c) 2001-2025, Jeff Lanzarotta
  3. " All rights reserved.
  4. "
  5. " Redistribution and use in source and binary forms, with or
  6. " without modification, are permitted provided that the
  7. " following conditions are met:
  8. "
  9. " * Redistributions of source code must retain the above
  10. " copyright notice, this list of conditions and the following
  11. " disclaimer.
  12. "
  13. " * Redistributions in binary form must reproduce the above
  14. " copyright notice, this list of conditions and the following
  15. " disclaimer in the documentation and/or other materials
  16. " provided with the distribution.
  17. "
  18. " * Neither the name of the {organization} nor the names of its
  19. " contributors may be used to endorse or promote products
  20. " derived from this software without specific prior written
  21. " permission.
  22. "
  23. " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  24. " CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  25. " INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  26. " MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  27. " DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  28. " CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  29. " SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  30. " NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. " HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  33. " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  34. " OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  35. " EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. " Name Of File: bufexplorer.vim
  37. " Description: Buffer Explorer Vim Plugin
  38. " Maintainer: Jeff Lanzarotta (my name at gmail dot com)
  39. " Last Changed: Monday, 17 February 2025
  40. " Version: See g:bufexplorer_version for version number.
  41. " Usage: This file should reside in the plugin directory and be
  42. " automatically sourced.
  43. "
  44. " You may use the default keymappings of
  45. "
  46. " <Leader>be - Opens BufExplorer
  47. " <Leader>bt - Toggles BufExplorer open or closed
  48. " <Leader>bs - Opens horizontally split window BufExplorer
  49. " <Leader>bv - Opens vertically split window BufExplorer
  50. "
  51. " Or you can override the defaults and define your own mapping
  52. " in your vimrc file, for example:
  53. "
  54. " nnoremap <silent> <F11> :BufExplorer<CR>
  55. " nnoremap <silent> <s-F11> :ToggleBufExplorer<CR>
  56. " nnoremap <silent> <m-F11> :BufExplorerHorizontalSplit<CR>
  57. " nnoremap <silent> <c-F11> :BufExplorerVerticalSplit<CR>
  58. "
  59. " Or you can use
  60. "
  61. " ":BufExplorer" - Opens BufExplorer
  62. " ":ToggleBufExplorer" - Opens/Closes BufExplorer
  63. " ":BufExplorerHorizontalSplit" - Opens horizontally window BufExplorer
  64. " ":BufExplorerVerticalSplit" - Opens vertically split window BufExplorer
  65. "
  66. " For more help see supplied documentation.
  67. " History: See supplied documentation.
  68. "=============================================================================
  69. " Exit quickly if already running or when 'compatible' is set. {{{1
  70. if exists("g:bufexplorer_version") || &cp
  71. finish
  72. endif
  73. "1}}}
  74. " Version number
  75. let g:bufexplorer_version = "7.6.0"
  76. " Plugin Code {{{1
  77. " Check for Vim version {{{2
  78. if !exists("g:bufExplorerVersionWarn")
  79. let g:bufExplorerVersionWarn = 1
  80. endif
  81. if v:version < 700
  82. if g:bufExplorerVersionWarn
  83. echohl WarningMsg
  84. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.0 or greater."
  85. echohl None
  86. endif
  87. finish
  88. endif
  89. " Check to see if the version of Vim has the correct patch applied, if not, do
  90. " not used <nowait>.
  91. if v:version > 703 || v:version == 703 && has('patch1261') && has('patch1264')
  92. " We are good to go.
  93. else
  94. if g:bufExplorerVersionWarn
  95. echohl WarningMsg
  96. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.3 or greater with patch1261 and patch1264."
  97. echohl None
  98. endif
  99. finish
  100. endif
  101. " Create commands {{{2
  102. command! BufExplorer :call BufExplorer()
  103. command! ToggleBufExplorer :call ToggleBufExplorer()
  104. command! BufExplorerHorizontalSplit :call BufExplorerHorizontalSplit()
  105. command! BufExplorerVerticalSplit :call BufExplorerVerticalSplit()
  106. " Set {{{2
  107. function! s:Set(var, default)
  108. if !exists(a:var)
  109. if type(a:default)
  110. execute "let" a:var "=" string(a:default)
  111. else
  112. execute "let" a:var "=" a:default
  113. endif
  114. return 1
  115. endif
  116. return 0
  117. endfunction
  118. " Script variables {{{2
  119. let s:MRU_Exclude_List = ["[BufExplorer]","__MRU_Files__","[Buf\ List]"]
  120. let s:MRUList = []
  121. let s:name = '[BufExplorer]'
  122. let s:originBuffer = 0
  123. let s:running = 0
  124. let s:sort_by = ["number", "name", "fullpath", "mru", "extension"]
  125. let s:splitMode = ""
  126. let s:didSplit = 0
  127. let s:types = ["fullname", "homename", "path", "relativename", "relativepath", "shortname"]
  128. " Setup the autocommands that handle the MRUList and other stuff. {{{2
  129. autocmd VimEnter * call s:Setup()
  130. " Reset MRUList and buffer->tab associations after loading a session. {{{2
  131. autocmd SessionLoadPost * call s:Reset()
  132. " Setup {{{2
  133. function! s:Setup()
  134. call s:Reset()
  135. " Now that the MRUList is created, add the other autocmds.
  136. augroup BufExplorer
  137. autocmd!
  138. autocmd BufEnter,BufNew * call s:ActivateBuffer()
  139. autocmd BufWipeOut * call s:DeactivateBuffer(1)
  140. autocmd BufDelete * call s:DeactivateBuffer(0)
  141. autocmd BufWinEnter \[BufExplorer\] call s:Initialize()
  142. autocmd BufWinLeave \[BufExplorer\] call s:Cleanup()
  143. augroup END
  144. endfunction
  145. " Reset {{{2
  146. function! s:Reset()
  147. " Build initial MRUList. This makes sure all the files specified on the
  148. " command line are picked up correctly. Check buffers exist so this also
  149. " works after wiping buffers and loading a session (e.g. sessionman.vim)
  150. let s:MRUList = filter(range(1, bufnr('$')), 'bufexists(v:val)')
  151. " Initialize the association of buffers to tabs for any buffers
  152. " that have been created prior to now, e.g., files specified as
  153. " vim command line arguments
  154. call s:CatalogBuffers()
  155. endfunction
  156. " CatalogBuffers {{{2
  157. " Create tab associations for any existing buffers
  158. function! s:CatalogBuffers()
  159. let ct = tabpagenr()
  160. for tab in range(1, tabpagenr('$'))
  161. silent execute 'normal! ' . tab . 'gt'
  162. for buf in tabpagebuflist()
  163. call s:UpdateTabBufData(buf)
  164. endfor
  165. endfor
  166. silent execute 'normal! ' . ct . 'gt'
  167. endfunction
  168. " AssociatedTab {{{2
  169. " Return the number of the tab associated with the specified buffer. If the
  170. " buffer is associated with more than one tab, the first one found is
  171. " returned. If the buffer is not associated with any tabs, -1 is returned.
  172. function! s:AssociatedTab(bufnr)
  173. for tab in range(1, tabpagenr('$'))
  174. let list = gettabvar(tab, 'bufexp_buf_list', [])
  175. let idx = index(list, a:bufnr)
  176. if idx != -1
  177. return tab
  178. endif
  179. endfor
  180. return -1
  181. endfunction
  182. " RemoveBufFromOtherTabs {{{2
  183. " Remove the specified buffer from the buffer lists of all tabs except the
  184. " current tab.
  185. function! s:RemoveBufFromOtherTabs(bufnr)
  186. for tab in range(1, tabpagenr('$'))
  187. if tab == tabpagenr()
  188. continue
  189. endif
  190. let list = gettabvar(tab, 'bufexp_buf_list', [])
  191. let idx = index(list, a:bufnr)
  192. if idx == -1
  193. continue
  194. endif
  195. call remove(list, idx)
  196. call settabvar(tab, 'bufexp_buf_list', list)
  197. endfor
  198. endfunction
  199. " AddBufToCurrentTab {{{2
  200. " Add the specified buffer to the list of buffers associated with the current
  201. " tab.
  202. function! s:AddBufToCurrentTab(bufnr)
  203. if index(t:bufexp_buf_list, a:bufnr) == -1
  204. call add(t:bufexp_buf_list, a:bufnr)
  205. endif
  206. endfunction
  207. " IsInCurrentTab {{{2
  208. " Returns whether the specified buffer is associated with the current tab.
  209. function! s:IsInCurrentTab(bufnr)
  210. " It shouldn't happen that the list of buffers is not defined but if it
  211. " does, play it safe and include the buffer.
  212. if !exists('t:bufexp_buf_list')
  213. return 1
  214. endif
  215. return (index(t:bufexp_buf_list, a:bufnr) != -1)
  216. endfunction
  217. " UpdateTabBufData {{{2
  218. " Update the tab buffer data for the specified buffer.
  219. "
  220. " The current tab's list is updated. If a buffer is only allowed to be
  221. " associated with one tab, it is removed from the lists of any other tabs
  222. " with which it may have been associated.
  223. "
  224. " The associations between tabs and buffers are maintained in separate lists
  225. " for each tab, which are stored in tab-specific variables
  226. " 't:bufexp_buf_list'.
  227. function! s:UpdateTabBufData(bufnr)
  228. " The first time we add a tab, Vim uses the current buffer as its starting
  229. " page even though we are about to edit a new page, and another BufEnter
  230. " for the new page is triggered later. Use this first BufEnter to
  231. " initialize the list of buffers, but don't add the buffer number to the
  232. " list if it is already associated with another tab.
  233. "
  234. " Unfortunately, this doesn't work right when the first buffer opened in
  235. " the tab should be associated with it, such as when 'tab split +buffer N'
  236. " is used.
  237. if !exists("t:bufexp_buf_list")
  238. let t:bufexp_buf_list = []
  239. if s:AssociatedTab(a:bufnr) != -1
  240. return
  241. endif
  242. endif
  243. call s:AddBufToCurrentTab(a:bufnr)
  244. if g:bufExplorerOnlyOneTab
  245. call s:RemoveBufFromOtherTabs(a:bufnr)
  246. endif
  247. endfunction
  248. " ActivateBuffer {{{2
  249. function! s:ActivateBuffer()
  250. let _bufnr = bufnr("%")
  251. call s:UpdateTabBufData(_bufnr)
  252. call s:MRUPush(_bufnr)
  253. endfunction
  254. " DeactivateBuffer {{{2
  255. function! s:DeactivateBuffer(remove)
  256. let _bufnr = str2nr(expand("<abuf>"))
  257. call s:MRUPop(_bufnr)
  258. endfunction
  259. " MRUPop {{{2
  260. function! s:MRUPop(bufnr)
  261. call filter(s:MRUList, 'v:val != '.a:bufnr)
  262. endfunction
  263. " MRUPush {{{2
  264. function! s:MRUPush(buf)
  265. " Skip temporary buffer with buftype set. Don't add the BufExplorer window
  266. " to the list.
  267. if s:ShouldIgnore(a:buf) == 1
  268. return
  269. endif
  270. " Remove the buffer number from the list if it already exists.
  271. call s:MRUPop(a:buf)
  272. " Add the buffer number to the head of the list.
  273. call insert(s:MRUList, a:buf)
  274. endfunction
  275. " ShouldIgnore {{{2
  276. function! s:ShouldIgnore(buf)
  277. " Ignore temporary buffers with buftype set.
  278. if empty(getbufvar(a:buf, "&buftype")) == 0
  279. return 1
  280. endif
  281. " Ignore buffers with no name.
  282. if empty(bufname(a:buf)) == 1
  283. return 1
  284. endif
  285. " Ignore the BufExplorer buffer.
  286. if fnamemodify(bufname(a:buf), ":t") == s:name
  287. return 1
  288. endif
  289. " Ignore any buffers in the exclude list.
  290. if index(s:MRU_Exclude_List, bufname(a:buf)) >= 0
  291. return 1
  292. endif
  293. " Else return 0 to indicate that the buffer was not ignored.
  294. return 0
  295. endfunction
  296. " Initialize {{{2
  297. function! s:Initialize()
  298. call s:SetLocalSettings()
  299. let s:running = 1
  300. endfunction
  301. " Cleanup {{{2
  302. function! s:Cleanup()
  303. if exists("s:_insertmode")
  304. let &insertmode = s:_insertmode
  305. endif
  306. if exists("s:_showcmd")
  307. let &showcmd = s:_showcmd
  308. endif
  309. if exists("s:_cpo")
  310. let &cpo = s:_cpo
  311. endif
  312. if exists("s:_report")
  313. let &report = s:_report
  314. endif
  315. let s:running = 0
  316. let s:splitMode = ""
  317. let s:didSplit = 0
  318. delmarks!
  319. endfunction
  320. " SetLocalSettings {{{2
  321. function! s:SetLocalSettings()
  322. let s:_insertmode = &insertmode
  323. set noinsertmode
  324. let s:_showcmd = &showcmd
  325. set noshowcmd
  326. let s:_cpo = &cpo
  327. set cpo&vim
  328. let s:_report = &report
  329. let &report = 10000
  330. setlocal nonumber
  331. setlocal foldcolumn=0
  332. setlocal nofoldenable
  333. setlocal cursorline
  334. setlocal nospell
  335. setlocal nobuflisted
  336. setlocal filetype=bufexplorer
  337. endfunction
  338. " BufExplorerHorizontalSplit {{{2
  339. function! BufExplorerHorizontalSplit()
  340. let s:splitMode = "sp"
  341. execute "BufExplorer"
  342. let s:splitMode = ""
  343. endfunction
  344. " BufExplorerVerticalSplit {{{2
  345. function! BufExplorerVerticalSplit()
  346. let s:splitMode = "vsp"
  347. execute "BufExplorer"
  348. let s:splitMode = ""
  349. endfunction
  350. " ToggleBufExplorer {{{2
  351. function! ToggleBufExplorer()
  352. if exists("s:running") && s:running == 1 && bufname(winbufnr(0)) == s:name
  353. call s:Close()
  354. else
  355. call BufExplorer()
  356. endif
  357. endfunction
  358. " BufExplorer {{{2
  359. function! BufExplorer()
  360. let name = s:name
  361. if !has("win32")
  362. " On non-Windows boxes, escape the name so that is shows up correctly.
  363. let name = escape(name, "[]")
  364. endif
  365. " Make sure there is only one explorer open at a time.
  366. if s:running == 1
  367. " Go to the open buffer.
  368. if has("gui")
  369. execute "drop" name
  370. endif
  371. return
  372. endif
  373. " Add zero to ensure the variable is treated as a number.
  374. let s:originBuffer = bufnr("%") + 0
  375. silent let s:raw_buffer_listing = s:GetBufferInfo(0)
  376. " We may have to split the current window.
  377. if s:splitMode != ""
  378. " Save off the original settings.
  379. let [_splitbelow, _splitright] = [&splitbelow, &splitright]
  380. " Set the setting to ours.
  381. let [&splitbelow, &splitright] = [g:bufExplorerSplitBelow, g:bufExplorerSplitRight]
  382. let _size = (s:splitMode == "sp") ? g:bufExplorerSplitHorzSize : g:bufExplorerSplitVertSize
  383. " Split the window either horizontally or vertically.
  384. if _size <= 0
  385. execute 'keepalt ' . s:splitMode
  386. else
  387. execute 'keepalt ' . _size . s:splitMode
  388. endif
  389. " Restore the original settings.
  390. let [&splitbelow, &splitright] = [_splitbelow, _splitright]
  391. " Remember that a split was triggered
  392. let s:didSplit = 1
  393. endif
  394. if !exists("b:displayMode") || b:displayMode != "winmanager"
  395. " Do not use keepalt when opening bufexplorer to allow the buffer that
  396. " we are leaving to become the new alternate buffer
  397. execute "silent keepjumps hide edit".name
  398. endif
  399. call s:DisplayBufferList()
  400. " Position the cursor in the newly displayed list on the line representing
  401. " the active buffer. The active buffer is the line with the '%' character
  402. " in it.
  403. execute search("%")
  404. endfunction
  405. " DisplayBufferList {{{2
  406. function! s:DisplayBufferList()
  407. setlocal buftype=nofile
  408. setlocal modifiable
  409. setlocal noreadonly
  410. setlocal noswapfile
  411. setlocal nowrap
  412. setlocal bufhidden=wipe
  413. call s:SetupSyntax()
  414. call s:MapKeys()
  415. " Wipe out any existing lines in case BufExplorer buffer exists and the
  416. " user had changed any global settings that might reduce the number of
  417. " lines needed in the buffer.
  418. silent keepjumps 1,$d _
  419. call setline(1, s:CreateHelp())
  420. call s:BuildBufferList()
  421. call cursor(s:firstBufferLine, 1)
  422. if !g:bufExplorerResize
  423. normal! zz
  424. endif
  425. setlocal nomodifiable
  426. endfunction
  427. " MapKeys {{{2
  428. function! s:MapKeys()
  429. if exists("b:displayMode") && b:displayMode == "winmanager"
  430. nnoremap <buffer> <silent> <tab> :call <SID>SelectBuffer()<CR>
  431. endif
  432. nnoremap <script> <silent> <nowait> <buffer> <2-leftmouse> :call <SID>SelectBuffer()<CR>
  433. nnoremap <script> <silent> <nowait> <buffer> <CR> :call <SID>SelectBuffer()<CR>
  434. nnoremap <script> <silent> <nowait> <buffer> <F1> :call <SID>ToggleHelp()<CR>
  435. nnoremap <script> <silent> <nowait> <buffer> <s-cr> :call <SID>SelectBuffer("tab")<CR>
  436. nnoremap <script> <silent> <nowait> <buffer> a :call <SID>ToggleFindActive()<CR>
  437. nnoremap <script> <silent> <nowait> <buffer> b :call <SID>SelectBuffer("ask")<CR>
  438. nnoremap <script> <silent> <nowait> <buffer> B :call <SID>ToggleOnlyOneTab()<CR>
  439. nnoremap <script> <silent> <nowait> <buffer> d :call <SID>RemoveBuffer("delete")<CR>
  440. xnoremap <script> <silent> <nowait> <buffer> d :call <SID>RemoveBuffer("delete")<CR>
  441. nnoremap <script> <silent> <nowait> <buffer> D :call <SID>RemoveBuffer("wipe")<CR>
  442. xnoremap <script> <silent> <nowait> <buffer> D :call <SID>RemoveBuffer("wipe")<CR>
  443. nnoremap <script> <silent> <nowait> <buffer> f :call <SID>SelectBuffer("split", "sb")<CR>
  444. nnoremap <script> <silent> <nowait> <buffer> F :call <SID>SelectBuffer("split", "st")<CR>
  445. nnoremap <script> <silent> <nowait> <buffer> m :call <SID>MRUListShow()<CR>
  446. nnoremap <script> <silent> <nowait> <buffer> o :call <SID>SelectBuffer()<CR>
  447. nnoremap <script> <silent> <nowait> <buffer> p :call <SID>ToggleSplitOutPathName()<CR>
  448. nnoremap <script> <silent> <nowait> <buffer> q :call <SID>Close()<CR>
  449. nnoremap <script> <silent> <nowait> <buffer> r :call <SID>SortReverse()<CR>
  450. nnoremap <script> <silent> <nowait> <buffer> R :call <SID>ToggleShowRelativePath()<CR>
  451. nnoremap <script> <silent> <nowait> <buffer> s :call <SID>SortSelect()<CR>
  452. nnoremap <script> <silent> <nowait> <buffer> S :call <SID>ReverseSortSelect()<CR>
  453. nnoremap <script> <silent> <nowait> <buffer> t :call <SID>SelectBuffer("tab")<CR>
  454. nnoremap <script> <silent> <nowait> <buffer> T :call <SID>ToggleShowTabBuffer()<CR>
  455. nnoremap <script> <silent> <nowait> <buffer> u :call <SID>ToggleShowUnlisted()<CR>
  456. nnoremap <script> <silent> <nowait> <buffer> v :call <SID>SelectBuffer("split", "vr")<CR>
  457. nnoremap <script> <silent> <nowait> <buffer> V :call <SID>SelectBuffer("split", "vl")<CR>
  458. nnoremap <script> <silent> <nowait> <buffer> H :call <SID>ToggleShowTerminal()<CR>
  459. for k in ["G", "n", "N", "L", "M", "H"]
  460. execute "nnoremap <buffer> <silent>" k ":keepjumps normal!" k."<CR>"
  461. endfor
  462. endfunction
  463. " SetupSyntax {{{2
  464. function! s:SetupSyntax()
  465. if has("syntax")
  466. syn match bufExplorerHelp "^\".*" contains=bufExplorerSortBy,bufExplorerMapping,bufExplorerTitle,bufExplorerSortType,bufExplorerToggleSplit,bufExplorerToggleOpen
  467. syn match bufExplorerOpenIn "Open in \w\+ window" contained
  468. syn match bufExplorerSplit "\w\+ split" contained
  469. syn match bufExplorerSortBy "Sorted by .*" contained contains=bufExplorerOpenIn,bufExplorerSplit
  470. syn match bufExplorerMapping "\" \zs.\+\ze :" contained
  471. syn match bufExplorerTitle "Buffer Explorer.*" contained
  472. syn match bufExplorerSortType "'\w\{-}'" contained
  473. syn match bufExplorerBufNbr /^\s*\d\+/
  474. syn match bufExplorerToggleSplit "toggle split type" contained
  475. syn match bufExplorerToggleOpen "toggle open mode" contained
  476. syn match bufExplorerModBuf /^\s*\d\+.\{4}+.*/
  477. syn match bufExplorerLockedBuf /^\s*\d\+.\{3}[\-=].*/
  478. syn match bufExplorerHidBuf /^\s*\d\+.\{2}h.*/
  479. syn match bufExplorerActBuf /^\s*\d\+.\{2}a.*/
  480. syn match bufExplorerCurBuf /^\s*\d\+.%.*/
  481. syn match bufExplorerAltBuf /^\s*\d\+.#.*/
  482. syn match bufExplorerUnlBuf /^\s*\d\+u.*/
  483. syn match bufExplorerInactBuf /^\s*\d\+ \{7}.*/
  484. hi def link bufExplorerBufNbr Number
  485. hi def link bufExplorerMapping NonText
  486. hi def link bufExplorerHelp Special
  487. hi def link bufExplorerOpenIn Identifier
  488. hi def link bufExplorerSortBy String
  489. hi def link bufExplorerSplit NonText
  490. hi def link bufExplorerTitle NonText
  491. hi def link bufExplorerSortType bufExplorerSortBy
  492. hi def link bufExplorerToggleSplit bufExplorerSplit
  493. hi def link bufExplorerToggleOpen bufExplorerOpenIn
  494. hi def link bufExplorerActBuf Identifier
  495. hi def link bufExplorerAltBuf String
  496. hi def link bufExplorerCurBuf Type
  497. hi def link bufExplorerHidBuf Constant
  498. hi def link bufExplorerLockedBuf Special
  499. hi def link bufExplorerModBuf Exception
  500. hi def link bufExplorerUnlBuf Comment
  501. hi def link bufExplorerInactBuf Comment
  502. endif
  503. endfunction
  504. " ToggleHelp {{{2
  505. function! s:ToggleHelp()
  506. let g:bufExplorerDetailedHelp = !g:bufExplorerDetailedHelp
  507. setlocal modifiable
  508. " Save position.
  509. normal! ma
  510. " Remove old header.
  511. if s:firstBufferLine > 1
  512. execute "keepjumps 1,".(s:firstBufferLine - 1) "d _"
  513. endif
  514. call append(0, s:CreateHelp())
  515. silent! normal! g`a
  516. delmarks a
  517. setlocal nomodifiable
  518. if exists("b:displayMode") && b:displayMode == "winmanager"
  519. call WinManagerForceReSize("BufExplorer")
  520. endif
  521. endfunction
  522. " GetHelpStatus {{{2
  523. function! s:GetHelpStatus()
  524. let ret = '" Sorted by '.((g:bufExplorerReverseSort == 1) ? "reverse " : "").g:bufExplorerSortBy
  525. let ret .= ' | '.((g:bufExplorerFindActive == 0) ? "Don't " : "")."Locate buffer"
  526. let ret .= ((g:bufExplorerShowUnlisted == 0) ? "" : " | Show unlisted")
  527. let ret .= ((g:bufExplorerShowTabBuffer == 0) ? "" : " | Show buffers/tab")
  528. let ret .= ((g:bufExplorerOnlyOneTab == 0) ? "" : " | One tab/buffer")
  529. let ret .= ' | '.((g:bufExplorerShowRelativePath == 0) ? "Absolute" : "Relative")
  530. let ret .= ' '.((g:bufExplorerSplitOutPathName == 0) ? "Full" : "Split")." path"
  531. let ret .= ((g:bufExplorerShowTerminal == 0) ? "" : " | Show terminal")
  532. return ret
  533. endfunction
  534. " CreateHelp {{{2
  535. function! s:CreateHelp()
  536. if g:bufExplorerDefaultHelp == 0 && g:bufExplorerDetailedHelp == 0
  537. let s:firstBufferLine = 1
  538. return []
  539. endif
  540. let header = []
  541. if g:bufExplorerDetailedHelp == 1
  542. call add(header, '" Buffer Explorer ('.g:bufexplorer_version.')')
  543. call add(header, '" --------------------------')
  544. call add(header, '" <F1> : toggle this help')
  545. call add(header, '" <enter> or o or Mouse-Double-Click : open buffer under cursor')
  546. call add(header, '" <shift-enter> or t : open buffer in another tab')
  547. call add(header, '" a : toggle find active buffer')
  548. call add(header, '" b : Fast buffer switching with b<any bufnum>')
  549. call add(header, '" B : toggle if to save/use recent tab or not')
  550. call add(header, '" d : delete buffer')
  551. call add(header, '" D : wipe buffer')
  552. call add(header, '" F : open buffer in another window above the current')
  553. call add(header, '" f : open buffer in another window below the current')
  554. call add(header, '" p : toggle splitting of file and path name')
  555. call add(header, '" q : quit')
  556. call add(header, '" r : reverse sort')
  557. call add(header, '" R : toggle showing relative or full paths')
  558. call add(header, '" s : cycle thru "sort by" fields '.string(s:sort_by).'')
  559. call add(header, '" S : reverse cycle thru "sort by" fields')
  560. call add(header, '" T : toggle if to show only buffers for this tab or not')
  561. call add(header, '" u : toggle showing unlisted buffers')
  562. call add(header, '" V : open buffer in another window on the left of the current')
  563. call add(header, '" v : open buffer in another window on the right of the current')
  564. else
  565. call add(header, '" Press <F1> for Help')
  566. endif
  567. if (!exists("b:displayMode") || b:displayMode != "winmanager") || (b:displayMode == "winmanager" && g:bufExplorerDetailedHelp == 1)
  568. call add(header, s:GetHelpStatus())
  569. call add(header, '"=')
  570. endif
  571. let s:firstBufferLine = len(header) + 1
  572. return header
  573. endfunction
  574. " CalculateBufferDetails {{{2
  575. " Calculate `buf`-related details.
  576. function! s:CalculateBufferDetails(buf)
  577. let buf = a:buf
  578. let name = bufname(buf._bufnr)
  579. let buf["hasNoName"] = empty(name)
  580. if buf.hasNoName
  581. let name = "[No Name]"
  582. endif
  583. let buf.isterminal = getbufvar(buf._bufnr, '&buftype') == 'terminal'
  584. if buf.isterminal
  585. let buf.fullname = name
  586. let buf.isdir = 0
  587. else
  588. let buf.fullname = simplify(fnamemodify(name, ':p'))
  589. let buf.isdir = getftype(buf.fullname) == "dir"
  590. endif
  591. if buf.isdir
  592. " `buf.fullname` ends with a path separator; this will be
  593. " removed via the first `:h` applied to `buf.fullname` (except
  594. " for the root directory, where the path separator will remain).
  595. let parent = fnamemodify(buf.fullname, ':h:h')
  596. let buf.shortname = fnamemodify(buf.fullname, ':h:t')
  597. " Special case for root directory: fnamemodify('/', ':h:t') == ''
  598. if buf.shortname == ''
  599. let buf.shortname = '.'
  600. endif
  601. " Must perform shortening (`:~`, `:.`) before `:h`.
  602. let buf.homename = fnamemodify(buf.fullname, ':~:h')
  603. let buf.relativename = fnamemodify(buf.fullname, ':~:.:h')
  604. else
  605. let parent = fnamemodify(buf.fullname, ':h')
  606. let buf.shortname = fnamemodify(buf.fullname, ':t')
  607. let buf.homename = fnamemodify(buf.fullname, ':~')
  608. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  609. endif
  610. " `:p` on `parent` adds back the path separator which permits more
  611. " effective shortening (`:~`, `:.`), but `:h` is required afterward
  612. " to trim this separator.
  613. let buf.path = fnamemodify(parent, ':p:~:h')
  614. let buf.relativepath = fnamemodify(parent, ':p:~:.:h')
  615. endfunction
  616. " GetBufferInfo {{{2
  617. function! s:GetBufferInfo(bufnr)
  618. redir => bufoutput
  619. " Show all buffers including the unlisted ones. [!] tells Vim to show the
  620. " unlisted ones.
  621. buffers!
  622. redir END
  623. if a:bufnr > 0
  624. " Since we are only interested in this specified buffer remove the
  625. " other buffers listed.
  626. let bufoutput = substitute(bufoutput."\n", '^.*\n\(\s*'.a:bufnr.'\>.\{-}\)\n.*', '\1', '')
  627. endif
  628. let all = {}
  629. " Loop over each line in the buffer.
  630. for line in split(bufoutput, '\n')
  631. let bits = split(line, '"')
  632. " Use first and last components after the split on '"', in case a
  633. " filename with an embedded '"' is present.
  634. let buf = {"attributes": bits[0], "line": substitute(bits[-1], '\s*', '', '')}
  635. let buf._bufnr = str2nr(buf.attributes)
  636. let all[buf._bufnr] = buf
  637. endfor
  638. return all
  639. endfunction
  640. " BuildBufferList {{{2
  641. function! s:BuildBufferList()
  642. let table = []
  643. " Loop through every buffer.
  644. for buf in values(s:raw_buffer_listing)
  645. " `buf.attributes` must exist, but we defer the expensive work of
  646. " calculating other buffer details (e.g., `buf.fullname`) until we know
  647. " the user wants to view this buffer.
  648. " Skip unlisted buffers if we are not to show them.
  649. if !g:bufExplorerShowUnlisted && buf.attributes =~ "u"
  650. " Skip unlisted buffers if we are not to show them.
  651. continue
  652. endif
  653. " Ensure buffer details are computed for this buffer.
  654. if !has_key(buf, 'fullname')
  655. call s:CalculateBufferDetails(buf)
  656. endif
  657. " Skip 'No Name' buffers if we are not to show them.
  658. if g:bufExplorerShowNoName == 0 && buf.hasNoName
  659. continue
  660. endif
  661. " Are we to show only buffer(s) for this tab?
  662. if g:bufExplorerShowTabBuffer && (!s:IsInCurrentTab(str2nr(buf.attributes)))
  663. continue
  664. endif
  665. " Skip terminal buffers if we are not to show them.
  666. if !g:bufExplorerShowTerminal && buf.isterminal
  667. continue
  668. endif
  669. " Skip directory buffers if we are not to show them.
  670. if !g:bufExplorerShowDirectories && buf.isdir
  671. continue
  672. endif
  673. let row = [buf.attributes]
  674. if exists("g:loaded_webdevicons")
  675. let row += [WebDevIconsGetFileTypeSymbol(buf.fullname, buf.isdir)]
  676. endif
  677. " Are we to split the path and file name?
  678. if g:bufExplorerSplitOutPathName
  679. let type = (g:bufExplorerShowRelativePath) ? "relativepath" : "path"
  680. let row += [buf.shortname, buf[type]]
  681. else
  682. let type = (g:bufExplorerShowRelativePath) ? "relativename" : "homename"
  683. let row += [buf[type]]
  684. endif
  685. let row += [buf.line]
  686. call add(table, row)
  687. endfor
  688. let lines = s:MakeLines(table)
  689. call setline(s:firstBufferLine, lines)
  690. call s:SortListing()
  691. endfunction
  692. " MakeLines {{{2
  693. function! s:MakeLines(table)
  694. if len(a:table) == 0
  695. return []
  696. endif
  697. let lines = []
  698. " To avoid trailing whitespace, do not pad the final column.
  699. let numColumnsToPad = len(a:table[0]) - 1
  700. let maxWidths = repeat([0], numColumnsToPad)
  701. for row in a:table
  702. let i = 0
  703. while i < numColumnsToPad
  704. let maxWidths[i] = max([maxWidths[i], s:StringWidth(row[i])])
  705. let i = i + 1
  706. endwhile
  707. endfor
  708. let pads = []
  709. for w in maxWidths
  710. call add(pads, repeat(' ', w))
  711. endfor
  712. for row in a:table
  713. let i = 0
  714. while i < numColumnsToPad
  715. let row[i] .= strpart(pads[i], s:StringWidth(row[i]))
  716. let i = i + 1
  717. endwhile
  718. call add(lines, join(row, ' '))
  719. endfor
  720. return lines
  721. endfunction
  722. " SelectBuffer {{{2
  723. function! s:SelectBuffer(...)
  724. " Sometimes messages are not cleared when we get here so it looks like an
  725. " error has occurred when it really has not.
  726. "echo ""
  727. let _bufNbr = -1
  728. if (a:0 == 1) && (a:1 == "ask")
  729. " Ask the user for input.
  730. call inputsave()
  731. let cmd = input("Enter buffer number to switch to: ")
  732. call inputrestore()
  733. " Clear the message area from the previous prompt.
  734. redraw | echo
  735. if strlen(cmd) > 0
  736. let _bufNbr = str2nr(cmd)
  737. else
  738. call s:Error("Invalid buffer number, try again.")
  739. return
  740. endif
  741. else
  742. " Are we on a line with a file name?
  743. if line('.') < s:firstBufferLine
  744. execute "normal! \<CR>"
  745. return
  746. endif
  747. let _bufNbr = str2nr(getline('.'))
  748. " Check and see if we are running BufferExplorer via WinManager.
  749. if exists("b:displayMode") && b:displayMode == "winmanager"
  750. let _bufName = expand("#"._bufNbr.":p")
  751. if (a:0 == 1) && (a:1 == "tab")
  752. call WinManagerFileEdit(_bufName, 1)
  753. else
  754. call WinManagerFileEdit(_bufName, 0)
  755. endif
  756. return
  757. endif
  758. endif
  759. if bufexists(_bufNbr)
  760. " Get the tab number where this buffer is located in.
  761. let tabNbr = s:GetTabNbr(_bufNbr)
  762. if exists("g:bufExplorerChgWin") && g:bufExplorerChgWin <=winnr("$")
  763. execute g:bufExplorerChgWin."wincmd w"
  764. execute "keepjumps keepalt silent b!" _bufNbr
  765. " Are we supposed to open the selected buffer in a tab?
  766. elseif (a:0 == 1) && (a:1 == "tab")
  767. call s:Close()
  768. " Open a new tab with the selected buffer in it.
  769. if v:version > 704 || ( v:version == 704 && has('patch2237') )
  770. " new syntax for last tab as of 7.4.2237
  771. execute "$tab split +buffer" . _bufNbr
  772. else
  773. execute "999tab split +buffer" . _bufNbr
  774. endif
  775. " Workaround for the issue mentioned in UpdateTabBufData.
  776. call s:UpdateTabBufData(_bufNbr)
  777. " Are we supposed to open the selected buffer in a split?
  778. elseif (a:0 == 2) && (a:1 == "split")
  779. call s:Close()
  780. if (a:2 == "vl")
  781. execute "vert topleft sb "._bufNbr
  782. elseif (a:2 == "vr")
  783. execute "vert belowright sb "._bufNbr
  784. elseif (a:2 == "st")
  785. execute "topleft sb "._bufNbr
  786. else " = sb
  787. execute "belowright sb "._bufNbr
  788. endif
  789. else
  790. " Request to open in current (BufExplorer) window.
  791. if g:bufExplorerFindActive && tabNbr > 0
  792. " Close BufExplorer window and switch to existing tab/window.
  793. call s:Close()
  794. execute tabNbr . "tabnext"
  795. execute bufwinnr(_bufNbr) . "wincmd w"
  796. else
  797. " Use BufExplorer window for the buffer.
  798. execute "keepjumps keepalt silent b!" _bufNbr
  799. endif
  800. endif
  801. " Make the buffer 'listed' again.
  802. call setbufvar(_bufNbr, "&buflisted", "1")
  803. " Call any associated function references. g:bufExplorerFuncRef may be
  804. " an individual function reference or it may be a list containing
  805. " function references. It will ignore anything that's not a function
  806. " reference.
  807. "
  808. " See :help FuncRef for more on function references.
  809. if exists("g:BufExplorerFuncRef")
  810. if type(g:BufExplorerFuncRef) == 2
  811. keepj call g:BufExplorerFuncRef()
  812. elseif type(g:BufExplorerFuncRef) == 3
  813. for FncRef in g:BufExplorerFuncRef
  814. if type(FncRef) == 2
  815. keepj call FncRef()
  816. endif
  817. endfor
  818. endif
  819. endif
  820. else
  821. call s:Error("Sorry, that buffer no longer exists, please select another")
  822. call s:DeleteBuffer(_bufNbr, "wipe")
  823. endif
  824. endfunction
  825. " RemoveBuffer {{{2
  826. function! s:RemoveBuffer(mode)
  827. " Are we on a line with a file name?
  828. if line('.') < s:firstBufferLine
  829. return
  830. endif
  831. let mode = a:mode
  832. " These commands are to temporarily suspend the activity of winmanager.
  833. if exists("b:displayMode") && b:displayMode == "winmanager"
  834. call WinManagerSuspendAUs()
  835. end
  836. let _bufNbr = str2nr(getline('.'))
  837. if getbufvar(_bufNbr, '&modified') == 1
  838. " Calling confirm() requires Vim built with dialog option.
  839. if !has("dialog_con") && !has("dialog_gui")
  840. call s:Error("Sorry, no write since last change for buffer "._bufNbr.", unable to delete")
  841. return
  842. endif
  843. let answer = confirm('No write since last change for buffer '._bufNbr.'. Delete anyway?', "&Yes\n&No", 2)
  844. if a:mode == "delete" && answer == 1
  845. let mode = "force_delete"
  846. elseif a:mode == "wipe" && answer == 1
  847. let mode = "force_wipe"
  848. else
  849. return
  850. endif
  851. endif
  852. " Okay, everything is good, delete or wipe the buffer.
  853. call s:DeleteBuffer(_bufNbr, mode)
  854. " Reactivate winmanager autocommand activity.
  855. if exists("b:displayMode") && b:displayMode == "winmanager"
  856. call WinManagerForceReSize("BufExplorer")
  857. call WinManagerResumeAUs()
  858. end
  859. endfunction
  860. " DeleteBuffer {{{2
  861. function! s:DeleteBuffer(buf, mode)
  862. " This routine assumes that the buffer to be removed is on the current line.
  863. try
  864. " Wipe/Delete buffer from Vim.
  865. if a:mode == "wipe"
  866. execute "silent bwipe" a:buf
  867. elseif a:mode == "force_wipe"
  868. execute "silent bwipe!" a:buf
  869. elseif a:mode == "force_delete"
  870. execute "silent bdelete!" a:buf
  871. else
  872. execute "silent bdelete" a:buf
  873. endif
  874. " Delete the buffer from the list on screen.
  875. setlocal modifiable
  876. normal! "_dd
  877. setlocal nomodifiable
  878. " Delete the buffer from the raw buffer list.
  879. unlet s:raw_buffer_listing[a:buf]
  880. catch
  881. call s:Error(v:exception)
  882. endtry
  883. endfunction
  884. " ListedAndCurrentTab {{{2
  885. " Returns whether the specified buffer is both listed and associated with the
  886. " current tab.
  887. function! s:ListedAndCurrentTab(buf)
  888. return buflisted(a:buf) && s:IsInCurrentTab(a:buf)
  889. endfunction
  890. " Close {{{2
  891. function! s:Close()
  892. " Get only the listed buffers associated with the current tab.
  893. let listed = filter(copy(s:MRUList), "s:ListedAndCurrentTab(v:val)")
  894. if len(listed) == 0
  895. let listed = filter(range(1, bufnr('$')), "s:ListedAndCurrentTab(v:val)")
  896. endif
  897. " If we needed to split the main window, close the split one.
  898. if s:didSplit
  899. execute "wincmd c"
  900. endif
  901. " Check to see if there are anymore buffers listed.
  902. if len(listed) == 0
  903. " Since there are no buffers left to switch to, open a new empty
  904. " buffers.
  905. execute "enew"
  906. else
  907. " Since there are buffers left to switch to, switch to the previous and
  908. " then the current.
  909. for b in reverse(listed[0:1])
  910. execute "keepjumps silent b ".b
  911. endfor
  912. endif
  913. " Clear any messages.
  914. echo
  915. endfunction
  916. " ToggleShowTerminal {{{2
  917. function! s:ToggleShowTerminal()
  918. let g:bufExplorerShowTerminal = !g:bufExplorerShowTerminal
  919. call s:RebuildBufferList()
  920. call s:UpdateHelpStatus()
  921. endfunction
  922. " ToggleSplitOutPathName {{{2
  923. function! s:ToggleSplitOutPathName()
  924. let g:bufExplorerSplitOutPathName = !g:bufExplorerSplitOutPathName
  925. call s:RebuildBufferList()
  926. call s:UpdateHelpStatus()
  927. endfunction
  928. " ToggleShowRelativePath {{{2
  929. function! s:ToggleShowRelativePath()
  930. let g:bufExplorerShowRelativePath = !g:bufExplorerShowRelativePath
  931. call s:RebuildBufferList()
  932. call s:UpdateHelpStatus()
  933. endfunction
  934. " ToggleShowTabBuffer {{{2
  935. function! s:ToggleShowTabBuffer()
  936. let g:bufExplorerShowTabBuffer = !g:bufExplorerShowTabBuffer
  937. call s:RebuildBufferList(g:bufExplorerShowTabBuffer)
  938. call s:UpdateHelpStatus()
  939. endfunction
  940. " ToggleOnlyOneTab {{{2
  941. function! s:ToggleOnlyOneTab()
  942. let g:bufExplorerOnlyOneTab = !g:bufExplorerOnlyOneTab
  943. call s:RebuildBufferList()
  944. call s:UpdateHelpStatus()
  945. endfunction
  946. " ToggleShowUnlisted {{{2
  947. function! s:ToggleShowUnlisted()
  948. let g:bufExplorerShowUnlisted = !g:bufExplorerShowUnlisted
  949. let num_bufs = s:RebuildBufferList(g:bufExplorerShowUnlisted == 0)
  950. call s:UpdateHelpStatus()
  951. endfunction
  952. " ToggleFindActive {{{2
  953. function! s:ToggleFindActive()
  954. let g:bufExplorerFindActive = !g:bufExplorerFindActive
  955. call s:UpdateHelpStatus()
  956. endfunction
  957. " RebuildBufferList {{{2
  958. function! s:RebuildBufferList(...)
  959. setlocal modifiable
  960. let curPos = getpos('.')
  961. if a:0 && a:000[0] && (line('$') >= s:firstBufferLine)
  962. " Clear the list first.
  963. execute "silent keepjumps ".s:firstBufferLine.',$d _'
  964. endif
  965. let num_bufs = s:BuildBufferList()
  966. call setpos('.', curPos)
  967. setlocal nomodifiable
  968. return num_bufs
  969. endfunction
  970. " UpdateHelpStatus {{{2
  971. function! s:UpdateHelpStatus()
  972. setlocal modifiable
  973. let text = s:GetHelpStatus()
  974. call setline(s:firstBufferLine - 2, text)
  975. setlocal nomodifiable
  976. endfunction
  977. " Key_number {{{2
  978. function! s:Key_number(line)
  979. let _bufnr = str2nr(a:line)
  980. let key = [printf('%9d', _bufnr)]
  981. return key
  982. endfunction
  983. " Key_name {{{2
  984. function! s:Key_name(line)
  985. let _bufnr = str2nr(a:line)
  986. let buf = s:raw_buffer_listing[_bufnr]
  987. let key = [buf.shortname, buf.fullname]
  988. return key
  989. endfunction
  990. " Key_fullpath {{{2
  991. function! s:Key_fullpath(line)
  992. let _bufnr = str2nr(a:line)
  993. let buf = s:raw_buffer_listing[_bufnr]
  994. let key = [buf.fullname]
  995. return key
  996. endfunction
  997. " Key_extension {{{2
  998. function! s:Key_extension(line)
  999. let _bufnr = str2nr(a:line)
  1000. let buf = s:raw_buffer_listing[_bufnr]
  1001. let extension = fnamemodify(buf.shortname, ':e')
  1002. let key = [extension, buf.shortname, buf.fullname]
  1003. return key
  1004. endfunction
  1005. " Key_mru {{{2
  1006. function! s:Key_mru(line)
  1007. let _bufnr = str2nr(a:line)
  1008. let buf = s:raw_buffer_listing[_bufnr]
  1009. let pos = index(s:MRUList, _bufnr)
  1010. if pos < 0
  1011. let pos = 0
  1012. endif
  1013. return [printf('%9d', pos), buf.fullname]
  1014. endfunction
  1015. " SortByKeyFunc {{{2
  1016. function! s:SortByKeyFunc(keyFunc)
  1017. let keyedLines = []
  1018. for line in getline(s:firstBufferLine, "$")
  1019. let key = eval(a:keyFunc . '(line)')
  1020. call add(keyedLines, join(key + [line], "\1"))
  1021. endfor
  1022. " Ignore case when sorting by passing `1`:
  1023. call sort(keyedLines, 1)
  1024. if g:bufExplorerReverseSort
  1025. call reverse(keyedLines)
  1026. endif
  1027. let lines = []
  1028. for keyedLine in keyedLines
  1029. call add(lines, split(keyedLine, "\1")[-1])
  1030. endfor
  1031. call setline(s:firstBufferLine, lines)
  1032. endfunction
  1033. " SortReverse {{{2
  1034. function! s:SortReverse()
  1035. let g:bufExplorerReverseSort = !g:bufExplorerReverseSort
  1036. call s:ReSortListing()
  1037. endfunction
  1038. " SortSelect {{{2
  1039. function! s:SortSelect()
  1040. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) + 1, s:sort_by[0])
  1041. call s:ReSortListing()
  1042. endfunction
  1043. " ReverseSortSelect {{{2
  1044. function! s:ReverseSortSelect()
  1045. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) - 1, s:sort_by[-1])
  1046. call s:ReSortListing()
  1047. endfunction
  1048. " ReSortListing {{{2
  1049. function! s:ReSortListing()
  1050. setlocal modifiable
  1051. let curPos = getpos('.')
  1052. call s:SortListing()
  1053. call s:UpdateHelpStatus()
  1054. call setpos('.', curPos)
  1055. setlocal nomodifiable
  1056. endfunction
  1057. " SortListing {{{2
  1058. function! s:SortListing()
  1059. call s:SortByKeyFunc("<SID>Key_" . g:bufExplorerSortBy)
  1060. endfunction
  1061. " MRUListShow {{{2
  1062. function! s:MRUListShow()
  1063. echomsg "MRUList=".string(s:MRUList)
  1064. endfunction
  1065. " Error {{{2
  1066. " Display a message using ErrorMsg highlight group.
  1067. function! s:Error(msg)
  1068. echohl ErrorMsg
  1069. echomsg a:msg
  1070. echohl None
  1071. endfunction
  1072. " Warning {{{2
  1073. " Display a message using WarningMsg highlight group.
  1074. function! s:Warning(msg)
  1075. echohl WarningMsg
  1076. echomsg a:msg
  1077. echohl None
  1078. endfunction
  1079. " GetTabNbr {{{2
  1080. function! s:GetTabNbr(bufNbr)
  1081. " Prefer current tab.
  1082. if bufwinnr(a:bufNbr) > 0
  1083. return tabpagenr()
  1084. endif
  1085. " Searching buffer bufno, in tabs.
  1086. for i in range(tabpagenr("$"))
  1087. if index(tabpagebuflist(i + 1), a:bufNbr) != -1
  1088. return i + 1
  1089. endif
  1090. endfor
  1091. return 0
  1092. endfunction
  1093. " GetWinNbr" {{{2
  1094. function! s:GetWinNbr(tabNbr, bufNbr)
  1095. " window number in tabpage.
  1096. let tablist = tabpagebuflist(a:tabNbr)
  1097. " Number: 0
  1098. " String: 1
  1099. " Funcref: 2
  1100. " List: 3
  1101. " Dictionary: 4
  1102. " Float: 5
  1103. if type(tablist) == 3
  1104. return index(tabpagebuflist(a:tabNbr), a:bufNbr) + 1
  1105. else
  1106. return 1
  1107. endif
  1108. endfunction
  1109. " StringWidth" {{{2
  1110. if exists('*strwidth')
  1111. function s:StringWidth(s)
  1112. return strwidth(a:s)
  1113. endfunction
  1114. else
  1115. function s:StringWidth(s)
  1116. return len(a:s)
  1117. endfunction
  1118. endif
  1119. " Winmanager Integration {{{2
  1120. let g:BufExplorer_title = "\[Buf\ List\]"
  1121. call s:Set("g:bufExplorerResize", 1)
  1122. call s:Set("g:bufExplorerMaxHeight", 25) " Handles dynamic resizing of the window.
  1123. " Evaluate a Vimscript expression in the context of this file.
  1124. " This enables debugging of script-local variables and functions from outside
  1125. " the plugin, e.g.:
  1126. " :echo BufExplorer_eval('s:bufMru')
  1127. function! BufExplorer_eval(expr)
  1128. return eval(a:expr)
  1129. endfunction
  1130. " Execute a Vimscript statement in the context of this file.
  1131. " This enables setting script-local variables from outside the plugin, e.g.:
  1132. " :call BufExplorer_execute('let s:bufMru = s:MRUNew(0)')
  1133. function! BufExplorer_execute(statement)
  1134. execute a:statement
  1135. endfunction
  1136. " function! to start display. Set the mode to 'winmanager' for this buffer.
  1137. " This is to figure out how this plugin was called. In a standalone fashion
  1138. " or by winmanager.
  1139. function! BufExplorer_Start()
  1140. let b:displayMode = "winmanager"
  1141. call s:SetLocalSettings()
  1142. call BufExplorer()
  1143. endfunction
  1144. " Returns whether the display is okay or not.
  1145. function! BufExplorer_IsValid()
  1146. return 0
  1147. endfunction
  1148. " Handles dynamic refreshing of the window.
  1149. function! BufExplorer_Refresh()
  1150. let b:displayMode = "winmanager"
  1151. call s:SetLocalSettings()
  1152. call BufExplorer()
  1153. endfunction
  1154. function! BufExplorer_ReSize()
  1155. if !g:bufExplorerResize
  1156. return
  1157. end
  1158. let nlines = min([line("$"), g:bufExplorerMaxHeight])
  1159. execute nlines." wincmd _"
  1160. " The following lines restore the layout so that the last file line is also
  1161. " the last window line. Sometimes, when a line is deleted, although the
  1162. " window size is exactly equal to the number of lines in the file, some of
  1163. " the lines are pushed up and we see some lagging '~'s.
  1164. let pres = getpos(".")
  1165. normal! $
  1166. let _scr = &scrolloff
  1167. let &scrolloff = 0
  1168. normal! z-
  1169. let &scrolloff = _scr
  1170. call setpos(".", pres)
  1171. endfunction
  1172. " Default values {{{2
  1173. call s:Set("g:bufExplorerDisableDefaultKeyMapping", 0) " Do not disable default key mappings.
  1174. call s:Set("g:bufExplorerDefaultHelp", 1) " Show default help?
  1175. call s:Set("g:bufExplorerDetailedHelp", 0) " Show detailed help?
  1176. call s:Set("g:bufExplorerFindActive", 1) " When selecting an active buffer, take you to the window where it is active?
  1177. call s:Set("g:bufExplorerOnlyOneTab", 1) " If ShowTabBuffer = 1, only store the most recent tab for this buffer.
  1178. call s:Set("g:bufExplorerReverseSort", 0) " Sort in reverse order by default?
  1179. call s:Set("g:bufExplorerShowDirectories", 1) " (Dir's are added by commands like ':e .')
  1180. call s:Set("g:bufExplorerShowRelativePath", 0) " Show listings with relative or absolute paths?
  1181. call s:Set("g:bufExplorerShowTabBuffer", 0) " Show only buffer(s) for this tab?
  1182. call s:Set("g:bufExplorerShowUnlisted", 0) " Show unlisted buffers?
  1183. call s:Set("g:bufExplorerShowNoName", 0) " Show 'No Name' buffers?
  1184. call s:Set("g:bufExplorerSortBy", "mru") " Sorting methods are in s:sort_by:
  1185. call s:Set("g:bufExplorerSplitBelow", &splitbelow) " Should horizontal splits be below or above current window?
  1186. call s:Set("g:bufExplorerSplitOutPathName", 1) " Split out path and file name?
  1187. call s:Set("g:bufExplorerSplitRight", &splitright) " Should vertical splits be on the right or left of current window?
  1188. call s:Set("g:bufExplorerSplitVertSize", 0) " Height for a vertical split. If <=0, default Vim size is used.
  1189. call s:Set("g:bufExplorerSplitHorzSize", 0) " Height for a horizontal split. If <=0, default Vim size is used.
  1190. call s:Set("g:bufExplorerShowTerminal", 1) " Show terminal buffers?
  1191. " Default key mapping {{{2
  1192. if !hasmapto('BufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1193. nnoremap <script> <silent> <unique> <Leader>be :BufExplorer<CR>
  1194. endif
  1195. if !hasmapto('ToggleBufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1196. nnoremap <script> <silent> <unique> <Leader>bt :ToggleBufExplorer<CR>
  1197. endif
  1198. if !hasmapto('BufExplorerHorizontalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1199. nnoremap <script> <silent> <unique> <Leader>bs :BufExplorerHorizontalSplit<CR>
  1200. endif
  1201. if !hasmapto('BufExplorerVerticalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1202. nnoremap <script> <silent> <unique> <Leader>bv :BufExplorerVerticalSplit<CR>
  1203. endif
  1204. " vim:ft=vim foldmethod=marker sw=4