bufexplorer.vim 52 KB

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