bufexplorer.vim 47 KB

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