Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that stores the list of substring positions that need to be highlighted. This structure is an Array where each element represents a line of text, containing arrays of objects with the positions of the substrings to be highlighted. For example, consider this text:

The moon
is pale and round
as is
also the sun

The words "moon", "pale", "round", and "sun" are to be highlighted. The structure for highlighting looks like this:

[
    [ { iStart:4, iEnd:7 } ], // "moon"
    [ { iStart:3, iEnd:6 }, { iStart:12, iEnd:16 } ], // "pale" and "round"
    [], 
    [ { iStart:9, iEnd:11 } ] // "sun"

]

In my attempts to achieve this, I initially tried creating a custom language mode but faced challenges due to CodeMirror's usage of tokens instead of lines. I needed to determine the line corresponding to the current token in order to retrieve the correct data from the highlight structure.

Subsequently, I experimented with an external function that applies highlighting by manually adding SPAN tags like so:

function highlightText()
{
    console.log( "highlightText()" );
    // Obtain references to the text lines in the code editor
    var codeLines = $("#editorContainer .CodeMirror-code pre>span" );
    for( var i=0; i<colorSegments.length; i++ ){
        // Check if there are elements to be highlighted in this line...
        if( colorSegments[i] && colorSegments[i].length > 0 ){
            // Retrieve the appropriate element and proceed with highlighting
            var lineElement = codeLines[i];
            highlightWordsInLine( lineElement, colorSegments[i] );
        }
    }
}

function highlightWordsInLine(element, positions) {     
    // Extract the raw text
    var str = $( element ).text();
    // Create a new string with highlighting tags.
    // Start 
    var out = str.substr(0, positions[0].iStart);
    for( var j=0; j<positions.length; j++ ){
        var position = positions[j];
        // Apply the highlighting tag
        out += '<span class="cm-s-ambiance cm-relation">';
        out += str.substr( position.iStart, position.iEnd - position.iStart + 1);
        out += '</span>';
        // Ensure inclusion of unhighlighted text in between
        if( j < positions.length-1 ){
            out += str.substr(  position.iEnd - position.iStart + 1, positions[j+1].iStart );
        }
    }
    // Complete end of line wrapping
    out +=  str.substr( position.iEnd + 1);

    // Update the html element value with applied highlight tags
    element.innerHTML = out;
}

Although I acknowledge this method may not be optimal and has some limitations such as causing certain text to become unselectable, it has provided partial success in managing the highlighting process.

Hence, my inquiry pertains to the proper approach for achieving this task. Should I persist with the language-mode approach, and if so, how should I proceed?

I have also been advised to explore Ace (), but it appears to lack support for handling highlighting based on string positions rather than keyword lists or regexp rules.

Thank you in advance for your guidance.

Answer №1

Utilizing the markText function simplifies tasks like this.

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

Understanding the reason why "undefined" is occurring in Javascript

Can anyone help me understand why the alert at the start is showing "undefined"? The alerts are displayed in this order: "success!" "Data" (the correct value) "undefined" I have gone through several threads and found that the issue usually arises du ...

Attempting to retrieve a stream buffer from a function

I am currently working on creating a zip file that contains a CSV file and returning it as a buffer from a function. Below is the code snippet I have implemented: const archiver = require('archiver'); const streamBuffers = require("stream-bu ...

Steps to refresh your nodejs project after making changes

As a newcomer to nodejs, I find myself constantly restarting the server every time I make changes to my HTML files or when using twig, jade, or ejs template engines. Does anyone have any suggestions on how to see these changes in the browser without having ...

The prototype object of the Datatable request parameter is missing

When attempting to make a datatable ajax request, I encountered an unexpected result on the server side. The console is logging the data as shown below: [Object: null prototype] { draw: '1', 'columns[0][data]': 'no', &ap ...

Encountered an issue with Nextjs dynamic routes and static pages where the error message states that the `paths` variable needs to be an

I have been following the official Next.js guide on generating statically generated pages with dynamic routes (Nextjs - Dynamic Routes). However, I am facing an issue when trying to generate pages with fetched data. The error message I am receiving is as f ...

When loading HTML using JavaScript, the CSS within the HTML is not properly processing. Leveraging Bootstrap 5 might help resolve

Currently utilizing bootstrap 5 for my project. I have a setup in index.html where I am loading the contents of nav.html using JavaScript. However, I am facing an issue wherein the CSS styling for the navbar is not being applied when loaded via JS. Strange ...

Detecting User Interaction with Email Link

On my webpage, there is a link that when clicked, opens the default Email client. I also want to track in my database if the user has clicked on this link or not. Since this interaction occurs at the client-side, I am wondering if there is a way to check ...

Changing dates in JavaScript / TypeScript can result in inaccurate dates being displayed after adding days

Recently, I encountered an issue with a simple code snippet that seems to produce inconsistent results. Take a look at the function below: addDays(date: Date, days: number): Date { console.log('adding ' + days + ' days'); con ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Utilizing pop-up alerts and AJAX requests in jQuery forms

I am looking to enhance my website by creating a form using PHP and jQuery. Currently, the form is placed in the footer of my website. However, I want to display the form results in a popup within the main section of the website without requiring a page ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

Displaying elements above my React sidebar

I am working on developing a Login application with a landing page using React Router and Redux. In order to have a Sidebar that is always present in all the components within the application, I have setup the Sidebar component as a route that is constantl ...

Toggle button to create a fade in/out effect

Below is the HTML code snippet: <html> <head> <Script type = "text/javascript" src = "CprMdlrSrch.js"></Script> <link type="text/css"rel="stylesheet"href="CprMdlrSrch.css"/> </head> <body> <div id=" ...

What is the best way to retrieve a value from a JSON object using AngularJS?

Using nodeJS, the server sends a JSON object to the controller: data = { "question": "theQuestion", "answer": "theAnswer" }; res.json(data); In the controller, I attempt to manipulate the variable as follows: data = QA.get(); $scope.q = data[que ...

How to transfer data from an HTML form to PHP using AJAX

I've encountered an issue while working on a simple application that consists of one HTML file communicating with a PHP page using AJAX. Take a look at my index.html below: <!DOCTYPE html> <html><head> <meta charset="utf-8"> & ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

Is it possible to postpone sending a message on Discord until a certain event has been successfully completed?

After the User leaves the Discord, I attempted to create a RichEmbed Message that would include a random GIF from Giphy. The GIF was meant to be generated using the getGiphyPic() function with the help of this node module: https://github.com/risan/giphy-ra ...

Accessing the name attribute of the TextField component, displayed as a Select Box in Material-UI, by utilizing the event object received from the onFocus prop

Utilizing the "@material-ui/core": "4.11.2" library along with "react": "16.8.6", I've encountered an issue with the TextField component where the select prop is set to true. Specifically, I am unable to access ...

Utilizing an Application Programming Interface in React Native

Recently diving into React Native, I embarked on creating a basic app leveraging the Marvel API along with an API wrapper. My aim is to implement an infinite scroll view using VirtualizedList. Here's where I could use some guidance: What should be pas ...