CodeMirror: foldAll or unfoldAll from button?

Viewed 143

I'd like to have buttons around the codemirror textarea that allow a user to unfoldAll or foldAll with the click of a button. This will avoid them having to learn shortcuts. Is it possible?

Here's the definition for the editor (the extraKeys do function as expected):

    var editor = CodeMirror.fromTextArea(document.getElementById("xmlViewer"), {
    mode: "text/html",
    lineNumbers: true,
    tabMode: 'indent',
    lineWrapping: true,
    autoCloseTags: true,
    height: "650px",
    width: "90%",
    parserfile: "parsexml.js",
    stylesheet: "css/xmlcolors.css",
    path: "js/",
    continuousScanning: 500,
    extraKeys: {
        "Ctrl-Q": function (cm) { cm.foldCode(cm.getCursor()); },
        "Alt-F": "findPersistent",
        "Ctrl-Y": "foldAll",
        "Ctrl-I": "unfoldAll"
    },
    foldGutter: true,
    autoRefresh: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
});

Here's the definition for the button:

<input type="button" id="expandAllBtn" value="Expand All" class="btn btn-outline-primary btn-sm" />

Here's the definition for the onclick:

$("#collapseAllBtn").on("click", function (e) {

        editor.foldAll; // nothing happens
        //editor.foldAll(); // error not a function
        //editor.commands.foldAll(); // cannot read property of undefined
        //editor.commands.foldAll; // cannot read property of undefined
    });
1 Answers

The following is the way to accomplish this :

$("#collapseAllBtn").on("click", function (e) {

        editor.execCommand("foldAll");

    });
Related