bufexplorer.vim 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  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. let s:windowAtLaunch = winnr()
  537. " Forget any cached MRU ordering from previous invocations.
  538. unlet! s:mruOrder
  539. let s:raw_buffer_listing = s:GetBufferInfo(0)
  540. call s:MRUGarbageCollectBufs()
  541. call s:MRUGarbageCollectTabs()
  542. " We may have to split the current window.
  543. if s:splitMode != ""
  544. " Save off the original settings.
  545. let [_splitbelow, _splitright] = [&splitbelow, &splitright]
  546. " Set the setting to ours.
  547. let [&splitbelow, &splitright] = [g:bufExplorerSplitBelow, g:bufExplorerSplitRight]
  548. let _size = (s:splitMode == "sp") ? g:bufExplorerSplitHorzSize : g:bufExplorerSplitVertSize
  549. " Split the window either horizontally or vertically.
  550. if _size <= 0
  551. execute 'keepalt ' . s:splitMode
  552. else
  553. execute 'keepalt ' . _size . s:splitMode
  554. endif
  555. " Restore the original settings.
  556. let [&splitbelow, &splitright] = [_splitbelow, _splitright]
  557. " Remember that a split was triggered
  558. let s:didSplit = 1
  559. endif
  560. if !exists("b:displayMode") || b:displayMode != "winmanager"
  561. " Do not use keepalt when opening bufexplorer to allow the buffer that
  562. " we are leaving to become the new alternate buffer
  563. execute "silent keepjumps hide edit".name
  564. endif
  565. " Record BufExplorer's buffer number.
  566. let s:bufExplorerBuffer = bufnr('%')
  567. call s:DisplayBufferList()
  568. " Position the cursor in the newly displayed list on the line representing
  569. " the active buffer. The active buffer is the line with the '%' character
  570. " in it.
  571. execute search("%")
  572. if exists('#User#BufExplorer_Started')
  573. " Notify that BufExplorer has started. This is an opportunity to make
  574. " custom buffer-local mappings and the like.
  575. doautocmd User BufExplorer_Started
  576. endif
  577. endfunction
  578. " Tracks `tabId` at BufExplorer launch.
  579. let s:tabIdAtLaunch = ''
  580. " Tracks window number at BufExplorer launch.
  581. let s:windowAtLaunch = 0
  582. " DisplayBufferList {{{2
  583. function! s:DisplayBufferList()
  584. setlocal buftype=nofile
  585. setlocal modifiable
  586. setlocal noreadonly
  587. setlocal noswapfile
  588. setlocal nowrap
  589. setlocal bufhidden=wipe
  590. call s:SetupSyntax()
  591. call s:MapKeys()
  592. " Wipe out any existing lines in case BufExplorer buffer exists and the
  593. " user had changed any global settings that might reduce the number of
  594. " lines needed in the buffer.
  595. silent keepjumps 1,$d _
  596. call setline(1, s:CreateHelp())
  597. call s:BuildBufferList()
  598. call cursor(s:firstBufferLine, 1)
  599. if !g:bufExplorerResize
  600. normal! zz
  601. endif
  602. setlocal nomodifiable
  603. endfunction
  604. " RedisplayBufferList {{{2
  605. function! s:RedisplayBufferList()
  606. call s:RebuildBufferList()
  607. call s:UpdateHelpStatus()
  608. endfunction
  609. " MapKeys {{{2
  610. function! s:MapKeys()
  611. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferDelete) :call <SID>RemoveBuffer("delete")<CR>
  612. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferDeleteForced) :call <SID>RemoveBuffer("force_delete")<CR>
  613. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferWipe) :call <SID>RemoveBuffer("wipe")<CR>
  614. nnoremap <silent> <buffer> <Plug>(BufExplorer_BufferWipeForced) :call <SID>RemoveBuffer("force_wipe")<CR>
  615. nnoremap <silent> <buffer> <Plug>(BufExplorer_Close) :call <SID>Close()<CR>
  616. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBuffer) :call <SID>SelectBuffer()<CR>
  617. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferAsk) :call <SID>SelectBuffer("ask")<CR>
  618. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferOriginalWindow) :call <SID>SelectBuffer("original_window")<CR>
  619. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitAbove) :call <SID>SelectBuffer("split", "st")<CR>
  620. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitBelow) :call <SID>SelectBuffer("split", "sb")<CR>
  621. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitLeft) :call <SID>SelectBuffer("split", "vl")<CR>
  622. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferSplitRight) :call <SID>SelectBuffer("split", "vr")<CR>
  623. nnoremap <silent> <buffer> <Plug>(BufExplorer_OpenBufferTab) :call <SID>SelectBuffer("tab")<CR>
  624. nnoremap <silent> <buffer> <Plug>(BufExplorer_SortByNext) :call <SID>SortSelect()<CR>
  625. nnoremap <silent> <buffer> <Plug>(BufExplorer_SortByPrev) :call <SID>ReverseSortSelect()<CR>
  626. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleFindActive) :call <SID>ToggleFindActive()<CR>
  627. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleHelp) :call <SID>ToggleHelp()<CR>
  628. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleOnlyOneTab) :call <SID>ToggleOnlyOneTab()<CR>
  629. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleReverseSort) :call <SID>SortReverse()<CR>
  630. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowRelativePath) :call <SID>ToggleShowRelativePath()<CR>
  631. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowTabBuffer) :call <SID>ToggleShowTabBuffer()<CR>
  632. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowTerminal) :call <SID>ToggleShowTerminal()<CR>
  633. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleShowUnlisted) :call <SID>ToggleShowUnlisted()<CR>
  634. nnoremap <silent> <buffer> <Plug>(BufExplorer_ToggleSplitOutPathName) :call <SID>ToggleSplitOutPathName()<CR>
  635. if exists("b:displayMode") && b:displayMode == "winmanager"
  636. nnoremap <buffer> <silent> <tab> :call <SID>SelectBuffer()<CR>
  637. endif
  638. nmap <nowait> <buffer> <2-leftmouse> <Plug>(BufExplorer_OpenBuffer)
  639. nmap <nowait> <buffer> <CR> <Plug>(BufExplorer_OpenBuffer)
  640. nmap <nowait> <buffer> <F1> <Plug>(BufExplorer_ToggleHelp)
  641. nmap <nowait> <buffer> <s-cr> <Plug>(BufExplorer_OpenBufferTab)
  642. nmap <nowait> <buffer> a <Plug>(BufExplorer_ToggleFindActive)
  643. nmap <nowait> <buffer> b <Plug>(BufExplorer_OpenBufferAsk)
  644. nmap <nowait> <buffer> B <Plug>(BufExplorer_ToggleOnlyOneTab)
  645. nmap <nowait> <buffer> d <Plug>(BufExplorer_BufferDelete)
  646. nmap <nowait> <buffer> D <Plug>(BufExplorer_BufferWipe)
  647. nmap <nowait> <buffer> f <Plug>(BufExplorer_OpenBufferSplitBelow)
  648. nmap <nowait> <buffer> F <Plug>(BufExplorer_OpenBufferSplitAbove)
  649. nmap <nowait> <buffer> o <Plug>(BufExplorer_OpenBuffer)
  650. nmap <nowait> <buffer> O <Plug>(BufExplorer_OpenBufferOriginalWindow)
  651. nmap <nowait> <buffer> p <Plug>(BufExplorer_ToggleSplitOutPathName)
  652. nmap <nowait> <buffer> q <Plug>(BufExplorer_Close)
  653. nmap <nowait> <buffer> r <Plug>(BufExplorer_ToggleReverseSort)
  654. nmap <nowait> <buffer> R <Plug>(BufExplorer_ToggleShowRelativePath)
  655. nmap <nowait> <buffer> s <Plug>(BufExplorer_SortByNext)
  656. nmap <nowait> <buffer> S <Plug>(BufExplorer_SortByPrev)
  657. nmap <nowait> <buffer> t <Plug>(BufExplorer_OpenBufferTab)
  658. nmap <nowait> <buffer> T <Plug>(BufExplorer_ToggleShowTabBuffer)
  659. nmap <nowait> <buffer> u <Plug>(BufExplorer_ToggleShowUnlisted)
  660. nmap <nowait> <buffer> v <Plug>(BufExplorer_OpenBufferSplitRight)
  661. nmap <nowait> <buffer> V <Plug>(BufExplorer_OpenBufferSplitLeft)
  662. nmap <nowait> <buffer> X <Plug>(BufExplorer_ToggleShowTerminal)
  663. for k in ["G", "n", "N", "L", "M", "H"]
  664. execute "nnoremap <buffer> <silent>" k ":keepjumps normal!" k."<CR>"
  665. endfor
  666. endfunction
  667. " SetupSyntax {{{2
  668. function! s:SetupSyntax()
  669. if has("syntax")
  670. syn match bufExplorerHelp "^\".*" contains=bufExplorerSortBy,bufExplorerMapping,bufExplorerTitle,bufExplorerSortType,bufExplorerToggleSplit,bufExplorerToggleOpen
  671. syn match bufExplorerOpenIn "Open in \w\+ window" contained
  672. syn match bufExplorerSplit "\w\+ split" contained
  673. syn match bufExplorerSortBy "Sorted by .*" contained contains=bufExplorerOpenIn,bufExplorerSplit
  674. syn match bufExplorerMapping "\" \zs.\+\ze :" contained
  675. syn match bufExplorerTitle "Buffer Explorer.*" contained
  676. syn match bufExplorerSortType "'\w\{-}'" contained
  677. syn match bufExplorerBufNbr /^\s*\d\+/
  678. syn match bufExplorerToggleSplit "toggle split type" contained
  679. syn match bufExplorerToggleOpen "toggle open mode" contained
  680. syn match bufExplorerModBuf /^\s*\d\+.\{4}+.*/
  681. syn match bufExplorerLockedBuf /^\s*\d\+.\{3}[\-=].*/
  682. syn match bufExplorerHidBuf /^\s*\d\+.\{2}h.*/
  683. syn match bufExplorerActBuf /^\s*\d\+.\{2}a.*/
  684. syn match bufExplorerCurBuf /^\s*\d\+.%.*/
  685. syn match bufExplorerAltBuf /^\s*\d\+.#.*/
  686. syn match bufExplorerUnlBuf /^\s*\d\+u.*/
  687. syn match bufExplorerInactBuf /^\s*\d\+ \{7}.*/
  688. hi def link bufExplorerBufNbr Number
  689. hi def link bufExplorerMapping NonText
  690. hi def link bufExplorerHelp Special
  691. hi def link bufExplorerOpenIn Identifier
  692. hi def link bufExplorerSortBy String
  693. hi def link bufExplorerSplit NonText
  694. hi def link bufExplorerTitle NonText
  695. hi def link bufExplorerSortType bufExplorerSortBy
  696. hi def link bufExplorerToggleSplit bufExplorerSplit
  697. hi def link bufExplorerToggleOpen bufExplorerOpenIn
  698. hi def link bufExplorerActBuf Identifier
  699. hi def link bufExplorerAltBuf String
  700. hi def link bufExplorerCurBuf Type
  701. hi def link bufExplorerHidBuf Constant
  702. hi def link bufExplorerLockedBuf Special
  703. hi def link bufExplorerModBuf Exception
  704. hi def link bufExplorerUnlBuf Comment
  705. hi def link bufExplorerInactBuf Comment
  706. endif
  707. endfunction
  708. " ToggleHelp {{{2
  709. function! s:ToggleHelp()
  710. let g:bufExplorerDetailedHelp = !g:bufExplorerDetailedHelp
  711. setlocal modifiable
  712. " Save position.
  713. normal! ma
  714. " Remove old header.
  715. if s:firstBufferLine > 1
  716. execute "keepjumps 1,".(s:firstBufferLine - 1) "d _"
  717. endif
  718. call append(0, s:CreateHelp())
  719. silent! normal! g`a
  720. delmarks a
  721. setlocal nomodifiable
  722. if exists("b:displayMode") && b:displayMode == "winmanager"
  723. call WinManagerForceReSize("BufExplorer")
  724. endif
  725. endfunction
  726. " GetHelpStatus {{{2
  727. function! s:GetHelpStatus()
  728. let ret = '" Sorted by '.((g:bufExplorerReverseSort == 1) ? "reverse " : "").g:bufExplorerSortBy
  729. let ret .= ' | '.((g:bufExplorerFindActive == 0) ? "Don't " : "")."Locate buffer"
  730. let ret .= ((g:bufExplorerShowUnlisted == 0) ? "" : " | Show unlisted")
  731. let ret .= ((g:bufExplorerShowTabBuffer == 0) ? "" : " | Show buffers/tab")
  732. let ret .= ((g:bufExplorerOnlyOneTab == 0) ? "" : " | One tab/buffer")
  733. let ret .= ' | '.((g:bufExplorerShowRelativePath == 0) ? "Absolute" : "Relative")
  734. let ret .= ' '.((g:bufExplorerSplitOutPathName == 0) ? "Full" : "Split")." path"
  735. let ret .= ((g:bufExplorerShowTerminal == 0) ? "" : " | Show terminal")
  736. return ret
  737. endfunction
  738. " CreateHelp {{{2
  739. function! s:CreateHelp()
  740. if g:bufExplorerDefaultHelp == 0 && g:bufExplorerDetailedHelp == 0
  741. let s:firstBufferLine = 1
  742. return []
  743. endif
  744. let header = []
  745. if g:bufExplorerDetailedHelp == 1
  746. call add(header, '" Buffer Explorer ('.g:bufexplorer_version.')')
  747. call add(header, '" --------------------------')
  748. call add(header, '" <F1> : toggle this help')
  749. call add(header, '" <enter> or o or Mouse-Double-Click : open buffer under cursor')
  750. call add(header, '" <shift-enter> or t : open buffer in another tab')
  751. call add(header, '" a : toggle find active buffer')
  752. call add(header, '" b : Fast buffer switching with b<any bufnum>')
  753. call add(header, '" B : toggle showing buffers only on their MRU tabs')
  754. call add(header, '" d : delete buffer')
  755. call add(header, '" D : wipe buffer')
  756. call add(header, '" F : open buffer in another window above the current')
  757. call add(header, '" f : open buffer in another window below the current')
  758. call add(header, '" O : open buffer in original window')
  759. call add(header, '" p : toggle splitting of file and path name')
  760. call add(header, '" q : quit')
  761. call add(header, '" r : reverse sort')
  762. call add(header, '" R : toggle showing relative or full paths')
  763. call add(header, '" s : cycle thru "sort by" fields '.string(s:sort_by).'')
  764. call add(header, '" S : reverse cycle thru "sort by" fields')
  765. call add(header, '" T : toggle showing all buffers/only buffers used on this tab')
  766. call add(header, '" u : toggle showing unlisted buffers')
  767. call add(header, '" V : open buffer in another window on the left of the current')
  768. call add(header, '" v : open buffer in another window on the right of the current')
  769. call add(header, '" X : toggle showing terminal buffers')
  770. else
  771. call add(header, '" Press <F1> for Help')
  772. endif
  773. if (!exists("b:displayMode") || b:displayMode != "winmanager") || (b:displayMode == "winmanager" && g:bufExplorerDetailedHelp == 1)
  774. call add(header, s:GetHelpStatus())
  775. call add(header, '"=')
  776. endif
  777. let s:firstBufferLine = len(header) + 1
  778. return header
  779. endfunction
  780. " CalculateBufferDetails {{{2
  781. " Calculate `buf`-related details.
  782. " Only these fields of `buf` must be defined on entry:
  783. " - `._bufnr`
  784. " - `.attributes`
  785. " - `.line`
  786. function! s:CalculateBufferDetails(buf)
  787. let buf = a:buf
  788. let name = bufname(buf._bufnr)
  789. let buf["hasNoName"] = empty(name)
  790. if buf.hasNoName
  791. let name = "[No Name]"
  792. endif
  793. let buf.isterminal = getbufvar(buf._bufnr, '&buftype') == 'terminal'
  794. if buf.isterminal
  795. " Neovim uses paths with `term://` prefix, where the provided path
  796. " is the current working directory when the terminal was launched, e.g.:
  797. " - Unix:
  798. " term://~/tmp/sort//1464953:/bin/bash
  799. " - Windows:
  800. " term://C:\apps\nvim-win64\bin//6408:C:\Windows\system32\cmd.exe
  801. " Vim uses paths starting with `!`, with no provided path, e.g.:
  802. " - Unix:
  803. " !/bin/bash
  804. " - Windows:
  805. " !C:\Windows\system32\cmd.exe
  806. " Use the terminal's current working directory as the `path`.
  807. " For `shortname`, use `!PID:shellName`, prefixed with `!` as Vim does,
  808. " and without the shell's path for brevity, e.g.:
  809. " `/bin/bash` -> `!bash`
  810. " `1464953:/bin/bash` -> `!1464953:bash`
  811. " `C:\Windows\system32\cmd.exe` -> `!cmd.exe`
  812. " `6408:C:\Windows\system32\cmd.exe` -> `!6408:cmd.exe`
  813. " Neovim-style name format:
  814. " term://(cwd)//(pid):(shellPath)
  815. " e.g.:
  816. " term://~/tmp/sort//1464953:/bin/bash
  817. " `cwd` is the directory at terminal launch.
  818. let termNameParts = matchlist(name, '\v\c^term://(.*)//(\d+):(.*)$')
  819. if len(termNameParts) > 0
  820. let [cwd, pidStr, shellPath] = termNameParts[1:3]
  821. let pid = str2nr(pidStr)
  822. let shellName = fnamemodify(shellPath, ':t')
  823. else
  824. " Default to Vim's current working directory.
  825. let cwd = '.'
  826. let shellName = fnamemodify(name, ':t')
  827. let pid = -1
  828. if exists('*term_getjob') && exists('*job_info')
  829. let job = term_getjob(buf._bufnr)
  830. if job != v:null
  831. let pid = job_info(job).process
  832. endif
  833. endif
  834. endif
  835. if pid < 0
  836. let shortname = '!' . shellName
  837. else
  838. let shortname = '!' . pid . ':' . shellName
  839. " On some systems having a `/proc` filesystem (e.g., Linux, *BSD,
  840. " Solaris), each process has a `cwd` symlink for the current working
  841. " directory. `resolve()` will return the actual current working
  842. " directory if possible; otherwise, it will return the symlink path
  843. " unchanged.
  844. let cwd_symlink = '/proc/' . pid . '/cwd'
  845. let resolved_cwd = resolve(cwd_symlink)
  846. if resolved_cwd != cwd_symlink
  847. let cwd = resolved_cwd
  848. endif
  849. endif
  850. let slashed_path = fnamemodify(cwd, ':p')
  851. let buf.fullname = slashed_path . shortname
  852. let buf.shortname = shortname
  853. let homepath = fnamemodify(slashed_path, ':~:h')
  854. let buf.path = homepath
  855. let buf.homename = fnamemodify(buf.fullname, ':~')
  856. let buf.relativepath = fnamemodify(slashed_path, ':~:.:h')
  857. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  858. return
  859. endif
  860. let buf.fullname = simplify(fnamemodify(name, ':p'))
  861. let buf.isdir = getftype(buf.fullname) == "dir"
  862. if buf.isdir
  863. " `buf.fullname` ends with a path separator; this will be
  864. " removed via the first `:h` applied to `buf.fullname` (except
  865. " for the root directory, where the path separator will remain).
  866. let parent = fnamemodify(buf.fullname, ':h:h')
  867. let buf.shortname = fnamemodify(buf.fullname, ':h:t')
  868. " Special case for root directory: fnamemodify('/', ':h:t') == ''
  869. if buf.shortname == ''
  870. let buf.shortname = '.'
  871. endif
  872. " Must perform shortening (`:~`, `:.`) before `:h`.
  873. let buf.homename = fnamemodify(buf.fullname, ':~:h')
  874. let buf.relativename = fnamemodify(buf.fullname, ':~:.:h')
  875. else
  876. let parent = fnamemodify(buf.fullname, ':h')
  877. let buf.shortname = fnamemodify(buf.fullname, ':t')
  878. let buf.homename = fnamemodify(buf.fullname, ':~')
  879. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  880. endif
  881. " `:p` on `parent` adds back the path separator which permits more
  882. " effective shortening (`:~`, `:.`), but `:h` is required afterward
  883. " to trim this separator.
  884. let buf.path = fnamemodify(parent, ':p:~:h')
  885. let buf.relativepath = fnamemodify(parent, ':p:~:.:h')
  886. endfunction
  887. " GetBufferInfo {{{2
  888. " Return dictionary `{ bufNbr : buf }`.
  889. " - If `onlyBufNbr > 0`, dictionary will contain at most that buffer.
  890. " On return, only these fields are set for each `buf`:
  891. " - `._bufnr`
  892. " - `.attributes`
  893. " - `.line`
  894. " Other fields will be populated by `s:CalculateBufferDetails()`.
  895. function! s:GetBufferInfo(onlyBufNbr)
  896. redir => bufoutput
  897. " Below, `:silent buffers` allows capturing the output via `:redir` but
  898. " prevents display to the user.
  899. if a:onlyBufNbr > 0 && buflisted(a:onlyBufNbr)
  900. " We care only about the listed buffer `a:onlyBufNbr`, so no need to
  901. " enumerate unlisted buffers.
  902. silent buffers
  903. else
  904. " Use `!` to show all buffers including the unlisted ones.
  905. silent buffers!
  906. endif
  907. redir END
  908. if a:onlyBufNbr > 0
  909. " Since we are only interested in this specified buffer remove the
  910. " other buffers listed.
  911. " Use a very-magic pattern starting with a newline and a run of zero or
  912. " more spaces/tabs:
  913. let onlyLinePattern = '\v\n\s*'
  914. " Continue with the buffer number followed by a non-digit character
  915. " (which will be a buffer attribute character such as `u` or ` `).
  916. let onlyLinePattern .= a:onlyBufNbr . '\D'
  917. " Finish with a run of zero or more non-newline characters plus newline:
  918. let onlyLinePattern .= '[^\n]*\n'
  919. let bufoutput = matchstr("\n" . bufoutput . "\n", onlyLinePattern)
  920. endif
  921. let all = {}
  922. " Loop over each line in the buffer.
  923. for line in split(bufoutput, '\n')
  924. let bits = split(line, '"')
  925. " Use first and last components after the split on '"', in case a
  926. " filename with an embedded '"' is present.
  927. let buf = {"attributes": bits[0], "line": substitute(bits[-1], '\s*', '', '')}
  928. let buf._bufnr = str2nr(buf.attributes)
  929. let all[buf._bufnr] = buf
  930. endfor
  931. return all
  932. endfunction
  933. " BuildBufferList {{{2
  934. function! s:BuildBufferList()
  935. let table = []
  936. " Loop through every buffer.
  937. for buf in values(s:raw_buffer_listing)
  938. " `buf.attributes` must exist, but we defer the expensive work of
  939. " calculating other buffer details (e.g., `buf.fullname`) until we know
  940. " the user wants to view this buffer.
  941. " Skip BufExplorer's buffer.
  942. if buf._bufnr == s:bufExplorerBuffer
  943. continue
  944. endif
  945. " Skip unlisted buffers if we are not to show them.
  946. if !g:bufExplorerShowUnlisted && buf.attributes =~ "u"
  947. " Skip unlisted buffers if we are not to show them.
  948. continue
  949. endif
  950. " Ensure buffer details are computed for this buffer.
  951. if !has_key(buf, 'fullname')
  952. call s:CalculateBufferDetails(buf)
  953. endif
  954. " Skip 'No Name' buffers if we are not to show them.
  955. if g:bufExplorerShowNoName == 0 && buf.hasNoName
  956. continue
  957. endif
  958. " Should we show this buffer in this tab?
  959. if !s:MRUTabShouldShowBuf(s:tabIdAtLaunch, buf._bufnr)
  960. continue
  961. endif
  962. " Skip terminal buffers if we are not to show them.
  963. if !g:bufExplorerShowTerminal && buf.isterminal
  964. continue
  965. endif
  966. " Skip directory buffers if we are not to show them.
  967. if !g:bufExplorerShowDirectories && buf.isdir
  968. continue
  969. endif
  970. let row = [buf.attributes]
  971. if exists("g:loaded_webdevicons")
  972. let row += [WebDevIconsGetFileTypeSymbol(buf.fullname, buf.isdir)]
  973. endif
  974. " Are we to split the path and file name?
  975. if g:bufExplorerSplitOutPathName
  976. let type = (g:bufExplorerShowRelativePath) ? "relativepath" : "path"
  977. let row += [buf.shortname, buf[type]]
  978. else
  979. let type = (g:bufExplorerShowRelativePath) ? "relativename" : "homename"
  980. let row += [buf[type]]
  981. endif
  982. let row += [buf.line]
  983. call add(table, row)
  984. endfor
  985. let lines = s:MakeLines(table)
  986. call setline(s:firstBufferLine, lines)
  987. let firstMissingLine = s:firstBufferLine + len(lines)
  988. if line('$') >= firstMissingLine
  989. " Clear excess lines starting with `firstMissingLine`.
  990. execute "silent keepjumps ".firstMissingLine.',$d _'
  991. endif
  992. call s:SortListing()
  993. endfunction
  994. " MakeLines {{{2
  995. function! s:MakeLines(table)
  996. if len(a:table) == 0
  997. return []
  998. endif
  999. let lines = []
  1000. " To avoid trailing whitespace, do not pad the final column.
  1001. let numColumnsToPad = len(a:table[0]) - 1
  1002. let maxWidths = repeat([0], numColumnsToPad)
  1003. for row in a:table
  1004. let i = 0
  1005. while i < numColumnsToPad
  1006. let maxWidths[i] = max([maxWidths[i], s:StringWidth(row[i])])
  1007. let i = i + 1
  1008. endwhile
  1009. endfor
  1010. let pads = []
  1011. for w in maxWidths
  1012. call add(pads, repeat(' ', w))
  1013. endfor
  1014. for row in a:table
  1015. let i = 0
  1016. while i < numColumnsToPad
  1017. let row[i] .= strpart(pads[i], s:StringWidth(row[i]))
  1018. let i = i + 1
  1019. endwhile
  1020. call add(lines, join(row, ' '))
  1021. endfor
  1022. return lines
  1023. endfunction
  1024. " SelectBuffer {{{2
  1025. " Valid arguments:
  1026. " `()` Open in current window.
  1027. " `("ask")` Prompt for buffer, then open in current window.
  1028. " `("original_window")` Open in original window.
  1029. " `("split", "st")` Open in horizontal split above current window.
  1030. " `("split", "sb")` Open in horizontal split below current window.
  1031. " `("split", "vl")` Open in vertical split left of current window.
  1032. " `("split", "vr")` Open in vertical split right of current window.
  1033. " `("tab")` Open in a new tab.
  1034. function! s:SelectBuffer(...)
  1035. " Sometimes messages are not cleared when we get here so it looks like an
  1036. " error has occurred when it really has not.
  1037. "echo ""
  1038. let _bufNbr = -1
  1039. if (a:0 == 1) && (a:1 == "ask")
  1040. " Ask the user for input.
  1041. call inputsave()
  1042. let cmd = input("Enter buffer number to switch to: ")
  1043. call inputrestore()
  1044. " Clear the message area from the previous prompt.
  1045. redraw | echo
  1046. if strlen(cmd) > 0
  1047. let _bufNbr = str2nr(cmd)
  1048. else
  1049. call s:Error("Invalid buffer number, try again.")
  1050. return
  1051. endif
  1052. else
  1053. " Are we on a line with a file name?
  1054. if line('.') < s:firstBufferLine
  1055. execute "normal! \<CR>"
  1056. return
  1057. endif
  1058. let _bufNbr = str2nr(getline('.'))
  1059. " Check and see if we are running BufferExplorer via WinManager.
  1060. if exists("b:displayMode") && b:displayMode == "winmanager"
  1061. let _bufName = expand("#"._bufNbr.":p")
  1062. if (a:0 == 1) && (a:1 == "tab")
  1063. call WinManagerFileEdit(_bufName, 1)
  1064. else
  1065. call WinManagerFileEdit(_bufName, 0)
  1066. endif
  1067. return
  1068. endif
  1069. endif
  1070. if bufexists(_bufNbr)
  1071. " Get the tab number where this buffer is located in.
  1072. let tabNbr = s:GetTabNbr(_bufNbr)
  1073. if exists("g:bufExplorerChgWin") && g:bufExplorerChgWin <=winnr("$")
  1074. execute g:bufExplorerChgWin."wincmd w"
  1075. execute "keepjumps keepalt silent b!" _bufNbr
  1076. " Are we supposed to open the selected buffer in a tab?
  1077. elseif (a:0 == 1) && (a:1 == "tab")
  1078. call s:Close()
  1079. " Open a new tab with the selected buffer in it.
  1080. if v:version > 704 || ( v:version == 704 && has('patch2237') )
  1081. " new syntax for last tab as of 7.4.2237
  1082. execute "$tab split +buffer" . _bufNbr
  1083. else
  1084. execute "999tab split +buffer" . _bufNbr
  1085. endif
  1086. " Are we supposed to open the selected buffer in a split?
  1087. elseif (a:0 == 2) && (a:1 == "split")
  1088. call s:Close()
  1089. if (a:2 == "vl")
  1090. execute "vert topleft sb "._bufNbr
  1091. elseif (a:2 == "vr")
  1092. execute "vert belowright sb "._bufNbr
  1093. elseif (a:2 == "st")
  1094. execute "topleft sb "._bufNbr
  1095. else " = sb
  1096. execute "belowright sb "._bufNbr
  1097. endif
  1098. " Are we supposed to open the selected buffer in the original window?
  1099. elseif (a:0 == 1) && (a:1 == "original_window")
  1100. call s:Close()
  1101. execute s:windowAtLaunch . "wincmd w"
  1102. execute "keepjumps keepalt silent b!" _bufNbr
  1103. else
  1104. " Request to open in current (BufExplorer) window.
  1105. if g:bufExplorerFindActive && tabNbr > 0
  1106. " Close BufExplorer window and switch to existing tab/window.
  1107. call s:Close()
  1108. execute tabNbr . "tabnext"
  1109. execute bufwinnr(_bufNbr) . "wincmd w"
  1110. else
  1111. " Use BufExplorer window for the buffer.
  1112. execute "keepjumps keepalt silent b!" _bufNbr
  1113. endif
  1114. endif
  1115. " Make the buffer 'listed' again.
  1116. call setbufvar(_bufNbr, "&buflisted", "1")
  1117. " Call any associated function references. g:bufExplorerFuncRef may be
  1118. " an individual function reference or it may be a list containing
  1119. " function references. It will ignore anything that's not a function
  1120. " reference.
  1121. "
  1122. " See :help FuncRef for more on function references.
  1123. if exists("g:BufExplorerFuncRef")
  1124. if type(g:BufExplorerFuncRef) == 2
  1125. keepj call g:BufExplorerFuncRef()
  1126. elseif type(g:BufExplorerFuncRef) == 3
  1127. for FncRef in g:BufExplorerFuncRef
  1128. if type(FncRef) == 2
  1129. keepj call FncRef()
  1130. endif
  1131. endfor
  1132. endif
  1133. endif
  1134. else
  1135. call s:Error("Sorry, that buffer no longer exists, please select another")
  1136. call s:DeleteBuffer(_bufNbr, "wipe")
  1137. endif
  1138. endfunction
  1139. " RemoveBuffer {{{2
  1140. " Valid `mode` values:
  1141. " - "delete"
  1142. " - "force_delete"
  1143. " - "wipe"
  1144. " - "force_wipe"
  1145. function! s:RemoveBuffer(mode)
  1146. " Are we on a line with a file name?
  1147. if line('.') < s:firstBufferLine
  1148. return
  1149. endif
  1150. let mode = a:mode
  1151. let forced = mode =~# '^force_'
  1152. " These commands are to temporarily suspend the activity of winmanager.
  1153. if exists("b:displayMode") && b:displayMode == "winmanager"
  1154. call WinManagerSuspendAUs()
  1155. end
  1156. let bufNbr = str2nr(getline('.'))
  1157. let buf = s:raw_buffer_listing[bufNbr]
  1158. if !forced && (buf.isterminal || getbufvar(bufNbr, '&modified'))
  1159. if buf.isterminal
  1160. let msg = "Buffer " . bufNbr . " is a terminal"
  1161. else
  1162. let msg = "No write since last change for buffer " . bufNbr
  1163. endif
  1164. " Calling confirm() requires Vim built with dialog option.
  1165. if !has("dialog_con") && !has("dialog_gui")
  1166. call s:Error(msg . "; cannot remove without 'force'")
  1167. return
  1168. endif
  1169. let answer = confirm(msg . "; Remove anyway?", "&Yes\n&No", 2)
  1170. if answer == 1
  1171. let mode = 'force_' . mode
  1172. else
  1173. return
  1174. endif
  1175. endif
  1176. " Okay, everything is good, delete or wipe the buffer.
  1177. call s:DeleteBuffer(bufNbr, mode)
  1178. " Reactivate winmanager autocommand activity.
  1179. if exists("b:displayMode") && b:displayMode == "winmanager"
  1180. call WinManagerForceReSize("BufExplorer")
  1181. call WinManagerResumeAUs()
  1182. end
  1183. endfunction
  1184. " DeleteBuffer {{{2
  1185. " Valid `mode` values:
  1186. " - "delete"
  1187. " - "force_delete"
  1188. " - "wipe"
  1189. " - "force_wipe"
  1190. function! s:DeleteBuffer(bufNbr, mode)
  1191. " This routine assumes that the buffer to be removed is on the current line.
  1192. if a:mode =~# 'delete$' && bufexists(a:bufNbr) && !buflisted(a:bufNbr)
  1193. call s:Error('Buffer ' . a:bufNbr
  1194. \ . ' is unlisted; must `wipe` to remove')
  1195. return
  1196. endif
  1197. try
  1198. " Wipe/Delete buffer from Vim.
  1199. if a:mode == "wipe"
  1200. execute "silent bwipe" a:bufNbr
  1201. elseif a:mode == "force_wipe"
  1202. execute "silent bwipe!" a:bufNbr
  1203. elseif a:mode == "force_delete"
  1204. execute "silent bdelete!" a:bufNbr
  1205. else
  1206. execute "silent bdelete" a:bufNbr
  1207. endif
  1208. catch
  1209. call s:Error(v:exception)
  1210. endtry
  1211. if bufexists(a:bufNbr)
  1212. " Buffer is still present. We may have failed to wipe it, or it may
  1213. " have changed attributes (as `:bd` only makes a buffer unlisted).
  1214. " Regather information on this buffer, update the buffer list, and
  1215. " redisplay.
  1216. let info = s:GetBufferInfo(a:bufNbr)
  1217. let s:raw_buffer_listing[a:bufNbr] = info[a:bufNbr]
  1218. call s:RedisplayBufferList()
  1219. else
  1220. " Delete the buffer from the list on screen.
  1221. setlocal modifiable
  1222. normal! "_dd
  1223. setlocal nomodifiable
  1224. " Delete the buffer from the raw buffer list.
  1225. unlet s:raw_buffer_listing[a:bufNbr]
  1226. endif
  1227. endfunction
  1228. " Close {{{2
  1229. function! s:Close()
  1230. " Get only the listed buffers associated with the current tab (up to 2).
  1231. let listed = s:MRUListedBuffersForTab(s:tabIdAtLaunch, 2)
  1232. " If we needed to split the main window, close the split one.
  1233. if s:didSplit
  1234. execute "wincmd c"
  1235. endif
  1236. " Check to see if there are anymore buffers listed.
  1237. if len(listed) == 0
  1238. " Since there are no buffers left to switch to, open a new empty
  1239. " buffers.
  1240. execute "enew"
  1241. else
  1242. " Since there are buffers left to switch to, switch to the previous and
  1243. " then the current.
  1244. for b in reverse(listed[0:1])
  1245. execute "keepjumps silent b ".b
  1246. endfor
  1247. endif
  1248. " Clear any messages.
  1249. echo
  1250. endfunction
  1251. " ToggleShowTerminal {{{2
  1252. function! s:ToggleShowTerminal()
  1253. let g:bufExplorerShowTerminal = !g:bufExplorerShowTerminal
  1254. call s:RedisplayBufferList()
  1255. endfunction
  1256. " ToggleSplitOutPathName {{{2
  1257. function! s:ToggleSplitOutPathName()
  1258. let g:bufExplorerSplitOutPathName = !g:bufExplorerSplitOutPathName
  1259. call s:RedisplayBufferList()
  1260. endfunction
  1261. " ToggleShowRelativePath {{{2
  1262. function! s:ToggleShowRelativePath()
  1263. let g:bufExplorerShowRelativePath = !g:bufExplorerShowRelativePath
  1264. call s:RedisplayBufferList()
  1265. endfunction
  1266. " ToggleShowTabBuffer {{{2
  1267. function! s:ToggleShowTabBuffer()
  1268. " Forget any cached MRU ordering, as it depends on
  1269. " `g:bufExplorerShowTabBuffer`.
  1270. unlet! s:mruOrder
  1271. let g:bufExplorerShowTabBuffer = !g:bufExplorerShowTabBuffer
  1272. call s:RedisplayBufferList()
  1273. endfunction
  1274. " ToggleOnlyOneTab {{{2
  1275. function! s:ToggleOnlyOneTab()
  1276. let g:bufExplorerOnlyOneTab = !g:bufExplorerOnlyOneTab
  1277. call s:RedisplayBufferList()
  1278. endfunction
  1279. " ToggleShowUnlisted {{{2
  1280. function! s:ToggleShowUnlisted()
  1281. let g:bufExplorerShowUnlisted = !g:bufExplorerShowUnlisted
  1282. call s:RedisplayBufferList()
  1283. endfunction
  1284. " ToggleFindActive {{{2
  1285. function! s:ToggleFindActive()
  1286. let g:bufExplorerFindActive = !g:bufExplorerFindActive
  1287. call s:UpdateHelpStatus()
  1288. endfunction
  1289. " RebuildBufferList {{{2
  1290. function! s:RebuildBufferList()
  1291. setlocal modifiable
  1292. let curPos = getpos('.')
  1293. let num_bufs = s:BuildBufferList()
  1294. call setpos('.', curPos)
  1295. setlocal nomodifiable
  1296. return num_bufs
  1297. endfunction
  1298. " UpdateHelpStatus {{{2
  1299. function! s:UpdateHelpStatus()
  1300. setlocal modifiable
  1301. let text = s:GetHelpStatus()
  1302. call setline(s:firstBufferLine - 2, text)
  1303. setlocal nomodifiable
  1304. endfunction
  1305. " Key_number {{{2
  1306. function! s:Key_number(line)
  1307. let _bufnr = str2nr(a:line)
  1308. let key = [printf('%9d', _bufnr)]
  1309. return key
  1310. endfunction
  1311. " Key_name {{{2
  1312. function! s:Key_name(line)
  1313. let _bufnr = str2nr(a:line)
  1314. let buf = s:raw_buffer_listing[_bufnr]
  1315. let key = [buf.shortname, buf.fullname]
  1316. return key
  1317. endfunction
  1318. " Key_fullpath {{{2
  1319. function! s:Key_fullpath(line)
  1320. let _bufnr = str2nr(a:line)
  1321. let buf = s:raw_buffer_listing[_bufnr]
  1322. let key = [buf.fullname]
  1323. return key
  1324. endfunction
  1325. " Key_extension {{{2
  1326. function! s:Key_extension(line)
  1327. let _bufnr = str2nr(a:line)
  1328. let buf = s:raw_buffer_listing[_bufnr]
  1329. let extension = fnamemodify(buf.shortname, ':e')
  1330. let key = [extension, buf.shortname, buf.fullname]
  1331. return key
  1332. endfunction
  1333. " Key_mru {{{2
  1334. function! s:Key_mru(line)
  1335. let _bufnr = str2nr(a:line)
  1336. let buf = s:raw_buffer_listing[_bufnr]
  1337. let pos = s:MRUOrderForBuf(_bufnr)
  1338. return [printf('%9d', pos), buf.fullname]
  1339. endfunction
  1340. " SortByKeyFunc {{{2
  1341. function! s:SortByKeyFunc(keyFunc)
  1342. let keyedLines = []
  1343. for line in getline(s:firstBufferLine, "$")
  1344. let key = eval(a:keyFunc . '(line)')
  1345. call add(keyedLines, join(key + [line], "\1"))
  1346. endfor
  1347. " Ignore case when sorting by passing `1`:
  1348. call sort(keyedLines, 1)
  1349. if g:bufExplorerReverseSort
  1350. call reverse(keyedLines)
  1351. endif
  1352. let lines = []
  1353. for keyedLine in keyedLines
  1354. call add(lines, split(keyedLine, "\1")[-1])
  1355. endfor
  1356. call setline(s:firstBufferLine, lines)
  1357. endfunction
  1358. " SortReverse {{{2
  1359. function! s:SortReverse()
  1360. let g:bufExplorerReverseSort = !g:bufExplorerReverseSort
  1361. call s:ReSortListing()
  1362. endfunction
  1363. " SortSelect {{{2
  1364. function! s:SortSelect()
  1365. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) + 1, s:sort_by[0])
  1366. call s:ReSortListing()
  1367. endfunction
  1368. " ReverseSortSelect {{{2
  1369. function! s:ReverseSortSelect()
  1370. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) - 1, s:sort_by[-1])
  1371. call s:ReSortListing()
  1372. endfunction
  1373. " ReSortListing {{{2
  1374. function! s:ReSortListing()
  1375. setlocal modifiable
  1376. let curPos = getpos('.')
  1377. call s:SortListing()
  1378. call s:UpdateHelpStatus()
  1379. call setpos('.', curPos)
  1380. setlocal nomodifiable
  1381. endfunction
  1382. " SortListing {{{2
  1383. function! s:SortListing()
  1384. call s:SortByKeyFunc("<SID>Key_" . g:bufExplorerSortBy)
  1385. endfunction
  1386. " Error {{{2
  1387. " Display a message using ErrorMsg highlight group.
  1388. function! s:Error(msg)
  1389. echohl ErrorMsg
  1390. echomsg a:msg
  1391. echohl None
  1392. endfunction
  1393. " Warning {{{2
  1394. " Display a message using WarningMsg highlight group.
  1395. function! s:Warning(msg)
  1396. echohl WarningMsg
  1397. echomsg a:msg
  1398. echohl None
  1399. endfunction
  1400. " GetTabNbr {{{2
  1401. function! s:GetTabNbr(bufNbr)
  1402. " Prefer current tab.
  1403. if bufwinnr(a:bufNbr) > 0
  1404. return tabpagenr()
  1405. endif
  1406. " Searching buffer bufno, in tabs.
  1407. for i in range(tabpagenr("$"))
  1408. if index(tabpagebuflist(i + 1), a:bufNbr) != -1
  1409. return i + 1
  1410. endif
  1411. endfor
  1412. return 0
  1413. endfunction
  1414. " GetWinNbr" {{{2
  1415. function! s:GetWinNbr(tabNbr, bufNbr)
  1416. " window number in tabpage.
  1417. let tablist = tabpagebuflist(a:tabNbr)
  1418. " Number: 0
  1419. " String: 1
  1420. " Funcref: 2
  1421. " List: 3
  1422. " Dictionary: 4
  1423. " Float: 5
  1424. if type(tablist) == 3
  1425. return index(tabpagebuflist(a:tabNbr), a:bufNbr) + 1
  1426. else
  1427. return 1
  1428. endif
  1429. endfunction
  1430. " StringWidth" {{{2
  1431. if exists('*strwidth')
  1432. function s:StringWidth(s)
  1433. return strwidth(a:s)
  1434. endfunction
  1435. else
  1436. function s:StringWidth(s)
  1437. return len(a:s)
  1438. endfunction
  1439. endif
  1440. " Winmanager Integration {{{2
  1441. let g:BufExplorer_title = "\[Buf\ List\]"
  1442. call s:Set("g:bufExplorerResize", 1)
  1443. call s:Set("g:bufExplorerMaxHeight", 25) " Handles dynamic resizing of the window.
  1444. " Evaluate a Vimscript expression in the context of this file.
  1445. " This enables debugging of script-local variables and functions from outside
  1446. " the plugin, e.g.:
  1447. " :echo BufExplorer_eval('s:bufMru')
  1448. function! BufExplorer_eval(expr)
  1449. return eval(a:expr)
  1450. endfunction
  1451. " Execute a Vimscript statement in the context of this file.
  1452. " This enables setting script-local variables from outside the plugin, e.g.:
  1453. " :call BufExplorer_execute('let s:bufMru = s:MRUNew(0)')
  1454. function! BufExplorer_execute(statement)
  1455. execute a:statement
  1456. endfunction
  1457. " function! to start display. Set the mode to 'winmanager' for this buffer.
  1458. " This is to figure out how this plugin was called. In a standalone fashion
  1459. " or by winmanager.
  1460. function! BufExplorer_Start()
  1461. let b:displayMode = "winmanager"
  1462. call s:SetLocalSettings()
  1463. call BufExplorer()
  1464. endfunction
  1465. " Returns whether the display is okay or not.
  1466. function! BufExplorer_IsValid()
  1467. return 0
  1468. endfunction
  1469. " Handles dynamic refreshing of the window.
  1470. function! BufExplorer_Refresh()
  1471. let b:displayMode = "winmanager"
  1472. call s:SetLocalSettings()
  1473. call BufExplorer()
  1474. endfunction
  1475. function! BufExplorer_ReSize()
  1476. if !g:bufExplorerResize
  1477. return
  1478. end
  1479. let nlines = min([line("$"), g:bufExplorerMaxHeight])
  1480. execute nlines." wincmd _"
  1481. " The following lines restore the layout so that the last file line is also
  1482. " the last window line. Sometimes, when a line is deleted, although the
  1483. " window size is exactly equal to the number of lines in the file, some of
  1484. " the lines are pushed up and we see some lagging '~'s.
  1485. let pres = getpos(".")
  1486. normal! $
  1487. let _scr = &scrolloff
  1488. let &scrolloff = 0
  1489. normal! z-
  1490. let &scrolloff = _scr
  1491. call setpos(".", pres)
  1492. endfunction
  1493. " Default values {{{2
  1494. call s:Set("g:bufExplorerDisableDefaultKeyMapping", 0) " Do not disable default key mappings.
  1495. call s:Set("g:bufExplorerDefaultHelp", 1) " Show default help?
  1496. call s:Set("g:bufExplorerDetailedHelp", 0) " Show detailed help?
  1497. call s:Set("g:bufExplorerFindActive", 1) " When selecting an active buffer, take you to the window where it is active?
  1498. call s:Set("g:bufExplorerOnlyOneTab", 1) " Show buffer only on MRU tab? (Applies when `g:bufExplorerShowTabBuffer` is true.)
  1499. call s:Set("g:bufExplorerReverseSort", 0) " Sort in reverse order by default?
  1500. call s:Set("g:bufExplorerShowDirectories", 1) " (Dir's are added by commands like ':e .')
  1501. call s:Set("g:bufExplorerShowRelativePath", 0) " Show listings with relative or absolute paths?
  1502. call s:Set("g:bufExplorerShowTabBuffer", 0) " Show only buffer(s) for this tab?
  1503. call s:Set("g:bufExplorerShowUnlisted", 0) " Show unlisted buffers?
  1504. call s:Set("g:bufExplorerShowNoName", 0) " Show 'No Name' buffers?
  1505. call s:Set("g:bufExplorerSortBy", "mru") " Sorting methods are in s:sort_by:
  1506. call s:Set("g:bufExplorerSplitBelow", &splitbelow) " Should horizontal splits be below or above current window?
  1507. call s:Set("g:bufExplorerSplitOutPathName", 1) " Split out path and file name?
  1508. call s:Set("g:bufExplorerSplitRight", &splitright) " Should vertical splits be on the right or left of current window?
  1509. call s:Set("g:bufExplorerSplitVertSize", 0) " Height for a vertical split. If <=0, default Vim size is used.
  1510. call s:Set("g:bufExplorerSplitHorzSize", 0) " Height for a horizontal split. If <=0, default Vim size is used.
  1511. call s:Set("g:bufExplorerShowTerminal", 1) " Show terminal buffers?
  1512. " Default key mapping {{{2
  1513. if !hasmapto('BufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1514. nnoremap <script> <silent> <unique> <Leader>be :BufExplorer<CR>
  1515. endif
  1516. if !hasmapto('ToggleBufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1517. nnoremap <script> <silent> <unique> <Leader>bt :ToggleBufExplorer<CR>
  1518. endif
  1519. if !hasmapto('BufExplorerHorizontalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1520. nnoremap <script> <silent> <unique> <Leader>bs :BufExplorerHorizontalSplit<CR>
  1521. endif
  1522. if !hasmapto('BufExplorerVerticalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1523. nnoremap <script> <silent> <unique> <Leader>bv :BufExplorerVerticalSplit<CR>
  1524. endif
  1525. " vim:ft=vim foldmethod=marker sw=4