CotEditor icon indicating copy to clipboard operation
CotEditor copied to clipboard

Syntax Highlighting For JavaScript Template Literals

Open karamfd opened this issue 9 months ago • 2 comments

Current issue

JavaScript template literals inside a string look like regular text so they are harder to debug in case of errors.

console.log(my name is ${name})

The solution you'd like

In the example below, the Github syntax highlighter makes it easier for me to read the JavaScript template literal ${name} inside the string.

console.log(`my name is ${name}`)

Alternatives you've considered

I looked at the syntax highlighter but haven't attempted to figure out if this feature can be added without needing to rewrite an entire syntax highlighter from scratch to be honest.

Feel free to close this issue if this feature is out of scope.

CotEditor version

5.1.1

macOS version

15.3.1

Additional context

No response

karamfd avatar Mar 06 '25 02:03 karamfd

Although I understand your need, unfortunately, it’s challenging to achieve this with the current syntax highlighting algorithms in CotEditor. I need to improve the highlighting algorithm first, but the plan is not fixed yet.

1024jp avatar Mar 12 '25 00:03 1024jp

Hi @1024jp, I can make this work with the regex \$\{[^}]*\} in the characters category. Below is a screenshot of the result:

Improved Template Literals in JavaScript

I'm not familiar with regex so I used AI to help me with this part. The regex will fail if I apply it to other categories like variables for example.

karamfd avatar Jun 14 '25 22:06 karamfd

I tried more complex examples and everything inside of ${} will get highlighted with the same colour as characters, which is not any better.

I did find a decent compromise by using the regex \$\{|\} instead. This regex will only highlight the ${} special characters. Whatever goes inside of it, will have the default string colours like the example below:

Example of highlighting the ${} special characters in JavaScript

I actually prefer this option for my needs. I can create a pull request if you agree.

karamfd avatar Jul 13 '25 15:07 karamfd

@karamfd thank you for your suggestion.

I am concerned that your \$\{|\} approach highlights ${ and } even when they appear by themselves outside of literals. } in particular will appear everywhere in the code, so unintentional highlighting will be the majority.

Thus, I would prefer to adopt your first approach, although It may be a little unhappy that even the content is highlighted. I will try a further improvement \$\{[^\n}]*\} which prohibits line breaks within braces.

I’ve already implemented it on a trial basis in CotEditor 6.2.1, which will be released this week, so please report back if there are any inconveniences.

1024jp avatar Jul 21 '25 14:07 1024jp