bufexplorer.vim 52 KB

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