bufexplorer.vim 56 KB

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