What is the best way to enable JavaScript syntax checking only within double curly braces ({{ }}
)? For example, I want JavaScript syntax checking for {{ some expression }}
, but treat everything outside as plain text.
Currently, I have JavaScript syntax checking enabled globally, but I need it to be restricted to within the curly braces. I attempted to use a combination StreamParser and StreamLanguage, but it didn’t work as expected.
This seems like it should be straightforward with a custom language, but I haven’t found the right combination of packages to achieve this in the editor. What is the best approach to accomplish this?
import { LanguageSupport, type StreamParser, StreamLanguage } from '@codemirror/language';
import { javascriptLanguage } from '@codemirror/lang-javascript';
const customLanguageParser: StreamParser<{ inJS: boolean; jsState: any }> = {
startState() {
return { inJS: false, jsState: null };
},
token(stream, state) {
if (!state.inJS) {
if (stream.match('{{')) {
state.inJS = true;
state.jsState = javascriptLanguage.parser.startParse('');
return 'brace';
}
stream.next();
return 'text';
} else {
if (stream.match('}}')) {
state.inJS = false;
return 'brace';
}
// Use the JavaScript parser for content inside curly braces
const jsToken = javascriptLanguage.parser.token(stream, state.jsState);
return jsToken ? jsToken.type : 'javascript';
}
},
};
const customLanguage = StreamLanguage.define(customLanguageParser);
export const customLanguageSupport = new LanguageSupport(customLanguage);
This returns a “Property ‘token’ does not exist on type ‘LRParser’” error.