I'm encountering the error message "CodeMirror.foldCode is not a function" repeatedly. Could it be that the code folding addon is incompatible with custom or simple modes?

Creating a basic website to assist in editing .filter files for Path of Exile, I have integrated CodeMirror and developed a custom mode to manage syntax highlighting using the mode/simple.js addon. Currently, I am working on incorporating code folding based on indentation.

Despite exploring the examples and documentation available on the CodeMirror website:

My searches on Stack Overflow yielded minimal results related to my issue, leading me to thoroughly review my work based on the solutions found in a single relevant thread here: CodeMirror foldCode method not working

However, the error persists. I even considered if the addon is incompatible with custom/simple modes, yet the online resources are lacking in both quality and quantity of information about CodeMirror.

I would greatly appreciate any assistance in resolving this matter. Additionally, if anyone is aware of high-quality tutorials on this subject, please share them.

Here's the structure of the HTML file:

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name='viewport' content='width=device-width, initial-scale=1'>

  <title>Filter Editor</title>
  <meta name="description" content="HTML Editor for PoE Filters">
  <meta name="author" content="author">

  <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">
  <link rel="stylesheet" href="codemirror/lib/codemirror.css">
  <link rel="stylesheet" href="codemirror/theme/twilight.css">
  <link rel="stylesheet" href="codemirror/addon/fold/foldgutter.css">

</head>

<body>
    <div id='app-container'>
        <div id='display-pane'>
            <!-- Include your content here -->
        </div>
        <div id='editor-pane'>
            <!-- Include your CodeMirror editor here -->
        </div>
    </div>



    <script src="js/jquery.min.js"></script>
    <script src="codemirror/lib/codemirror.js"></script>
    <script src="codemirror/addon/fold/foldcode.js"></script>
    <script src="codemirror/addon/fold/foldgutter.js"></script>
    <script src="codemirror/addon/fold/indent-fold.js"></script>
    <script src="codemirror/addon/mode/simple.js"></script>
    <script src="codemirror/mode/filter/poefilter.js"></script>
    <script src="js/scripts.js"></script>

</body>
</html>

Below is the JavaScript where I initialize the CodeMirror instance:

