bufexplorer.vim 51 KB

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