Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/frontend/codemirror/extensions/fold-code-selection.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import * as CodeMirror from "codemirror";6import { cm_start_end } from "./util";78/*9The variable mode determines whether we are folding or unfolding *everything*10selected. If mode='fold', fold everything; if mode='unfold', unfolding everything;11and if mode=undefined, not yet decided. If undecided, which is decided on the first12thing that we would toggle, e.g., if the first fold point is unfolded, we make sure13everything is folded in all ranges, but if the first fold point is not folded, we then14make everything unfolded.15*/1617CodeMirror.defineExtension(18"foldCodeSelectionAware",19function (mode: undefined | "fold" | "unfold") {20// @ts-ignore21const editor: any = this;22for (const selection of editor.listSelections()) {23const { start_line, end_line } = cm_start_end(selection);24for (let n = start_line; n <= end_line; n++) {25const pos = CodeMirror.Pos(n);26try {27if (mode != null) {28editor.foldCode(pos, null, mode);29} else {30// try to toggle and see if anything happens31const is_folded = editor.isLineFolded(n);32editor.foldCode(pos);33if (editor.isLineFolded(n) !== is_folded) {34// this is a foldable line, and what did we just do? What it was, keep doing it.35mode = editor.isLineFolded(n) ? "fold" : "unfold";36}37}38} catch (err) {39// I've observed in production getting40// "Inserting collapsed marker partially overlapping an existing one"41// raised in production. It's way better to just log this in the console.42// In particular, this happens for the file fcs.tsx as of this writing, when43// you select all and hit control+Q:44// https://github.com/sagemathinc/cocalc/blob/250045ad8af9db9f485d810141f065096c52f11b/src/@cocalc/frontend/project/info/fcs.tsx4546console.warn(`WARNING: ${err}`);47}48}49}50}51);5253// This isFolded extension that comes with CodeMirror isn't useful for the above, since it54// is only at a *point*, not a line.55CodeMirror.defineExtension("isLineFolded", function (line: number): boolean {56// @ts-ignore57const editor: any = this;58for (const mark of editor.findMarks(59{ line, ch: 0 },60{ line: line + 1, ch: 0 }61)) {62if (mark.__isFold) {63return true;64}65}66return false;67});686970