bufexplorer.vim 59 KB

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