I'm trying to find a way to test if the cursor is preceded by a specific string and then trigger an event.
Example of what I'm trying to do:
User clicks somewhere inside the editor, a cursorActivity
(cursor or editor changed) event is fired, I catch the event and test whether or not the previous 6 characters matches the string 'color:'
If so then do I something.
I can't seem to find any kind of method that lets you actually read directly from the editor though, aside from catching the readInput
event which is triggered every time a character is typed or a string is pasted. This works to a point but fails when a user moves the cursor with a mouse click.
TL;DR How can I detect when the cursor has moved somewhere immediately after a specific string?
First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.
To get the value of the CodeMirror text editor we need to write some javascript code in the default. js file. $(document). ready(function(){ //code here...
CodeMirror uses a concept of operations, which start by calling a specific set-up function that clears the state and end by calling another function that reads this state and does the required updating. Most event handlers, and all the user-visible methods that change state are wrapped like this.
This could be used to, for example, replace a textarea with a real editor: var myCodeMirror = CodeMirror(function(elt) { myTextArea. parentNode. replaceChild(elt, myTextArea); }, {value: myTextArea.
Ok finally found a solution. You can retrieve the actual document using editor.doc
which lets you get the cursor line & character position. Then you can retrieve the desired line with editor.doc.getLine(n)
and compare your substring
Here's my test case:
<!-- Create a simple CodeMirror instance -->
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<textarea id="myTextarea"></textarea>
<script>
var editor = CodeMirror.fromTextArea(myTextarea, {
lineNumbers: true
});
//Catch cursor change event
editor.on('cursorActivity',function(e){
var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
stringToMatch = "color:",
n = stringToMatch.length,
stringToTest = e.doc.getLine(line).substr(Math.max(ch - n,0),n);
if (stringToTest == stringToMatch) console.log("SUCCESS!!!");
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With