bufexplorer.vim 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  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: Thursday, 20 March 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.9.0"
  76. " Plugin Code {{{1
  77. " Check for Vim version {{{2
  78. if !exists("g:bufExplorerVersionWarn")
  79. let g:bufExplorerVersionWarn = 1
  80. endif
  81. " Make sure we are using the correct version of Vim. If not, do not load the
  82. " plugin.
  83. if v:version < 704
  84. if g:bufExplorerVersionWarn
  85. echohl WarningMsg
  86. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.4 or greater."
  87. echohl None
  88. endif
  89. finish
  90. endif
  91. " Create commands {{{2
  92. command! BufExplorer :call BufExplorer()
  93. command! ToggleBufExplorer :call ToggleBufExplorer()
  94. command! BufExplorerHorizontalSplit :call BufExplorerHorizontalSplit()
  95. command! BufExplorerVerticalSplit :call BufExplorerVerticalSplit()
  96. " Set {{{2
  97. function! s:Set(var, default)
  98. if !exists(a:var)
  99. if type(a:default)
  100. execute "let" a:var "=" string(a:default)
  101. else
  102. execute "let" a:var "=" a:default
  103. endif
  104. return 1
  105. endif
  106. return 0
  107. endfunction
  108. " Script variables {{{2
  109. let s:MRU_Exclude_List = ["[BufExplorer]","__MRU_Files__","[Buf\ List]"]
  110. let s:name = '[BufExplorer]'
  111. " Buffer number of the BufExplorer window.
  112. let s:bufExplorerBuffer = 0
  113. let s:running = 0
  114. let s:sort_by = ["number", "name", "fullpath", "mru", "extension"]
  115. let s:splitMode = ""
  116. let s:didSplit = 0
  117. let s:types = ["fullname", "homename", "path", "relativename", "relativepath", "shortname"]
  118. " Setup the autocommands that handle stuff. {{{2
  119. augroup BufExplorer
  120. autocmd!
  121. autocmd WinEnter * call s:DoWinEnter()
  122. autocmd BufEnter * call s:DoBufEnter()
  123. autocmd BufDelete * call s:DoBufDelete()
  124. if exists('##TabClosed')
  125. autocmd TabClosed * call s:DoTabClosed()
  126. endif
  127. autocmd BufWinEnter \[BufExplorer\] call s:Initialize()
  128. autocmd BufWinLeave \[BufExplorer\] call s:Cleanup()
  129. augroup END
  130. " AssignTabId {{{2
  131. " Assign a `tabId` to the given tab.
  132. function! s:AssignTabId(tabNbr)
  133. " Create a unique `tabId` based on the current time and an incrementing
  134. " counter value that helps ensure uniqueness.
  135. let tabId = reltimestr(reltime()) . ':' . s:tabIdCounter
  136. call settabvar(a:tabNbr, 'bufexp_tabId', tabId)
  137. let s:tabIdCounter = (s:tabIdCounter + 1) % 1000000000
  138. return tabId
  139. endfunction
  140. let s:tabIdCounter = 0
  141. " GetTabId {{{2
  142. " Retrieve the `tabId` for the given tab (or '' if the tab has no `tabId`).
  143. function! s:GetTabId(tabNbr)
  144. return gettabvar(a:tabNbr, 'bufexp_tabId', '')
  145. endfunction
  146. " MRU data structure {{{2
  147. " An MRU data structure is a dictionary that holds a circular doubly linked list
  148. " of `item` values. The dictionary contains three keys:
  149. " 'head': a sentinel `item` representing the head of the list.
  150. " 'next': a dictionary mapping an `item` to the next `item` in the list.
  151. " 'prev': a dictionary mapping an `item` to the previous `item` in the list.
  152. " E.g., an MRU holding buffer numbers will use `0` (an invalid buffer number) as
  153. " `head`. With the buffer numbers `1`, `2`, and `3`, an example MRU would be:
  154. "
  155. " +--<---------<---------<---------<---------<+
  156. " `next` | |
  157. " +--> +---+ --> +---+ --> +---+ --> +---+ -->+
  158. " `head` | 0 | | 1 | | 2 | | 3 |
  159. " +<-- +---+ <-- +---+ <-- +---+ <-- +---+ <--+
  160. " `prev` | |
  161. " +->-------->--------->--------->--------->--+
  162. "
  163. " `head` allows the chosen sentinel item to differ in value and type; for
  164. " example, `head` could be the string '.', allowing an MRU of strings (such as
  165. " for `TabId` values).
  166. "
  167. " Note that dictionary keys are always strings. Integers may be used, but they
  168. " are converted to strings when used (and `keys(theDictionary)` will be a
  169. " list of strings, not of integers).
  170. " MRUNew {{{2
  171. function! s:MRUNew(head)
  172. let [next, prev] = [{}, {}]
  173. let next[a:head] = a:head
  174. let prev[a:head] = a:head
  175. return { 'head': a:head, 'next': next, 'prev': prev }
  176. endfunction
  177. " MRULen {{{2
  178. function! s:MRULen(mru)
  179. " Do not include the always-present `mru.head` item.
  180. return len(a:mru.next) - 1
  181. endfunction
  182. " MRURemoveMustExist {{{2
  183. " `item` must exist in `mru`.
  184. function! s:MRURemoveMustExist(mru, item)
  185. let [next, prev] = [a:mru.next, a:mru.prev]
  186. let prevItem = prev[a:item]
  187. let nextItem = next[a:item]
  188. let next[prevItem] = nextItem
  189. let prev[nextItem] = prevItem
  190. unlet next[a:item]
  191. unlet prev[a:item]
  192. endfunction
  193. " MRURemove {{{2
  194. " `item` need not exist in `mru`.
  195. function! s:MRURemove(mru, item)
  196. if has_key(a:mru.next, a:item)
  197. call s:MRURemoveMustExist(a:mru, a:item)
  198. endif
  199. endfunction
  200. " MRUAdd {{{2
  201. function! s:MRUAdd(mru, item)
  202. let [next, prev] = [a:mru.next, a:mru.prev]
  203. let prevItem = a:mru.head
  204. let nextItem = next[prevItem]
  205. if a:item != nextItem
  206. call s:MRURemove(a:mru, a:item)
  207. let next[a:item] = nextItem
  208. let prev[a:item] = prevItem
  209. let next[prevItem] = a:item
  210. let prev[nextItem] = a:item
  211. endif
  212. endfunction
  213. " MRUGetItems {{{2
  214. " Return list of up to `maxItems` items in MRU order.
  215. " `maxItems == 0` => unlimited.
  216. function! s:MRUGetItems(mru, maxItems)
  217. let [head, next] = [a:mru.head, a:mru.next]
  218. let items = []
  219. let item = next[head]
  220. while item != head
  221. if a:maxItems > 0 && len(items) >= a:maxItems
  222. break
  223. endif
  224. call add(items, item)
  225. let item = next[item]
  226. endwhile
  227. return items
  228. endfunction
  229. " MRUGetOrdering {{{2
  230. " Return dictionary mapping up to `maxItems` from `item` to MRU order.
  231. " `maxItems == 0` => unlimited.
  232. function! s:MRUGetOrdering(mru, maxItems)
  233. let [head, next] = [a:mru.head, a:mru.next]
  234. let items = {}
  235. let order = 0
  236. let item = next[head]
  237. while item != head
  238. if a:maxItems > 0 && order >= a:maxItems
  239. break
  240. endif
  241. let items[item] = order
  242. let order = order + 1
  243. let item = next[item]
  244. endwhile
  245. return items
  246. endfunction
  247. " MRU trackers {{{2
  248. " `.head` value for tab MRU:
  249. let s:tabIdHead = '.'
  250. " Track MRU buffers globally (independent of tabs).
  251. let s:bufMru = s:MRUNew(0)
  252. " Track MRU buffers for each tab, indexed by `tabId`.
  253. " `s:bufMruByTab[tabId] -> MRU structure`.
  254. let s:bufMruByTab = {}
  255. " Track MRU tabs for each buffer, indexed by `bufNbr`.
  256. " `s:tabMruByBuf[burNbr] -> MRU structure`.
  257. let s:tabMruByBuf = {}
  258. " MRURemoveBuf {{{2
  259. function! s:MRURemoveBuf(bufNbr)
  260. call s:MRURemove(s:bufMru, a:bufNbr)
  261. if has_key(s:tabMruByBuf, a:bufNbr)
  262. let mru = s:tabMruByBuf[a:bufNbr]
  263. let [head, next] = [mru.head, mru.next]
  264. let tabId = next[head]
  265. while tabId != head
  266. call s:MRURemoveMustExist(s:bufMruByTab[tabId], a:bufNbr)
  267. let tabId = next[tabId]
  268. endwhile
  269. unlet s:tabMruByBuf[a:bufNbr]
  270. endif
  271. endfunction
  272. " MRURemoveTab {{{2
  273. function! s:MRURemoveTab(tabId)
  274. if has_key(s:bufMruByTab, a:tabId)
  275. let mru = s:bufMruByTab[a:tabId]
  276. let [head, next] = [mru.head, mru.next]
  277. let bufNbr = next[head]
  278. while bufNbr != head
  279. call s:MRURemoveMustExist(s:tabMruByBuf[bufNbr], a:tabId)
  280. let bufNbr = next[bufNbr]
  281. endwhile
  282. unlet s:bufMruByTab[a:tabId]
  283. endif
  284. endfunction
  285. " MRUAddBufTab {{{2
  286. function! s:MRUAddBufTab(bufNbr, tabId)
  287. if s:ShouldIgnore(a:bufNbr)
  288. return
  289. endif
  290. call s:MRUAdd(s:bufMru, a:bufNbr)
  291. if !has_key(s:bufMruByTab, a:tabId)
  292. let s:bufMruByTab[a:tabId] = s:MRUNew(0)
  293. endif
  294. let bufMru = s:bufMruByTab[a:tabId]
  295. call s:MRUAdd(bufMru, a:bufNbr)
  296. if !has_key(s:tabMruByBuf, a:bufNbr)
  297. let s:tabMruByBuf[a:bufNbr] = s:MRUNew(s:tabIdHead)
  298. endif
  299. let tabMru = s:tabMruByBuf[a:bufNbr]
  300. call s:MRUAdd(tabMru, a:tabId)
  301. endfunction
  302. " MRUTabForBuf {{{2
  303. " Return `tabId` most recently used by `bufNbr`.
  304. " If no `tabId` is found for `bufNbr`, return `s:tabIdHead`.
  305. function! s:MRUTabForBuf(bufNbr)
  306. let tabMru = get(s:tabMruByBuf, a:bufNbr, s:alwaysEmptyTabMru)
  307. return tabMru.next[tabMru.head]
  308. endfunction
  309. " An always-empty MRU for tabs as a default when looking up
  310. " `s:tabMruByBuf[bufNbr]` for an unknown `bufNbr`.
  311. let s:alwaysEmptyTabMru = s:MRUNew(s:tabIdHead)
  312. " MRUTabHasSeenBuf {{{2
  313. " Return true if `tabId` has ever seen `bufNbr`.
  314. function! s:MRUTabHasSeenBuf(tabId, bufNbr)
  315. let mru = get(s:bufMruByTab, a:tabId, s:alwaysEmptyBufMru)
  316. return has_key(mru.next, a:bufNbr)
  317. endfunction
  318. " MRUTabShouldShowBuf {{{2
  319. " Return true if `tabId` should show `bufNbr`.
  320. " This is a function of current display modes.
  321. function! s:MRUTabShouldShowBuf(tabId, bufNbr)
  322. if !g:bufExplorerShowTabBuffer
  323. " We are showing buffers from all tabs.
  324. return 1
  325. elseif g:bufExplorerOnlyOneTab
  326. " We are showing buffers that were most recently seen in this tab.
  327. return s:MRUTabForBuf(a:bufNbr) == a:tabId
  328. else
  329. " We are showing buffers that have ever been seen in this tab.
  330. return s:MRUTabHasSeenBuf(a:tabId, a:bufNbr)
  331. endif
  332. endfunction
  333. " MRUListedBuffersForTab {{{2
  334. " Return list of up to `maxBuffers` listed buffers in MRU order for the tab.
  335. " `maxBuffers == 0` => unlimited.
  336. function! s:MRUListedBuffersForTab(tabId, maxBuffers)
  337. let bufNbrs = []
  338. let mru = get(s:bufMruByTab, a:tabId, s:alwaysEmptyBufMru)
  339. let [head, next] = [mru.head, mru.next]
  340. let bufNbr = next[head]
  341. while bufNbr != head
  342. if a:maxBuffers > 0 && len(bufNbrs) >= a:maxBuffers
  343. break
  344. endif
  345. if buflisted(bufNbr) && s:MRUTabShouldShowBuf(a:tabId, bufNbr)
  346. call add(bufNbrs, bufNbr)
  347. endif
  348. let bufNbr = next[bufNbr]
  349. endwhile
  350. return bufNbrs
  351. endfunction
  352. " An always-empty MRU for buffers as a default when looking up
  353. " `s:bufMruByTab[tabId]` for an unknown `tabId`.
  354. let s:alwaysEmptyBufMru = s:MRUNew(0)
  355. " MRUOrderForBuf {{{2
  356. " Return the position of `bufNbr` in the current MRU ordering.
  357. " This is a function of the current display mode. When showing buffers from all
  358. " tabs, it's the global MRU order; otherwise, it the MRU order for the tab at
  359. " BufExplorer launch. The latter includes all buffers seen in this tab, which
  360. " is sufficient whether `g:bufExplorerOnlyOneTab` is true or false.
  361. function! s:MRUOrderForBuf(bufNbr)
  362. if !exists('s:mruOrder')
  363. if g:bufExplorerShowTabBuffer
  364. let mru = get(s:bufMruByTab, s:tabIdAtLaunch, s:alwaysEmptyBufMru)
  365. else
  366. let mru = s:bufMru
  367. endif
  368. let s:mruOrder = s:MRUGetOrdering(mru, 0)
  369. endif
  370. return get(s:mruOrder, a:bufNbr, len(s:mruOrder))
  371. endfunction
  372. " MRUEnsureTabId {{{2
  373. function! s:MRUEnsureTabId(tabNbr)
  374. let tabId = s:GetTabId(a:tabNbr)
  375. if tabId == ''
  376. let tabId = s:AssignTabId(a:tabNbr)
  377. for bufNbr in tabpagebuflist(a:tabNbr)
  378. call s:MRUAddBufTab(bufNbr, tabId)
  379. endfor
  380. endif
  381. return tabId
  382. endfunction
  383. " MRUGarbageCollectBufs {{{2
  384. " Requires `s:raw_buffer_listing`.
  385. function! s:MRUGarbageCollectBufs()
  386. for bufNbr in values(s:bufMru.next)
  387. if bufNbr != 0 && !has_key(s:raw_buffer_listing, bufNbr)
  388. call s:MRURemoveBuf(bufNbr)
  389. endif
  390. endfor
  391. endfunction
  392. " MRUGarbageCollectTabs {{{2
  393. function! s:MRUGarbageCollectTabs()
  394. let numTabs = tabpagenr('$')
  395. let liveTabIds = {}
  396. for tabNbr in range(1, numTabs)
  397. let tabId = s:GetTabId(tabNbr)
  398. if tabId != ''
  399. let liveTabIds[tabId] = 1
  400. endif
  401. endfor
  402. for tabId in keys(s:bufMruByTab)
  403. if tabId != s:tabIdHead && !has_key(liveTabIds, tabId)
  404. call s:MRURemoveTab(tabId)
  405. endif
  406. endfor
  407. endfunction
  408. " DoWinEnter {{{2
  409. function! s:DoWinEnter()
  410. let bufNbr = str2nr(expand("<abuf>"))
  411. let tabNbr = tabpagenr()
  412. let tabId = s:GetTabId(tabNbr)
  413. " Ignore `WinEnter` for a newly created tab; this event comes when creating
  414. " a new tab, and the buffer at that moment is one that is about to be
  415. " replaced by the buffer to which we are switching; this latter buffer will
  416. " be handled by the forthcoming `BufEnter` event.
  417. if tabId != ''
  418. call s:MRUAddBufTab(bufNbr, tabId)
  419. endif
  420. endfunction
  421. " DoBufEnter {{{2
  422. function! s:DoBufEnter()
  423. let bufNbr = str2nr(expand("<abuf>"))
  424. let tabNbr = tabpagenr()
  425. let tabId = s:MRUEnsureTabId(tabNbr)
  426. call s:MRUAddBufTab(bufNbr, tabId)
  427. endfunction
  428. " DoBufDelete {{{2
  429. function! s:DoBufDelete()
  430. let bufNbr = str2nr(expand("<abuf>"))
  431. call s:MRURemoveBuf(bufNbr)
  432. endfunction
  433. " DoTabClosed {{{2
  434. function! s:DoTabClosed()
  435. call s:MRUGarbageCollectTabs()
  436. endfunction
  437. " ShouldIgnore {{{2
  438. function! s:ShouldIgnore(buf)
  439. " Ignore temporary buffers with buftype set.
  440. if empty(getbufvar(a:buf, "&buftype")) == 0
  441. return 1
  442. endif
  443. " Ignore buffers with no name.
  444. if empty(bufname(a:buf)) == 1
  445. return 1
  446. endif
  447. " Ignore the BufExplorer buffer.
  448. if fnamemodify(bufname(a:buf), ":t") == s:name
  449. return 1
  450. endif
  451. " Ignore any buffers in the exclude list.
  452. if index(s:MRU_Exclude_List, bufname(a:buf)) >= 0
  453. return 1
  454. endif
  455. " Else return 0 to indicate that the buffer was not ignored.
  456. return 0
  457. endfunction
  458. " Initialize {{{2
  459. function! s:Initialize()
  460. call s:SetLocalSettings()
  461. let s:running = 1
  462. endfunction
  463. " Cleanup {{{2
  464. function! s:Cleanup()
  465. if exists("s:_insertmode")
  466. let &insertmode = s:_insertmode
  467. endif
  468. if exists("s:_showcmd")
  469. let &showcmd = s:_showcmd
  470. endif
  471. if exists("s:_cpo")
  472. let &cpo = s:_cpo
  473. endif
  474. if exists("s:_report")
  475. let &report = s:_report
  476. endif
  477. let s:running = 0
  478. let s:splitMode = ""
  479. let s:didSplit = 0
  480. delmarks!
  481. endfunction
  482. " SetLocalSettings {{{2
  483. function! s:SetLocalSettings()
  484. let s:_insertmode = &insertmode
  485. set noinsertmode
  486. let s:_showcmd = &showcmd
  487. set noshowcmd
  488. let s:_cpo = &cpo
  489. set cpo&vim
  490. let s:_report = &report
  491. let &report = 10000
  492. setlocal nonumber
  493. setlocal foldcolumn=0
  494. setlocal nofoldenable
  495. setlocal cursorline
  496. setlocal nospell
  497. setlocal nobuflisted
  498. setlocal filetype=bufexplorer
  499. endfunction
  500. " BufExplorerHorizontalSplit {{{2
  501. function! BufExplorerHorizontalSplit()
  502. let s:splitMode = "sp"
  503. execute "BufExplorer"
  504. let s:splitMode = ""
  505. endfunction
  506. " BufExplorerVerticalSplit {{{2
  507. function! BufExplorerVerticalSplit()
  508. let s:splitMode = "vsp"
  509. execute "BufExplorer"
  510. let s:splitMode = ""
  511. endfunction
  512. " ToggleBufExplorer {{{2
  513. function! ToggleBufExplorer()
  514. if exists("s:running") && s:running == 1 && bufname(winbufnr(0)) == s:name
  515. call s:Close()
  516. else
  517. call BufExplorer()
  518. endif
  519. endfunction
  520. " BufExplorer {{{2
  521. function! BufExplorer()
  522. let [tabNbr, winNbr] = s:FindBufExplorer()
  523. if tabNbr > 0
  524. execute 'keepjumps ' . tabNbr . 'tabnext'
  525. execute 'keepjumps ' . winNbr . 'wincmd w'
  526. return
  527. endif
  528. let name = s:name
  529. if !has("win32")
  530. " On non-Windows boxes, escape the name so that is shows up correctly.
  531. let name = escape(name, "[]")
  532. endif
  533. let s:tabIdAtLaunch = s:MRUEnsureTabId(tabpagenr())
  534. let s:windowAtLaunch = winnr()
  535. " Forget any cached MRU ordering from previous invocations.
  536. unlet! s:mruOrder
  537. let s:raw_buffer_listing = s:GetBufferInfo(0)
  538. call s:MRUGarbageCollectBufs()
  539. call s:MRUGarbageCollectTabs()
  540. " We may have to split the current window.
  541. if s:splitMode != ""
  542. " Save off the original settings.
  543. let [_splitbelow, _splitright] = [&splitbelow, &splitright]
  544. " Set the setting to ours.
  545. let [&splitbelow, &splitright] = [g:bufExplorerSplitBelow, g:bufExplorerSplitRight]
  546. let _size = (s:splitMode == "sp") ? g:bufExplorerSplitHorzSize : g:bufExplorerSplitVertSize
  547. " Split the window either horizontally or vertically.
  548. if _size <= 0
  549. execute 'keepalt ' . s:splitMode
  550. else
  551. execute 'keepalt ' . _size . s:splitMode
  552. endif
  553. " Restore the original settings.
  554. let [&splitbelow, &splitright] = [_splitbelow, _splitright]
  555. " Remember that a split was triggered
  556. let s:didSplit = 1
  557. endif
  558. if !exists("b:displayMode") || b:displayMode != "winmanager"
  559. " Do not use keepalt when opening bufexplorer to allow the buffer that
  560. " we are leaving to become the new alternate buffer
  561. execute "silent keepjumps hide edit".name
  562. endif
  563. " Record BufExplorer's buffer number.
  564. let s:bufExplorerBuffer = bufnr('%')
  565. call s:DisplayBufferList()
  566. " Position the cursor in the newly displayed list on the line representing
  567. " the active buffer. The active buffer is the line with the '%' character
  568. " in it.
  569. execute search("%")
  570. if exists('#User#BufExplorer_Started')
  571. " Notify that BufExplorer has started. This is an opportunity to make
  572. " custom buffer-local mappings and the like.
  573. doautocmd User BufExplorer_Started
  574. endif
  575. endfunction
  576. " Tracks `tabId` at BufExplorer launch.
  577. let s:tabIdAtLaunch = ''
  578. " Tracks window number at BufExplorer launch.
  579. let s:windowAtLaunch = 0
  580. " DisplayBufferList {{{2
  581. function! s:DisplayBufferList()
  582. setlocal buftype=nofile
  583. setlocal modifiable
  584. setlocal noreadonly
  585. setlocal noswapfile
  586. setlocal nowrap
  587. setlocal bufhidden=wipe
  588. call s:MapKeys()
  589. " Wipe out any existing lines in case BufExplorer buffer exists and the
  590. " user had changed any global settings that might reduce the number of
  591. " lines needed in the buffer.
  592. silent keepjumps 1,$d _
  593. call setline(1, s:CreateHelp())
  594. call s:BuildBufferList()
  595. call cursor(s:firstBufferLine, 1)
  596. if !g:bufExplorerResize
  597. normal! zz
  598. endif
  599. setlocal nomodifiable
  600. endfunction
  601. " RedisplayBufferList {{{2
  602. function! s:RedisplayBufferList()
  603. call s:RebuildBufferList()
  604. call s:UpdateHelpStatus()
  605. endfunction
  606. " MapKeys {{{2
  607. function! s:MapKeys()
  608. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferDelete) :call <SID>RemoveBuffer("delete")<CR>
  609. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferDeleteForced) :call <SID>RemoveBuffer("force_delete")<CR>
  610. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferWipe) :call <SID>RemoveBuffer("wipe")<CR>
  611. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferWipeForced) :call <SID>RemoveBuffer("force_wipe")<CR>
  612. nnoremap <silent> <buffer> <Plug>(BufExplorer_Close) :call <SID>Close()<CR>
  613. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBuffer) :call <SID>SelectBuffer()<CR>
  614. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferAsk) :call <SID>SelectBuffer("ask")<CR>
  615. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferOriginalWindow) :call <SID>SelectBuffer("original_window")<CR>
  616. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitAbove) :call <SID>SelectBuffer("split", "st")<CR>
  617. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitBelow) :call <SID>SelectBuffer("split", "sb")<CR>
  618. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitLeft) :call <SID>SelectBuffer("split", "vl")<CR>
  619. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitRight) :call <SID>SelectBuffer("split", "vr")<CR>
  620. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferTab) :call <SID>SelectBuffer("tab")<CR>
  621. nnoremap <silent> <buffer> <Plug>(BufExplorer_SortByNext) :call <SID>SortSelect()<CR>
  622. nnoremap <silent> <buffer> <Plug>(BufExplorer_SortByPrev) :call <SID>ReverseSortSelect()<CR>
  623. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleFindActive) :call <SID>ToggleFindActive()<CR>
  624. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleHelp) :call <SID>ToggleHelp()<CR>
  625. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleOnlyOneTab) :call <SID>ToggleOnlyOneTab()<CR>
  626. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleReverseSort) :call <SID>SortReverse()<CR>
  627. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowRelativePath) :call <SID>ToggleShowRelativePath()<CR>
  628. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowTabBuffer) :call <SID>ToggleShowTabBuffer()<CR>
  629. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowTerminal) :call <SID>ToggleShowTerminal()<CR>
  630. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowUnlisted) :call <SID>ToggleShowUnlisted()<CR>
  631. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleSplitOutPathName) :call <SID>ToggleSplitOutPathName()<CR>
  632. if exists("b:displayMode") && b:displayMode == "winmanager"
  633. nnoremap <buffer> <silent> <tab> :call <SID>SelectBuffer()<CR>
  634. endif
  635. nmap <nowait> <buffer> <2-leftmouse> <Plug>(BufExplorer_OpenBuffer)
  636. nmap <nowait> <buffer> <CR> <Plug>(BufExplorer_OpenBuffer)
  637. nmap <nowait> <buffer> <F1> <Plug>(BufExplorer_ToggleHelp)
  638. nmap <nowait> <buffer> <s-cr> <Plug>(BufExplorer_OpenBufferTab)
  639. nmap <nowait> <buffer> a <Plug>(BufExplorer_ToggleFindActive)
  640. nmap <nowait> <buffer> b <Plug>(BufExplorer_OpenBufferAsk)
  641. nmap <nowait> <buffer> B <Plug>(BufExplorer_ToggleOnlyOneTab)
  642. nmap <nowait> <buffer> d <Plug>(BufExplorer_BufferDelete)
  643. nmap <nowait> <buffer> D <Plug>(BufExplorer_BufferWipe)
  644. nmap <nowait> <buffer> f <Plug>(BufExplorer_OpenBufferSplitBelow)
  645. nmap <nowait> <buffer> F <Plug>(BufExplorer_OpenBufferSplitAbove)
  646. nmap <nowait> <buffer> o <Plug>(BufExplorer_OpenBuffer)
  647. nmap <nowait> <buffer> O <Plug>(BufExplorer_OpenBufferOriginalWindow)
  648. nmap <nowait> <buffer> p <Plug>(BufExplorer_ToggleSplitOutPathName)
  649. nmap <nowait> <buffer> q <Plug>(BufExplorer_Close)
  650. nmap <nowait> <buffer> r <Plug>(BufExplorer_ToggleReverseSort)
  651. nmap <nowait> <buffer> R <Plug>(BufExplorer_ToggleShowRelativePath)
  652. nmap <nowait> <buffer> s <Plug>(BufExplorer_SortByNext)
  653. nmap <nowait> <buffer> S <Plug>(BufExplorer_SortByPrev)
  654. nmap <nowait> <buffer> t <Plug>(BufExplorer_OpenBufferTab)
  655. nmap <nowait> <buffer> T <Plug>(BufExplorer_ToggleShowTabBuffer)
  656. nmap <nowait> <buffer> u <Plug>(BufExplorer_ToggleShowUnlisted)
  657. nmap <nowait> <buffer> v <Plug>(BufExplorer_OpenBufferSplitRight)
  658. nmap <nowait> <buffer> V <Plug>(BufExplorer_OpenBufferSplitLeft)
  659. nmap <nowait> <buffer> X <Plug>(BufExplorer_ToggleShowTerminal)
  660. for k in ["G", "n", "N", "L", "M", "H"]
  661. execute "nnoremap <buffer> <silent>" k ":keepjumps normal!" k."<CR>"
  662. endfor
  663. endfunction
  664. " ToggleHelp {{{2
  665. function! s:ToggleHelp()
  666. let g:bufExplorerDetailedHelp = !g:bufExplorerDetailedHelp
  667. setlocal modifiable
  668. " Save position.
  669. normal! ma
  670. " Remove old header.
  671. if s:firstBufferLine > 1
  672. execute "keepjumps 1,".(s:firstBufferLine - 1) "d _"
  673. endif
  674. call append(0, s:CreateHelp())
  675. silent! normal! g`a
  676. delmarks a
  677. setlocal nomodifiable
  678. if exists("b:displayMode") && b:displayMode == "winmanager"
  679. call WinManagerForceReSize("BufExplorer")
  680. endif
  681. endfunction
  682. " GetHelpStatus {{{2
  683. function! s:GetHelpStatus()
  684. let ret = '" Sorted by '.((g:bufExplorerReverseSort == 1) ? "reverse " : "").g:bufExplorerSortBy
  685. let ret .= ' | '.((g:bufExplorerFindActive == 0) ? "Don't " : "")."Locate buffer"
  686. let ret .= ((g:bufExplorerShowUnlisted == 0) ? "" : " | Show unlisted")
  687. let ret .= ((g:bufExplorerShowTabBuffer == 0) ? "" : " | Show buffers/tab")
  688. let ret .= ((g:bufExplorerOnlyOneTab == 0) ? "" : " | One tab/buffer")
  689. let ret .= ' | '.((g:bufExplorerShowRelativePath == 0) ? "Absolute" : "Relative")
  690. let ret .= ' '.((g:bufExplorerSplitOutPathName == 0) ? "Full" : "Split")." path"
  691. let ret .= ((g:bufExplorerShowTerminal == 0) ? "" : " | Show terminal")
  692. return ret
  693. endfunction
  694. " CreateHelp {{{2
  695. function! s:CreateHelp()
  696. if g:bufExplorerDefaultHelp == 0 && g:bufExplorerDetailedHelp == 0
  697. let s:firstBufferLine = 1
  698. return []
  699. endif
  700. let header = []
  701. if g:bufExplorerDetailedHelp == 1
  702. call add(header, '" Buffer Explorer ('.g:bufexplorer_version.')')
  703. call add(header, '" --------------------------')
  704. call add(header, '" <F1> : toggle this help')
  705. call add(header, '" <enter> or o or Mouse-Double-Click : open buffer under cursor')
  706. call add(header, '" <shift-enter> or t : open buffer in another tab')
  707. call add(header, '" a : toggle find active buffer')
  708. call add(header, '" b : Fast buffer switching with b<any bufnum>')
  709. call add(header, '" B : toggle showing buffers only on their MRU tabs')
  710. call add(header, '" d : delete buffer')
  711. call add(header, '" D : wipe buffer')
  712. call add(header, '" F : open buffer in another window above the current')
  713. call add(header, '" f : open buffer in another window below the current')
  714. call add(header, '" O : open buffer in original window')
  715. call add(header, '" p : toggle splitting of file and path name')
  716. call add(header, '" q : quit')
  717. call add(header, '" r : reverse sort')
  718. call add(header, '" R : toggle showing relative or full paths')
  719. call add(header, '" s : cycle thru "sort by" fields '.string(s:sort_by).'')
  720. call add(header, '" S : reverse cycle thru "sort by" fields')
  721. call add(header, '" T : toggle showing all buffers/only buffers used on this tab')
  722. call add(header, '" u : toggle showing unlisted buffers')
  723. call add(header, '" V : open buffer in another window on the left of the current')
  724. call add(header, '" v : open buffer in another window on the right of the current')
  725. call add(header, '" X : toggle showing terminal buffers')
  726. else
  727. call add(header, '" Press <F1> for Help')
  728. endif
  729. if (!exists("b:displayMode") || b:displayMode != "winmanager") || (b:displayMode == "winmanager" && g:bufExplorerDetailedHelp == 1)
  730. call add(header, s:GetHelpStatus())
  731. call add(header, '"=')
  732. endif
  733. let s:firstBufferLine = len(header) + 1
  734. return header
  735. endfunction
  736. " CalculateBufferDetails {{{2
  737. " Calculate `buf`-related details.
  738. " Only these fields of `buf` must be defined on entry:
  739. " - `._bufnr`
  740. " - `.attributes`
  741. " - `.line`
  742. function! s:CalculateBufferDetails(buf)
  743. let buf = a:buf
  744. let name = bufname(buf._bufnr)
  745. let buf["hasNoName"] = empty(name)
  746. if buf.hasNoName
  747. let name = "[No Name]"
  748. endif
  749. let buf.isterminal = getbufvar(buf._bufnr, '&buftype') == 'terminal'
  750. if buf.isterminal
  751. " Neovim uses paths with `term://` prefix, where the provided path
  752. " is the current working directory when the terminal was launched, e.g.:
  753. " - Unix:
  754. " term://~/tmp/sort//1464953:/bin/bash
  755. " - Windows:
  756. " term://C:\apps\nvim-win64\bin//6408:C:\Windows\system32\cmd.exe
  757. " Vim uses paths starting with `!`, with no provided path, e.g.:
  758. " - Unix:
  759. " !/bin/bash
  760. " - Windows:
  761. " !C:\Windows\system32\cmd.exe
  762. " Use the terminal's current working directory as the `path`.
  763. " For `shortname`, use `!PID:shellName`, prefixed with `!` as Vim does,
  764. " and without the shell's path for brevity, e.g.:
  765. " `/bin/bash` -> `!bash`
  766. " `1464953:/bin/bash` -> `!1464953:bash`
  767. " `C:\Windows\system32\cmd.exe` -> `!cmd.exe`
  768. " `6408:C:\Windows\system32\cmd.exe` -> `!6408:cmd.exe`
  769. " Neovim-style name format:
  770. " term://(cwd)//(pid):(shellPath)
  771. " e.g.:
  772. " term://~/tmp/sort//1464953:/bin/bash
  773. " `cwd` is the directory at terminal launch.
  774. let termNameParts = matchlist(name, '\v\c^term://(.*)//(\d+):(.*)$')
  775. if len(termNameParts) > 0
  776. let [cwd, pidStr, shellPath] = termNameParts[1:3]
  777. let pid = str2nr(pidStr)
  778. let shellName = fnamemodify(shellPath, ':t')
  779. else
  780. " Default to Vim's current working directory.
  781. let cwd = '.'
  782. let shellName = fnamemodify(name, ':t')
  783. let pid = -1
  784. if exists('*term_getjob') && exists('*job_info')
  785. let job = term_getjob(buf._bufnr)
  786. if job != v:null
  787. let pid = job_info(job).process
  788. endif
  789. endif
  790. endif
  791. if pid < 0
  792. let shortname = '!' . shellName
  793. else
  794. let shortname = '!' . pid . ':' . shellName
  795. " On some systems having a `/proc` filesystem (e.g., Linux, *BSD,
  796. " Solaris), each process has a `cwd` symlink for the current working
  797. " directory. `resolve()` will return the actual current working
  798. " directory if possible; otherwise, it will return the symlink path
  799. " unchanged.
  800. let cwd_symlink = '/proc/' . pid . '/cwd'
  801. let resolved_cwd = resolve(cwd_symlink)
  802. if resolved_cwd != cwd_symlink
  803. let cwd = resolved_cwd
  804. endif
  805. endif
  806. let slashed_path = fnamemodify(cwd, ':p')
  807. let buf.fullname = slashed_path . shortname
  808. let buf.shortname = shortname
  809. let homepath = fnamemodify(slashed_path, ':~:h')
  810. let buf.path = homepath
  811. let buf.homename = fnamemodify(buf.fullname, ':~')
  812. let buf.relativepath = fnamemodify(slashed_path, ':~:.:h')
  813. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  814. return
  815. endif
  816. let buf.fullname = simplify(fnamemodify(name, ':p'))
  817. let buf.isdir = getftype(buf.fullname) == "dir"
  818. if buf.isdir
  819. " `buf.fullname` ends with a path separator; this will be
  820. " removed via the first `:h` applied to `buf.fullname` (except
  821. " for the root directory, where the path separator will remain).
  822. let parent = fnamemodify(buf.fullname, ':h:h')
  823. let buf.shortname = fnamemodify(buf.fullname, ':h:t')
  824. " Special case for root directory: fnamemodify('/', ':h:t') == ''
  825. if buf.shortname == ''
  826. let buf.shortname = '.'
  827. endif
  828. " Must perform shortening (`:~`, `:.`) before `:h`.
  829. let buf.homename = fnamemodify(buf.fullname, ':~:h')
  830. let buf.relativename = fnamemodify(buf.fullname, ':~:.:h')
  831. else
  832. let parent = fnamemodify(buf.fullname, ':h')
  833. let buf.shortname = fnamemodify(buf.fullname, ':t')
  834. let buf.homename = fnamemodify(buf.fullname, ':~')
  835. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  836. endif
  837. " `:p` on `parent` adds back the path separator which permits more
  838. " effective shortening (`:~`, `:.`), but `:h` is required afterward
  839. " to trim this separator.
  840. let buf.path = fnamemodify(parent, ':p:~:h')
  841. let buf.relativepath = fnamemodify(parent, ':p:~:.:h')
  842. endfunction
  843. " GetBufferInfo {{{2
  844. " Return dictionary `{ bufNbr : buf }`.
  845. " - If `onlyBufNbr > 0`, dictionary will contain at most that buffer.
  846. " On return, only these fields are set for each `buf`:
  847. " - `._bufnr`
  848. " - `.attributes`
  849. " - `.line`
  850. " Other fields will be populated by `s:CalculateBufferDetails()`.
  851. function! s:GetBufferInfo(onlyBufNbr)
  852. redir => bufoutput
  853. " Below, `:silent buffers` allows capturing the output via `:redir` but
  854. " prevents display to the user.
  855. if a:onlyBufNbr > 0 && buflisted(a:onlyBufNbr)
  856. " We care only about the listed buffer `a:onlyBufNbr`, so no need to
  857. " enumerate unlisted buffers.
  858. silent buffers
  859. else
  860. " Use `!` to show all buffers including the unlisted ones.
  861. silent buffers!
  862. endif
  863. redir END
  864. if a:onlyBufNbr > 0
  865. " Since we are only interested in this specified buffer remove the
  866. " other buffers listed.
  867. " Use a very-magic pattern starting with a newline and a run of zero or
  868. " more spaces/tabs:
  869. let onlyLinePattern = '\v\n\s*'
  870. " Continue with the buffer number followed by a non-digit character
  871. " (which will be a buffer attribute character such as `u` or ` `).
  872. let onlyLinePattern .= a:onlyBufNbr . '\D'
  873. " Finish with a run of zero or more non-newline characters plus newline:
  874. let onlyLinePattern .= '[^\n]*\n'
  875. let bufoutput = matchstr("\n" . bufoutput . "\n", onlyLinePattern)
  876. endif
  877. let all = {}
  878. " Loop over each line in the buffer.
  879. for line in split(bufoutput, '\n')
  880. let bits = split(line, '"')
  881. " Use first and last components after the split on '"', in case a
  882. " filename with an embedded '"' is present.
  883. let buf = {"attributes": bits[0], "line": substitute(bits[-1], '\s*', '', '')}
  884. let buf._bufnr = str2nr(buf.attributes)
  885. let all[buf._bufnr] = buf
  886. endfor
  887. return all
  888. endfunction
  889. " BuildBufferList {{{2
  890. function! s:BuildBufferList()
  891. let table = []
  892. " Loop through every buffer.
  893. for buf in values(s:raw_buffer_listing)
  894. " `buf.attributes` must exist, but we defer the expensive work of
  895. " calculating other buffer details (e.g., `buf.fullname`) until we know
  896. " the user wants to view this buffer.
  897. " Skip BufExplorer's buffer.
  898. if buf._bufnr == s:bufExplorerBuffer
  899. continue
  900. endif
  901. " Skip unlisted buffers if we are not to show them.
  902. if !g:bufExplorerShowUnlisted && buf.attributes =~ "u"
  903. " Skip unlisted buffers if we are not to show them.
  904. continue
  905. endif
  906. " Ensure buffer details are computed for this buffer.
  907. if !has_key(buf, 'fullname')
  908. call s:CalculateBufferDetails(buf)
  909. endif
  910. " Skip 'No Name' buffers if we are not to show them.
  911. if g:bufExplorerShowNoName == 0 && buf.hasNoName
  912. continue
  913. endif
  914. " Should we show this buffer in this tab?
  915. if !s:MRUTabShouldShowBuf(s:tabIdAtLaunch, buf._bufnr)
  916. continue
  917. endif
  918. " Skip terminal buffers if we are not to show them.
  919. if !g:bufExplorerShowTerminal && buf.isterminal
  920. continue
  921. endif
  922. " Skip directory buffers if we are not to show them.
  923. if !g:bufExplorerShowDirectories && buf.isdir
  924. continue
  925. endif
  926. let row = [buf.attributes]
  927. if exists("g:loaded_webdevicons")
  928. let row += [WebDevIconsGetFileTypeSymbol(buf.fullname, buf.isdir)]
  929. endif
  930. " Are we to split the path and file name?
  931. if g:bufExplorerSplitOutPathName
  932. let type = (g:bufExplorerShowRelativePath) ? "relativepath" : "path"
  933. let row += [buf.shortname, buf[type]]
  934. else
  935. let type = (g:bufExplorerShowRelativePath) ? "relativename" : "homename"
  936. let row += [buf[type]]
  937. endif
  938. let row += [buf.line]
  939. call add(table, row)
  940. endfor
  941. let lines = s:MakeLines(table)
  942. call setline(s:firstBufferLine, lines)
  943. let firstMissingLine = s:firstBufferLine + len(lines)
  944. if line('$') >= firstMissingLine
  945. " Clear excess lines starting with `firstMissingLine`.
  946. execute "silent keepjumps ".firstMissingLine.',$d _'
  947. endif
  948. call s:SortListing()
  949. endfunction
  950. " MakeLines {{{2
  951. function! s:MakeLines(table)
  952. if len(a:table) == 0
  953. return []
  954. endif
  955. let lines = []
  956. " To avoid trailing whitespace, do not pad the final column.
  957. let numColumnsToPad = len(a:table[0]) - 1
  958. let maxWidths = repeat([0], numColumnsToPad)
  959. for row in a:table
  960. let i = 0
  961. while i < numColumnsToPad
  962. let maxWidths[i] = max([maxWidths[i], s:StringWidth(row[i])])
  963. let i = i + 1
  964. endwhile
  965. endfor
  966. let pads = []
  967. for w in maxWidths
  968. call add(pads, repeat(' ', w))
  969. endfor
  970. for row in a:table
  971. let i = 0
  972. while i < numColumnsToPad
  973. let row[i] .= strpart(pads[i], s:StringWidth(row[i]))
  974. let i = i + 1
  975. endwhile
  976. call add(lines, join(row, ' '))
  977. endfor
  978. return lines
  979. endfunction
  980. " SelectBuffer {{{2
  981. " Valid arguments:
  982. " `()` Open in current window.
  983. " `("ask")` Prompt for buffer, then open in current window.
  984. " `("original_window")` Open in original window.
  985. " `("split", "st")` Open in horizontal split above current window.
  986. " `("split", "sb")` Open in horizontal split below current window.
  987. " `("split", "vl")` Open in vertical split left of current window.
  988. " `("split", "vr")` Open in vertical split right of current window.
  989. " `("tab")` Open in a new tab.
  990. function! s:SelectBuffer(...)
  991. " Sometimes messages are not cleared when we get here so it looks like an
  992. " error has occurred when it really has not.
  993. "echo ""
  994. let _bufNbr = -1
  995. if (a:0 == 1) && (a:1 == "ask")
  996. " Ask the user for input.
  997. call inputsave()
  998. let cmd = input("Enter buffer number to switch to: ")
  999. call inputrestore()
  1000. " Clear the message area from the previous prompt.
  1001. redraw | echo
  1002. if strlen(cmd) > 0
  1003. let _bufNbr = str2nr(cmd)
  1004. else
  1005. call s:Error("Invalid buffer number, try again.")
  1006. return
  1007. endif
  1008. else
  1009. " Are we on a line with a file name?
  1010. if line('.') < s:firstBufferLine
  1011. execute "normal! \<CR>"
  1012. return
  1013. endif
  1014. let _bufNbr = str2nr(getline('.'))
  1015. " Check and see if we are running BufferExplorer via WinManager.
  1016. if exists("b:displayMode") && b:displayMode == "winmanager"
  1017. let _bufName = expand("#"._bufNbr.":p")
  1018. if (a:0 == 1) && (a:1 == "tab")
  1019. call WinManagerFileEdit(_bufName, 1)
  1020. else
  1021. call WinManagerFileEdit(_bufName, 0)
  1022. endif
  1023. return
  1024. endif
  1025. endif
  1026. if bufexists(_bufNbr)
  1027. " Get the tab number where this buffer is located in.
  1028. let tabNbr = s:GetTabNbr(_bufNbr)
  1029. if exists("g:bufExplorerChgWin") && g:bufExplorerChgWin <=winnr("$")
  1030. execute g:bufExplorerChgWin."wincmd w"
  1031. execute "keepjumps keepalt silent b!" _bufNbr
  1032. " Are we supposed to open the selected buffer in a tab?
  1033. elseif (a:0 == 1) && (a:1 == "tab")
  1034. call s:Close()
  1035. " Open a new tab with the selected buffer in it.
  1036. if v:version > 704 || ( v:version == 704 && has('patch2237') )
  1037. " new syntax for last tab as of 7.4.2237
  1038. execute "$tab split +buffer" . _bufNbr
  1039. else
  1040. execute "999tab split +buffer" . _bufNbr
  1041. endif
  1042. " Are we supposed to open the selected buffer in a split?
  1043. elseif (a:0 == 2) && (a:1 == "split")
  1044. call s:Close()
  1045. if (a:2 == "vl")
  1046. execute "vert topleft sb "._bufNbr
  1047. elseif (a:2 == "vr")
  1048. execute "vert belowright sb "._bufNbr
  1049. elseif (a:2 == "st")
  1050. execute "topleft sb "._bufNbr
  1051. else " = sb
  1052. execute "belowright sb "._bufNbr
  1053. endif
  1054. " Are we supposed to open the selected buffer in the original window?
  1055. elseif (a:0 == 1) && (a:1 == "original_window")
  1056. call s:Close()
  1057. execute s:windowAtLaunch . "wincmd w"
  1058. execute "keepjumps keepalt silent b!" _bufNbr
  1059. else
  1060. " Request to open in current (BufExplorer) window.
  1061. if g:bufExplorerFindActive && tabNbr > 0
  1062. " Close BufExplorer window and switch to existing tab/window.
  1063. call s:Close()
  1064. execute tabNbr . "tabnext"
  1065. execute bufwinnr(_bufNbr) . "wincmd w"
  1066. else
  1067. " Use BufExplorer window for the buffer.
  1068. execute "keepjumps keepalt silent b!" _bufNbr
  1069. endif
  1070. endif
  1071. " Make the buffer 'listed' again.
  1072. call setbufvar(_bufNbr, "&buflisted", "1")
  1073. " Call any associated function references. g:bufExplorerFuncRef may be
  1074. " an individual function reference or it may be a list containing
  1075. " function references. It will ignore anything that's not a function
  1076. " reference.
  1077. "
  1078. " See :help FuncRef for more on function references.
  1079. if exists("g:BufExplorerFuncRef")
  1080. if type(g:BufExplorerFuncRef) == 2
  1081. keepj call g:BufExplorerFuncRef()
  1082. elseif type(g:BufExplorerFuncRef) == 3
  1083. for FncRef in g:BufExplorerFuncRef
  1084. if type(FncRef) == 2
  1085. keepj call FncRef()
  1086. endif
  1087. endfor
  1088. endif
  1089. endif
  1090. else
  1091. call s:Error("Sorry, that buffer no longer exists, please select another")
  1092. call s:DeleteBuffer(_bufNbr, "wipe")
  1093. endif
  1094. endfunction
  1095. " RemoveBuffer {{{2
  1096. " Valid `mode` values:
  1097. " - "delete"
  1098. " - "force_delete"
  1099. " - "wipe"
  1100. " - "force_wipe"
  1101. function! s:RemoveBuffer(mode)
  1102. " Are we on a line with a file name?
  1103. if line('.') < s:firstBufferLine
  1104. return
  1105. endif
  1106. let mode = a:mode
  1107. let forced = mode =~# '^force_'
  1108. " These commands are to temporarily suspend the activity of winmanager.
  1109. if exists("b:displayMode") && b:displayMode == "winmanager"
  1110. call WinManagerSuspendAUs()
  1111. end
  1112. let bufNbr = str2nr(getline('.'))
  1113. let buf = s:raw_buffer_listing[bufNbr]
  1114. if !forced && (buf.isterminal || getbufvar(bufNbr, '&modified'))
  1115. if buf.isterminal
  1116. let msg = "Buffer " . bufNbr . " is a terminal"
  1117. else
  1118. let msg = "No write since last change for buffer " . bufNbr
  1119. endif
  1120. " Calling confirm() requires Vim built with dialog option.
  1121. if !has("dialog_con") && !has("dialog_gui")
  1122. call s:Error(msg . "; cannot remove without 'force'")
  1123. return
  1124. endif
  1125. let answer = confirm(msg . "; Remove anyway?", "&Yes\n&No", 2)
  1126. if answer == 1
  1127. let mode = 'force_' . mode
  1128. else
  1129. return
  1130. endif
  1131. endif
  1132. " Okay, everything is good, delete or wipe the buffer.
  1133. call s:DeleteBuffer(bufNbr, mode)
  1134. " Reactivate winmanager autocommand activity.
  1135. if exists("b:displayMode") && b:displayMode == "winmanager"
  1136. call WinManagerForceReSize("BufExplorer")
  1137. call WinManagerResumeAUs()
  1138. end
  1139. endfunction
  1140. " DeleteBuffer {{{2
  1141. " Valid `mode` values:
  1142. " - "delete"
  1143. " - "force_delete"
  1144. " - "wipe"
  1145. " - "force_wipe"
  1146. function! s:DeleteBuffer(bufNbr, mode)
  1147. " This routine assumes that the buffer to be removed is on the current line.
  1148. if a:mode =~# 'delete$' && bufexists(a:bufNbr) && !buflisted(a:bufNbr)
  1149. call s:Error('Buffer ' . a:bufNbr
  1150. \ . ' is unlisted; must `wipe` to remove')
  1151. return
  1152. endif
  1153. try
  1154. " Wipe/Delete buffer from Vim.
  1155. if a:mode == "wipe"
  1156. execute "silent bwipe" a:bufNbr
  1157. elseif a:mode == "force_wipe"
  1158. execute "silent bwipe!" a:bufNbr
  1159. elseif a:mode == "force_delete"
  1160. execute "silent bdelete!" a:bufNbr
  1161. else
  1162. execute "silent bdelete" a:bufNbr
  1163. endif
  1164. catch
  1165. call s:Error(v:exception)
  1166. endtry
  1167. if bufexists(a:bufNbr)
  1168. " Buffer is still present. We may have failed to wipe it, or it may
  1169. " have changed attributes (as `:bd` only makes a buffer unlisted).
  1170. " Regather information on this buffer, update the buffer list, and
  1171. " redisplay.
  1172. let info = s:GetBufferInfo(a:bufNbr)
  1173. let s:raw_buffer_listing[a:bufNbr] = info[a:bufNbr]
  1174. call s:RedisplayBufferList()
  1175. else
  1176. " Delete the buffer from the list on screen.
  1177. setlocal modifiable
  1178. normal! "_dd
  1179. setlocal nomodifiable
  1180. " Delete the buffer from the raw buffer list.
  1181. unlet s:raw_buffer_listing[a:bufNbr]
  1182. endif
  1183. endfunction
  1184. " Close {{{2
  1185. function! s:Close()
  1186. let [tabNbr, winNbr] = s:FindBufExplorer()
  1187. if tabNbr == 0
  1188. return
  1189. endif
  1190. let [curTabNbr, curWinNbr] = [tabpagenr(), winnr()]
  1191. if [tabNbr, winNbr] != [curTabNbr, curWinNbr]
  1192. " User has switched away from the original BufExplorer window.
  1193. " It's unclear how to do better than simply wiping out the
  1194. " BufExplorer buffer.
  1195. execute 'bwipeout ' . s:bufExplorerBuffer
  1196. return
  1197. endif
  1198. " Get only the listed buffers associated with the current tab (up to 2).
  1199. let listed = s:MRUListedBuffersForTab(s:tabIdAtLaunch, 2)
  1200. " If we needed to split the main window, close the split one.
  1201. if s:didSplit
  1202. execute "wincmd c"
  1203. endif
  1204. " Check to see if there are anymore buffers listed.
  1205. if len(listed) == 0
  1206. " Since there are no buffers left to switch to, open a new empty
  1207. " buffers.
  1208. execute "enew"
  1209. else
  1210. " Since there are buffers left to switch to, switch to the previous and
  1211. " then the current.
  1212. for b in reverse(listed[0:1])
  1213. execute "keepjumps silent b ".b
  1214. endfor
  1215. endif
  1216. " Clear any messages.
  1217. echo
  1218. endfunction
  1219. " FindBufExplorer {{{2
  1220. " Return `[tabNbr, winNbr]`; both numbers will be zero if not found.
  1221. function! s:FindBufExplorer()
  1222. let result = [0, 0]
  1223. if s:running
  1224. let numTabs = tabpagenr('$')
  1225. for tabNbr in range(1, numTabs)
  1226. let winNbr = index(tabpagebuflist(tabNbr), s:bufExplorerBuffer) + 1
  1227. if winNbr > 0
  1228. let result = [tabNbr, winNbr]
  1229. break
  1230. endif
  1231. endfor
  1232. endif
  1233. return result
  1234. endfunction
  1235. " ToggleShowTerminal {{{2
  1236. function! s:ToggleShowTerminal()
  1237. let g:bufExplorerShowTerminal = !g:bufExplorerShowTerminal
  1238. call s:RedisplayBufferList()
  1239. endfunction
  1240. " ToggleSplitOutPathName {{{2
  1241. function! s:ToggleSplitOutPathName()
  1242. let g:bufExplorerSplitOutPathName = !g:bufExplorerSplitOutPathName
  1243. call s:RedisplayBufferList()
  1244. endfunction
  1245. " ToggleShowRelativePath {{{2
  1246. function! s:ToggleShowRelativePath()
  1247. let g:bufExplorerShowRelativePath = !g:bufExplorerShowRelativePath
  1248. call s:RedisplayBufferList()
  1249. endfunction
  1250. " ToggleShowTabBuffer {{{2
  1251. function! s:ToggleShowTabBuffer()
  1252. " Forget any cached MRU ordering, as it depends on
  1253. " `g:bufExplorerShowTabBuffer`.
  1254. unlet! s:mruOrder
  1255. let g:bufExplorerShowTabBuffer = !g:bufExplorerShowTabBuffer
  1256. call s:RedisplayBufferList()
  1257. endfunction
  1258. " ToggleOnlyOneTab {{{2
  1259. function! s:ToggleOnlyOneTab()
  1260. let g:bufExplorerOnlyOneTab = !g:bufExplorerOnlyOneTab
  1261. call s:RedisplayBufferList()
  1262. endfunction
  1263. " ToggleShowUnlisted {{{2
  1264. function! s:ToggleShowUnlisted()
  1265. let g:bufExplorerShowUnlisted = !g:bufExplorerShowUnlisted
  1266. call s:RedisplayBufferList()
  1267. endfunction
  1268. " ToggleFindActive {{{2
  1269. function! s:ToggleFindActive()
  1270. let g:bufExplorerFindActive = !g:bufExplorerFindActive
  1271. call s:UpdateHelpStatus()
  1272. endfunction
  1273. " RebuildBufferList {{{2
  1274. function! s:RebuildBufferList()
  1275. setlocal modifiable
  1276. let curPos = getpos('.')
  1277. let num_bufs = s:BuildBufferList()
  1278. call setpos('.', curPos)
  1279. setlocal nomodifiable
  1280. return num_bufs
  1281. endfunction
  1282. " UpdateHelpStatus {{{2
  1283. function! s:UpdateHelpStatus()
  1284. setlocal modifiable
  1285. let text = s:GetHelpStatus()
  1286. call setline(s:firstBufferLine - 2, text)
  1287. setlocal nomodifiable
  1288. endfunction
  1289. " Key_number {{{2
  1290. function! s:Key_number(line)
  1291. let _bufnr = str2nr(a:line)
  1292. let key = [printf('%9d', _bufnr)]
  1293. return key
  1294. endfunction
  1295. " Key_name {{{2
  1296. function! s:Key_name(line)
  1297. let _bufnr = str2nr(a:line)
  1298. let buf = s:raw_buffer_listing[_bufnr]
  1299. let key = [buf.shortname, buf.fullname]
  1300. return key
  1301. endfunction
  1302. " Key_fullpath {{{2
  1303. function! s:Key_fullpath(line)
  1304. let _bufnr = str2nr(a:line)
  1305. let buf = s:raw_buffer_listing[_bufnr]
  1306. let key = [buf.fullname]
  1307. return key
  1308. endfunction
  1309. " Key_extension {{{2
  1310. function! s:Key_extension(line)
  1311. let _bufnr = str2nr(a:line)
  1312. let buf = s:raw_buffer_listing[_bufnr]
  1313. let extension = fnamemodify(buf.shortname, ':e')
  1314. let key = [extension, buf.shortname, buf.fullname]
  1315. return key
  1316. endfunction
  1317. " Key_mru {{{2
  1318. function! s:Key_mru(line)
  1319. let _bufnr = str2nr(a:line)
  1320. let buf = s:raw_buffer_listing[_bufnr]
  1321. let pos = s:MRUOrderForBuf(_bufnr)
  1322. return [printf('%9d', pos), buf.fullname]
  1323. endfunction
  1324. " SortByKeyFunc {{{2
  1325. function! s:SortByKeyFunc(keyFunc)
  1326. let keyedLines = []
  1327. for line in getline(s:firstBufferLine, "$")
  1328. let key = eval(a:keyFunc . '(line)')
  1329. call add(keyedLines, join(key + [line], "\1"))
  1330. endfor
  1331. " Ignore case when sorting by passing `1`:
  1332. call sort(keyedLines, 1)
  1333. if g:bufExplorerReverseSort
  1334. call reverse(keyedLines)
  1335. endif
  1336. let lines = []
  1337. for keyedLine in keyedLines
  1338. call add(lines, split(keyedLine, "\1")[-1])
  1339. endfor
  1340. call setline(s:firstBufferLine, lines)
  1341. endfunction
  1342. " SortReverse {{{2
  1343. function! s:SortReverse()
  1344. let g:bufExplorerReverseSort = !g:bufExplorerReverseSort
  1345. call s:ReSortListing()
  1346. endfunction
  1347. " SortSelect {{{2
  1348. function! s:SortSelect()
  1349. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) + 1, s:sort_by[0])
  1350. call s:ReSortListing()
  1351. endfunction
  1352. " ReverseSortSelect {{{2
  1353. function! s:ReverseSortSelect()
  1354. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) - 1, s:sort_by[-1])
  1355. call s:ReSortListing()
  1356. endfunction
  1357. " ReSortListing {{{2
  1358. function! s:ReSortListing()
  1359. setlocal modifiable
  1360. let curPos = getpos('.')
  1361. call s:SortListing()
  1362. call s:UpdateHelpStatus()
  1363. call setpos('.', curPos)
  1364. setlocal nomodifiable
  1365. endfunction
  1366. " SortListing {{{2
  1367. function! s:SortListing()
  1368. call s:SortByKeyFunc("<SID>Key_" . g:bufExplorerSortBy)
  1369. endfunction
  1370. " Error {{{2
  1371. " Display a message using ErrorMsg highlight group.
  1372. function! s:Error(msg)
  1373. echohl ErrorMsg
  1374. echomsg a:msg
  1375. echohl None
  1376. endfunction
  1377. " Warning {{{2
  1378. " Display a message using WarningMsg highlight group.
  1379. function! s:Warning(msg)
  1380. echohl WarningMsg
  1381. echomsg a:msg
  1382. echohl None
  1383. endfunction
  1384. " GetTabNbr {{{2
  1385. function! s:GetTabNbr(bufNbr)
  1386. " Prefer current tab.
  1387. if bufwinnr(a:bufNbr) > 0
  1388. return tabpagenr()
  1389. endif
  1390. " Searching buffer bufno, in tabs.
  1391. for i in range(tabpagenr("$"))
  1392. if index(tabpagebuflist(i + 1), a:bufNbr) != -1
  1393. return i + 1
  1394. endif
  1395. endfor
  1396. return 0
  1397. endfunction
  1398. " GetWinNbr" {{{2
  1399. function! s:GetWinNbr(tabNbr, bufNbr)
  1400. " window number in tabpage.
  1401. let tablist = tabpagebuflist(a:tabNbr)
  1402. " Number: 0
  1403. " String: 1
  1404. " Funcref: 2
  1405. " List: 3
  1406. " Dictionary: 4
  1407. " Float: 5
  1408. if type(tablist) == 3
  1409. return index(tabpagebuflist(a:tabNbr), a:bufNbr) + 1
  1410. else
  1411. return 1
  1412. endif
  1413. endfunction
  1414. " StringWidth" {{{2
  1415. if exists('*strwidth')
  1416. function s:StringWidth(s)
  1417. return strwidth(a:s)
  1418. endfunction
  1419. else
  1420. function s:StringWidth(s)
  1421. return len(a:s)
  1422. endfunction
  1423. endif
  1424. " Winmanager Integration {{{2
  1425. let g:BufExplorer_title = "\[Buf\ List\]"
  1426. call s:Set("g:bufExplorerResize", 1)
  1427. call s:Set("g:bufExplorerMaxHeight", 25) " Handles dynamic resizing of the window.
  1428. " Evaluate a Vimscript expression in the context of this file.
  1429. " This enables debugging of script-local variables and functions from outside
  1430. " the plugin, e.g.:
  1431. " :echo BufExplorer_eval('s:bufMru')
  1432. function! BufExplorer_eval(expr)
  1433. return eval(a:expr)
  1434. endfunction
  1435. " Execute a Vimscript statement in the context of this file.
  1436. " This enables setting script-local variables from outside the plugin, e.g.:
  1437. " :call BufExplorer_execute('let s:bufMru = s:MRUNew(0)')
  1438. function! BufExplorer_execute(statement)
  1439. execute a:statement
  1440. endfunction
  1441. " function! to start display. Set the mode to 'winmanager' for this buffer.
  1442. " This is to figure out how this plugin was called. In a standalone fashion
  1443. " or by winmanager.
  1444. function! BufExplorer_Start()
  1445. let b:displayMode = "winmanager"
  1446. call s:SetLocalSettings()
  1447. call BufExplorer()
  1448. endfunction
  1449. " Returns whether the display is okay or not.
  1450. function! BufExplorer_IsValid()
  1451. return 0
  1452. endfunction
  1453. " Handles dynamic refreshing of the window.
  1454. function! BufExplorer_Refresh()
  1455. let b:displayMode = "winmanager"
  1456. call s:SetLocalSettings()
  1457. call BufExplorer()
  1458. endfunction
  1459. function! BufExplorer_ReSize()
  1460. if !g:bufExplorerResize
  1461. return
  1462. end
  1463. let nlines = min([line("$"), g:bufExplorerMaxHeight])
  1464. execute nlines." wincmd _"
  1465. " The following lines restore the layout so that the last file line is also
  1466. " the last window line. Sometimes, when a line is deleted, although the
  1467. " window size is exactly equal to the number of lines in the file, some of
  1468. " the lines are pushed up and we see some lagging '~'s.
  1469. let pres = getpos(".")
  1470. normal! $
  1471. let _scr = &scrolloff
  1472. let &scrolloff = 0
  1473. normal! z-
  1474. let &scrolloff = _scr
  1475. call setpos(".", pres)
  1476. endfunction
  1477. " Default values {{{2
  1478. call s:Set("g:bufExplorerDisableDefaultKeyMapping", 0) " Do not disable default key mappings.
  1479. call s:Set("g:bufExplorerDefaultHelp", 1) " Show default help?
  1480. call s:Set("g:bufExplorerDetailedHelp", 0) " Show detailed help?
  1481. call s:Set("g:bufExplorerFindActive", 1) " When selecting an active buffer, take you to the window where it is active?
  1482. call s:Set("g:bufExplorerOnlyOneTab", 1) " Show buffer only on MRU tab? (Applies when `g:bufExplorerShowTabBuffer` is true.)
  1483. call s:Set("g:bufExplorerReverseSort", 0) " Sort in reverse order by default?
  1484. call s:Set("g:bufExplorerShowDirectories", 1) " (Dir's are added by commands like ':e .')
  1485. call s:Set("g:bufExplorerShowRelativePath", 0) " Show listings with relative or absolute paths?
  1486. call s:Set("g:bufExplorerShowTabBuffer", 0) " Show only buffer(s) for this tab?
  1487. call s:Set("g:bufExplorerShowUnlisted", 0) " Show unlisted buffers?
  1488. call s:Set("g:bufExplorerShowNoName", 0) " Show 'No Name' buffers?
  1489. call s:Set("g:bufExplorerSortBy", "mru") " Sorting methods are in s:sort_by:
  1490. call s:Set("g:bufExplorerSplitBelow", &splitbelow) " Should horizontal splits be below or above current window?
  1491. call s:Set("g:bufExplorerSplitOutPathName", 1) " Split out path and file name?
  1492. call s:Set("g:bufExplorerSplitRight", &splitright) " Should vertical splits be on the right or left of current window?
  1493. call s:Set("g:bufExplorerSplitVertSize", 0) " Height for a vertical split. If <=0, default Vim size is used.
  1494. call s:Set("g:bufExplorerSplitHorzSize", 0) " Height for a horizontal split. If <=0, default Vim size is used.
  1495. call s:Set("g:bufExplorerShowTerminal", 1) " Show terminal buffers?
  1496. " Default key mapping {{{2
  1497. if !hasmapto('BufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1498. nnoremap <script> <silent> <unique> <Leader>be :BufExplorer<CR>
  1499. endif
  1500. if !hasmapto('ToggleBufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1501. nnoremap <script> <silent> <unique> <Leader>bt :ToggleBufExplorer<CR>
  1502. endif
  1503. if !hasmapto('BufExplorerHorizontalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1504. nnoremap <script> <silent> <unique> <Leader>bs :BufExplorerHorizontalSplit<CR>
  1505. endif
  1506. if !hasmapto('BufExplorerVerticalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1507. nnoremap <script> <silent> <unique> <Leader>bv :BufExplorerVerticalSplit<CR>
  1508. endif
  1509. " vim:ft=vim foldmethod=marker sw=4