pchr8
pchr8

Reputation: 115

How can I save in vim a file with the actual fold text? ("+-- 43 lines [...]")?

I am looking for a way to save to a new text file a file that is folded, with all the folds closed. In other words, just as I see it on the screen.

Is it possible?

(I will have to print the code later, and parts of it are irrelevant to my purposes; the folding mechanism would be ideal for this, my other alternative is manually adding "[X lines omitted]" to the saved text.)

Upvotes: 1

Views: 316

Answers (3)

Ingo Karkat
Ingo Karkat

Reputation: 172698

Here is a custom :RenderClosedFolds command, which will modify the current buffer / range. It also attempts to maintain the Folded highlighting of the original folds.

":[range]RenderClosedFolds
"           Replace all lines currently hidden inside closed folds
"           with a single line representing 'foldtext'.
function! s:RenderClosedFolds()
    if line('.') == foldclosed('.')
        let l:result = foldtextresult('.')
        call setline('.', l:result)
        execute printf('syntax match renderedFold "\V\^%s\$" containedin=ALL keepend', escape(l:result, '"\'))
    else
        delete _
    endif
endfunction
command! -bar -range=% RenderClosedFolds
\   highlight def link renderedFold Folded |
\   let g:ingocommands_IsEntireBuffer = (<line1> == 1 && <line2> == line('$')) |
\   if g:ingocommands_IsEntireBuffer | syntax clear renderedFold | endif |
\   let g:save_foldmethod = &l:foldmethod | setlocal foldmethod=manual |
\   execute '<line1>,<line2>folddoclosed call <SID>RenderClosedFolds()' |
\   if g:ingocommands_IsEntireBuffer | setlocal nofoldenable | endif |
\   let &l:foldmethod = g:save_foldmethod | unlet g:save_foldmethod g:ingocommands_IsEntireBuffer

Upvotes: 2

Christian Brabandt
Christian Brabandt

Reputation: 8248

I have once created a script, that saves all folds to a new buffer.

Upvotes: 2

tossbyte
tossbyte

Reputation: 380

Fold your text as needed and then use :TOhtml to convert to an HTML file. This will preserve your folding. If you need it as a plain text file, you can post-process e.g. with w3m, which renders HTML to text and allows to dump it to a text file.

Upvotes: 3

Related Questions