bufexplorer.vim 59 KB

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