Custom Syntax Highlighting Not Working

I’m trying to extend the parser in @codemirror/lang-python with hightlighting for custom words e.g CustomType. I have extended the pythonLanguage parser with a StyleTags as specified by Codemirror 6 and lezer/highlight documentation but the highlighting is not reflected. I don’t know what I’m missing here.

import {basicSetup, EditorView} from "codemirror"
import { styleTags, tags as t, Tag } from "@lezer/highlight";
import {python, pythonLanguage} from "@codemirror/lang-python"
import { LanguageSupport, LRLanguage } from "@codemirror/language";

const customParser = pythonLanguage.parser.configure({
  props: [
    styleTags({
      CustomType: t.null,
     }),
  ]
})

const CustomPython = () => {
  return new LanguageSupport(LRLanguage.define({ parser: customParser }), [

  ]);
};

new EditorView({
  doc: `\
def main():
  y = CustomType(4)
  x = None
  print("Hello")`,
  extensions: [basicSetup, CustomPython()],
  // extensions: [basicSetup, python()],
  parent: document.body
})

The sample code above can be tested here Try CodeMirror

Or in a react environment here: https://codesandbox.io/p/sandbox/jolly-panka-3y75zm

styleTags targets syntax tree node names, not identifier content. The Python parser does not emit any nodes called CustomType, so your tag will not be assigned to any syntax.

It’s not possible to style specific identifier in this way. You’d have to create a new parser or a separate extension that scans the syntax tree, finds the identifiers you’re interested in, and assigns decorations to them.

1 Like

I suspected there was an error in my understanding. I will go through the documentation for assigning decorations.

Thank you @marijn

@marijn while researching further, I saw this example - Codemirror 6 highlighting specific substring - #4 by patricia. From this I see I can create an extension to style specific identifiers both when the extension is initialized and upon subsequent document changes.

Is this what you had in mind or did you have a better approach?

Thank you again.