2

In vim I need to glance over a folded json text and see the value of a key as the folds title?

Looking through the help I saw how to fold by reqular expression though not how to change the folds title.

What suggestions do you have?

Screenshot

Edit: Screenshot of result thanks to @Mass solution Screenshot

  • Do you use filetype=json and fdm=syntax? – mike Dec 10 '17 at 12:24
5

No problem. Here is a basic implementation:

set foldtext=FoldText()

function! FoldText()
  let l:fs = match(getline(v:foldstart, v:foldend), '"label":')
  if l:fs < 0
    return foldtext()
  endif
  let l:label = matchstr(getline(v:foldstart + l:fs),
        \ '"label":\s\+"\zs[^"]\+\ze"')
  let l:ft = substitute(foldtext(), ': \zs.\+', l:label, '')
  return l:ft
endfunction
  • Result !Screenshot – AikenCura Dec 11 '17 at 6:46
  • @Mass Wow! How did you figure that out? I looked through advanced folding and could not find anything suitable. – mike Dec 11 '17 at 13:43
  • 2
    @mike, basically by thoroughly reading the help section :help folding (which links to :help foldtext), I knew there was an option to change the fold text vim uses. From there is was just writing a function to grab the label from a particular block of text. Losh's book is great, but it is not always comprehensive. – Mass Dec 11 '17 at 15:19
1

Vim will always show the beginning of the first line as hint.

You wrote, that you use JSON. JSON is a pure data format, if it was something else, I would have advised, to use a comment at the beginning of the fold, so that you could see it.

The only possible workaround, that I see, would be to follow the advise given here, so that the first field in an entry contains the desired string. If you fold then, it would result in what you are looking for.

However, this may not be what you are looking for, because you will need some kind of filter, to prepare your json file.

  • Im fairly certain there’s a way to change the foldstring... – D. Ben Knoble Dec 10 '17 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.