Checking if a given element's text is inside a range in the source code


#1

Hello there,

I’m building an app with CodeMirror and I’ve got the following problem. I’ve got an editor with a given source code/value which is a string. In the middle of this string there’s a keyword (i.e., there’s a specific range of characters inside the string), which I’d like to highlight, when the mouse hovers over it. This keyword may vary from editor to editor, so I need a generic solution.

I’d like to know if there’s any way to find which part of the source code’s string has been clicked (probably just a single character index should be enough). I’ll try to provide an example:

public static void go()
{	Rectangle r1 = new Rectangle(0,0,5,5);
	System.out.println("In method go. r1 " + r1 + "\n");
	// could have been 
	//System.out.prinltn("r1" + r1.toString());
	r1.setSize(10, 15);
	System.out.println("In method go. r1 " + r1 + "\n");
	alterPointee(r1);
	System.out.println("In method go. r1 " + r1 + "\n");
	
	alterPointer(r1);
	System.out.println("In method go. r1 " + r1 + "\n");
}

Let’s say this is the original source code, and this below is the string I pass into the editor:

\tpublic static void go()\n\t{\tRectangle r1 = new Rectangle(0,0,5,5);\n\t\tSystem.out.println(\"In method go. r1 \" + r1 + \"\\n\");\n\t\t// could have been \n\t\t//System.out.prinltn(\"r1\" + r1.toString());\n\t\tr1.setSize(10, 15);\n\t\tSystem.out.println(\"In method go. r1 \" + r1 + \"\\n\");\n\t\talterPointee(r1);\n\t\tSystem.out.println(\"In method go. r1 \" + r1 + \"\\n\");\n\t\t\n\t\talterPointer(r1);\n\t\tSystem.out.println(\"In method go. r1 \" + r1 + \"\\n\");\n\t}

Now let’s say I want to highlight the first setSize function call. In the string I passed into the editor, it’s range starts at some character with index X and ends at another character with index Y. I’d like the setSize call to highlight, when the mouse hovers over it.

Thanks for any insight


#2

posAtCoords can tell you which character is at the mouse position. markText can be used to highlight something.


#3

Hello @marijn, thank you for your answer. I had seen some people talking about posAtCoords but I can’t seem to find them in the manual, so I thought it was an old deprecated function. Can you point me to its docs? Sorry to bother you.


#4

My bad, it’s called coordsChar.


#5

Yep, I’ve played around with that and getTokenAt and it seems to be exactly what I needed! Thanks a lot!