bufexplorer.vim 54 KB

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