bufexplorer.vim 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. "============================================================================
  2. " Copyright: Copyright (c) 2001-2024, 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: Tuesday, 13 August 2024
  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.27"
  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. setlocal buftype=nofile
  413. setlocal modifiable
  414. setlocal noreadonly
  415. setlocal noswapfile
  416. setlocal nowrap
  417. setlocal bufhidden=wipe
  418. call s:SetupSyntax()
  419. call s:MapKeys()
  420. " Wipe out any existing lines in case BufExplorer buffer exists and the
  421. " user had changed any global settings that might reduce the number of
  422. " lines needed in the buffer.
  423. silent keepjumps 1,$d _
  424. call setline(1, s:CreateHelp())
  425. call s:BuildBufferList()
  426. call cursor(s:firstBufferLine, 1)
  427. if !g:bufExplorerResize
  428. normal! zz
  429. endif
  430. setlocal nomodifiable
  431. endfunction
  432. " MapKeys {{{2
  433. function! s:MapKeys()
  434. if exists("b:displayMode") && b:displayMode == "winmanager"
  435. nnoremap <buffer> <silent> <tab> :call <SID>SelectBuffer()<CR>
  436. endif
  437. nnoremap <script> <silent> <nowait> <buffer> <2-leftmouse> :call <SID>SelectBuffer()<CR>
  438. nnoremap <script> <silent> <nowait> <buffer> <CR> :call <SID>SelectBuffer()<CR>
  439. nnoremap <script> <silent> <nowait> <buffer> <F1> :call <SID>ToggleHelp()<CR>
  440. nnoremap <script> <silent> <nowait> <buffer> <s-cr> :call <SID>SelectBuffer("tab")<CR>
  441. nnoremap <script> <silent> <nowait> <buffer> a :call <SID>ToggleFindActive()<CR>
  442. nnoremap <script> <silent> <nowait> <buffer> b :call <SID>SelectBuffer("ask")<CR>
  443. nnoremap <script> <silent> <nowait> <buffer> d :call <SID>RemoveBuffer("delete")<CR>
  444. xnoremap <script> <silent> <nowait> <buffer> d :call <SID>RemoveBuffer("delete")<CR>
  445. nnoremap <script> <silent> <nowait> <buffer> D :call <SID>RemoveBuffer("wipe")<CR>
  446. xnoremap <script> <silent> <nowait> <buffer> D :call <SID>RemoveBuffer("wipe")<CR>
  447. nnoremap <script> <silent> <nowait> <buffer> f :call <SID>SelectBuffer("split", "sb")<CR>
  448. nnoremap <script> <silent> <nowait> <buffer> F :call <SID>SelectBuffer("split", "st")<CR>
  449. nnoremap <script> <silent> <nowait> <buffer> m :call <SID>MRUListShow()<CR>
  450. nnoremap <script> <silent> <nowait> <buffer> o :call <SID>SelectBuffer()<CR>
  451. nnoremap <script> <silent> <nowait> <buffer> p :call <SID>ToggleSplitOutPathName()<CR>
  452. nnoremap <script> <silent> <nowait> <buffer> q :call <SID>Close()<CR>
  453. nnoremap <script> <silent> <nowait> <buffer> r :call <SID>SortReverse()<CR>
  454. nnoremap <script> <silent> <nowait> <buffer> R :call <SID>ToggleShowRelativePath()<CR>
  455. nnoremap <script> <silent> <nowait> <buffer> s :call <SID>SortSelect()<CR>
  456. nnoremap <script> <silent> <nowait> <buffer> S :call <SID>ReverseSortSelect()<CR>
  457. nnoremap <script> <silent> <nowait> <buffer> t :call <SID>SelectBuffer("tab")<CR>
  458. nnoremap <script> <silent> <nowait> <buffer> T :call <SID>ToggleShowTabBuffer()<CR>
  459. nnoremap <script> <silent> <nowait> <buffer> u :call <SID>ToggleShowUnlisted()<CR>
  460. nnoremap <script> <silent> <nowait> <buffer> v :call <SID>SelectBuffer("split", "vr")<CR>
  461. nnoremap <script> <silent> <nowait> <buffer> V :call <SID>SelectBuffer("split", "vl")<CR>
  462. for k in ["G", "n", "N", "L", "M", "H"]
  463. execute "nnoremap <buffer> <silent>" k ":keepjumps normal!" k."<CR>"
  464. endfor
  465. endfunction
  466. " SetupSyntax {{{2
  467. function! s:SetupSyntax()
  468. if has("syntax")
  469. syn match bufExplorerHelp "^\".*" contains=bufExplorerSortBy,bufExplorerMapping,bufExplorerTitle,bufExplorerSortType,bufExplorerToggleSplit,bufExplorerToggleOpen
  470. syn match bufExplorerOpenIn "Open in \w\+ window" contained
  471. syn match bufExplorerSplit "\w\+ split" contained
  472. syn match bufExplorerSortBy "Sorted by .*" contained contains=bufExplorerOpenIn,bufExplorerSplit
  473. syn match bufExplorerMapping "\" \zs.\+\ze :" contained
  474. syn match bufExplorerTitle "Buffer Explorer.*" contained
  475. syn match bufExplorerSortType "'\w\{-}'" contained
  476. syn match bufExplorerBufNbr /^\s*\d\+/
  477. syn match bufExplorerToggleSplit "toggle split type" contained
  478. syn match bufExplorerToggleOpen "toggle open mode" contained
  479. syn match bufExplorerModBuf /^\s*\d\+.\{4}+.*/
  480. syn match bufExplorerLockedBuf /^\s*\d\+.\{3}[\-=].*/
  481. syn match bufExplorerHidBuf /^\s*\d\+.\{2}h.*/
  482. syn match bufExplorerActBuf /^\s*\d\+.\{2}a.*/
  483. syn match bufExplorerCurBuf /^\s*\d\+.%.*/
  484. syn match bufExplorerAltBuf /^\s*\d\+.#.*/
  485. syn match bufExplorerUnlBuf /^\s*\d\+u.*/
  486. syn match bufExplorerInactBuf /^\s*\d\+ \{7}.*/
  487. hi def link bufExplorerBufNbr Number
  488. hi def link bufExplorerMapping NonText
  489. hi def link bufExplorerHelp Special
  490. hi def link bufExplorerOpenIn Identifier
  491. hi def link bufExplorerSortBy String
  492. hi def link bufExplorerSplit NonText
  493. hi def link bufExplorerTitle NonText
  494. hi def link bufExplorerSortType bufExplorerSortBy
  495. hi def link bufExplorerToggleSplit bufExplorerSplit
  496. hi def link bufExplorerToggleOpen bufExplorerOpenIn
  497. hi def link bufExplorerActBuf Identifier
  498. hi def link bufExplorerAltBuf String
  499. hi def link bufExplorerCurBuf Type
  500. hi def link bufExplorerHidBuf Constant
  501. hi def link bufExplorerLockedBuf Special
  502. hi def link bufExplorerModBuf Exception
  503. hi def link bufExplorerUnlBuf Comment
  504. hi def link bufExplorerInactBuf Comment
  505. endif
  506. endfunction
  507. " ToggleHelp {{{2
  508. function! s:ToggleHelp()
  509. let g:bufExplorerDetailedHelp = !g:bufExplorerDetailedHelp
  510. setlocal modifiable
  511. " Save position.
  512. normal! ma
  513. " Remove old header.
  514. if s:firstBufferLine > 1
  515. execute "keepjumps 1,".(s:firstBufferLine - 1) "d _"
  516. endif
  517. call append(0, s:CreateHelp())
  518. silent! normal! g`a
  519. delmarks a
  520. setlocal nomodifiable
  521. if exists("b:displayMode") && b:displayMode == "winmanager"
  522. call WinManagerForceReSize("BufExplorer")
  523. endif
  524. endfunction
  525. " GetHelpStatus {{{2
  526. function! s:GetHelpStatus()
  527. let ret = '" Sorted by '.((g:bufExplorerReverseSort == 1) ? "reverse " : "").g:bufExplorerSortBy
  528. let ret .= ' | '.((g:bufExplorerFindActive == 0) ? "Don't " : "")."Locate buffer"
  529. let ret .= ((g:bufExplorerShowUnlisted == 0) ? "" : " | Show unlisted")
  530. let ret .= ((g:bufExplorerShowTabBuffer == 0) ? "" : " | Show buffers/tab")
  531. let ret .= ((g:bufExplorerOnlyOneTab == 0) ? "" : " | One tab/buffer")
  532. let ret .= ' | '.((g:bufExplorerShowRelativePath == 0) ? "Absolute" : "Relative")
  533. let ret .= ' '.((g:bufExplorerSplitOutPathName == 0) ? "Full" : "Split")." path"
  534. return ret
  535. endfunction
  536. " CreateHelp {{{2
  537. function! s:CreateHelp()
  538. if g:bufExplorerDefaultHelp == 0 && g:bufExplorerDetailedHelp == 0
  539. let s:firstBufferLine = 1
  540. return []
  541. endif
  542. let header = []
  543. if g:bufExplorerDetailedHelp == 1
  544. call add(header, '" Buffer Explorer ('.g:bufexplorer_version.')')
  545. call add(header, '" --------------------------')
  546. call add(header, '" <F1> : toggle this help')
  547. call add(header, '" <enter> or o or Mouse-Double-Click : open buffer under cursor')
  548. call add(header, '" <shift-enter> or t : open buffer in another tab')
  549. call add(header, '" a : toggle find active buffer')
  550. call add(header, '" b : Fast buffer switching with b<any bufnum>')
  551. call add(header, '" B : toggle if to save/use recent tab or not')
  552. call add(header, '" d : delete buffer')
  553. call add(header, '" D : wipe buffer')
  554. call add(header, '" F : open buffer in another window above the current')
  555. call add(header, '" f : open buffer in another window below the current')
  556. call add(header, '" p : toggle splitting of file and path name')
  557. call add(header, '" q : quit')
  558. call add(header, '" r : reverse sort')
  559. call add(header, '" R : toggle showing relative or full paths')
  560. call add(header, '" s : cycle thru "sort by" fields '.string(s:sort_by).'')
  561. call add(header, '" S : reverse cycle thru "sort by" fields')
  562. call add(header, '" T : toggle if to show only buffers for this tab or not')
  563. call add(header, '" u : toggle showing unlisted buffers')
  564. call add(header, '" V : open buffer in another window on the left of the current')
  565. call add(header, '" v : open buffer in another window on the right of the current')
  566. else
  567. call add(header, '" Press <F1> for Help')
  568. endif
  569. if (!exists("b:displayMode") || b:displayMode != "winmanager") || (b:displayMode == "winmanager" && g:bufExplorerDetailedHelp == 1)
  570. call add(header, s:GetHelpStatus())
  571. call add(header, '"=')
  572. endif
  573. let s:firstBufferLine = len(header) + 1
  574. return header
  575. endfunction
  576. " GetBufferInfo {{{2
  577. function! s:GetBufferInfo(bufnr)
  578. redir => bufoutput
  579. " Show all buffers including the unlisted ones. [!] tells Vim to show the
  580. " unlisted ones.
  581. buffers!
  582. redir END
  583. if a:bufnr > 0
  584. " Since we are only interested in this specified buffer
  585. " remove the other buffers listed
  586. let bufoutput = substitute(bufoutput."\n", '^.*\n\(\s*'.a:bufnr.'\>.\{-}\)\n.*', '\1', '')
  587. endif
  588. let [all, allwidths, listedwidths] = [[], {}, {}]
  589. for n in keys(s:types)
  590. let allwidths[n] = []
  591. let listedwidths[n] = []
  592. endfor
  593. " Loop over each line in the buffer.
  594. for buf in split(bufoutput, '\n')
  595. let bits = split(buf, '"')
  596. " Use first and last components after the split on '"', in case a
  597. " filename with an embedded '"' is present.
  598. let b = {"attributes": bits[0], "line": substitute(bits[-1], '\s*', '', '')}
  599. let name = bufname(str2nr(b.attributes))
  600. let b["hasNoName"] = empty(name)
  601. if b.hasNoName
  602. let name = "[No Name]"
  603. endif
  604. " Filter out term:// buffers if g:bufExplorerShowTerminal is 0
  605. if !g:bufExplorerShowTerminal && name =~ '^term://'
  606. continue
  607. endif
  608. for [key, val] in items(s:types)
  609. let b[key] = fnamemodify(name, val)
  610. endfor
  611. if getftype(b.fullname) == "dir" && g:bufExplorerShowDirectories == 1
  612. let b.shortname = "<DIRECTORY>"
  613. endif
  614. call add(all, b)
  615. for n in keys(s:types)
  616. call add(allwidths[n], s:StringWidth(b[n]))
  617. if b.attributes !~ "u"
  618. call add(listedwidths[n], s:StringWidth(b[n]))
  619. endif
  620. endfor
  621. endfor
  622. let [s:allpads, s:listedpads] = [{}, {}]
  623. for n in keys(s:types)
  624. let s:allpads[n] = repeat(' ', max(allwidths[n]))
  625. let s:listedpads[n] = repeat(' ', max(listedwidths[n]))
  626. endfor
  627. return all
  628. endfunction
  629. " BuildBufferList {{{2
  630. function! s:BuildBufferList()
  631. let lines = []
  632. " Loop through every buffer.
  633. for buf in s:raw_buffer_listing
  634. " Skip unlisted buffers if we are not to show them.
  635. if !g:bufExplorerShowUnlisted && buf.attributes =~ "u"
  636. " Skip unlisted buffers if we are not to show them.
  637. continue
  638. endif
  639. " Skip "No Name" buffers if we are not to show them.
  640. if g:bufExplorerShowNoName == 0 && buf.hasNoName
  641. continue
  642. endif
  643. " Are we to show only buffer(s) for this tab?
  644. if g:bufExplorerShowTabBuffer && (!s:IsInCurrentTab(str2nr(buf.attributes)))
  645. continue
  646. endif
  647. let line = buf.attributes." "
  648. if exists("g:loaded_webdevicons")
  649. let line .= WebDevIconsGetFileTypeSymbol(buf.shortname)
  650. let line .= " "
  651. endif
  652. " Are we to split the path and file name?
  653. if g:bufExplorerSplitOutPathName
  654. let type = (g:bufExplorerShowRelativePath) ? "relativepath" : "path"
  655. let path = substitute( buf[type], $HOME."\\>", "~", "" )
  656. let pad = (g:bufExplorerShowUnlisted) ? s:allpads.shortname : s:listedpads.shortname
  657. let line .= buf.shortname." ".strpart(pad.path, s:StringWidth(buf.shortname))
  658. else
  659. let type = (g:bufExplorerShowRelativePath) ? "relativename" : "fullname"
  660. let path = substitute( buf[type], $HOME."\\>", "~", "" )
  661. let line .= path
  662. endif
  663. let pads = (g:bufExplorerShowUnlisted) ? s:allpads : s:listedpads
  664. if !empty(pads[type])
  665. let line .= strpart(pads[type], s:StringWidth(path))." "
  666. endif
  667. let line .= buf.line
  668. call add(lines, line)
  669. endfor
  670. call setline(s:firstBufferLine, lines)
  671. call s:SortListing()
  672. endfunction
  673. " SelectBuffer {{{2
  674. function! s:SelectBuffer(...)
  675. " Sometimes messages are not cleared when we get here so it looks like an
  676. " error has occurred when it really has not.
  677. "echo ""
  678. let _bufNbr = -1
  679. if (a:0 == 1) && (a:1 == "ask")
  680. " Ask the user for input.
  681. call inputsave()
  682. let cmd = input("Enter buffer number to switch to: ")
  683. call inputrestore()
  684. " Clear the message area from the previous prompt.
  685. redraw | echo
  686. if strlen(cmd) > 0
  687. let _bufNbr = str2nr(cmd)
  688. else
  689. call s:Error("Invalid buffer number, try again.")
  690. return
  691. endif
  692. else
  693. " Are we on a line with a file name?
  694. if line('.') < s:firstBufferLine
  695. execute "normal! \<CR>"
  696. return
  697. endif
  698. let _bufNbr = str2nr(getline('.'))
  699. " Check and see if we are running BufferExplorer via WinManager.
  700. if exists("b:displayMode") && b:displayMode == "winmanager"
  701. let _bufName = expand("#"._bufNbr.":p")
  702. if (a:0 == 1) && (a:1 == "tab")
  703. call WinManagerFileEdit(_bufName, 1)
  704. else
  705. call WinManagerFileEdit(_bufName, 0)
  706. endif
  707. return
  708. endif
  709. endif
  710. if bufexists(_bufNbr)
  711. if bufnr("#") == _bufNbr && !exists("g:bufExplorerChgWin")
  712. return s:Close()
  713. endif
  714. " Get the tab number where this bufer is located in.
  715. let tabNbr = s:GetTabNbr(_bufNbr)
  716. " Are we supposed to open the selected buffer in a tab?
  717. if (a:0 == 1) && (a:1 == "tab")
  718. " Restore [BufExplorer] buffer.
  719. execute "silent buffer!".s:originBuffer
  720. " Was the tab found?
  721. if tabNbr == 0
  722. " _bufNbr is not opened in any tabs. Open a new tab with the
  723. " selected buffer in it.
  724. if v:version > 704 || ( v:version == 704 && has('patch2237') )
  725. " new syntax for last tab as of 7.4.2237
  726. execute "$tab split +buffer" . _bufNbr
  727. else
  728. execute "999tab split +buffer" . _bufNbr
  729. endif
  730. " Workaround for the issue mentioned in UpdateTabBufData.
  731. call s:UpdateTabBufData(_bufNbr)
  732. else
  733. " The _bufNbr is already opened in a tab, go to that tab.
  734. execute tabNbr . "tabnext"
  735. " Focus window.
  736. execute s:GetWinNbr(tabNbr, _bufNbr) . "wincmd w"
  737. endif
  738. " Are we supposed to open the selected buffer in a split?
  739. elseif (a:0 == 2) && (a:1 == "split")
  740. if g:bufExplorerFindActive
  741. call s:Close()
  742. endif
  743. " Was the tab found?
  744. if tabNbr != 0
  745. " Yes, the buffer is located in a tab. Go to that tab instead of
  746. " opening split
  747. execute tabNbr . "tabnext"
  748. else
  749. "Nope, the buffer is not in a tab, open it accordingly
  750. let _bufName = expand("#"._bufNbr.":p")
  751. if (a:2 == "vl")
  752. execute _bufName ?
  753. \ "vert topleft sb ".escape(_bufName, " ") :
  754. \ "vert topleft sb "._bufNbr
  755. elseif (a:2 == "vr")
  756. execute _bufName ?
  757. \ "vert belowright sb ".escape(_bufName, " ") :
  758. \ "vert belowright sb "._bufNbr
  759. elseif (a:2 == "st")
  760. execute _bufName ?
  761. \ "topleft sb ".escape(_bufName, " ") :
  762. \ "topleft sb "._bufNbr
  763. else " = sb
  764. execute _bufName ?
  765. \ "belowright sb ".escape(_bufName, " ") :
  766. \ "belowright sb "._bufNbr
  767. endif
  768. endif
  769. " Switch to selected buffer
  770. execute "keepalt silent b!" _bufNbr
  771. " Default, open in current window
  772. else
  773. " Are we suppose to move to the tab where the active buffer is?
  774. if exists("g:bufExplorerChgWin")
  775. execute g:bufExplorerChgWin."wincmd w"
  776. elseif bufloaded(_bufNbr) && g:bufExplorerFindActive
  777. if g:bufExplorerFindActive
  778. call s:Close()
  779. endif
  780. " Was the tab found?
  781. if tabNbr != 0
  782. " Yes, the buffer is located in a tab. Go to that tab number.
  783. execute tabNbr . "tabnext"
  784. else
  785. "Nope, the buffer is not in a tab. Simply switch to that
  786. "buffer.
  787. let _bufName = expand("#"._bufNbr.":p")
  788. execute _bufName ? "drop ".escape(_bufName, " ") : "buffer "._bufNbr
  789. endif
  790. endif
  791. " Switch to the selected buffer.
  792. execute "keepjumps keepalt silent b!" _bufNbr
  793. endif
  794. " Make the buffer 'listed' again.
  795. call setbufvar(_bufNbr, "&buflisted", "1")
  796. " Call any associated function references. g:bufExplorerFuncRef may be
  797. " an individual function reference or it may be a list containing
  798. " function references. It will ignore anything that's not a function
  799. " reference.
  800. "
  801. " See :help FuncRef for more on function references.
  802. if exists("g:BufExplorerFuncRef")
  803. if type(g:BufExplorerFuncRef) == 2
  804. keepj call g:BufExplorerFuncRef()
  805. elseif type(g:BufExplorerFuncRef) == 3
  806. for FncRef in g:BufExplorerFuncRef
  807. if type(FncRef) == 2
  808. keepj call FncRef()
  809. endif
  810. endfor
  811. endif
  812. endif
  813. else
  814. call s:Error("Sorry, that buffer no longer exists, please select another")
  815. call s:DeleteBuffer(_bufNbr, "wipe")
  816. endif
  817. endfunction
  818. " RemoveBuffer {{{2
  819. function! s:RemoveBuffer(mode)
  820. " Are we on a line with a file name?
  821. if line('.') < s:firstBufferLine
  822. return
  823. endif
  824. let mode = a:mode
  825. " These commands are to temporarily suspend the activity of winmanager.
  826. if exists("b:displayMode") && b:displayMode == "winmanager"
  827. call WinManagerSuspendAUs()
  828. end
  829. let _bufNbr = str2nr(getline('.'))
  830. if getbufvar(_bufNbr, '&modified') == 1
  831. " Calling confirm() requires Vim built with dialog option
  832. if !has("dialog_con") && !has("dialog_gui")
  833. call s:Error("Sorry, no write since last change for buffer "._bufNbr.", unable to delete")
  834. return
  835. endif
  836. let answer = confirm('No write since last change for buffer '._bufNbr.'. Delete anyway?', "&Yes\n&No", 2)
  837. if a:mode == "delete" && answer == 1
  838. let mode = "force_delete"
  839. elseif a:mode == "wipe" && answer == 1
  840. let mode = "force_wipe"
  841. else
  842. return
  843. endif
  844. endif
  845. " Okay, everything is good, delete or wipe the buffer.
  846. call s:DeleteBuffer(_bufNbr, mode)
  847. " Reactivate winmanager autocommand activity.
  848. if exists("b:displayMode") && b:displayMode == "winmanager"
  849. call WinManagerForceReSize("BufExplorer")
  850. call WinManagerResumeAUs()
  851. end
  852. endfunction
  853. " DeleteBuffer {{{2
  854. function! s:DeleteBuffer(buf, mode)
  855. " This routine assumes that the buffer to be removed is on the current line.
  856. try
  857. " Wipe/Delete buffer from Vim.
  858. if a:mode == "wipe"
  859. execute "silent bwipe" a:buf
  860. elseif a:mode == "force_wipe"
  861. execute "silent bwipe!" a:buf
  862. elseif a:mode == "force_delete"
  863. execute "silent bdelete!" a:buf
  864. else
  865. execute "silent bdelete" a:buf
  866. endif
  867. " Delete the buffer from the list on screen.
  868. setlocal modifiable
  869. normal! "_dd
  870. setlocal nomodifiable
  871. " Delete the buffer from the raw buffer list.
  872. call filter(s:raw_buffer_listing, 'v:val.attributes !~ " '.a:buf.' "')
  873. catch
  874. call s:Error(v:exception)
  875. endtry
  876. endfunction
  877. " ListedAndCurrentTab {{{2
  878. " Returns whether the specified buffer is both listed and associated
  879. " with the current tab
  880. function! s:ListedAndCurrentTab(buf)
  881. return buflisted(a:buf) && s:IsInCurrentTab(a:buf)
  882. endfunction
  883. " Close {{{2
  884. function! s:Close()
  885. " Get only the listed buffers associated with the current tab
  886. let listed = filter(copy(s:MRUList), "s:ListedAndCurrentTab(v:val)")
  887. if len(listed) == 0
  888. let listed = filter(range(1, bufnr('$')), "s:ListedAndCurrentTab(v:val)")
  889. endif
  890. " If we needed to split the main window, close the split one.
  891. if s:didSplit == 1 && bufwinnr(s:originBuffer) != -1
  892. execute "wincmd c"
  893. endif
  894. " Check to see if there are anymore buffers listed.
  895. if len(listed) == 0
  896. " Since there are no buffers left to switch to, open a new empty
  897. " buffers.
  898. execute "enew"
  899. else
  900. " Since there are buffers left to switch to, switch to the previous and
  901. " then the current.
  902. for b in reverse(listed[0:1])
  903. execute "keepjumps silent b ".b
  904. endfor
  905. endif
  906. " Clear any messages.
  907. echo
  908. endfunction
  909. " ToggleSplitOutPathName {{{2
  910. function! s:ToggleSplitOutPathName()
  911. let g:bufExplorerSplitOutPathName = !g:bufExplorerSplitOutPathName
  912. call s:RebuildBufferList()
  913. call s:UpdateHelpStatus()
  914. endfunction
  915. " ToggleShowRelativePath {{{2
  916. function! s:ToggleShowRelativePath()
  917. let g:bufExplorerShowRelativePath = !g:bufExplorerShowRelativePath
  918. call s:RebuildBufferList()
  919. call s:UpdateHelpStatus()
  920. endfunction
  921. " ToggleShowTabBuffer {{{2
  922. function! s:ToggleShowTabBuffer()
  923. let g:bufExplorerShowTabBuffer = !g:bufExplorerShowTabBuffer
  924. call s:RebuildBufferList(g:bufExplorerShowTabBuffer)
  925. call s:UpdateHelpStatus()
  926. endfunction
  927. " ToggleOnlyOneTab {{{2
  928. function! s:ToggleOnlyOneTab()
  929. let g:bufExplorerOnlyOneTab = !g:bufExplorerOnlyOneTab
  930. call s:RebuildBufferList()
  931. call s:UpdateHelpStatus()
  932. endfunction
  933. " ToggleShowUnlisted {{{2
  934. function! s:ToggleShowUnlisted()
  935. let g:bufExplorerShowUnlisted = !g:bufExplorerShowUnlisted
  936. let num_bufs = s:RebuildBufferList(g:bufExplorerShowUnlisted == 0)
  937. call s:UpdateHelpStatus()
  938. endfunction
  939. " ToggleFindActive {{{2
  940. function! s:ToggleFindActive()
  941. let g:bufExplorerFindActive = !g:bufExplorerFindActive
  942. call s:UpdateHelpStatus()
  943. endfunction
  944. " RebuildBufferList {{{2
  945. function! s:RebuildBufferList(...)
  946. setlocal modifiable
  947. let curPos = getpos('.')
  948. if a:0 && a:000[0] && (line('$') >= s:firstBufferLine)
  949. " Clear the list first.
  950. execute "silent keepjumps ".s:firstBufferLine.',$d _'
  951. endif
  952. let num_bufs = s:BuildBufferList()
  953. call setpos('.', curPos)
  954. setlocal nomodifiable
  955. return num_bufs
  956. endfunction
  957. " UpdateHelpStatus {{{2
  958. function! s:UpdateHelpStatus()
  959. setlocal modifiable
  960. let text = s:GetHelpStatus()
  961. call setline(s:firstBufferLine - 2, text)
  962. setlocal nomodifiable
  963. endfunction
  964. " MRUCmp {{{2
  965. function! s:MRUCmp(line1, line2)
  966. return index(s:MRUList, str2nr(a:line1)) - index(s:MRUList, str2nr(a:line2))
  967. endfunction
  968. " SortReverse {{{2
  969. function! s:SortReverse()
  970. let g:bufExplorerReverseSort = !g:bufExplorerReverseSort
  971. call s:ReSortListing()
  972. endfunction
  973. " SortSelect {{{2
  974. function! s:SortSelect()
  975. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) + 1, s:sort_by[0])
  976. call s:ReSortListing()
  977. endfunction
  978. " ReverseSortSelect {{{2
  979. function! s:ReverseSortSelect()
  980. let g:bufExplorerSortBy = get(s:sort_by, index(s:sort_by, g:bufExplorerSortBy) - 1, s:sort_by[-1])
  981. call s:ReSortListing()
  982. endfunction
  983. " ReSortListing {{{2
  984. function! s:ReSortListing()
  985. setlocal modifiable
  986. let curPos = getpos('.')
  987. call s:SortListing()
  988. call s:UpdateHelpStatus()
  989. call setpos('.', curPos)
  990. setlocal nomodifiable
  991. endfunction
  992. " SortListing {{{2
  993. function! s:SortListing()
  994. let sort = s:firstBufferLine.",$sort".((g:bufExplorerReverseSort == 1) ? "!": "")
  995. if g:bufExplorerSortBy == "number"
  996. " Easiest case.
  997. execute sort 'n'
  998. elseif g:bufExplorerSortBy == "name"
  999. " Sort by full path first
  1000. execute sort 'ir /\zs\f\+\ze\s\+line/'
  1001. if g:bufExplorerSplitOutPathName
  1002. execute sort 'ir /\d.\{7}\zs\f\+\ze/'
  1003. else
  1004. execute sort 'ir /\zs[^\/\\]\+\ze\s*line/'
  1005. endif
  1006. elseif g:bufExplorerSortBy == "fullpath"
  1007. if g:bufExplorerSplitOutPathName
  1008. " Sort twice - first on the file name then on the path.
  1009. execute sort 'ir /\d.\{7}\zs\f\+\ze/'
  1010. endif
  1011. execute sort 'ir /\zs\f\+\ze\s\+line/'
  1012. elseif g:bufExplorerSortBy == "extension"
  1013. " Sort by full path...
  1014. execute sort 'ir /\zs\f\+\ze\s\+line/'
  1015. " Sort by name...
  1016. if g:bufExplorerSplitOutPathName
  1017. " Sort twice - first on the file name then on the path.
  1018. execute sort 'ir /\d.\{7}\zs\f\+\ze/'
  1019. endif
  1020. " Sort by extension.
  1021. execute sort 'ir /\.\zs\w\+\ze\s/'
  1022. elseif g:bufExplorerSortBy == "mru"
  1023. let l = getline(s:firstBufferLine, "$")
  1024. call sort(l, "<SID>MRUCmp")
  1025. if g:bufExplorerReverseSort
  1026. call reverse(l)
  1027. endif
  1028. call setline(s:firstBufferLine, l)
  1029. endif
  1030. endfunction
  1031. " MRUListShow {{{2
  1032. function! s:MRUListShow()
  1033. echomsg "MRUList=".string(s:MRUList)
  1034. endfunction
  1035. " Error {{{2
  1036. " Display a message using ErrorMsg highlight group.
  1037. function! s:Error(msg)
  1038. echohl ErrorMsg
  1039. echomsg a:msg
  1040. echohl None
  1041. endfunction
  1042. " Warning {{{2
  1043. " Display a message using WarningMsg highlight group.
  1044. function! s:Warning(msg)
  1045. echohl WarningMsg
  1046. echomsg a:msg
  1047. echohl None
  1048. endfunction
  1049. " GetTabNbr {{{2
  1050. function! s:GetTabNbr(bufNbr)
  1051. " Searching buffer bufno, in tabs.
  1052. for i in range(tabpagenr("$"))
  1053. if index(tabpagebuflist(i + 1), a:bufNbr) != -1
  1054. return i + 1
  1055. endif
  1056. endfor
  1057. return 0
  1058. endfunction
  1059. " GetWinNbr" {{{2
  1060. function! s:GetWinNbr(tabNbr, bufNbr)
  1061. " window number in tabpage.
  1062. let tablist = tabpagebuflist(a:tabNbr)
  1063. " Number: 0
  1064. " String: 1
  1065. " Funcref: 2
  1066. " List: 3
  1067. " Dictionary: 4
  1068. " Float: 5
  1069. if type(tablist) == 3
  1070. return index(tabpagebuflist(a:tabNbr), a:bufNbr) + 1
  1071. else
  1072. return 1
  1073. endif
  1074. endfunction
  1075. " StringWidth" {{{2
  1076. if exists('*strwidth')
  1077. function s:StringWidth(s)
  1078. return strwidth(a:s)
  1079. endfunction
  1080. else
  1081. function s:StringWidth(s)
  1082. return len(a:s)
  1083. endfunction
  1084. endif
  1085. " Winmanager Integration {{{2
  1086. let g:BufExplorer_title = "\[Buf\ List\]"
  1087. call s:Set("g:bufExplorerResize", 1)
  1088. call s:Set("g:bufExplorerMaxHeight", 25) " Handles dynamic resizing of the window.
  1089. " function! to start display. Set the mode to 'winmanager' for this buffer.
  1090. " This is to figure out how this plugin was called. In a standalone fashion
  1091. " or by winmanager.
  1092. function! BufExplorer_Start()
  1093. let b:displayMode = "winmanager"
  1094. call s:SetLocalSettings()
  1095. call BufExplorer()
  1096. endfunction
  1097. " Returns whether the display is okay or not.
  1098. function! BufExplorer_IsValid()
  1099. return 0
  1100. endfunction
  1101. " Handles dynamic refreshing of the window.
  1102. function! BufExplorer_Refresh()
  1103. let b:displayMode = "winmanager"
  1104. call s:SetLocalSettings()
  1105. call BufExplorer()
  1106. endfunction
  1107. function! BufExplorer_ReSize()
  1108. if !g:bufExplorerResize
  1109. return
  1110. end
  1111. let nlines = min([line("$"), g:bufExplorerMaxHeight])
  1112. execute nlines." wincmd _"
  1113. " The following lines restore the layout so that the last file line is also
  1114. " the last window line. Sometimes, when a line is deleted, although the
  1115. " window size is exactly equal to the number of lines in the file, some of
  1116. " the lines are pushed up and we see some lagging '~'s.
  1117. let pres = getpos(".")
  1118. normal! $
  1119. let _scr = &scrolloff
  1120. let &scrolloff = 0
  1121. normal! z-
  1122. let &scrolloff = _scr
  1123. call setpos(".", pres)
  1124. endfunction
  1125. " Default values {{{2
  1126. call s:Set("g:bufExplorerDisableDefaultKeyMapping", 0) " Do not disable default key mappings.
  1127. call s:Set("g:bufExplorerDefaultHelp", 1) " Show default help?
  1128. call s:Set("g:bufExplorerDetailedHelp", 0) " Show detailed help?
  1129. call s:Set("g:bufExplorerFindActive", 1) " When selecting an active buffer, take you to the window where it is active?
  1130. call s:Set("g:bufExplorerOnlyOneTab", 1) " If ShowTabBuffer = 1, only store the most recent tab for this buffer.
  1131. call s:Set("g:bufExplorerReverseSort", 0) " Sort in reverse order by default?
  1132. call s:Set("g:bufExplorerShowDirectories", 1) " (Dir's are added by commands like ':e .')
  1133. call s:Set("g:bufExplorerShowRelativePath", 0) " Show listings with relative or absolute paths?
  1134. call s:Set("g:bufExplorerShowTabBuffer", 0) " Show only buffer(s) for this tab?
  1135. call s:Set("g:bufExplorerShowUnlisted", 0) " Show unlisted buffers?
  1136. call s:Set("g:bufExplorerShowNoName", 0) " Show 'No Name' buffers?
  1137. call s:Set("g:bufExplorerSortBy", "mru") " Sorting methods are in s:sort_by:
  1138. call s:Set("g:bufExplorerSplitBelow", &splitbelow) " Should horizontal splits be below or above current window?
  1139. call s:Set("g:bufExplorerSplitOutPathName", 1) " Split out path and file name?
  1140. call s:Set("g:bufExplorerSplitRight", &splitright) " Should vertical splits be on the right or left of current window?
  1141. call s:Set("g:bufExplorerSplitVertSize", 0) " Height for a vertical split. If <=0, default Vim size is used.
  1142. call s:Set("g:bufExplorerSplitHorzSize", 0) " Height for a horizontal split. If <=0, default Vim size is used.
  1143. call s:Set("g:bufExplorerShowTerminal", 1) " Show terminal buffers?
  1144. " Default key mapping {{{2
  1145. if !hasmapto('BufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1146. nnoremap <script> <silent> <unique> <Leader>be :BufExplorer<CR>
  1147. endif
  1148. if !hasmapto('ToggleBufExplorer') && g:bufExplorerDisableDefaultKeyMapping == 0
  1149. nnoremap <script> <silent> <unique> <Leader>bt :ToggleBufExplorer<CR>
  1150. endif
  1151. if !hasmapto('BufExplorerHorizontalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1152. nnoremap <script> <silent> <unique> <Leader>bs :BufExplorerHorizontalSplit<CR>
  1153. endif
  1154. if !hasmapto('BufExplorerVerticalSplit') && g:bufExplorerDisableDefaultKeyMapping == 0
  1155. nnoremap <script> <silent> <unique> <Leader>bv :BufExplorerVerticalSplit<CR>
  1156. endif
  1157. " vim:ft=vim foldmethod=marker sw=4