sara sara - 1 month ago 9
HTML Question

How I can to color an word only after i check to some conditions?

I am using codemirror editor ... I knew how I can color a specific word where ever the word match .... But I did not like it ... because I have my own class and some fields follow each class ... so suppose I have :

class1 has fields aaa

class2 has fields bbb

so I want to color aaa in red only if it came after class1 like this class1.aaa .... But when I write class2.aaa I did not want to color aaa in red this code :



CodeMirror.defineMode("mymode", function() {

return {
token: function(stream, state) {

if (stream.match("aaa")) {
return "style1";
} else if (stream.match("bbb")) {
return "style2";
} else {
stream.next();
return null;
}
}
};

});


var editor = CodeMirror.fromTextArea(document.getElementById('cm'), {
mode: "mymode",
lineNumbers: true
});

.cm-style1 {
color: red;
}
.cm-style2 {
color: blue;
}

<link href="http://codemirror.net/lib/codemirror.css" rel="stylesheet" />
<script src="http://codemirror.net/lib/codemirror.js"></script>
<textarea rows="4" cols="30" id="cm" name="cm">aaa bbb ccc</textarea>





and this the the jsfiddle.

Note :
I have function return true if (aaa) came after class1 ... so only what I want to knew how to color aaa in red only if it came after class1 like this class1.aaa ?

Answer

You will need to check and store previous token in a variable and then check it along with your condition to ensure that if current token is aaa then previous token is class1. Check this code:

CodeMirror.defineMode("mymode", function() {
    
    return {
        token: function(stream,state) {
        //console.log(prevToken);
            if (stream.match("class1.") ) {
                prevToken = "class1";
                stream.eatSpace();
                return null;
            } else if (stream.match("class2.") ) {
                prevToken = "class2";
                stream.eatSpace();
                return null;
            } else if (prevToken === "class1" && stream.match("aaa") ) {
                prevToken = null;
                //stream.eatSpace();
                return "style1";
            } else if (prevToken === "class2" && stream.match("bbb") ) {
                prevToken = null;
                //stream.eatSpace();
                return "style2";
            } else {
                prevToken = null;
                //stream.eatSpace();
                stream.next();
                return null;
            }
        }
    };
    
});
var ind = 0;
var prevToken = null;

var editor = CodeMirror.fromTextArea(document.getElementById('cm'), {
    mode: "mymode",
    lineNumbers: true
});  
.cm-style1 { color: red; }
.cm-style2 { color: blue; }
<link href="http://codemirror.net/lib/codemirror.css" rel="stylesheet"/>
<script src="http://codemirror.net/lib/codemirror.js"></script>
<textarea rows="4" cols="30" id="cm" name="cm">class1 aaa class1.aaa class2 aaa class2 bbb class2.bbb ccc</textarea>