bufexplorer.vim 46 KB

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