Monaco Editor in Action: Adding Code Folding

ohdarling
4 min readSep 11, 2023

In the previous article 4 Steps to Add Custom Language Support to Monaco Editor, we learned how to use Monaco Editor to create an editor that supports custom programming languages. However, as a standard code editor, we also need it to support code folding. This allows us to conveniently collapse certain code blocks when working with code files that have a large amount of content, making it easier to understand the overall code structure while reading the code.

In this article, we will explore how to add code folding functionality to Monaco Editor.

Official Example

In the Folding Provider Example of the Monaco Editor Playground, you can see how to add code folding support to a custom language:

monaco.languages.registerFoldingRangeProvider("foldLanguage", {
provideFoldingRanges: function (model, context, token) {
return [
// comment1
{
start: 5,
end: 7,
kind: monaco.languages.FoldingRangeKind.Comment,
},
// ...
]
}
});

Indeed, as you can see, after registering a custom language, you simply need to register a foldingRangeProvider. In the provideFoldingRanges callback function, you can identify the code blocks that can be folded, define the range by specifying the start and end line numbers, and return them to Monaco Editor.

In the example, the folding range was provided by hard-coding the start and end line numbers. However, in real-world…

--

--

ohdarling
ohdarling

Written by ohdarling

Coding and creating, build apps on tickplant.com.

No responses yet