$(document).ready(function() {

    // CodeMirror Stuff
    var code = $("#code-mirror")[0];
    var editor = CodeMirror.fromTextArea(code, {
        mode: "poefilter",
        theme: "twilight",
        lineNumbers: true,
        lineWrapping: true,
        viewportMargin: 30,
        // saveFunction: "saveFunction",
        indentUnit: 4,
        minHeight: "100%",
        extraKeys: {"Ctrl-Q": function(cm){     CodeMirror.foldCode(cm.getCursor()); }},
        foldGutter: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
    });

    editor.foldCode(CodeMirror.Pos(0, 0));
    editor.setSize("100%", "100%");

Here's the custom mode (poefilter.js) that I've written:

var test = {
        block: /(?:Show|Hide)/,
        condition: /(?:ItemLevel|DropLevel|Quality|Rarity|Class|Sockets|LinkedSockets|SocketGroup|Height|Width|AnyEnchantment|StackSize|GemLevel|Identified|Corrupted|ElderItem|ShaperItem|FracturedItem|SynthesisedItem|ShapedMap|BlightedMap|MapTier)/,
        opencond: /BaseType|Prophecy|HasExplicitMod|HasEnchantment|CustomAlertSound/,
        action: /(?:SetBorderColor|SetTextColor|SetBackgroundColor|SetFontSize|PlayAlertSoundPositional|PlayAlertSound|DisableDropSound|MinimapIcon|PlayEffect)/,
        operators: /(?:<|<=|=|>|>=)/,
        number: /[0-9]+/,
        literal: /(?:True|False|Normal|Magic|Rare|Unique|Temp|Red|Green|Blue|Yellow|Brown|White|Triangle|Square|Circle|Diamond|Hexagon|R|G|B)/,
        itemclass: /(?:"Life Flasks"|"Mana Flasks"|"Hybrid Flasks"|"Utility Flasks"|"Critical Utility Flasks"|Flasks|"Stackable Currency"|"Delve Stackable Socketable Currency"|"Socketable Currency"|Currency|Amulets|Rings|Claws|"Rune Dagger"|Daggers|Wands|"One Hand Swords"|"Thrusting One Hand Swords"|"Two Hand Swords"|Swords|"One Hand Axes"|"Two Hand Axes"|Axes|"One Hand Maces"|"Two Hand Maces"|Maces|Bows|Quivers|Staves|Warstaff|"Active Skill Gems"|"Support Skill Gems"|Gems|Belts|Gloves|Boots|"Body Armours"|Body|Helmets|Shields|"Quest Items"|Sceptres|Unarmed|"Fishing Rods"|"Map Fragments"|"Hideout Doodads"|Microtransactions|"Abyss Jewel"|Jewel|"Divination Card"|"Labyrinth Item"|"Labyrinth Trinket"|"Labyrinth Map Item"|Labyrinth|"Misc Map Items"|Leaguestones|"Pantheon Soul"|Piece|"Incursion Item"|Incubator|"Shard Heart"|Shard|Maps|Map)/,
        comment: /#.*/,
        custom: /.*/
    }

CodeMirror.defineSimpleMode("poefilter", {
    start: [
        {regex: test.comment, token: ["comment"]},
        {regex: test.block, token: "header"},
        {regex: test.condition, token: "attribute"},
        {regex: test.opencond, token: "attribute", next: "custom"},
        {regex: test.action, token: "def"},
        {regex: test.operators, token: "operator"},
        {regex: test.number, token: "number"},
        {regex: test.itemclass, token: "string-2"},
        {regex: test.literal, token: "number"}
    ],
    custom: [
        {regex: test.custom, token: "string", next: "start"}
    ],
    fold: "poefilter"
});

The expected outcome includes clickable arrows in the gutter for folding and unfolding sections of the code. Instead, there are no arrows visible, and an error appears in the developer console indicating:

scripts.js:19 Uncaught TypeError: CodeMirror.foldcode is not a function

Answer №1

After some careful troubleshooting, I was able to successfully resolve the issue at hand.

Upon inspecting the last line of the mode file, it became clear that the code snippet fold: "poefilter" was causing some errors.

First and foremost, the value "poefilter" needed to be changed to "indent", as this corresponds to the fold type intended for use with the foldcode addon (via indent-fold.js).

Furthermore, given that I was working with a simplistic mode, it was crucial to encapsulate the option within the meta property as follows:

meta: {
    fold: "indent"
}

By rectifying these two aspects, the functionality now operates seamlessly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Search for Div IDs while filtering as you type

Is there a search jQuery plugin that enables real-time filtering based on Div ID as you type in the search box? It would be great if the filter instantly refreshes. ...

What is the process for assigning values once the Google Charts program has completed its drawing?

It might sound strange, but I have a piece of code here: let globalResult = []; let defaultData = ["None", 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200]; $(document).ready(() => { // add a listener to the textbox $('#in ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

Guide on implementing hapi js with Firebase Cloud Function

Looking into a sample from GitHub, I am trying to integrate express and handlebars on Firebase. With the express method, we can pass the "app" instance directly to "functions.https.onRequest" like this: const app = express(); ... app.get('/', ( ...

npm run serve does not utilize vue.config.js configurations for devServer

I encountered a CORS issue when trying to use my flask HTTP APIs with my VUE js webapp on the development server. To resolve this, I decided to set up a reverse proxy by creating a vue.config.js file in the project directory: module.exports = { devServer ...

Encountering difficulties retrieving JSON response from Express in a production environment

When in Development mode, react and express connect flawlessly, allowing for successful data retrieval from the backend. However, in Production mode, although a status code of 200 is returned, the JSON response from express cannot be obtained. The specifi ...

Manipulate a pair of span elements with a singular function in AngularJS

I have a pair of span tags and p tags as follows: <span class="span1" ng-click="show()">Span_1</span> <p class="p1" ng-show="var1">P_1</p> <span class="span2" ng-click="show()">Span_2</span> <p class="p2" ng-show="va ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

Is it possible to swap squares for circles in a Three.js PointCloud?

Currently, I am loading a .ply file using PLYLoader in three.js and displaying it as a PointCloud. Here is the code snippet: var loader = new THREE.PLYLoader(); loader.addEventListener('load', function (event) { var geometry = event.content; ...

If the form is empty, clicking on the Login button will direct you to the page. It is necessary for an error to occur

What should happen when the form is empty and the Login button is pressed? Currently, the page opens without any errors. However, I want to display an error message under such circumstances. How can I modify the function to achieve this? const login = (e ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Safari does not respond to the dropdown function

Currently in the process of developing my website, using Bootstrap and Javascript (including jQuery). I have a navigation menu bar featuring a dropdown menu that should slide down upon hovering on mouse-enabled devices, and otherwise activate upon click/ ...

Is there a way to extract SVG data from the Echarts library in AngularJS?

Currently, I am attempting to retrieve the SVG of Echarts elements in angularjs. Despite my efforts to search for a solution, I have not come across anything useful yet. I require a similar function like the one I utilized with highchart: const chart ...

Analyzing information stored on the client's side to create the page layout

What is the most efficient method for handling data from client-side storage to facilitate page rendering with a flexible abstract architecture that allows changes on the backend to reflect on the frontend? For example, I receive deeply nested JSON on the ...

Issue with Highcharts: Overlapping yAxis labels when displaying multiple series data

I am facing an issue with a highchart that I have rendered for multiple series data. The y-axis labels are overlapping. Is there a way to resolve this problem? You can view the chart here: https://jsfiddle.net/sharadkalya/mhg52js4/ https://i.sstatic.net/ ...

Customizing the add row functionality in material table

Before the add row in the editable table opens, I would like to run a function. https://i.sstatic.net/7kVVL.png It is important for me to execute a specific function before this user interface becomes visible. (such as console.log('Hello')) Here ...

Whenever I attempt to use for or while loops in my application, it consistently crashes

I've recently started learning reactjs and I'm working on a simple app. I created a decrement button that should only work if the item count is greater than or equal to zero. However, when I tried using while and for loops in my code, my app cras ...

Using the drag and drop feature with the v-textarea component in Vuetify

Struggling to incorporate a Drag and Drop feature on vuetify v-textarea. Encountering an issue where clicking on the v-textarea results in the value from a dropped component being removed. Unsure if it's a flaw in my code or a limitation in vuetify v- ...

The art of browser manipulation: Javascript positioning

My issue revolves around the positioning of a Hello Bar. The CSS is set to relative, which has caused the entire site to be pushed down. To address this issue, I have implemented the following JavaScript function: <script language="javascript"> $( ...

Trying to assign a value to a property that is not defined

I'm attempting to initiate the loading and exhibition of a .stl file through three.js by implementing the following code: var stlLoader = new THREE.STLLoader(); stlLoader.load('assets/Cap.stl', function (object){ object.position.y = - 1 ...