bufexplorer.vim 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. "============================================================================
  2. " Copyright: Copyright (c) 2001-2025, Jeff Lanzarotta
  3. " All rights reserved.
  4. "
  5. " Redistribution and use in source and binary forms, with or
  6. " without modification, are permitted provided that the
  7. " following conditions are met:
  8. "
  9. " * Redistributions of source code must retain the above
  10. " copyright notice, this list of conditions and the following
  11. " disclaimer.
  12. "
  13. " * Redistributions in binary form must reproduce the above
  14. " copyright notice, this list of conditions and the following
  15. " disclaimer in the documentation and/or other materials
  16. " provided with the distribution.
  17. "
  18. " * Neither the name of the {organization} nor the names of its
  19. " contributors may be used to endorse or promote products
  20. " derived from this software without specific prior written
  21. " permission.
  22. "
  23. " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  24. " CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  25. " INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  26. " MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  27. " DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  28. " CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  29. " SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  30. " NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. " HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  33. " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  34. " OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  35. " EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. " Name Of File: bufexplorer.vim
  37. " Description: Buffer Explorer Vim Plugin
  38. " Maintainer: Jeff Lanzarotta (my name at gmail dot com)
  39. " Last Changed: Monday, 17 February 2025
  40. " Version: See g:bufexplorer_version for version number.
  41. " Usage: This file should reside in the plugin directory and be
  42. " automatically sourced.
  43. "
  44. " You may use the default keymappings of
  45. "
  46. " <Leader>be - Opens BufExplorer
  47. " <Leader>bt - Toggles BufExplorer open or closed
  48. " <Leader>bs - Opens horizontally split window BufExplorer
  49. " <Leader>bv - Opens vertically split window BufExplorer
  50. "
  51. " Or you can override the defaults and define your own mapping
  52. " in your vimrc file, for example:
  53. "
  54. " nnoremap <silent> <F11> :BufExplorer<CR>
  55. " nnoremap <silent> <s-F11> :ToggleBufExplorer<CR>
  56. " nnoremap <silent> <m-F11> :BufExplorerHorizontalSplit<CR>
  57. " nnoremap <silent> <c-F11> :BufExplorerVerticalSplit<CR>
  58. "
  59. " Or you can use
  60. "
  61. " ":BufExplorer" - Opens BufExplorer
  62. " ":ToggleBufExplorer" - Opens/Closes BufExplorer
  63. " ":BufExplorerHorizontalSplit" - Opens horizontally window BufExplorer
  64. " ":BufExplorerVerticalSplit" - Opens vertically split window BufExplorer
  65. "
  66. " For more help see supplied documentation.
  67. " History: See supplied documentation.
  68. "=============================================================================
  69. " Exit quickly if already running or when 'compatible' is set. {{{1
  70. if exists("g:bufexplorer_version") || &cp
  71. finish
  72. endif
  73. "1}}}
  74. " Version number
  75. let g:bufexplorer_version = "7.6.0"
  76. " Plugin Code {{{1
  77. " Check for Vim version {{{2
  78. if !exists("g:bufExplorerVersionWarn")
  79. let g:bufExplorerVersionWarn = 1
  80. endif
  81. if v:version < 700
  82. if g:bufExplorerVersionWarn
  83. echohl WarningMsg
  84. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.0 or greater."
  85. echohl None
  86. endif
  87. finish
  88. endif
  89. " Check to see if the version of Vim has the correct patch applied, if not, do
  90. " not used <nowait>.
  91. if v:version > 703 || v:version == 703 && has('patch1261') && has('patch1264')
  92. " We are good to go.
  93. else
  94. if g:bufExplorerVersionWarn
  95. echohl WarningMsg
  96. echo "Sorry, bufexplorer ".g:bufexplorer_version." required Vim 7.3 or greater with patch1261 and patch1264."
  97. echohl None
  98. endif
  99. finish
  100. endif
  101. " Create commands {{{2
  102. command! BufExplorer :call BufExplorer()
  103. command! ToggleBufExplorer :call ToggleBufExplorer()
  104. command! BufExplorerHorizontalSplit :call BufExplorerHorizontalSplit()
  105. command! BufExplorerVerticalSplit :call BufExplorerVerticalSplit()
  106. " Set {{{2
  107. function! s:Set(var, default)
  108. if !exists(a:var)
  109. if type(a:default)
  110. execute "let" a:var "=" string(a:default)
  111. else
  112. execute "let" a:var "=" a:default
  113. endif
  114. return 1
  115. endif
  116. return 0
  117. endfunction
  118. " Script variables {{{2
  119. let s:MRU_Exclude_List = ["[BufExplorer]","__MRU_Files__","[Buf\ List]"]
  120. let s:MRUList = []
  121. let s:name = '[BufExplorer]'
  122. let s:originBuffer = 0
  123. let s:running = 0
  124. let s:sort_by = ["number", "name", "fullpath", "mru", "extension"]
  125. let s:splitMode = ""
  126. let s:didSplit = 0
  127. let s:types = ["fullname", "homename", "path", "relativename", "relativepath", "shortname"]
  128. " Setup the autocommands that handle the MRUList and other stuff. {{{2
  129. autocmd VimEnter * call s:Setup()
  130. " Reset MRUList and buffer->tab associations after loading a session. {{{2
  131. autocmd SessionLoadPost * call s:Reset()
  132. " Setup {{{2
  133. function! s:Setup()
  134. call s:Reset()
  135. " Now that the MRUList is created, add the other autocmds.
  136. augroup BufExplorer
  137. autocmd!
  138. autocmd BufEnter,BufNew * call s:ActivateBuffer()
  139. autocmd BufWipeOut * call s:DeactivateBuffer(1)
  140. autocmd BufDelete * call s:DeactivateBuffer(0)
  141. autocmd BufWinEnter \[BufExplorer\] call s:Initialize()
  142. autocmd BufWinLeave \[BufExplorer\] call s:Cleanup()
  143. augroup END
  144. endfunction
  145. " Reset {{{2
  146. function! s:Reset()
  147. " Build initial MRUList. This makes sure all the files specified on the
  148. " command line are picked up correctly. Check buffers exist so this also
  149. " works after wiping buffers and loading a session (e.g. sessionman.vim)
  150. let s:MRUList = filter(range(1, bufnr('$')), 'bufexists(v:val)')
  151. " Initialize the association of buffers to tabs for any buffers
  152. " that have been created prior to now, e.g., files specified as
  153. " vim command line arguments
  154. call s:CatalogBuffers()
  155. endfunction
  156. " CatalogBuffers {{{2
  157. " Create tab associations for any existing buffers
  158. function! s:CatalogBuffers()
  159. let ct = tabpagenr()
  160. for tab in range(1, tabpagenr('$'))
  161. silent execute 'normal! ' . tab . 'gt'
  162. for buf in tabpagebuflist()
  163. call s:UpdateTabBufData(buf)
  164. endfor
  165. endfor
  166. silent execute 'normal! ' . ct . 'gt'
  167. endfunction
  168. " 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)
  576. let buf = a:buf
  577. let name = bufname(buf._bufnr)
  578. let buf["hasNoName"] = empty(name)
  579. if buf.hasNoName
  580. let name = "[No Name]"
  581. endif
  582. let buf.isterminal = getbufvar(buf._bufnr, '&buftype') == 'terminal'
  583. if buf.isterminal
  584. let buf.fullname = name
  585. let buf.isdir = 0
  586. else
  587. let buf.fullname = simplify(fnamemodify(name, ':p'))
  588. let buf.isdir = getftype(buf.fullname) == "dir"
  589. endif
  590. if buf.isdir
  591. " `buf.fullname` ends with a path separator; this will be
  592. " removed via the first `:h` applied to `buf.fullname` (except
  593. " for the root directory, where the path separator will remain).
  594. let parent = fnamemodify(buf.fullname, ':h:h')
  595. let buf.shortname = fnamemodify(buf.fullname, ':h:t')
  596. " Special case for root directory: fnamemodify('/', ':h:t') == ''
  597. if buf.shortname == ''
  598. let buf.shortname = '.'
  599. endif
  600. " Must perform shortening (`:~`, `:.`) before `:h`.
  601. let buf.homename = fnamemodify(buf.fullname, ':~:h')
  602. let buf.relativename = fnamemodify(buf.fullname, ':~:.:h')
  603. else
  604. let parent = fnamemodify(buf.fullname, ':h')
  605. let buf.shortname = fnamemodify(buf.fullname, ':t')
  606. let buf.homename = fnamemodify(buf.fullname, ':~')
  607. let buf.relativename = fnamemodify(buf.fullname, ':~:.')
  608. endif
  609. " `:p` on `parent` adds back the path separator which permits more
  610. " effective shortening (`:~`, `:.`), but `:h` is required afterward
  611. " to trim this separator.
  612. let buf.path = fnamemodify(parent, ':p:~:h')
  613. let buf.relativepath = fnamemodify(parent, ':p:~:.:h')
  614. endfunction
  615. " GetBufferInfo {{{2
  616. function! s:GetBufferInfo(bufnr)
  617. redir => bufoutput
  618. " Show all buffers including the unlisted ones. [!] tells Vim to show the
  619. " unlisted ones.
  620. buffers!
  621. redir END
  622. if a:bufnr > 0
  623. " Since we are only interested in this specified buffer remove the
  624. " other buffers listed.
  625. let bufoutput = substitute(bufoutput."\n", '^.*\n\(\s*'.a:bufnr.'\>.\{-}\)\n.*', '\1', '')
  626. endif
  627. let all = {}
  628. " Loop over each line in the buffer.
  629. for line in split(bufoutput, '\n')
  630. let bits = split(line, '"')
  631. " Use first and last components after the split on '"', in case a
  632. " filename with an embedded '"' is present.
  633. let buf = {"attributes": bits[0], "line": substitute(bits[-1], '\s*', '', '')}
  634. let buf._bufnr = str2nr(buf.attributes)
  635. let all[buf._bufnr] = buf
  636. endfor
  637. return all
  638. endfunction
  639. " BuildBufferList {{{2
  640. function! s:BuildBufferList()
  641. let table = []
  642. " Loop through every buffer.
  643. for buf in values(s:raw_buffer_listing)
  644. " `buf.attributes` must exist, but we defer the expensive work of
  645. " calculating other buffer details (e.g., `buf.fullname`) until we know
  646. " the user wants to view this buffer.
  647. " Skip unlisted buffers if we are not to show them.
  648. if !g:bufExplorerShowUnlisted && buf.attributes =~ "u"
  649. " Skip unlisted buffers if we are not to show them.
  650. continue
  651. endif
  652. " Ensure buffer details are computed for this buffer.
  653. if !has_key(buf, 'fullname')
  654. call s:CalculateBufferDetails(buf)
  655. endif
  656. " Skip 'No Name' buffers if we are not to show them.
  657. if g:bufExplorerShowNoName == 0 && buf.hasNoName
  658. continue
  659. endif
  660. " Are we to show only buffer(s) for this tab?
  661. if g:bufExplorerShowTabBuffer && (!s:IsInCurrentTab(str2nr(buf.attributes)))
  662. continue
  663. endif
  664. " Skip terminal buffers if we are not to show them.
  665. if !g:bufExplorerShowTerminal && buf.isterminal
  666. continue
  667. endif
  668. " Skip directory buffers if we are not to show them.
  669. if !g:bufExplorerShowDirectories && buf.isdir
  670. continue
  671. endif
  672. let row = [buf.attributes]
  673. if exists("g:loaded_webdevicons")
  674. let row += [WebDevIconsGetFileTypeSymbol(buf.fullname, buf.isdir)]
  675. endif
  676. " Are we to split the path and file name?
  677. if g:bufExplorerSplitOutPathName
  678. let type = (g:bufExplorerShowRelativePath) ? "relativepath" : "path"
  679. let row += [buf.shortname, buf[type]]
  680. else
  681. let type = (g:bufExplorerShowRelativePath) ? "relativename" : "homename"
  682. let row += [buf[type]]
  683. endif
  684. let row += [buf.line]
  685. call add(table, row)
  686. endfor
  687. let lines = s:MakeLines(table)
  688. call setline(s:firstBufferLine, lines)
  689. call s:SortListing()
  690. endfunction
  691. " MakeLines {{{2
  692. function! s:MakeLines(table)
  693. if len(a:table) == 0
  694. return []
  695. endif
  696. let lines = []
  697. " To avoid trailing whitespace, do not pad the final column.
  698. let numColumnsToPad = len(a:table[0]) - 1
  699. let maxWidths = repeat([0], numColumnsToPad)
  700. for row in a:table
  701. let i = 0
  702. while i < numColumnsToPad
  703. let maxWidths[i] = max([maxWidths[i], s:StringWidth(row[i])])
  704. let i = i + 1
  705. endwhile
  706. endfor
  707. let pads = []
  708. for w in maxWidths
  709. call add(pads, repeat(' ', w))
  710. endfor
  711. for row in a:table
  712. let i = 0
  713. while i < numColumnsToPad
  714. let row[i] .= strpart(pads[i], s:StringWidth(row[i]))
  715. let i = i + 1
  716. endwhile
  717. call add(lines, join(row, ' '))
  718. endfor
  719. return lines
  720. endfunction
  721. " SelectBuffer {{{2
  722. function! s:SelectBuffer(...)
  723. " Sometimes messages are not cleared when we get here so it looks like an
  724. " error has occurred when it really has not.
  725. "echo ""
  726. let _bufNbr = -1
  727. if (a:0 == 1) && (a:1 == "ask")
  728. " Ask the user for input.
  729. call inputsave()
  730. let cmd = input("Enter buffer number to switch to: ")
  731. call inputrestore()
  732. " Clear the message area from the previous prompt.
  733. redraw | echo
  734. if strlen(cmd) > 0
  735. let _bufNbr = str2nr(cmd)
  736. else
  737. call s:Error("Invalid buffer number, try again.")
  738. return
  739. endif
  740. else
  741. " Are we on a line with a file name?
  742. if line('.') < s:firstBufferLine
  743. execute "normal! \<CR>"
  744. return
  745. endif
  746. let _bufNbr = str2nr(getline('.'))
  747. " Check and see if we are running BufferExplorer via WinManager.
  748. if exists("b:displayMode") && b:displayMode == "winmanager"
  749. let _bufName = expand("#"._bufNbr.":p")
  750. if (a:0 == 1) && (a:1 == "tab")
  751. call WinManagerFileEdit(_bufName, 1)
  752. else
  753. call WinManagerFileEdit(_bufName, 0)
  754. endif
  755. return
  756. endif
  757. endif
  758. if bufexists(_bufNbr)
  759. " Get the tab number where this buffer is located in.
  760. let tabNbr = s:GetTabNbr(_bufNbr)
  761. if exists("g:bufExplorerChgWin") && g:bufExplorerChgWin <=winnr("$")
  762. execute g:bufExplorerChgWin."wincmd w"
  763. execute "keepjumps keepalt silent b!" _bufNbr
  764. " Are we supposed to open the selected buffer in a tab?
  765. elseif (a:0 == 1) && (a:1 == "tab")
  766. call s:Close()
  767. " Open a new tab with the selected buffer in it.
  768. if v:version > 704 || ( v:version == 704 && has('patch2237') )
  769. " new syntax for last tab as of 7.4.2237
  770. execute "$tab split +buffer" . _bufNbr
  771. else
  772. execute "999tab split +buffer" . _bufNbr
  773. endif
  774. " Workaround for the issue mentioned in UpdateTabBufData.
  775. call s:UpdateTabBufData(_bufNbr)
  776. " Are we supposed to open the selected buffer in a split?
  777. elseif (a:0 == 2) && (a:1 == "split")
  778. call s:Close()
  779. if (a:2 == "vl")
  780. execute "vert topleft sb "._bufNbr
  781. elseif (a:2 == "vr")
  782. execute "vert belowright sb "._bufNbr
  783. elseif (a:2 == "st")
  784. execute "topleft sb "._bufNbr
  785. else " = sb
  786. execute "belowright sb "._bufNbr
  787. endif
  788. else
  789. " Request to open in current (BufExplorer) window.
  790. if g:bufExplorerFindActive && tabNbr > 0
  791. " Close BufExplorer window and switch to existing tab/window.
  792. call s:Close()
  793. execute tabNbr . "tabnext"
  794. execute bufwinnr(_bufNbr) . "wincmd w"
  795. else
  796. " Use BufExplorer window for the buffer.
  797. execute "keepjumps keepalt silent b!" _bufNbr
  798. endif
  799. endif
  800. " Make the buffer 'listed' again.
  801. call setbufvar(_bufNbr, "&buflisted", "1")
  802. " Call any associated function references. g:bufExplorerFuncRef may be
  803. " an individual function reference or it may be a list containing
  804. " function references. It will ignore anything that's not a function
  805. " reference.
  806. "
  807. " See :help FuncRef for more on function references.
  808. if exists("g:BufExplorerFuncRef")
  809. if type(g:BufExplorerFuncRef) == 2
  810. keepj call g:BufExplorerFuncRef()
  811. elseif type(g:BufExplorerFuncRef) == 3
  812. for FncRef in g:BufExplorerFuncRef
  813. if type(FncRef) == 2
  814. keepj call FncRef()
  815. endif
  816. endfor
  817. endif
  818. endif
  819. else
  820. call s:Error("Sorry, that buffer no longer exists, please select another")
  821. call s:DeleteBuffer(_bufNbr, "wipe")
  822. endif
  823. endfunction
  824. " RemoveBuffer {{{2
  825. function! s:RemoveBuffer(mode)
  826. " Are we on a line with a file name?
  827. if line('.') < s:firstBufferLine
  828. return
  829. endif
  830. let mode = a:mode
  831. " These commands are to temporarily suspend the activity of winmanager.
  832. if exists("b:displayMode") && b:displayMode == "winmanager"
  833. call WinManagerSuspendAUs()
  834. end
  835. let _bufNbr = str2nr(getline('.'))
  836. if getbufvar(_bufNbr, '&modified') == 1
  837. " Calling confirm() requires Vim built with dialog option.
  838. if !has("dialog_con") && !has("dialog_gui")
  839. call s:Error("Sorry, no write since last change for buffer "._bufNbr.", unable to delete")
  840. return
  841. endif
  842. let answer = confirm('No write since last change for buffer '._bufNbr.'. Delete anyway?', "&Yes\n&No", 2)
  843. if a:mode == "delete" && answer == 1
  844. let mode = "force_delete"
  845. elseif a:mode == "wipe" && answer == 1
  846. let mode = "force_wipe"
  847. else
  848. return
  849. endif
  850. endif
  851. " Okay, everything is good, delete or wipe the buffer.
  852. call s:DeleteBuffer(_bufNbr, mode)
  853. " Reactivate winmanager autocommand activity.
  854. if exists("b:displayMode") && b:displayMode == "winmanager"
  855. call WinManagerForceReSize("BufExplorer")
  856. call WinManagerResumeAUs()
  857. end
  858. endfunction
  859. " DeleteBuffer {{{2
  860. function! s:DeleteBuffer(buf, mode)
  861. " This routine assumes that the buffer to be removed is on the current line.
  862. try
  863. " Wipe/Delete buffer from Vim.
  864. if a:mode == "wipe"
  865. execute "silent bwipe" a:buf
  866. elseif a:mode == "force_wipe"
  867. execute "silent bwipe!" a:buf
  868. elseif a:mode == "force_delete"
  869. execute "silent bdelete!" a:buf
  870. else
  871. execute "silent bdelete" a:buf
  872. endif
  873. " Delete the buffer from the list on screen.
  874. setlocal modifiable
  875. normal! "_dd
  876. setlocal nomodifiable
  877. " Delete the buffer from the raw buffer list.
  878. unlet s:raw_buffer_listing[a:buf]
  879. catch
  880. call s:Error(v:exception)
  881. endtry
  882. endfunction
  883. " ListedAndCurrentTab {{{2
  884. " Returns whether the specified buffer is both listed and associated with the
  885. " current tab.
  886. function! s:ListedAndCurrentTab(buf)
  887. return buflisted(a:buf) && s:IsInCurrentTab(a:buf)
  888. endfunction
  889. " Close {{{2
  890. function! s:Close()
  891. " Get only the listed buffers associated with the current tab.
  892. let listed = filter(copy(s:MRUList), "s:ListedAndCurrentTab(v:val)")
  893. if len(listed) == 0
  894. let listed = filter(range(1, bufnr('$')), "s:ListedAndCurrentTab(v:val)")
  895. endif
  896. " If we needed to split the main window, close the split one.
  897. if s:didSplit
  898. execute "wincmd c"
  899. endif
  900. " Check to see if there are anymore buffers listed.
  901. if len(listed) == 0
  902. " Since there are no buffers left to switch to, open a new empty
  903. " buffers.
  904. execute "enew"
  905. else
  906. " Since there are buffers left to switch to, switch to the previous and
  907. " then the current.
  908. for b in reverse(listed[0:1])
  909. execute "keepjumps silent b ".b
  910. endfor
  911. endif
  912. " Clear any messages.
  913. echo
  914. endfunction
  915. " ToggleShowTerminal {{{2
  916. function! s:ToggleShowTerminal()
  917. let g:bufExplorerShowTerminal = !g:bufExplorerShowTerminal
  918. call s:RebuildBufferList()
  919. call s:UpdateHelpStatus()
  920. endfunction
  921. " ToggleSplitOutPathName {{{2
  922. function! s:ToggleSplitOutPathName()
  923. let g:bufExplorerSplitOutPathName = !g:bufExplorerSplitOutPathName
  924. call s:RebuildBufferList()
  925. call s:UpdateHelpStatus()
  926. endfunction
  927. " ToggleShowRelativePath {{{2
  928. function! s:ToggleShowRelativePath()
  929. let g:bufExplorerShowRelativePath = !g:bufExplorerShowRelativePath
  930. call s:RebuildBufferList()
  931. call s:UpdateHelpStatus()
  932. endfunction
  933. " ToggleShowTabBuffer {{{2
  934. function! s:ToggleShowTabBuffer()
  935. let g:bufExplorerShowTabBuffer = !g:bufExplorerShowTabBuffer
  936. call s:RebuildBufferList(g:bufExplorerShowTabBuffer)
  937. call s:UpdateHelpStatus()
  938. endfunction
  939. " ToggleOnlyOneTab {{{2
  940. function! s:ToggleOnlyOneTab()
  941. let g:bufExplorerOnlyOneTab = !g:bufExplorerOnlyOneTab
  942. call s:RebuildBufferList()
  943. call s:UpdateHelpStatus()
  944. endfunction
  945. " ToggleShowUnlisted {{{2
  946. function! s:ToggleShowUnlisted()
  947. let g:bufExplorerShowUnlisted = !g:bufExplorerShowUnlisted
  948. let num_bufs = s:RebuildBufferList(g:bufExplorerShowUnlisted == 0)
  949. call s:UpdateHelpStatus()
  950. endfunction
  951. " ToggleFindActive {{{2
  952. function! s:ToggleFindActive()
  953. let g:bufExplorerFindActive = !g:bufExplorerFindActive
  954. call s:UpdateHelpStatus()
  955. endfunction
  956. " RebuildBufferList {{{2
  957. function! s:RebuildBufferList(...)
  958. setlocal modifiable
  959. let curPos = getpos('.')
  960. if a:0 && a:000[0] && (line('$') >= s:firstBufferLine)
  961. " Clear the list first.
  962. execute "silent keepjumps ".s:firstBufferLine.',$d _'
  963. endif
  964. let num_bufs = s:BuildBufferList()
  965. call setpos('.', curPos)
  966. setlocal nomodifiable
  967. return num_bufs
  968. endfunction
  969. " UpdateHelpStatus {{{2
  970. function! s:UpdateHelpStatus()
  971. setlocal modifiable
  972. let text = s:GetHelpStatus()
  973. call setline(s:firstBufferLine - 2, text)
  974. setlocal nomodifiable
  975. endfunction
  976. " Key_number {{{2
  977. function! s:Key_number(line)
  978. let _bufnr = str2nr(a:line)
  979. let key = [printf('%9d', _bufnr)]
  980. return key
  981. endfunction
  982. " Key_name {{{2
  983. function! s:Key_name(line)
  984. let _bufnr = str2nr(a:line)
  985. let buf = s:raw_buffer_listing[_bufnr]
  986. let key = [buf.shortname, buf.fullname]
  987. return key
  988. endfunction
  989. " Key_fullpath {{{2
  990. function! s:Key_fullpath(line)
  991. let _bufnr = str2nr(a:line)
  992. let buf = s:raw_buffer_listing[_bufnr]
  993. let key = [buf.fullname]
  994. return key
  995. endfunction
  996. " Key_extension {{{2
  997. function! s:Key_extension(line)
  998. let _bufnr = str2nr(a:line)
  999. let buf = s:raw_buffer_listing[_bufnr]
  1000. let extension = fnamemodify(buf.shortname, ':e')
  1001. let key = [extension, buf.shortname, buf.fullname]
  1002. return key
  1003. endfunction
  1004. " Key_mru {{{2
  1005. function! s:Key_mru(line)
  1006. let _bufnr = str2nr(a:line)
  1007. let buf = s:raw_buffer_listing[_bufnr]
  1008. let pos = index(s:MRUList, _bufnr)
  1009. if pos < 0
  1010. let pos = 0
  1011. endif
  1012. return [printf('%9d', pos), buf.fullname]
  1013. endfunction
  1014. " SortByKeyFunc {{{2
  1015. function! s:SortByKeyFunc(keyFunc)
  1016. let keyedLines = []
  1017. for line in getline(s:firstBufferLine, "$")
  1018. let key = eval(a:keyFunc . '(line)')
  1019. call add(keyedLines, join(key + [line], "\1"))
  1020. endfor
  1021. " Ignore case when sorting by passing `1`:
  1022. call sort(keyedLines, 1)
  1023. if g:bufExplorerReverseSort
  1024. call reverse(keyedLines)
  1025. endif
  1026. let lines = []
  1027. for keyedLine in keyedLines
  1028. call add(lines, split(keyedLine, "\1")[-1])
  1029. endfor
  1030. call setline(s:firstBufferLine, lines)
  1031. endfunction
  1032. " SortReverse {{{2
  1033. function! s:SortReverse()
  1034. let g:bufExplorerReverseSort = !g:bufExplorerReverseSort
  1035. call s:ReSortListing()
  1036. endfunction
  1037. " SortSelect {{{2
  1038. function! s:SortSelect()
  1039. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) + 1, s:sort_by[0])
  1040. call s:ReSortListing()
  1041. endfunction
  1042. " ReverseSortSelect {{{2
  1043. function! s:ReverseSortSelect()
  1044. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) - 1, s:sort_by[-1])
  1045. call s:ReSortListing()
  1046. endfunction
  1047. " ReSortListing {{{2
  1048. function! s:ReSortListing()
  1049. setlocal modifiable
  1050. let curPos = getpos('.')
  1051. call s:SortListing()
  1052. call s:UpdateHelpStatus()
  1053. call setpos('.', curPos)
  1054. setlocal nomodifiable
  1055. endfunction
  1056. " SortListing {{{2
  1057. function! s:SortListing()
  1058. call s:SortByKeyFunc("<SID>Key_" . g:bufExplorerSortBy)
  1059. endfunction
  1060. " MRUListShow {{{2
  1061. function! s:MRUListShow()
  1062. echomsg "MRUList=".string(s:MRUList)
  1063. endfunction
  1064. " Error {{{2
  1065. " Display a message using ErrorMsg highlight group.
  1066. function! s:Error(msg)
  1067. echohl ErrorMsg
  1068. echomsg a:msg
  1069. echohl None
  1070. endfunction
  1071. " Warning {{{2
  1072. " Display a message using WarningMsg highlight group.
  1073. function! s:Warning(msg)
  1074. echohl WarningMsg
  1075. echomsg a:msg
  1076. echohl None
  1077. endfunction
  1078. " GetTabNbr {{{2
  1079. function! s:GetTabNbr(bufNbr)
  1080. " Prefer current tab.
  1081. if bufwinnr(a:bufNbr) > 0
  1082. return tabpagenr()
  1083. endif
  1084. " Searching buffer bufno, in tabs.
  1085. for i in range(tabpagenr("$"))
  1086. if index(tabpagebuflist(i + 1), a:bufNbr) != -1
  1087. return i + 1
  1088. endif
  1089. endfor
  1090. return 0
  1091. endfunction
  1092. " GetWinNbr" {{{2
  1093. function! s:GetWinNbr(tabNbr, bufNbr)
  1094. " window number in tabpage.
  1095. let tablist = tabpagebuflist(a:tabNbr)
  1096. " Number: 0
  1097. " String: 1
  1098. " Funcref: 2
  1099. " List: 3
  1100. " Dictionary: 4
  1101. " Float: 5
  1102. if type(tablist) == 3
  1103. return index(tabpagebuflist(a:tabNbr), a:bufNbr) + 1
  1104. else
  1105. return 1
  1106. endif
  1107. endfunction
  1108. " StringWidth" {{{2
  1109. if exists('*strwidth')
  1110. function s:StringWidth(s)
  1111. return strwidth(a:s)
  1112. endfunction
  1113. else
  1114. function s:StringWidth(s)
  1115. return len(a:s)
  1116. endfunction
  1117. endif
  1118. " Winmanager Integration {{{2
  1119. let g:BufExplorer_title = "\[Buf\ List\]"
  1120. call s:Set("g:bufExplorerResize", 1)
  1121. call s:Set("g:bufExplorerMaxHeight", 25) " Handles dynamic resizing of the window.
  1122. " function! to start display. Set the mode to 'winmanager' for this buffer.
  1123. " This is to figure out how this plugin was called. In a standalone fashion
  1124. " or by winmanager.
  1125. function! BufExplorer_Start()
  1126. let b:displayMode = "winmanager"
  1127. call s:SetLocalSettings()
  1128. call BufExplorer()
  1129. endfunction
  1130. " Returns whether the display is okay or not.
  1131. function! BufExplorer_IsValid()
  1132. return 0
  1133. endfunction
  1134. " Handles dynamic refreshing of the window.
  1135. function! BufExplorer_Refresh()
  1136. let b:displayMode = "winmanager"
  1137. call s:SetLocalSettings()
  1138. call BufExplorer()
  1139. endfunction
  1140. function! BufExplorer_ReSize()
  1141. if !g:bufExplorerResize
  1142. return
  1143. end
  1144. let nlines = min([line("$"), g:bufExplorerMaxHeight])
  1145. execute nlines." wincmd _"
  1146. " The following lines restore the layout so that the last file line is also
  1147. " the last window line. Sometimes, when a line is deleted, although the
  1148. " window size is exactly equal to the number of lines in the file, some of
  1149. " the lines are pushed up and we see some lagging '~'s.
  1150. let pres = getpos(".")
  1151. normal! $
  1152. let _scr = &scrolloff
  1153. let &scrolloff = 0
  1154. normal! z-
  1155. let &scrolloff = _scr
  1156. call setpos(".", pres)
  1157. endfunction
  1158. " Default values {{{2
  1159. call s:Set("g:bufExplorerDisableDefaultKeyMapping", 0) " Do not disable default key mappings.
  1160. call s:Set("g:bufExplorerDefaultHelp", 1) " Show default help?
  1161. call s:Set("g:bufExplorerDetailedHelp", 0) " Show detailed help?
  1162. call s:Set("g:bufExplorerFindActive", 1) " When selecting an active buffer, take you to the window where it is active?
  1163. call s:Set("g:bufExplorerOnlyOneTab", 1) " If ShowTabBuffer = 1, only store the most recent tab for this buffer.
  1164. call s:Set("g:bufExplorerReverseSort", 0) " Sort in reverse order by default?
  1165. call s:Set("g:bufExplorerShowDirectories", 1) " (Dir's are added by commands like ':e .')
  1166. call s:Set("g:bufExplorerShowRelativePath", 0) " Show listings with relative or absolute paths?
  1167. call s:Set("g:bufExplorerShowTabBuffer", 0) " Show only buffer(s) for this tab?
  1168. call s:Set("g:bufExplorerShowUnlisted", 0) " Show unlisted buffers?
  1169. call s:Set("g:bufExplorerShowNoName", 0) " Show 'No Name' buffers?
  1170. call s:Set("g:bufExplorerSortBy", "mru") " Sorting methods are in s:sort_by:
  1171. call s:Set("g:bufExplorerSplitBelow", &splitbelow) " Should horizontal splits be below or above current window?
  1172. call s:Set("g:bufExplorerSplitOutPathName", 1) " Split out path and file name?
  1173. call s:Set("g:bufExplorerSplitRight", &splitright) " Should vertical splits be on the right or left of current window?
  1174. call s:Set("g:bufExplorerSplitVertSize", 0) " Height for a vertical split. If <=0, default Vim size is used.
  1175. call s:Set("g:bufExplorerSplitHorzSize", 0) " Height for a horizontal split. If <=0, default Vim size is used.
  1176. call s:Set("g:bufExplorerShowTerminal", 1) " Show terminal buffers?
  1177. " Default key mapping {{{2
  1178. if !hasmapto('BufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1179. nnoremap <script> <silent> <unique> <Leader>be :BufExplorer<CR>
  1180. endif
  1181. if !hasmapto('ToggleBufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1182. nnoremap <script> <silent> <unique> <Leader>bt :ToggleBufExplorer<CR>
  1183. endif
  1184. if !hasmapto('BufExplorerHorizontalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1185. nnoremap <script> <silent> <unique> <Leader>bs :BufExplorerHorizontalSplit<CR>
  1186. endif
  1187. if !hasmapto('BufExplorerVerticalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1188. nnoremap <script> <silent> <unique> <Leader>bv :BufExplorerVerticalSplit<CR>
  1189. endif
  1190. " vim:ft=vim foldmethod=marker sw=4