bufexplorer.vim 60 KB

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