Prism: Prism removes <br/> on Prism.highlightAll()

Created on 2 Dec 2015  路  4Comments  路  Source: PrismJS/prism

Example:

Console.WriteLine("Hey");
int i = 5;

This is how it should look and how it looks in my TinyMCE prism integration. This works fine and has the line break tags (br) in it. When I put that code somwhere else on my page and call Prism.highlightAll(); though, it removes the breaks and everything is displayed in one line which looks really ugly.

Most helpful comment

Maybe too late, but I found another work around.

It looks like Prism uses element.textContent but textContent method does not treat <br/> tag as a line feed and then everything become inline.

https://github.com/PrismJS/prism/blob/6530709e85533b7a5aa5da93f894512aefde3d4f/components/prism-core.js#L195

I added plugin hook to force Prism to use element.innerText(that treats <br/> tag as a line feed) and now it works well for me :)

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

All 4 comments

+1 I have this same issue

For a workaround I have found that this works:

Step 1: Use TinyMCE's APIs to extract the content from the editor. For example:

var htmlToLoad = tinyMCE.get('area3').getContent();

Step 2: Replace any<br /> elements in the content with a simple newline:

var htmlToLoad = tinyMCE.get('area3').getContent();
htmlToLoad = htmlToLoad.replace(/<br \/>/g,'\n');

You need to do this because Prism's highlight function will remove the <br /> tags causing the spacing to not look as things do in TinyMCE.

Step 3: Place the content into an HTML block element:

document.getElementById("result").innerHTML = htmlToLoad;

Step 4: Run Prism's highlight function

Prism.highlightAll();

This triggers Prism to re-evaluate the DOM for things that it should highlight - it won't do this automatically.

Maybe too late, but I found another work around.

It looks like Prism uses element.textContent but textContent method does not treat <br/> tag as a line feed and then everything become inline.

https://github.com/PrismJS/prism/blob/6530709e85533b7a5aa5da93f894512aefde3d4f/components/prism-core.js#L195

I added plugin hook to force Prism to use element.innerText(that treats <br/> tag as a line feed) and now it works well for me :)

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

Hi all! Have you tried using the Keep Markup plugin? I just did a quick test and it seems to work as you would expect.

I'll close this issue. If you think this issue deserves a better solution, please tell us so we can reopen it!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

myst729 picture myst729  路  6Comments

finnianr picture finnianr  路  4Comments

RobLoach picture RobLoach  路  9Comments

jiantosca picture jiantosca  路  4Comments

kizu picture kizu  路  7Comments