Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Highlight.JS Inline Code Syntax Highlightning #945

Closed
ghost opened this issue Sep 27, 2015 · 16 comments · Fixed by #3180
Closed

Highlight.JS Inline Code Syntax Highlightning #945

ghost opened this issue Sep 27, 2015 · 16 comments · Fixed by #3180

Comments

@ghost
Copy link

ghost commented Sep 27, 2015

Highlight.js is a great highlightning tool. But now i want to know if it is also possible to make inline highlighting, so not like a block (like at http://tekkkz.com/posts/articles/arch_installation.html) but inside a text paragraph?

If it is possible, how?


The answer, for version 11 and up.

If using version 11 or newer of highlight.js you can use the following to also highlight <code> elements.

hljs.config({ cssSelector: 'code' });;
hljs.highlightAll();

Otherwise, check our README (this can be done with just a few lines of code) or skim below for possibly more specific examples.

@Sannis
Copy link
Collaborator

Sannis commented Oct 11, 2015

Yes, you can use highlight.js not only with <pre><code> blocks, but with any other, see README#custom-initialization.

@Sannis Sannis closed this as completed Oct 11, 2015
@Sannis Sannis added the other label Oct 11, 2015
@tylerlong
Copy link

Problem is:

.hljs {
    display: block;
}

The code won't be displayed as inline.

Solution is to add the following to your css code:

pre code.hljs {
  display: block;
}

code.hljs {
  display: inline;
}

@frnco
Copy link

frnco commented Dec 14, 2015

Just pointing out, the ideal solution is to have pre > code.hljs on the library for display: block; and padding rules, but I solved this in my case with two lines, though I will expand the JS in here to make it clearer.

Intialize like this (Without jQuery):

for (i in document.getElementsByTagName("code")) {
  console.log(document.getElementsByTagName("code")[i]);
};

Or like this (With jQuery):

$('pre code').each(function(i, block) {
  hljs.highlightBlock(block);
});

And add this CSS: p code.hljs, li code.hljs { display: inline; padding: .2em }

The padding change is necessary for Solarized Dark, with .5em it overlaps for more convoluted examples, at least on my blog, and feels utterly ugly.

@q2apro
Copy link

q2apro commented Feb 7, 2021

Ping from the year 2021. This solution above is still valid. Add the CSS as described.

pre code.hljs {
  display: block;
}

code.hljs {
  display: inline;
}

JamesTheAwesomeDude added a commit to JamesTheAwesomeDude/highlight.js that referenced this issue May 7, 2021
Resolves highlightjs#945 for non-technical users such as those using
highlight.js via a WordPress plugin, allowing trivial and much-
less-invasive inclusion of other elements (such as <code>s not
wrapped in a <pre>) than existing proposed solutions
@JamesTheAwesomeDude
Copy link
Contributor

JamesTheAwesomeDude commented May 7, 2021

This thread is still one of the top google search results for those trying to solve this on WordPress

Using the following init function got it working for me:

// alternate init script to enable inline <code> tag highlighting
// NO LONGER NEEDED AS OF JANUARY 13th, 2022:
// https://github.com/highlightjs/highlight.js/issues/945#issuecomment-835573185
window.addEventListener('DOMContentLoaded', event => {
  let sheet = event.target.getElementById('prismatic-highlight-css').sheet;
  sheet.addRule('.hljs:not(pre>*)', 'padding: revert');
  Array.from(sheet.rules)
  .filter(rule => rule.selectorText == '.hljs'
               && rule.style.display == 'block')
  .forEach(rule => {
    rule.style.removeProperty('display');
  });
  event.target.querySelectorAll('code')
  .forEach(hljs.highlightElement || hljs.highlightBlock);
}, false);

@joshgoebel
Copy link
Member

FYI: hljs.highlightBlock

This API is already deprecated (and will be removed in the future) in favor of highlightElement

JamesTheAwesomeDude added a commit to JamesTheAwesomeDude/highlight.js that referenced this issue May 7, 2021
joshgoebel added a commit that referenced this issue May 8, 2021
* Allow highlightAll to be used with custom selectors

Resolves #945 for non-technical users such as those using
highlight.js via a WordPress plugin, allowing simpler inclusion 
of other elements (such as <code>s not wrapped in a <pre>) 
than existing proposed solutions

* Move highlightAll's querySelector into options

* Don't coerce any non-block elements to be blocks

This nearly-singlehandedly resolves
#945

* mention as a breaking change

Co-authored-by: Josh Goebel <me@joshgoebel.com>
@JamesTheAwesomeDude
Copy link
Contributor

JamesTheAwesomeDude commented May 8, 2021

WordPress users here from Google, read this:

When/if Prismatic updates to version 11 or newer of highlight.js (check the changelog to know),
Since version 3.0 of Prismatic (released in January of 2022), use the following init script:

hljs.configure({ cssSelector: 'code' });
hljs.highlightAll();

if you're stuck on an older version for some ungodly reason, use the workaround posted above

@joshgoebel
Copy link
Member

@JamesTheAwesomeDude Your v10 solution seems awful complex... can Wordpress users not alter their CSS? I'm not sure why this shouldn't be 3 lines of JS + a few lines of CSS?

@JamesTheAwesomeDude
Copy link
Contributor

JamesTheAwesomeDude commented May 9, 2021

@joshgoebel From a config managament perspective, what's easier to keep track of, when you're applying one conceptual patch (to perform one single task - enable inline code highlighting):

  1. A pasted chunk of JavaScript inside Prismatic's settings
  2. A pasted chunk of JavaScript inside Prismatic's settings, and a pasted chunk of CSS inside the last option of the Customizer

Once HLJS v11 comes out, how likely is a user to even remember there's other changed config shards laying around their system to accomplish that single task when (or if) they go to switch the old workaround out for the new .config-based setup?

They both perform the same thing: change highlight.js boot-up to also affect .hljs:not(pre>*), and remove the .hljs { display: block; } mandate; it's just that one of them requires two system changes and the other requires one system change… not everyone who uses WordPress is a programmer!

Not to mention the fact that only one of these solutions has no unforseeable, potential, or future interactions with their CSS. (And, yes, it's not likely that the forgotten cruft will affect any given user; but I've been "that user" who's affected by forgotten CSS workarounds, and it's not great.)

@joshgoebel
Copy link
Member

joshgoebel commented May 9, 2021

Sounds like a Prismatic problem, maybe. I feel users should actually know and understand their setup and how they are altering it. Far too much harm comes from from people copying and pasting code they don't understand from one box to another. Perhaps you've never been "that user" yet though. :-)

