Don't highlight TypeScript-only keywords in JavaScript (#24)

The fallback highlighter used one keyword list for JavaScript and
TypeScript, so plain JavaScript coloured `type`, `readonly`, `namespace`,
`keyof`, `declare` and `abstract` as keywords, as in `event.type`.
JavaScript now has its own list, and TypeScript adds those six to it, so
TypeScript highlights as before.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aleksander HelgakerandClaude Opus 5.5 authored and GitHub committed 2026-11-09 01:11:45 +01:00
1 parent 8269f7c411
commit 0afe145eba
1 file changed
+45 -10
+45 -10
View File
@@ -802,9 +802,8 @@ impl Language {
fn new(language: &str) -> Option<Self> {
match language.to_lowercase().as_str() {
"c" | "h" | "hpp" | "cpp" | "c++" => Some(Self::cpp()),
"js" | "javascript" | "jsx" | "mjs" | "ts" | "typescript" | "tsx" => {
Some(Self::javascript())
}
"js" | "javascript" | "jsx" | "mjs" => Some(Self::javascript()),
"ts" | "typescript" | "tsx" => Some(Self::typescript()),
"json" | "jsonc" | "json5" => Some(Self::json()),
"py" | "python" => Some(Self::python()),
"rs" | "rust" => Some(Self::rust()),
@@ -938,7 +937,7 @@ impl Language {
}
}
/// JavaScript and TypeScript.
/// JavaScript.
fn javascript() -> Self {
Self {
double_slash_comments: true,
@@ -948,7 +947,6 @@ impl Language {
string_delimiters: &["\"", "'", "`"],
case_insensitive_keywords: false,
keywords: [
"abstract",
"as",
"async",
"await",
@@ -959,7 +957,6 @@ impl Language {
"const",
"continue",
"debugger",
"declare",
"default",
"delete",
"do",
@@ -978,16 +975,13 @@ impl Language {
"in",
"instanceof",
"interface",
"keyof",
"let",
"namespace",
"new",
"null",
"of",
"private",
"protected",
"public",
"readonly",
"return",
"static",
"super",
@@ -996,7 +990,6 @@ impl Language {
"throw",
"true",
"try",
"type",
"typeof",
"undefined",
"var",
@@ -1010,6 +1003,20 @@ impl Language {
}
}
/// TypeScript: JavaScript and the keywords TypeScript adds.
fn typescript() -> Self {
let mut language = Self::javascript();
language.keywords.extend([
"abstract",
"declare",
"keyof",
"namespace",
"readonly",
"type",
]);
language
}
fn json() -> Self {
Self {
double_slash_comments: true, // for json5 etc. Common extension.
@@ -1323,6 +1330,34 @@ mod tests {
assert_eq!(token_type_of(text, "ts", "log"), Some(TokenType::Function));
}
#[test]
fn typescript_keywords_are_names_in_javascript() {
for word in [
"abstract",
"declare",
"keyof",
"namespace",
"readonly",
"type",
] {
let text = format!("{word} = event.{word}");
assert_eq!(
token_type_of(&text, "js", word),
Some(TokenType::Literal),
"{word}"
);
assert_eq!(
token_type_of(&text, "ts", word),
Some(TokenType::Keyword),
"{word}"
);
}
assert_eq!(
token_type_of("let x", "js", "let"),
Some(TokenType::Keyword)
);
}
#[test]
fn shell() {
let text = "if true; then echo 'hi'; fi # done";