bufexplorer.vim 60 KB

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