Skip to content

Instantly share code, notes, and snippets.

@jeff-r
Created September 19, 2011 16:02
Show Gist options
  • Save jeff-r/1226832 to your computer and use it in GitHub Desktop.
Save jeff-r/1226832 to your computer and use it in GitHub Desktop.
Vim bindings to fold Ruby class and spec files.
" Folding for Ruby
"
" ,z -- Show only last search
" ,zz -- Show only "describe ..." and "it ..." lines in specs
" ,zd -- Show only "class ..." and "def ..." lines in Ruby files
" zR -- Remove all folds
"
" From http://vim.wikia.com/wiki/Folding_with_Regular_Expression
nnoremap ,z :setlocal foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\\|\\|(getline(v:lnum+1)=~@/)?1:2 foldmethod=expr foldlevel=0 foldcolumn=2<CR>
" Then variations on that, with different searches ...
"
" Fold spec files, displaying "describe ..." and "it ..." lines
function! FoldSpec()
let @/='\(describe.*do$\|it.*do$\)'
setlocal foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\\|\\|(getline(v:lnum+1)=~@/)?1:2 foldmethod=expr foldlevel=0 foldcolumn=2
endfunction
map ,zz :call FoldSpec()<CR>
" Fold Ruby, showing class and method definitions
function! FoldDefs()
let @/='\(module\ \|class\ \|has_many\ \|belongs_to\ \|_filter\ \|helper\ \|belongs_to\ \|def\ \|private\|protected\)'
setlocal foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\\|\\|(getline(v:lnum+1)=~@/)?1:2 foldmethod=expr foldlevel=0 foldcolumn=2
endfunction
map ,zd :call FoldDefs()<CR>
" Set the text that represents folded lines to a simple dash, showing no
" information.
" This way, when viewing folded specs and classes, there is minimal cruft on
" the screen to distract from the unfolded content.
set foldtext=MyFoldText()
function! MyFoldText()
return "-"
endfunction
@krisleech
Copy link

FoldDefs - Is there any way to have the fold on the same line as the def? The fold appears on the line below the def.

@jeff-r
Copy link
Author

jeff-r commented Nov 1, 2011

I don't think so. I'm pretty sure it is limited to showing up on the following line. But if you find out it can appear on the same line, let me know!

@krisleech
Copy link

I sure will, thanks for getting back to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment