问题
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?
回答1:
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>
来源:https://stackoverflow.com/questions/32622128/codemirror-how-to-read-editor-text-before-or-after-cursor-position