2015-09-17 119 views
0

我試圖找到一種方法來測試如果光標前面是特定的字符串,然後觸發事件。CodeMirror:如何閱讀光標位置之前或之後的編輯器文本

的什麼,我試圖做例子: 用戶點擊編輯器中的某個地方,一個cursorActivity(光標或編輯改變)事件被激發,我趕上事件,並測試是否將以前的6個字符匹配字符串'color:'如果是這樣,然後做我的東西。

我似乎找不到任何一種方法可以讓你直接從編輯器中直接讀取,除了捕獲每次鍵入字符或粘貼字符串時觸發的readInput事件。這適用於某一點,但當用戶通過單擊鼠標移動光標時失敗。

TL; DR 如何檢測遊標何時移動到特定字符串後的某處?

回答

2

好吧終於找到了解決方案。您可以使用editor.doc檢索實際文檔,該文檔可讓您獲取光標行&字符位置。然後,你可以用editor.doc.getLine(n)檢索所需的線和比較你的子

這裏是我的測試案例:

<!-- 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> 
+0

HI @Deftwun有人問你的問題一樣的問題可以幫助呢?此鏈接:http://stackoverflow.com/questions/39917590/how-to-read-editor-text-before-cursor-position-to-match-specific-words – sam

相關問題