简体   繁体   中英

how I can color comment in specific color in my mode in codemirror

I want to color my comment that come between the /* */ in specific color in codemirror ... I search and found sample to color the string between the " " and it work fine .

when I replace the " " by /* */ in the code then the code not color my comment .

the work code is :

CodeMirror.defineMode("strings", function() {
  return {
    startState: function() {return {inString: false};},
    token: function(stream, state) {
      // If a string starts here
      if (!state.inString && stream.peek() == '"') {
        stream.next();            // Skip quote
        state.inString = true;    // Update state
      }

      if (state.inString) {
        if (stream.skipTo('"')) { // Quote found on this line
          stream.next();          // Skip quote
          state.inString = false; // Clear flag
        } else {
           stream.skipToEnd();    // Rest of line is string
        }
        return "string";          // Token style
      } else {
        stream.skipTo('"') || stream.skipToEnd();
        return null;              // Unstyled token
      }
    }
  };
});

my try : Note I only replace the " by / and " by / but the code not work this is my try online jsbin but not work

so what my wrong ?

As specified in the documentation ,

peek() → string

Returns the next character in the stream without advancing it. Will return a null at the end of the line.

stream.peek() only returns 1 character, you want to match "/*" , which is 2 characters.

You want to use stream.match()

match(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean
match(pattern: regexp, ?consume: boolean) → array

Act like a multi-character eat—if consume is true or not given—or a look-ahead that doesn't update the stream position—if it is false. pattern can be either a string or a regular expression starting with ^. When it is a string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned by match, in case you need to extract matched groups.

This will return true if the current stream position matches "/*" and will eat the 2 characters:

stream.match('/*', true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM