googlearchive / code-prettify

An embeddable script that makes source-code snippets in HTML prettier.
Apache License 2.0
5.79k stars 905 forks source link

JavaScript template literals not highlighted properly. #492

Open JC3 opened 7 years ago

JC3 commented 7 years ago

The lang-js highlighter (as used on Stack Exchange) does not appear to recognize backticked strings properly:

let s = `a a a 'a a a' "a a a" a a ${true}`;  // not quite
let t = `a a a 'a a a ${true}'`;              // a little worse
let u = 'a a a \'a a a\' "a a a"';            // correct
let v = "a a a 'a a a' \"a a a\"";            // correct
let w = `a 'a a`; if (true) { }               // very not correct, but only if last line.

Currently renders like this (when js highlighter specified):

enter image description here

A number of issues are shown above:

All text except placeholder expressions should be highlighted as a string (or perhaps even a unique color, Tampermonkey style) when inside backticks.

Chrome 58, Windows.

AncientSwordRage commented 5 years ago

The same is true for // inside backticks

philBrown commented 5 years ago

To elaborate on the above comment, with a string like

let url = `http://example.com`

everything after http: is interpreted as a comment by the syntax highlighter.

Possibly related to https://github.com/google/code-prettify/issues/217

mikemaccana commented 5 years ago

Just a note this is affecting all current JavaScript on StackOverflow

mikesamuel commented 5 years ago

Handling this properly will require keeping a bracket stack.

`start of string
${  // inside an interpolation
{ toString() { return 'foo' } }  // None of these brackets put us back into the string
/* but this one does --> */}
now we're back in the string 
${ /but not for long [}]/ 
} and we're back but 
${ 
  `this string is in a string ${ `me too` }`
}`;
jolleekin commented 5 years ago

Tagged template literals should be supported as well in order to support frameworks such as lit-element

const style = css`
  /* formatted as CSS */
  p {
    color: blue;
  }
`;

const template = html`
  <!-- formatted as HTML -->
  <p>Hello world</p>
  <my-element
    .hidden=${/* formatted as JS */ a + b > c}
  ></my-element>
`;
mikesamuel commented 5 years ago

@jolleekin How would prettify know that the html and css tags correspond to those languages?

jolleekin commented 5 years ago

@mikesamuel It's based on the tag function. Please look at these projects