Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monaco editor - Programmatic folding

Anybody else find Monaco difficult?

I have the API docs open in several tabs and am crawling all over it trying to glean actual information on how things work.

But the docs are extremely blank. Just no actual contextual information. They're like adding a comment to the line i++; as // Add one to i

I have the editor... "functioning". I'm resorting to stepping through the code in editor.main.js trying to see how it works!

I'd like to add a folding rule. Not replace the existing one(s).

monaco.languages.registerFoldingRangeProvider('javascript...

I added a folding rule which makes a single block of "import" statements a foldable block. Great. Super!

But that kills all other folding. The term "register" usually implies adding. Not replacing.

Do they actually not want people to use this? Because the API docs, while technically correct are hostile. I checked monaco questions here on StackOverflow and 90% of them have zero answers. Why do they not document it properly?

like image 934
NIge Avatar asked Sep 02 '26 01:09

NIge


1 Answers

Thanks - Looking for a way to fold codeblocks, I was also going round in circles till I read your answer. This is the complete solution I ended up with:

async function foldAllCodeBlocks() {
const model = editor.getModel()
const codeBlockRegExp = /```[\s\S]*?```/g
let matches
while ((matches = codeBlockRegExp.exec(model.getValue())) !== null) {
    const startLineNumber = model.getPositionAt(matches.index).lineNumber
    const endLineNumber = model.getPositionAt(matches.index + matches[0].length).lineNumber
    editor.setSelection(new monaco.Selection(startLineNumber, 1, endLineNumber, 1))
    await editor.getAction('editor.createFoldingRangeFromSelection').run()
    }
}
like image 142
marzetti Avatar answered Sep 05 '26 15:09

marzetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!