Is ad hoc code folding possible


I’m trying to us code folding to show specific lines of content and hide the irrelevant lines at initialisation. The lines I want to fold are ad hoc and not dependant on any feature of the language mode.

For example in one editor I need to show only lines 3-7 and 19-23, and fold the rest.

I’ve tried dispatching foldEffects for the lines I want to fold, but nothing happens, I get no errors and not sure how to go about debugging this.

                effects: foldEffect.of({ from: 1, to: 5 })

Guesswork, but I think what is happening is that the background code is determining that the code at these lines are not ‘foldable’. Is this likely to be the case?

I’ve tried providing a FoldService but I don’t think there’s anything here that can help. Foldable sounds like it might be a direction to investigate but I haven’t managed to figure out how to provide my own foldable implementation yet as examples are quite sparse.

Is this something that should be possibl, and if so does anyone have any pointers as to where to look?

Alternatively, while it feels hacky, could selecting multiple lines programmatically and calling FoldCode potentially be a solution? While this feels hacky, I suspect it would probably fall foul of the same issue I have dispatching the FoldEffect as this feels like it’s probably doing something very similar in the background.

This should work. Unless the cursor is inside the folded range, then it will automatically be unfolded again immediately.

Thanks for the reply @marijn.

I’ve created a minimum script trying this out and still getting no luck. Am I doing anything glaringly wrong here?

import {basicSetup, EditorView} from "codemirror";
import {foldEffect} from "@codemirror/fold";

new EditorView({
  doc: "a\nb\nc\nd\ne\nf\ng\nh\n",
  extensions: [
  parent: document.body

  effects: foldEffect.of({ from: 3, to: 5 })

@codemirror/fold is deprecated (your npm should have emitted a warning about that) since 6.0. Its exports live in @codemirror/language now. In general, mixing 0.19 and 6.0 versions of packages will definitely not work.

1 Like


Thanks @marijn that’s solved it. Npm does emit a warning I just wasn’t paying attention.

Thanks for your time. Very much appreciated.