highlightjs / highlight.js

JavaScript syntax highlighter with language auto-detection and zero dependencies.
https://highlightjs.org/
BSD 3-Clause "New" or "Revised" License
23.3k stars 3.52k forks source link

(typescript) Using `namespace` as a variable name breaks highlighter state #3972

Closed pkaminski closed 4 months ago

pkaminski commented 5 months ago

Describe the issue When I use namespace as the name of the variable, everything that follows is highlighted incorrectly. While namespace is a TS keyword it's fine to use it as a variable name too.

Which language seems to have the issue? typescript

Are you using highlight or highlightAuto? highlight

Sample Code to Reproduce

const message = 'foo';
const namespace = 'bar';
function baz() {}

https://jsfiddle.net/g0fu1zmw/1/ https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgUwhAhgcwTAvDA5AMxBFwG4BYAKFEljBUQgAcVhMdcAjFAJ1MvwCuYYFACW4GFwBeACgCUMAN4BfSkA

Expected behavior See GitHub or TS playground renderings above, for example. It's fine (though not ideal) if namespace is highlighted as a keyword in this context, as long as it doesn't break highlighting of everything that follows.

Additional information Original problem report in https://github.com/Reviewable/Reviewable/issues/1134.

joshgoebel commented 5 months ago

Can you provide a more complex example than this for proper namespace use:

namespace Validation {

Or are namespaces always so simple?

pkaminski commented 5 months ago

I'm far from an expert on TypeScript but I think that's pretty much it, though it can be prefixed by a few other keywords, and can also be nested in case that matters:

declare namespace Foo {
  export namespace Bar {
  }
}
joshgoebel commented 5 months ago

Then I think we could solve this with a multi-matcher (see second example of beginScope: https://highlightjs.readthedocs.io/en/latest/mode-reference.html#beginscope)... to match patterns like:

"namespace" [ws] [className] [ws] "{"

Much better than the existing match namespace and then get stuck until you see a {.

akhtarmdsaad commented 4 months ago

Please go through my pull request. I think it resolves the issue.