Skip to content

Commit b7eab79

Browse files
author
Simon Fuet
committed
feat: collapse code sections
1 parent a72ad5e commit b7eab79

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/tools.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,50 @@ export function hideCodeWithoutDecoration (editor: monaco.editor.IStandaloneCode
220220
editor.setHiddenAreas(otherHiddenAreas)
221221
}
222222
}
223+
224+
/**
225+
* Collapse everything between startToken and endToken
226+
*/
227+
export async function collapseCodeSections (editor: monaco.editor.IStandaloneCodeEditor, startToken: string, endToken: string, isRegex: boolean = false): Promise<void> {
228+
const editorModel = editor.getModel()
229+
const ranges: monaco.IRange[] = []
230+
if (editorModel != null) {
231+
let currentPosition = editorModel.getFullModelRange().getStartPosition()
232+
let match: monaco.editor.FindMatch | null
233+
while ((match = editorModel.findNextMatch(startToken,
234+
/* searchStart */currentPosition,
235+
/* isRegex */isRegex,
236+
/* matchCase */true,
237+
/* wordSeparators */null,
238+
/* captureMatches */false
239+
)) != null) {
240+
if (match.range.getStartPosition().isBefore(currentPosition)) {
241+
break
242+
}
243+
const matchEnd = editorModel.findNextMatch(endToken,
244+
/* searchStart */match.range.getEndPosition(),
245+
/* isRegex */isRegex,
246+
/* matchCase */true,
247+
/* wordSeparators */null,
248+
/* captureMatches */false
249+
)
250+
if (matchEnd != null && matchEnd.range.getStartPosition().isBefore(match.range.getStartPosition())) {
251+
break
252+
}
253+
currentPosition = matchEnd?.range.getEndPosition() ?? editorModel.getFullModelRange().getEndPosition()
254+
ranges.push(monaco.Range.fromPositions(match.range.getStartPosition(), currentPosition))
255+
}
256+
257+
const selections = editor.getSelections()
258+
editor.setSelections(ranges.map(r => ({
259+
selectionStartLineNumber: r.startLineNumber,
260+
selectionStartColumn: r.startColumn,
261+
positionLineNumber: r.endLineNumber,
262+
positionColumn: r.endColumn
263+
})))
264+
await editor.getAction('editor.createFoldingRangeFromSelection').run()
265+
if (selections != null) {
266+
editor.setSelections(selections)
267+
}
268+
}
269+
}

0 commit comments

Comments
 (0)