prism:
 line breaks get deleted when calling prism.highlightElement(code)

I set up my HTML using the following snippet:

<div>
 <pre><code class=" language-js" contenteditable="true"></code></pre>
</div>

When I call prism.highlightElement(code); from the following TypeScript snippet:

import * as prism from "prismjs";

const code: HTMLElement = document.getElementsByTagName("code")[0];

prism.highlightElement(code);

… all line breaks in the <code> element get deleted when calling prism.highlightElement(code).

The result is that all code is getting displayed in a single line then:

before

multiple lines

after

one liner

I believe this is not supposed to happen?


About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 20 (8 by maintainers)

Most upvoted comments

The hook appears to be incorrect. The correct hook name is: before-highlight

Prism.hooks.add('before-highlight', function (env)
{
  env.code = env.element.innerText;
});

innerText has a few other properties which make it less useful for Prism. It would also change the current behavior of Prism, so for some people out there, this might be a breaking change.

Also, you can use hooks to make Prism use innerText.

Prism.hooks.add('before-sanity-check', function (env) {
    env.code = env.element.innerText;
});

The hook appears to be incorrect. The correct hook name is: before-highlight

Prism.hooks.add('before-highlight', function (env)
{
  env.code = env.element.innerText;
});

I had this issue trying to add Prism.js to Anki card template and I fixed it by adding this hook to Prism.js code. Thank you!

The resulting html has no line break despite the 3 \n in the source code.

Prism’s HTML output is intended for pre elements which use white-space: pre by default. Set this property for the element you’re using for displaying code, and everything should work fine.

From the description you mentioned I can only read the inteded behaviour and a performance issue.

Performance aside: Is breaking change not enough reason?

Also, I don’t think that it’s a good idea for the text Prism highlights to change depending on whether the element is being rendered or not.

What do you think @mAAdhaTTah ?