bufexplorer.vim 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. "============================================================================
  2. " Copyright: Copyright (c) 2001-2025, Jeff Lanzarotta
  3. " All rights reserved.
  4. "
  5. " Redistribution and use in source and binary forms, with or
  6. " without modification, are permitted provided that the
  7. " following conditions are met:
  8. "
  9. " * Redistributions of source code must retain the above
  10. " copyright notice, this list of conditions and the following
  11. " disclaimer.
  12. "
  13. " * Redistributions in binary form must reproduce the above
  14. " copyright notice, this list of conditions and the following
  15. " disclaimer in the documentation and/or other materials
  16. " provided with the distribution.
  17. "
  18. " * Neither the name of the {organization} nor the names of its
  19. " contributors may be used to endorse or promote products
  20. " derived from this software without specific prior written
  21. " permission.
  22. "
  23. " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  24. " CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  25. " INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  26. " MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  27. " DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  28. " CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  29. " SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  30. " NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. " HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  33. " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  34. " OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  35. " EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. " Name Of File: bufexplorer.vim
  37. " Description: Buffer Explorer Vim Plugin
  38. " Maintainer: Jeff Lanzarotta (my name at gmail dot com)
  39. " Last Changed: Monday, 17 February 2025
  40. " Version: See g:bufexplorer_version for version number.
  41. " Usage: This file should reside in the plugin directory and be
  42. " automatically sourced.
  43. "
  44. " You may use the default keymappings of
  45. "
  46. " <Leader>be - Opens BufExplorer
  47. " <Leader>bt - Toggles BufExplorer open or closed
  48. " <Leader>bs - Opens horizontally split window BufExplorer
  49. " <Leader>bv - Opens vertically split window BufExplorer
  50. "
  51. " Or you can override the defaults and define your own mapping
  52. " in your vimrc file, for example:
  53. "
  54. " nnoremap <silent> <F11> :BufExplorer<CR>
  55. " nnoremap <silent> <s-F11> :ToggleBufExplorer<CR>
  56. " nnoremap <silent> <m-F11> :BufExplorerHorizontalSplit<CR>
  57. " nnoremap <silent> <c-F11> :BufExplorerVerticalSplit<CR>
  58. "
  59. " Or you can use
  60. "
  61. " ":BufExplorer" - Opens BufExplorer
  62. " ":ToggleBufExplorer" - Opens/Closes BufExplorer
  63. " ":BufExplorerHorizontalSplit" - Opens horizontally window BufExplorer
  64. " ":BufExplorerVerticalSplit" - Opens vertically split window BufExplorer
  65. "
  66. " For more help see supplied documentation.
  67. " History: See supplied documentation.
  68. "=============================================================================
  69. " Exit quickly if already running or when 'compatible' is set. {{{1
  70. if exists("g:bufexplorer_version") || &cp
  71. finish
  72. endif
  73. "1}}}
  74. " Version number
  75. let g:bufexplorer_version = "7.6.0"
  76. " Plugin Code {{{1
  77. " Check for Vim version {{{2
  78. if !exists("g:bufExplorerVersionWarn")
  79. let g:bufExplorerVersionWarn = 1
  80. endif
  81. if v:version < 700
  82. if g:bufExplorerVersionWarn
  83. echohl WarningMsg
  84. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.0 or greater."
  85. echohl None
  86. endif
  87. finish
  88. endif
  89. " Check to see if the version of Vim has the correct patch applied, if not, do
  90. " not used <nowait>.
  91. if v:version > 703 || v:version == 703 && has('patch1261') && has('patch1264')
  92. " We are good to go.
  93. else
  94. if g:bufExplorerVersionWarn
  95. echohl WarningMsg
  96. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.3 or greater with patch1261 and patch1264."
  97. echohl None
  98. endif
  99. finish
  100. endif
  101. " Create commands {{{2
  102. command! BufExplorer :call BufExplorer()
  103. command! ToggleBufExplorer :call ToggleBufExplorer()
  104. command! BufExplorerHorizontalSplit :call BufExplorerHorizontalSplit()
  105. command! BufExplorerVerticalSplit :call BufExplorerVerticalSplit()
  106. " Set {{{2
  107. function! s:Set(var, default)
  108. if !exists(a:var)
  109. if type(a:default)
  110. execute "let" a:var "=" string(a:default)
  111. else
  112. execute "let" a:var "=" a:default
  113. endif
  114. return 1
  115. endif
  116. return 0
  117. endfunction
  118. " Script variables {{{2
  119. let s:MRU_Exclude_List = ["[BufExplorer]","__MRU_Files__","[Buf\ List]"]
  120. let s:name = '[BufExplorer]'
  121. let s:originBuffer = 0
  122. let s:running = 0
  123. let s:sort_by = ["number", "name", "fullpath", "mru", "extension"]
  124. let s:splitMode = ""
  125. let s:didSplit = 0
  126. let s:types = ["fullname", "homename", "path", "relativename", "relativepath", "shortname"]
  127. " Setup the autocommands that handle stuff. {{{2
  128. autocmd VimEnter * call s:Setup()
  129. " Setup {{{2
  130. function! s:Setup()
  131. " Add the other autocmds.
  132. augroup BufExplorer
  133. autocmd!
  134. autocmd WinEnter * call s:DoWinEnter()
  135. autocmd BufEnter * call s:DoBufEnter()
  136. autocmd BufDelete * call s:DoBufDelete()
  137. autocmd BufWinEnter \[BufExplorer\] call s:Initialize()
  138. autocmd BufWinLeave \[BufExplorer\] call s:Cleanup()
  139. augroup END
  140. endfunction
  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. " DoWinEnter {{{2
  395. function! s:DoWinEnter()
  396. let bufNbr = str2nr(expand("<abuf>"))
  397. let tabNbr = tabpagenr()
  398. let tabId = s:GetTabId(tabNbr)
  399. " Ignore `WinEnter` for a newly created tab; this event comes when creating
  400. " a new tab, and the buffer at that moment is one that is about to be
  401. " replaced by the buffer to which we are switching; this latter buffer will
  402. " be handled by the forthcoming `BufEnter` event.
  403. if tabId != ''
  404. call s:MRUAddBufTab(bufNbr, tabId)
  405. endif
  406. endfunction
  407. " DoBufEnter {{{2
  408. function! s:DoBufEnter()
  409. let bufNbr = str2nr(expand("<abuf>"))
  410. let tabNbr = tabpagenr()
  411. let tabId = s:MRUEnsureTabId(tabNbr)
  412. call s:MRUAddBufTab(bufNbr, tabId)
  413. endfunction
  414. " DoBufDelete {{{2
  415. function! s:DoBufDelete()
  416. let bufNbr = str2nr(expand("<abuf>"))
  417. call s:MRURemoveBuf(bufNbr)
  418. endfunction
  419. " ShouldIgnore {{{2
  420. function! s:ShouldIgnore(buf)
  421. " Ignore temporary buffers with buftype set.
  422. if empty(getbufvar(a:buf, "&buftype")) == 0
  423. return 1
  424. endif
  425. " Ignore buffers with no name.
  426. if empty(bufname(a:buf)) == 1
  427. return 1
  428. endif
  429. " Ignore the BufExplorer buffer.
  430. if fnamemodify(bufname(a:buf), ":t") == s:name
  431. return 1
  432. endif
  433. " Ignore any buffers in the exclude list.
  434. if index(s:MRU_Exclude_List, bufname(a:buf)) >= 0
  435. return 1
  436. endif
  437. " Else return 0 to indicate that the buffer was not ignored.
  438. return 0
  439. endfunction
  440. " Initialize {{{2
  441. function! s:Initialize()
  442. call s:SetLocalSettings()
  443. let s:running = 1
  444. endfunction
  445. " Cleanup {{{2
  446. function! s:Cleanup()
  447. if exists("s:_insertmode")
  448. let &insertmode = s:_insertmode
  449. endif
  450. if exists("s:_showcmd")
  451. let &showcmd = s:_showcmd
  452. endif
  453. if exists("s:_cpo")
  454. let &cpo = s:_cpo
  455. endif
  456. if exists("s:_report")
  457. let &report = s:_report
  458. endif
  459. let s:running = 0
  460. let s:splitMode = ""
  461. let s:didSplit = 0
  462. delmarks!
  463. endfunction
  464. " SetLocalSettings {{{2
  465. function! s:SetLocalSettings()
  466. let s:_insertmode = &insertmode
  467. set noinsertmode
  468. let s:_showcmd = &showcmd
  469. set noshowcmd
  470. let s:_cpo = &cpo
  471. set cpo&vim
  472. let s:_report = &report
  473. let &report = 10000
  474. setlocal nonumber
  475. setlocal foldcolumn=0
  476. setlocal nofoldenable
  477. setlocal cursorline
  478. setlocal nospell
  479. setlocal nobuflisted
  480. setlocal filetype=bufexplorer
  481. endfunction
  482. " BufExplorerHorizontalSplit {{{2
  483. function! BufExplorerHorizontalSplit()
  484. let s:splitMode = "sp"
  485. execute "BufExplorer"
  486. let s:splitMode = ""
  487. endfunction
  488. " BufExplorerVerticalSplit {{{2
  489. function! BufExplorerVerticalSplit()
  490. let s:splitMode = "vsp"
  491. execute "BufExplorer"
  492. let s:splitMode = ""
  493. endfunction
  494. " ToggleBufExplorer {{{2
  495. function! ToggleBufExplorer()
  496. if exists("s:running") && s:running == 1 && bufname(winbufnr(0)) == s:name
  497. call s:Close()
  498. else
  499. call BufExplorer()
  500. endif
  501. endfunction
  502. " BufExplorer {{{2
  503. function! BufExplorer()
  504. let name = s:name
  505. if !has("win32")
  506. " On non-Windows boxes, escape the name so that is shows up correctly.
  507. let name = escape(name, "[]")
  508. endif
  509. " Make sure there is only one explorer open at a time.
  510. if s:running == 1
  511. " Go to the open buffer.
  512. if has("gui")
  513. execute "drop" name
  514. endif
  515. return
  516. endif
  517. " Add zero to ensure the variable is treated as a number.
  518. let s:originBuffer = bufnr("%") + 0
  519. let s:tabIdAtLaunch = s:MRUEnsureTabId(tabpagenr())
  520. " Forget any cached MRU ordering from previous invocations.
  521. unlet! s:mruOrder
  522. silent let s:raw_buffer_listing = s:GetBufferInfo(0)
  523. " We may have to split the current window.
  524. if s:splitMode != ""
  525. " Save off the original settings.
  526. let [_splitbelow, _splitright] = [&splitbelow, &splitright]
  527. " Set the setting to ours.
  528. let [&splitbelow, &splitright] = [g:bufExplorerSplitBelow, g:bufExplorerSplitRight]
  529. let _size = (s:splitMode == "sp") ? g:bufExplorerSplitHorzSize : g:bufExplorerSplitVertSize
  530. " Split the window either horizontally or vertically.
  531. if _size <= 0
  532. execute 'keepalt ' . s:splitMode
  533. else
  534. execute 'keepalt ' . _size . s:splitMode
  535. endif
  536. " Restore the original settings.
  537. let [&splitbelow, &splitright] = [_splitbelow, _splitright]
  538. " Remember that a split was triggered
  539. let s:didSplit = 1
  540. endif
  541. if !exists("b:displayMode") || b:displayMode != "winmanager"
  542. " Do not use keepalt when opening bufexplorer to allow the buffer that
  543. " we are leaving to become the new alternate buffer
  544. execute "silent keepjumps hide edit".name
  545. endif
  546. call s:DisplayBufferList()
  547. " Position the cursor in the newly displayed list on the line representing
  548. " the active buffer. The active buffer is the line with the '%' character
  549. " in it.
  550. execute search("%")
  551. endfunction
  552. " Tracks `tabId` at BufExplorer launch.
  553. let s:tabIdAtLaunch = ''
  554. " DisplayBufferList {{{2
  555. function! s:DisplayBufferList()
  556. setlocal buftype=nofile
  557. setlocal modifiable
  558. setlocal noreadonly
  559. setlocal noswapfile
  560. setlocal nowrap
  561. setlocal bufhidden=wipe
  562. call s:SetupSyntax()
  563. call s:MapKeys()
  564. " Wipe out any existing lines in case BufExplorer buffer exists and the
  565. " user had changed any global settings that might reduce the number of
  566. " lines needed in the buffer.
  567. silent keepjumps 1,$d _
  568. call setline(1, s:CreateHelp())
  569. call s:BuildBufferList()
  570. call cursor(s:firstBufferLine, 1)
  571. if !g:bufExplorerResize
  572. normal! zz
  573. endif
  574. setlocal nomodifiable
  575. endfunction
  576. " MapKeys {{{2
  577. function! s:MapKeys()
  578. if exists("b:displayMode") && b:displayMode == "winmanager"
  579. nnoremap <buffer> <silent> <tab> :call <SID>SelectBuffer()<CR>
  580. endif
  581. nnoremap <script> <silent> <nowait> <buffer> <2-leftmouse> :call <SID>SelectBuffer()<CR>
  582. nnoremap <script> <silent> <nowait> <buffer> <CR> :call <SID>SelectBuffer()<CR>
  583. nnoremap <script> <silent> <nowait> <buffer> <F1> :call <SID>ToggleHelp()<CR>
  584. nnoremap <script> <silent> <nowait> <buffer> <s-cr> :call <SID>SelectBuffer("tab")<CR>
  585. nnoremap <script> <silent> <nowait> <buffer> a :call <SID>ToggleFindActive()<CR>
  586. nnoremap <script> <silent> <nowait> <buffer> b :call <SID>SelectBuffer("ask")<CR>
  587. nnoremap <script> <silent> <nowait> <buffer> B :call <SID>ToggleOnlyOneTab()<CR>
  588. nnoremap <script> <silent> <nowait> <buffer> d :call <SID>RemoveBuffer("delete")<CR>
  589. xnoremap <script> <silent> <nowait> <buffer> d :call <SID>RemoveBuffer("delete")<CR>
  590. nnoremap <script> <silent> <nowait> <buffer> D :call <SID>RemoveBuffer("wipe")<CR>
  591. xnoremap <script> <silent> <nowait> <buffer> D :call <SID>RemoveBuffer("wipe")<CR>
  592. nnoremap <script> <silent> <nowait> <buffer> f :call <SID>SelectBuffer("split", "sb")<CR>
  593. nnoremap <script> <silent> <nowait> <buffer> F :call <SID>SelectBuffer("split", "st")<CR>
  594. nnoremap <script> <silent> <nowait> <buffer> o :call <SID>SelectBuffer()<CR>
  595. nnoremap <script> <silent> <nowait> <buffer> p :call <SID>ToggleSplitOutPathName()<CR>
  596. nnoremap <script> <silent> <nowait> <buffer> q :call <SID>Close()<CR>
  597. nnoremap <script> <silent> <nowait> <buffer> r :call <SID>SortReverse()<CR>
  598. nnoremap <script> <silent> <nowait> <buffer> R :call <SID>ToggleShowRelativePath()<CR>
  599. nnoremap <script> <silent> <nowait> <buffer> s :call <SID>SortSelect()<CR>
  600. nnoremap <script> <silent> <nowait> <buffer> S :call <SID>ReverseSortSelect()<CR>
  601. nnoremap <script> <silent> <nowait> <buffer> t :call <SID>SelectBuffer("tab")<CR>
  602. nnoremap <script> <silent> <nowait> <buffer> T :call <SID>ToggleShowTabBuffer()<CR>
  603. nnoremap <script> <silent> <nowait> <buffer> u :call <SID>ToggleShowUnlisted()<CR>
  604. nnoremap <script> <silent> <nowait> <buffer> v :call <SID>SelectBuffer("split", "vr")<CR>
  605. nnoremap <script> <silent> <nowait> <buffer> V :call <SID>SelectBuffer("split", "vl")<CR>
  606. nnoremap <script> <silent> <nowait> <buffer> H :call <SID>ToggleShowTerminal()<CR>
  607. for k in ["G", "n", "N", "L", "M", "H"]
  608. execute "nnoremap <buffer> <silent>" k ":keepjumps normal!" k."<CR>"
  609. endfor
  610. endfunction
  611. " SetupSyntax {{{2
  612. function! s:SetupSyntax()
  613. if has("syntax")
  614. syn match bufExplorerHelp "^\".*" contains=bufExplorerSortBy,bufExplorerMapping,bufExplorerTitle,bufExplorerSortType,bufExplorerToggleSplit,bufExplorerToggleOpen
  615. syn match bufExplorerOpenIn "Open in \w\+ window" contained
  616. syn match bufExplorerSplit "\w\+ split" contained
  617. syn match bufExplorerSortBy "Sorted by .*" contained contains=bufExplorerOpenIn,bufExplorerSplit
  618. syn match bufExplorerMapping "\" \zs.\+\ze :" contained
  619. syn match bufExplorerTitle "Buffer Explorer.*" contained
  620. syn match bufExplorerSortType "'\w\{-}'" contained
  621. syn match bufExplorerBufNbr /^\s*\d\+/
  622. syn match bufExplorerToggleSplit "toggle split type" contained
  623. syn match bufExplorerToggleOpen "toggle open mode" contained
  624. syn match bufExplorerModBuf /^\s*\d\+.\{4}+.*/
  625. syn match bufExplorerLockedBuf /^\s*\d\+.\{3}[\-=].*/
  626. syn match bufExplorerHidBuf /^\s*\d\+.\{2}h.*/
  627. syn match bufExplorerActBuf /^\s*\d\+.\{2}a.*/
  628. syn match bufExplorerCurBuf /^\s*\d\+.%.*/
  629. syn match bufExplorerAltBuf /^\s*\d\+.#.*/
  630. syn match bufExplorerUnlBuf /^\s*\d\+u.*/
  631. syn match bufExplorerInactBuf /^\s*\d\+ \{7}.*/
  632. hi def link bufExplorerBufNbr Number
  633. hi def link bufExplorerMapping NonText
  634. hi def link bufExplorerHelp Special
  635. hi def link bufExplorerOpenIn Identifier
  636. hi def link bufExplorerSortBy String
  637. hi def link bufExplorerSplit NonText
  638. hi def link bufExplorerTitle NonText
  639. hi def link bufExplorerSortType bufExplorerSortBy
  640. hi def link bufExplorerToggleSplit bufExplorerSplit
  641. hi def link bufExplorerToggleOpen bufExplorerOpenIn
  642. hi def link bufExplorerActBuf Identifier
  643. hi def link bufExplorerAltBuf String
  644. hi def link bufExplorerCurBuf Type
  645. hi def link bufExplorerHidBuf Constant
  646. hi def link bufExplorerLockedBuf Special
  647. hi def link bufExplorerModBuf Exception
  648. hi def link bufExplorerUnlBuf Comment
  649. hi def link bufExplorerInactBuf Comment
  650. endif
  651. endfunction
  652. " ToggleHelp {{{2
  653. function! s:ToggleHelp()
  654. let g:bufExplorerDetailedHelp = !g:bufExplorerDetailedHelp
  655. setlocal modifiable
  656. " Save position.
  657. normal! ma
  658. " Remove old header.
  659. if s:firstBufferLine > 1
  660. execute "keepjumps 1,".(s:firstBufferLine - 1) "d _"
  661. endif
  662. call append(0, s:CreateHelp())
  663. silent! normal! g`a
  664. delmarks a
  665. setlocal nomodifiable
  666. if exists("b:displayMode") && b:displayMode == "winmanager"
  667. call WinManagerForceReSize("BufExplorer")
  668. endif
  669. endfunction
  670. " GetHelpStatus {{{2
  671. function! s:GetHelpStatus()
  672. let ret = '" Sorted by '.((g:bufExplorerReverseSort == 1) ? "reverse " : "").g:bufExplorerSortBy
  673. let ret .= ' | '.((g:bufExplorerFindActive == 0) ? "Don't " : "")."Locate buffer"
  674. let ret .= ((g:bufExplorerShowUnlisted == 0) ? "" : " | Show unlisted")
  675. let ret .= ((g:bufExplorerShowTabBuffer == 0) ? "" : " | Show buffers/tab")
  676. let ret .= ((g:bufExplorerOnlyOneTab == 0) ? "" : " | One tab/buffer")
  677. let ret .= ' | '.((g:bufExplorerShowRelativePath == 0) ? "Absolute" : "Relative")
  678. let ret .= ' '.((g:bufExplorerSplitOutPathName == 0) ? "Full" : "Split")." path"
  679. let ret .= ((g:bufExplorerShowTerminal == 0) ? "" : " | Show terminal")
  680. return ret
  681. endfunction
  682. " CreateHelp {{{2
  683. function! s:CreateHelp()
  684. if g:bufExplorerDefaultHelp == 0 && g:bufExplorerDetailedHelp == 0
  685. let s:firstBufferLine = 1
  686. return []
  687. endif
  688. let header = []
  689. if g:bufExplorerDetailedHelp == 1
  690. call add(header, '" Buffer Explorer ('.g:bufexplorer_version.')')
  691. call add(header, '" --------------------------')
  692. call add(header, '" <F1> : toggle this help')
  693. call add(header, '" <enter> or o or Mouse-Double-Click : open buffer under cursor')
  694. call add(header, '" <shift-enter> or t : open buffer in another tab')
  695. call add(header, '" a : toggle find active buffer')
  696. call add(header, '" b : Fast buffer switching with b<any bufnum>')
  697. call add(header, '" B : toggle if to save/use recent tab or not')
  698. call add(header, '" d : delete buffer')
  699. call add(header, '" D : wipe buffer')
  700. call add(header, '" F : open buffer in another window above the current')
  701. call add(header, '" f : open buffer in another window below the current')
  702. call add(header, '" p : toggle splitting of file and path name')
  703. call add(header, '" q : quit')
  704. call add(header, '" r : reverse sort')
  705. call add(header, '" R : toggle showing relative or full paths')
  706. call add(header, '" s : cycle thru "sort by" fields '.string(s:sort_by).'')
  707. call add(header, '" S : reverse cycle thru "sort by" fields')
  708. call add(header, '" T : toggle if to show only buffers for this tab or not')
  709. call add(header, '" u : toggle showing unlisted buffers')
  710. call add(header, '" V : open buffer in another window on the left of the current')
  711. call add(header, '" v : open buffer in another window on the right of the current')
  712. else
  713. call add(header, '" Press <F1> for Help')
  714. endif
  715. if (!exists("b:displayMode") || b:displayMode != "winmanager") || (b:displayMode == "winmanager" && g:bufExplorerDetailedHelp == 1)
  716. call add(header, s:GetHelpStatus())
  717. call add(header, '"=')
  718. endif
  719. let s:firstBufferLine = len(header) + 1
  720. return header
  721. endfunction
  722. " CalculateBufferDetails {{{2
  723. " Calculate `buf`-related details.
  724. function! s:CalculateBufferDetails(buf)
  725. let buf = a:buf
  726. let name = bufname(buf._bufnr)
  727. let buf["hasNoName"] = empty(name)
  728. if buf.hasNoName
  729. let name = "[No Name]"
  730. endif
  731. let buf.isterminal = getbufvar(buf._bufnr, '&buftype') == 'terminal'
  732. if buf.isterminal
  733. let buf.fullname = name
  734. let buf.isdir = 0
  735. else
  736. let buf.fullname = simplify(fnamemodify(name, ':p'))
  737. let buf.isdir = getftype(buf.fullname) == "dir"
  738. endif
  739. if buf.isdir
  740. " `buf.fullname` ends with a path separator; this will be
  741. " removed via the first `:h` applied to `buf.fullname` (except
  742. " for the root directory, where the path separator will remain).
  743. let parent = fnamemodify(buf.fullname, ':h:h')
  744. let buf.shortname = fnamemodify(buf.fullname, ':h:t')
  745. " Special case for root directory: fnamemodify('/', ':h:t') == ''
  746. if buf.shortname == ''
  747. let buf.shortname = '.'
  748. endif
  749. " Must perform shortening (`:~`, `:.`) before `:h`.
  750. let buf.homename = fnamemodify(buf.fullname, ':~:h')
  751. let buf.relativename = fnamemodify(buf.fullname, ':~:.:h')
  752. else
  753. let parent = fnamemodify(buf.fullname, ':h')
  754. let buf.shortname = fnamemodify(buf.fullname, ':t')
  755. let buf.homename = fnamemodify(buf.fullname, ':~')
  756. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  757. endif
  758. " `:p` on `parent` adds back the path separator which permits more
  759. " effective shortening (`:~`, `:.`), but `:h` is required afterward
  760. " to trim this separator.
  761. let buf.path = fnamemodify(parent, ':p:~:h')
  762. let buf.relativepath = fnamemodify(parent, ':p:~:.:h')
  763. endfunction
  764. " GetBufferInfo {{{2
  765. function! s:GetBufferInfo(bufnr)
  766. redir => bufoutput
  767. " Show all buffers including the unlisted ones. [!] tells Vim to show the
  768. " unlisted ones.
  769. buffers!
  770. redir END
  771. if a:bufnr > 0
  772. " Since we are only interested in this specified buffer remove the
  773. " other buffers listed.
  774. let bufoutput = substitute(bufoutput."\n", '^.*\n\(\s*'.a:bufnr.'\>.\{-}\)\n.*', '\1', '')
  775. endif
  776. let all = {}
  777. " Loop over each line in the buffer.
  778. for line in split(bufoutput, '\n')
  779. let bits = split(line, '"')
  780. " Use first and last components after the split on '"', in case a
  781. " filename with an embedded '"' is present.
  782. let buf = {"attributes": bits[0], "line": substitute(bits[-1], '\s*', '', '')}
  783. let buf._bufnr = str2nr(buf.attributes)
  784. let all[buf._bufnr] = buf
  785. endfor
  786. return all
  787. endfunction
  788. " BuildBufferList {{{2
  789. function! s:BuildBufferList()
  790. let table = []
  791. " Loop through every buffer.
  792. for buf in values(s:raw_buffer_listing)
  793. " `buf.attributes` must exist, but we defer the expensive work of
  794. " calculating other buffer details (e.g., `buf.fullname`) until we know
  795. " the user wants to view this buffer.
  796. " Skip unlisted buffers if we are not to show them.
  797. if !g:bufExplorerShowUnlisted && buf.attributes =~ "u"
  798. " Skip unlisted buffers if we are not to show them.
  799. continue
  800. endif
  801. " Ensure buffer details are computed for this buffer.
  802. if !has_key(buf, 'fullname')
  803. call s:CalculateBufferDetails(buf)
  804. endif
  805. " Skip 'No Name' buffers if we are not to show them.
  806. if g:bufExplorerShowNoName == 0 && buf.hasNoName
  807. continue
  808. endif
  809. " Should we show this buffer in this tab?
  810. if !s:MRUTabShouldShowBuf(s:tabIdAtLaunch, buf._bufnr)
  811. continue
  812. endif
  813. " Skip terminal buffers if we are not to show them.
  814. if !g:bufExplorerShowTerminal && buf.isterminal
  815. continue
  816. endif
  817. " Skip directory buffers if we are not to show them.
  818. if !g:bufExplorerShowDirectories && buf.isdir
  819. continue
  820. endif
  821. let row = [buf.attributes]
  822. if exists("g:loaded_webdevicons")
  823. let row += [WebDevIconsGetFileTypeSymbol(buf.fullname, buf.isdir)]
  824. endif
  825. " Are we to split the path and file name?
  826. if g:bufExplorerSplitOutPathName
  827. let type = (g:bufExplorerShowRelativePath) ? "relativepath" : "path"
  828. let row += [buf.shortname, buf[type]]
  829. else
  830. let type = (g:bufExplorerShowRelativePath) ? "relativename" : "homename"
  831. let row += [buf[type]]
  832. endif
  833. let row += [buf.line]
  834. call add(table, row)
  835. endfor
  836. let lines = s:MakeLines(table)
  837. call setline(s:firstBufferLine, lines)
  838. let firstMissingLine = s:firstBufferLine + len(lines)
  839. if line('$') >= firstMissingLine
  840. " Clear excess lines starting with `firstMissingLine`.
  841. execute "silent keepjumps ".firstMissingLine.',$d _'
  842. endif
  843. call s:SortListing()
  844. endfunction
  845. " MakeLines {{{2
  846. function! s:MakeLines(table)
  847. if len(a:table) == 0
  848. return []
  849. endif
  850. let lines = []
  851. " To avoid trailing whitespace, do not pad the final column.
  852. let numColumnsToPad = len(a:table[0]) - 1
  853. let maxWidths = repeat([0], numColumnsToPad)
  854. for row in a:table
  855. let i = 0
  856. while i < numColumnsToPad
  857. let maxWidths[i] = max([maxWidths[i], s:StringWidth(row[i])])
  858. let i = i + 1
  859. endwhile
  860. endfor
  861. let pads = []
  862. for w in maxWidths
  863. call add(pads, repeat(' ', w))
  864. endfor
  865. for row in a:table
  866. let i = 0
  867. while i < numColumnsToPad
  868. let row[i] .= strpart(pads[i], s:StringWidth(row[i]))
  869. let i = i + 1
  870. endwhile
  871. call add(lines, join(row, ' '))
  872. endfor
  873. return lines
  874. endfunction
  875. " SelectBuffer {{{2
  876. function! s:SelectBuffer(...)
  877. " Sometimes messages are not cleared when we get here so it looks like an
  878. " error has occurred when it really has not.
  879. "echo ""
  880. let _bufNbr = -1
  881. if (a:0 == 1) && (a:1 == "ask")
  882. " Ask the user for input.
  883. call inputsave()
  884. let cmd = input("Enter buffer number to switch to: ")
  885. call inputrestore()
  886. " Clear the message area from the previous prompt.
  887. redraw | echo
  888. if strlen(cmd) > 0
  889. let _bufNbr = str2nr(cmd)
  890. else
  891. call s:Error("Invalid buffer number, try again.")
  892. return
  893. endif
  894. else
  895. " Are we on a line with a file name?
  896. if line('.') < s:firstBufferLine
  897. execute "normal! \<CR>"
  898. return
  899. endif
  900. let _bufNbr = str2nr(getline('.'))
  901. " Check and see if we are running BufferExplorer via WinManager.
  902. if exists("b:displayMode") && b:displayMode == "winmanager"
  903. let _bufName = expand("#"._bufNbr.":p")
  904. if (a:0 == 1) && (a:1 == "tab")
  905. call WinManagerFileEdit(_bufName, 1)
  906. else
  907. call WinManagerFileEdit(_bufName, 0)
  908. endif
  909. return
  910. endif
  911. endif
  912. if bufexists(_bufNbr)
  913. " Get the tab number where this buffer is located in.
  914. let tabNbr = s:GetTabNbr(_bufNbr)
  915. if exists("g:bufExplorerChgWin") && g:bufExplorerChgWin <=winnr("$")
  916. execute g:bufExplorerChgWin."wincmd w"
  917. execute "keepjumps keepalt silent b!" _bufNbr
  918. " Are we supposed to open the selected buffer in a tab?
  919. elseif (a:0 == 1) && (a:1 == "tab")
  920. call s:Close()
  921. " Open a new tab with the selected buffer in it.
  922. if v:version > 704 || ( v:version == 704 && has('patch2237') )
  923. " new syntax for last tab as of 7.4.2237
  924. execute "$tab split +buffer" . _bufNbr
  925. else
  926. execute "999tab split +buffer" . _bufNbr
  927. endif
  928. " Are we supposed to open the selected buffer in a split?
  929. elseif (a:0 == 2) && (a:1 == "split")
  930. call s:Close()
  931. if (a:2 == "vl")
  932. execute "vert topleft sb "._bufNbr
  933. elseif (a:2 == "vr")
  934. execute "vert belowright sb "._bufNbr
  935. elseif (a:2 == "st")
  936. execute "topleft sb "._bufNbr
  937. else " = sb
  938. execute "belowright sb "._bufNbr
  939. endif
  940. else
  941. " Request to open in current (BufExplorer) window.
  942. if g:bufExplorerFindActive && tabNbr > 0
  943. " Close BufExplorer window and switch to existing tab/window.
  944. call s:Close()
  945. execute tabNbr . "tabnext"
  946. execute bufwinnr(_bufNbr) . "wincmd w"
  947. else
  948. " Use BufExplorer window for the buffer.
  949. execute "keepjumps keepalt silent b!" _bufNbr
  950. endif
  951. endif
  952. " Make the buffer 'listed' again.
  953. call setbufvar(_bufNbr, "&buflisted", "1")
  954. " Call any associated function references. g:bufExplorerFuncRef may be
  955. " an individual function reference or it may be a list containing
  956. " function references. It will ignore anything that's not a function
  957. " reference.
  958. "
  959. " See :help FuncRef for more on function references.
  960. if exists("g:BufExplorerFuncRef")
  961. if type(g:BufExplorerFuncRef) == 2
  962. keepj call g:BufExplorerFuncRef()
  963. elseif type(g:BufExplorerFuncRef) == 3
  964. for FncRef in g:BufExplorerFuncRef
  965. if type(FncRef) == 2
  966. keepj call FncRef()
  967. endif
  968. endfor
  969. endif
  970. endif
  971. else
  972. call s:Error("Sorry, that buffer no longer exists, please select another")
  973. call s:DeleteBuffer(_bufNbr, "wipe")
  974. endif
  975. endfunction
  976. " RemoveBuffer {{{2
  977. function! s:RemoveBuffer(mode)
  978. " Are we on a line with a file name?
  979. if line('.') < s:firstBufferLine
  980. return
  981. endif
  982. let mode = a:mode
  983. " These commands are to temporarily suspend the activity of winmanager.
  984. if exists("b:displayMode") && b:displayMode == "winmanager"
  985. call WinManagerSuspendAUs()
  986. end
  987. let _bufNbr = str2nr(getline('.'))
  988. if getbufvar(_bufNbr, '&modified') == 1
  989. " Calling confirm() requires Vim built with dialog option.
  990. if !has("dialog_con") && !has("dialog_gui")
  991. call s:Error("Sorry, no write since last change for buffer "._bufNbr.", unable to delete")
  992. return
  993. endif
  994. let answer = confirm('No write since last change for buffer '._bufNbr.'. Delete anyway?', "&Yes\n&No", 2)
  995. if a:mode == "delete" && answer == 1
  996. let mode = "force_delete"
  997. elseif a:mode == "wipe" && answer == 1
  998. let mode = "force_wipe"
  999. else
  1000. return
  1001. endif
  1002. endif
  1003. " Okay, everything is good, delete or wipe the buffer.
  1004. call s:DeleteBuffer(_bufNbr, mode)
  1005. " Reactivate winmanager autocommand activity.
  1006. if exists("b:displayMode") && b:displayMode == "winmanager"
  1007. call WinManagerForceReSize("BufExplorer")
  1008. call WinManagerResumeAUs()
  1009. end
  1010. endfunction
  1011. " DeleteBuffer {{{2
  1012. function! s:DeleteBuffer(buf, mode)
  1013. " This routine assumes that the buffer to be removed is on the current line.
  1014. try
  1015. " Wipe/Delete buffer from Vim.
  1016. if a:mode == "wipe"
  1017. execute "silent bwipe" a:buf
  1018. elseif a:mode == "force_wipe"
  1019. execute "silent bwipe!" a:buf
  1020. elseif a:mode == "force_delete"
  1021. execute "silent bdelete!" a:buf
  1022. else
  1023. execute "silent bdelete" a:buf
  1024. endif
  1025. " Delete the buffer from the list on screen.
  1026. setlocal modifiable
  1027. normal! "_dd
  1028. setlocal nomodifiable
  1029. " Delete the buffer from the raw buffer list.
  1030. unlet s:raw_buffer_listing[a:buf]
  1031. catch
  1032. call s:Error(v:exception)
  1033. endtry
  1034. endfunction
  1035. " Close {{{2
  1036. function! s:Close()
  1037. " Get only the listed buffers associated with the current tab (up to 2).
  1038. let listed = s:MRUListedBuffersForTab(s:tabIdAtLaunch, 2)
  1039. " If we needed to split the main window, close the split one.
  1040. if s:didSplit
  1041. execute "wincmd c"
  1042. endif
  1043. " Check to see if there are anymore buffers listed.
  1044. if len(listed) == 0
  1045. " Since there are no buffers left to switch to, open a new empty
  1046. " buffers.
  1047. execute "enew"
  1048. else
  1049. " Since there are buffers left to switch to, switch to the previous and
  1050. " then the current.
  1051. for b in reverse(listed[0:1])
  1052. execute "keepjumps silent b ".b
  1053. endfor
  1054. endif
  1055. " Clear any messages.
  1056. echo
  1057. endfunction
  1058. " ToggleShowTerminal {{{2
  1059. function! s:ToggleShowTerminal()
  1060. let g:bufExplorerShowTerminal = !g:bufExplorerShowTerminal
  1061. call s:RebuildBufferList()
  1062. call s:UpdateHelpStatus()
  1063. endfunction
  1064. " ToggleSplitOutPathName {{{2
  1065. function! s:ToggleSplitOutPathName()
  1066. let g:bufExplorerSplitOutPathName = !g:bufExplorerSplitOutPathName
  1067. call s:RebuildBufferList()
  1068. call s:UpdateHelpStatus()
  1069. endfunction
  1070. " ToggleShowRelativePath {{{2
  1071. function! s:ToggleShowRelativePath()
  1072. let g:bufExplorerShowRelativePath = !g:bufExplorerShowRelativePath
  1073. call s:RebuildBufferList()
  1074. call s:UpdateHelpStatus()
  1075. endfunction
  1076. " ToggleShowTabBuffer {{{2
  1077. function! s:ToggleShowTabBuffer()
  1078. " Forget any cached MRU ordering, as it depends on
  1079. " `g:bufExplorerShowTabBuffer`.
  1080. unlet! s:mruOrder
  1081. let g:bufExplorerShowTabBuffer = !g:bufExplorerShowTabBuffer
  1082. call s:RebuildBufferList()
  1083. call s:UpdateHelpStatus()
  1084. endfunction
  1085. " ToggleOnlyOneTab {{{2
  1086. function! s:ToggleOnlyOneTab()
  1087. let g:bufExplorerOnlyOneTab = !g:bufExplorerOnlyOneTab
  1088. call s:RebuildBufferList()
  1089. call s:UpdateHelpStatus()
  1090. endfunction
  1091. " ToggleShowUnlisted {{{2
  1092. function! s:ToggleShowUnlisted()
  1093. let g:bufExplorerShowUnlisted = !g:bufExplorerShowUnlisted
  1094. let num_bufs = s:RebuildBufferList()
  1095. call s:UpdateHelpStatus()
  1096. endfunction
  1097. " ToggleFindActive {{{2
  1098. function! s:ToggleFindActive()
  1099. let g:bufExplorerFindActive = !g:bufExplorerFindActive
  1100. call s:UpdateHelpStatus()
  1101. endfunction
  1102. " RebuildBufferList {{{2
  1103. function! s:RebuildBufferList()
  1104. setlocal modifiable
  1105. let curPos = getpos('.')
  1106. let num_bufs = s:BuildBufferList()
  1107. call setpos('.', curPos)
  1108. setlocal nomodifiable
  1109. return num_bufs
  1110. endfunction
  1111. " UpdateHelpStatus {{{2
  1112. function! s:UpdateHelpStatus()
  1113. setlocal modifiable
  1114. let text = s:GetHelpStatus()
  1115. call setline(s:firstBufferLine - 2, text)
  1116. setlocal nomodifiable
  1117. endfunction
  1118. " Key_number {{{2
  1119. function! s:Key_number(line)
  1120. let _bufnr = str2nr(a:line)
  1121. let key = [printf('%9d', _bufnr)]
  1122. return key
  1123. endfunction
  1124. " Key_name {{{2
  1125. function! s:Key_name(line)
  1126. let _bufnr = str2nr(a:line)
  1127. let buf = s:raw_buffer_listing[_bufnr]
  1128. let key = [buf.shortname, buf.fullname]
  1129. return key
  1130. endfunction
  1131. " Key_fullpath {{{2
  1132. function! s:Key_fullpath(line)
  1133. let _bufnr = str2nr(a:line)
  1134. let buf = s:raw_buffer_listing[_bufnr]
  1135. let key = [buf.fullname]
  1136. return key
  1137. endfunction
  1138. " Key_extension {{{2
  1139. function! s:Key_extension(line)
  1140. let _bufnr = str2nr(a:line)
  1141. let buf = s:raw_buffer_listing[_bufnr]
  1142. let extension = fnamemodify(buf.shortname, ':e')
  1143. let key = [extension, buf.shortname, buf.fullname]
  1144. return key
  1145. endfunction
  1146. " Key_mru {{{2
  1147. function! s:Key_mru(line)
  1148. let _bufnr = str2nr(a:line)
  1149. let buf = s:raw_buffer_listing[_bufnr]
  1150. let pos = s:MRUOrderForBuf(_bufnr)
  1151. return [printf('%9d', pos), buf.fullname]
  1152. endfunction
  1153. " SortByKeyFunc {{{2
  1154. function! s:SortByKeyFunc(keyFunc)
  1155. let keyedLines = []
  1156. for line in getline(s:firstBufferLine, "$")
  1157. let key = eval(a:keyFunc . '(line)')
  1158. call add(keyedLines, join(key + [line], "\1"))
  1159. endfor
  1160. " Ignore case when sorting by passing `1`:
  1161. call sort(keyedLines, 1)
  1162. if g:bufExplorerReverseSort
  1163. call reverse(keyedLines)
  1164. endif
  1165. let lines = []
  1166. for keyedLine in keyedLines
  1167. call add(lines, split(keyedLine, "\1")[-1])
  1168. endfor
  1169. call setline(s:firstBufferLine, lines)
  1170. endfunction
  1171. " SortReverse {{{2
  1172. function! s:SortReverse()
  1173. let g:bufExplorerReverseSort = !g:bufExplorerReverseSort
  1174. call s:ReSortListing()
  1175. endfunction
  1176. " SortSelect {{{2
  1177. function! s:SortSelect()
  1178. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) + 1, s:sort_by[0])
  1179. call s:ReSortListing()
  1180. endfunction
  1181. " ReverseSortSelect {{{2
  1182. function! s:ReverseSortSelect()
  1183. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) - 1, s:sort_by[-1])
  1184. call s:ReSortListing()
  1185. endfunction
  1186. " ReSortListing {{{2
  1187. function! s:ReSortListing()
  1188. setlocal modifiable
  1189. let curPos = getpos('.')
  1190. call s:SortListing()
  1191. call s:UpdateHelpStatus()
  1192. call setpos('.', curPos)
  1193. setlocal nomodifiable
  1194. endfunction
  1195. " SortListing {{{2
  1196. function! s:SortListing()
  1197. call s:SortByKeyFunc("<SID>Key_" . g:bufExplorerSortBy)
  1198. endfunction
  1199. " Error {{{2
  1200. " Display a message using ErrorMsg highlight group.
  1201. function! s:Error(msg)
  1202. echohl ErrorMsg
  1203. echomsg a:msg
  1204. echohl None
  1205. endfunction
  1206. " Warning {{{2
  1207. " Display a message using WarningMsg highlight group.
  1208. function! s:Warning(msg)
  1209. echohl WarningMsg
  1210. echomsg a:msg
  1211. echohl None
  1212. endfunction
  1213. " GetTabNbr {{{2
  1214. function! s:GetTabNbr(bufNbr)
  1215. " Prefer current tab.
  1216. if bufwinnr(a:bufNbr) > 0
  1217. return tabpagenr()
  1218. endif
  1219. " Searching buffer bufno, in tabs.
  1220. for i in range(tabpagenr("$"))
  1221. if index(tabpagebuflist(i + 1), a:bufNbr) != -1
  1222. return i + 1
  1223. endif
  1224. endfor
  1225. return 0
  1226. endfunction
  1227. " GetWinNbr" {{{2
  1228. function! s:GetWinNbr(tabNbr, bufNbr)
  1229. " window number in tabpage.
  1230. let tablist = tabpagebuflist(a:tabNbr)
  1231. " Number: 0
  1232. " String: 1
  1233. " Funcref: 2
  1234. " List: 3
  1235. " Dictionary: 4
  1236. " Float: 5
  1237. if type(tablist) == 3
  1238. return index(tabpagebuflist(a:tabNbr), a:bufNbr) + 1
  1239. else
  1240. return 1
  1241. endif
  1242. endfunction
  1243. " StringWidth" {{{2
  1244. if exists('*strwidth')
  1245. function s:StringWidth(s)
  1246. return strwidth(a:s)
  1247. endfunction
  1248. else
  1249. function s:StringWidth(s)
  1250. return len(a:s)
  1251. endfunction
  1252. endif
  1253. " Winmanager Integration {{{2
  1254. let g:BufExplorer_title = "\[Buf\ List\]"
  1255. call s:Set("g:bufExplorerResize", 1)
  1256. call s:Set("g:bufExplorerMaxHeight", 25) " Handles dynamic resizing of the window.
  1257. " Evaluate a Vimscript expression in the context of this file.
  1258. " This enables debugging of script-local variables and functions from outside
  1259. " the plugin, e.g.:
  1260. " :echo BufExplorer_eval('s:bufMru')
  1261. function! BufExplorer_eval(expr)
  1262. return eval(a:expr)
  1263. endfunction
  1264. " Execute a Vimscript statement in the context of this file.
  1265. " This enables setting script-local variables from outside the plugin, e.g.:
  1266. " :call BufExplorer_execute('let s:bufMru = s:MRUNew(0)')
  1267. function! BufExplorer_execute(statement)
  1268. execute a:statement
  1269. endfunction
  1270. " function! to start display. Set the mode to 'winmanager' for this buffer.
  1271. " This is to figure out how this plugin was called. In a standalone fashion
  1272. " or by winmanager.
  1273. function! BufExplorer_Start()
  1274. let b:displayMode = "winmanager"
  1275. call s:SetLocalSettings()
  1276. call BufExplorer()
  1277. endfunction
  1278. " Returns whether the display is okay or not.
  1279. function! BufExplorer_IsValid()
  1280. return 0
  1281. endfunction
  1282. " Handles dynamic refreshing of the window.
  1283. function! BufExplorer_Refresh()
  1284. let b:displayMode = "winmanager"
  1285. call s:SetLocalSettings()
  1286. call BufExplorer()
  1287. endfunction
  1288. function! BufExplorer_ReSize()
  1289. if !g:bufExplorerResize
  1290. return
  1291. end
  1292. let nlines = min([line("$"), g:bufExplorerMaxHeight])
  1293. execute nlines." wincmd _"
  1294. " The following lines restore the layout so that the last file line is also
  1295. " the last window line. Sometimes, when a line is deleted, although the
  1296. " window size is exactly equal to the number of lines in the file, some of
  1297. " the lines are pushed up and we see some lagging '~'s.
  1298. let pres = getpos(".")
  1299. normal! $
  1300. let _scr = &scrolloff
  1301. let &scrolloff = 0
  1302. normal! z-
  1303. let &scrolloff = _scr
  1304. call setpos(".", pres)
  1305. endfunction
  1306. " Default values {{{2
  1307. call s:Set("g:bufExplorerDisableDefaultKeyMapping", 0) " Do not disable default key mappings.
  1308. call s:Set("g:bufExplorerDefaultHelp", 1) " Show default help?
  1309. call s:Set("g:bufExplorerDetailedHelp", 0) " Show detailed help?
  1310. call s:Set("g:bufExplorerFindActive", 1) " When selecting an active buffer, take you to the window where it is active?
  1311. call s:Set("g:bufExplorerOnlyOneTab", 1) " If ShowTabBuffer = 1, only store the most recent tab for this buffer.
  1312. call s:Set("g:bufExplorerReverseSort", 0) " Sort in reverse order by default?
  1313. call s:Set("g:bufExplorerShowDirectories", 1) " (Dir's are added by commands like ':e .')
  1314. call s:Set("g:bufExplorerShowRelativePath", 0) " Show listings with relative or absolute paths?
  1315. call s:Set("g:bufExplorerShowTabBuffer", 0) " Show only buffer(s) for this tab?
  1316. call s:Set("g:bufExplorerShowUnlisted", 0) " Show unlisted buffers?
  1317. call s:Set("g:bufExplorerShowNoName", 0) " Show 'No Name' buffers?
  1318. call s:Set("g:bufExplorerSortBy", "mru") " Sorting methods are in s:sort_by:
  1319. call s:Set("g:bufExplorerSplitBelow", &splitbelow) " Should horizontal splits be below or above current window?
  1320. call s:Set("g:bufExplorerSplitOutPathName", 1) " Split out path and file name?
  1321. call s:Set("g:bufExplorerSplitRight", &splitright) " Should vertical splits be on the right or left of current window?
  1322. call s:Set("g:bufExplorerSplitVertSize", 0) " Height for a vertical split. If <=0, default Vim size is used.
  1323. call s:Set("g:bufExplorerSplitHorzSize", 0) " Height for a horizontal split. If <=0, default Vim size is used.
  1324. call s:Set("g:bufExplorerShowTerminal", 1) " Show terminal buffers?
  1325. " Default key mapping {{{2
  1326. if !hasmapto('BufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1327. nnoremap <script> <silent> <unique> <Leader>be :BufExplorer<CR>
  1328. endif
  1329. if !hasmapto('ToggleBufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1330. nnoremap <script> <silent> <unique> <Leader>bt :ToggleBufExplorer<CR>
  1331. endif
  1332. if !hasmapto('BufExplorerHorizontalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1333. nnoremap <script> <silent> <unique> <Leader>bs :BufExplorerHorizontalSplit<CR>
  1334. endif
  1335. if !hasmapto('BufExplorerVerticalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1336. nnoremap <script> <silent> <unique> <Leader>bv :BufExplorerVerticalSplit<CR>
  1337. endif
  1338. " vim:ft=vim foldmethod=marker sw=4