@JamesTheAwesomeDude
Copy link
Contributor

Far too much harm comes from from people copying and pasting code they don't understand from one box to another.

Hah! Indeed. (I'm actually considering sneaking a PR to Prismatic to add a GUI toggle for this before their next release…)

Perhaps you've never been "that user" yet though. :-)

I've been that user far too many times, in fact; you name specifically my worry: if non-technical users are to be pasting code to get this working anyway, it should be self-contained and have as few side-effects and add as little gum to their system as possible. I can see virtually no harm that can come from the workaround as-written, and I can see at least some relevant harm that would be made possible by any other implementation of the workaround.


The JavaScript I've written may look superficially ugly, but it boils down to two parts:

  1. sheet.rules.filter.forEach Checks for the old version of the CSS which breaks inline code, and, if and only if found, patches it to remove just 2 detrimental rules.
  2. querySelectorAll.forEach does almost precisely what newer versions of config-augmented highlightAll() do.

I cannot see any less-invasive, less-likely-to-break-something (now or in the future) way of allowing WordPress users on version 10 of hljs to get inline code highlighting. I've already made several tweaks to the workaround as-written to minimize the possibility of complications as much as possible, and have got it to the point where I wouldn't feel nervous about recommending it to an arbitrary user.

I don't know how long it'll be till v11 comes out, and then I don't know how long it'll be till Prismatic includes the updated library, so I wanted to make this workaround as perfect and effective as possible while being maximally unlikely to cause any unintended effects, especially for non-technical users who are unlikely to be able to troubleshoot anything that happens. If you see any ways to improve on it from that frame of reference, I'd love to hear it and update it once more with your feedback.

@joshgoebel
Copy link
Member

but it boils down to two parts:

You don't need to explain it to me. Obviously I can read it. :-)

I don't know how long it'll be till v11 comes out

Hopefully this month. Betas are more than usable now. But of course no idea on Prismatic's timetable...

If you see any ways to improve on it

I'd probably just inject a blob of new CSS vs manhandling existing CSS, but I haven't given it much thought.

@JamesTheAwesomeDude
Copy link
Contributor

I'd probably just inject a blob of new CSS vs manhandling existing CSS, but I haven't given it much thought.

I was doing that in a previous revision of the script, actually, until I realized that that might have unforseeable interactions with user styles (what's better: directly removing something inappropriate, or putting more tape on top of it that might have further interactions with other site-specific configs?)

Also, you copied an outdated version of my v11+ config change into the OP: the double-semicolon was a typo on my part 😉. (Might consider prepending that line with “Wordpress' Prismatic users:”, too, since it links to that changelog for context.)

@joshgoebel
Copy link
Member

what's better

I think it's impossible to say. Anytime you extend anything you risk breaking it with future changes. Since I can't know the future I'd choose to go with a simpler solution that is more readable, etc... but we can agree to disagree.


;; doesn't hurt anything. :) I made it more generic now as this isn't just an answer for Prismatic users... it's a valid question for anyone using our library.

@joshgoebel
Copy link
Member

Thanks again for the PR.

@jaymody
Copy link

jaymody commented May 14, 2022

The following worked for me with version 11.5.1:

hljs.configure({ cssSelector: 'code' });;
hljs.highlightAll();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants