Vim Search Folding!
Created: 2023-01-26Here’s a quick vim shortcut that I’m loving: I call it "search folding".
How it works:
-
Do any kind of search (with
/
or*
, etc.) -
Hit F7 to show only the matching lines (uses folding). View and make changes to the lines.
-
Hit F7 again to go back to the regular view.
Let’s see an example, after which I’ve got the source of the function and its mapping to the F7 key.
Example in action
Imagine you’re working on this weird code and you need to make a change to the paradox_scraper
object. You’ll need to do several changes depending on the context, so this isn’t a find/replace job.
Warning: Silly Example Code!
var paradox_scraper = { matter: 1.22223, scrape: "Bitter surface tasted!", trivial: true, piano: ['a','b','c'], }; function mechanical_frog(flag){ var straw_condition = flag ? 'yellow' : 'green'; // Outline engine(straw_condition); var beans = snake.gold.scan(paradox_scraper); // Important! The paradox_scraper.piano MUST have an 'e' // to continue with the harsh_outline!!! paradox_scraper.piano.push('e'); var sugar = harsh_outline(paradox_scraper); return { beans: beans, sugar : sugar }; } function RoleInflator(hog){ var solid_diameter = hog.wash(); var crude_rule = 1.2; if(hog.paradox_scraper.trivial){ crude_rule = 7; } return { melted: invite.blaster, crunchy: hog.paradox_scaper.matter, frozen: solid_diameter, stained: crude_rule, } }
I can search with /paradox_scraper
, or just hit *
with my cursor on that keyword.
Now I hit F7 and now I’m looking at just the matching lines for me to review and edit. The rest is folded away!:
var paradox_scraper = { +-- 11 lines: matter: 1.22223,-------------------------------- var beans = snake.gold.scan(paradox_scraper); // Important! The paradox_scraper.piano MUST have an 'e' // to continue with the harsh_outline!!! paradox_scraper.piano.push('e'); var sugar = harsh_outline(paradox_scraper); +-- 8 lines: return { beans: beans, sugar : sugar };--------- if(hog.paradox_scraper.trivial){ +-- 10 lines: crude_rule = 7;---------------------------------
Once I’m done doing whatever it is I need to do with the paradox_scraper
(gotta be careful with those things!), I hit F7 again to return to the normal, non-folded view.
The vimscript
Here’s the function and mapping straight out of my .vimrc
:
" Search folding (after any regular search, this folds all non-matched lines) let g:search_folded = 0 function! FoldTheSearch() if g:search_folded echom "Opening all folds" set nofoldenable let g:search_folded = 0 else set foldexpr=getline(v:lnum)!~@/ set foldmethod=expr set foldenable let g:search_folded = 1 endif endfunction nnoremap <F7> :call FoldTheSearch()<cr>
I owe the basic concept to the two line "Simple folding" example here:
Related: vim-convenience (where I have shorter examples)