bufexplorer.vim 45 KB

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