bufexplorer.vim 52 KB

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