Enable syntax highlighting for code

Editorial comment
As of 7th August 2017 there is quite strong support for the proposal. The developers have been asked via e-mail to take a closer look.

Here is a block of Python, indented by 4 spaced on each line to get verbatim/typewriter text:

from chempy import ReactionSystem  # The rate constants below are arbitrary
rsys = ReactionSystem.from_string("""2 Fe+2 + H2O2 -> 2 Fe+3 + 2 OH-; 42
2 Fe+3 + H2O2 -> 2 Fe+2 + O2 + 2 H+; 17
H+ + OH- -> H2O; 1e10
H2O -> H+ + OH-; 1e-4
Fe+3 + 2 H2O -> FeOOH(s) + 3 H+; 1
FeOOH(s) + 3 H+ -> Fe+3 + 2 H2O; 2.5""")  # "[H2O]" = 1.0 (actually 55.4 at RT)
from chempy.kinetics.ode import get_odesys
odesys, extra = get_odesys(rsys)
from collections import defaultdict
import numpy as np
tout = sorted(np.concatenate((np.linspace(0, 23), np.logspace(-8, 1))))
c0 = defaultdict(float, {'Fe+2': 0.05, 'H2O2': 0.1, 'H2O': 1.0, 'H+': 1e-7, 'OH-': 1e-7})
result = odesys.integrate(tout, c0, atol=1e-12, rtol=1e-14)
import matplotlib.pyplot as plt
_ = plt.subplot(1, 2, 1)
_ = result.plot(names=[k for k in rsys.substances if k != 'H2O'])
_ = plt.legend(loc='best', prop={'size': 9}); _ = plt.xlabel('Time'); _ = plt.ylabel('Concentration')
_ = plt.subplot(1, 2, 2)
_ = result.plot(names=[k for k in rsys.substances if k != 'H2O'], xscale='log', yscale='log')
_ = plt.legend(loc='best', prop={'size': 9}); _ = plt.xlabel('Time'); _ = plt.ylabel('Concentration')
_ = plt.tight_layout()
plt.show()  # doctest: +SKIP


If I posted this in a Q or A on Stack Overflow that had , the Prettify JS library would automatically highlight it nicely, otherwise it could be forced with the following HTML comment (not indented 4 spaces) placed above the indented block:

<!-- language: lang-python -->


I tried doing that for a post, and it didn't work. Could we get this enabled? I've posted code enough times that I'd like to have it.

In case anyone doesn't know what this looks like with syntax highlighting, here's a screenshot using a theme from my text editor.

Here are some Q/A examples containing blocks of code where this may be beneficial.

Unfortunately there wouldn't be support for Mathematica. Interestingly, I can't find examples for languages other than Python or Mathematica.

EDIT: Here are the results of our labor, now with the code prettifying enabled. In case it ever gets stolen by code-haters, there's an image link in a source code comment.

from chempy import ReactionSystem  # The rate constants below are arbitrary
rsys = ReactionSystem.from_string("""2 Fe+2 + H2O2 -> 2 Fe+3 + 2 OH-; 42
2 Fe+3 + H2O2 -> 2 Fe+2 + O2 + 2 H+; 17
H+ + OH- -> H2O; 1e10
H2O -> H+ + OH-; 1e-4
Fe+3 + 2 H2O -> FeOOH(s) + 3 H+; 1
FeOOH(s) + 3 H+ -> Fe+3 + 2 H2O; 2.5""")  # "[H2O]" = 1.0 (actually 55.4 at RT)
from chempy.kinetics.ode import get_odesys
odesys, extra = get_odesys(rsys)
from collections import defaultdict
import numpy as np
tout = sorted(np.concatenate((np.linspace(0, 23), np.logspace(-8, 1))))
c0 = defaultdict(float, {'Fe+2': 0.05, 'H2O2': 0.1, 'H2O': 1.0, 'H+': 1e-7, 'OH-': 1e-7})
result = odesys.integrate(tout, c0, atol=1e-12, rtol=1e-14)
import matplotlib.pyplot as plt
_ = plt.subplot(1, 2, 1)
_ = result.plot(names=[k for k in rsys.substances if k != 'H2O'])
_ = plt.legend(loc='best', prop={'size': 9}); _ = plt.xlabel('Time'); _ = plt.ylabel('Concentration')
_ = plt.subplot(1, 2, 2)
_ = result.plot(names=[k for k in rsys.substances if k != 'H2O'], xscale='log', yscale='log')
_ = plt.legend(loc='best', prop={'size': 9}); _ = plt.xlabel('Time'); _ = plt.ylabel('Concentration')
_ = plt.tight_layout()
plt.show()  # doctest: +SKIP

• I support this, but I guess it would be good to have a couple of examples from the main site to support the feature request, i.e. to show that this is necessary/ beneficial. – Martin - マーチン May 19 '17 at 6:28
• @Martin-マーチン I wouldn't say that it's necessary (technically, it isn't even necessary when you're writing it), it's just a nice thing to have. I've edited the post to include some examples. – pentavalentcarbon May 19 '17 at 15:32
• How many questions that are that code-heavy are really on-topic here? – Jon Custer Jun 13 '17 at 13:20
• @Jon Custer not much indeed. But I see more and more chemists are trying to move along with reproducible research concept, which involves a lot of scripting and some latexing, so having some code highlighting (I personally really enjoy GitHub's one) on ChemSE in the future would be a cherry on top. – andselisk Jun 28 '17 at 23:56

This is enabled, but not by default - lots of existing posts use code formatting for things that don't benefit from syntax highlighting, and I don't see any pervasive language tags that would be useful here...

So you'll want to rely on language hint comments to specify which (if any) highlighting you want to apply.

• For some reason I thought it didn't work before, otherwise I wouldn't have asked for it, but it definitely works now. – pentavalentcarbon Aug 7 '17 at 15:55
• Also, I'm certainly in the minority here, and it would never get approved, but I'd want python to be pervasive. – pentavalentcarbon Aug 7 '17 at 15:56
• Didn't mean to make you second-guess yourself; I meant that it's enabled now. Because of your request. – Shog9 Aug 7 '17 at 21:58

I support this.

(Vote here if you support this, too.)

As a computational chemist I am clearly biased, but currently cannot find any good reason to not have code highlighting. I have seen enough other computational chemists here and questions dealing with cheminformatics approaches that I think for a growing subset of questions it will become beneficial.

I therefore propose the following:

1. I have featured the post and added a notice that we are seeking a decision. Currently it seems (8 up/ 0 down) like an acceptable idea.
2. This post (the control group) gets a couple votes, and there is no counter argument (please post a new answer) with more up-votes. We'll then give it , otherwise .
3. Depending on the outcome we'll harass ask the developers on other channels than our in-site meta.
4. Eventually they will either implement it, or decline it for reasons we cannot foresee, which they will hopefully explain then. Either way, we can see the proposal as closed then.
• Not that I can imagine ever using it, but I can't see any issue why not. I do wonder if it has the same lag issues as MathJax though (i.e. if you had a post mixing theory of some computation described with MathJax and then added some code snippets which were highlighted, would it slow down to a complete halt). – NotEvans. Jul 25 '17 at 14:31
• @NotEvans. It is client-side JS like MathJax, but I have never seen this sort of issue on Stack Overflow where code blocks are used without math. If you are also referring to editing JS-highlighted code in posts that contain math, that would crawl. However, this happens anyway with normal text because MathJax re-renders every time you change a character in a text box, doesn't matter what "kind" of character it is. – pentavalentcarbon Jul 25 '17 at 14:56
• I have thought about that, but came to the conclusion that someone with more experience will give us advice on that. I think this extension is a lot faster than MathJax, so on those posts that take long to load you probably won't find a big difference. However, I understand this concern and would encourage you, @NotEvans., to write it as an answer, so that it is more visible. – Martin - マーチン Jul 25 '17 at 15:11
• @NotEvans. I ran a test with an 810 line/34600 character Python file dumped into a Stack Overflow question box, with syntax highlighting turned on, then starting typing at the bottom. Highlighting didn't refresh for a few seconds until after I stopped typing, and I could tell there were a few more milliseconds of input lag. It did not slow down to the level of having 1 MathJax equation on a page. Speed is a non-issue. – pentavalentcarbon Jul 26 '17 at 14:12
• Given SO is already doing this, why not here too. – bonCodigo Jul 27 '17 at 8:53

I support this too.

But I think it should have to be explicitly enabled by each post's author

We don't have the same natural categorization system as does Stack Overflow: we don't have or , for example. Therefore, it's not clear to me how the site would be configured to autodetect the relevant language.

THEREFORE, I move to amend/clarify the proposal, that in the final implementation it will be required to use some sort of explicit markup in the body of the post, perhaps just the <!-- language: lang-python --> flag noted by penta. This way no non-programmers will have their content 'hijacked' by undesired source formatting, and programmers will not have to worry about their code being mis-detected as a language it's not.

Subject to community discussion, I propose that if the overall proposal is accepted and this answer has a net positive (negative or zero) score, then it shall be considered ratified (rejected).

• I believe notepad++ has a dropdown menu to select language. I know github allows you to select the language by typing in the extension. Both detect based on the selection of the language so not only could we allow users to select the language, but perhaps selecting the language could be how we enable markup. Example with Ruby language selected (highlighted): gist.github.com/MelanieS/47932a06f571f65ebf7e20e1e50777f6 Example without a language selected (no highlighting): gist.github.com/MelanieS/cf03cce566a6dc9504f213b175006dbc – Melanie Jul 26 '17 at 4:25
• @MelanieShebel Absolutely, having something integrated with the UI of the webpage would be ideal, but that will depend on what is feasible and represents a reasonable expenditure of resources for the SO team. – hBy2Py Jul 26 '17 at 4:29
• I am against this. It is counter-intuitive, and counter-productive. The library used by SE is Google Code Prettify, and it is able to guess the language you are using. If there is the need to enable syntax highlighting, then you need to (1) know it exists and (2) know how to enable it. That means that any existing posts need to be found and updated (very meh.). Otherwise the feature would not be used much and would add overhead at no benefit. – Martin - マーチン Jul 26 '17 at 7:02
• @Martin-マーチン Hmm, the searching of the site backlog is definitely a concern. I was figuring that relatively few of the site's users likely to post code would not be savvy enough to figure out the highlighting, but maybe that's not a safe assumption. Perhaps you should convert your comment to a new answer, and we can decide on a balanced ratification/rejection criterion? – hBy2Py Jul 26 '17 at 13:16
• I think that is a technicality which the developers will give us a lot more insight to, once I bring it up to them. Let's not overthink this. There are obviously certain restrictions/ limitations to the whole thing. A change to the UI that is not universal to the whole network will not happen for example. What is the actual downside of having it on by default? – Martin - マーチン Jul 26 '17 at 13:21
• @Martin-マーチン Mainly, it resulting in formatting being applied to content that isn't actually code. (I don't have a good feel for how smart Code Prettify is, though being a Google product it's probably pretty good). – hBy2Py Jul 26 '17 at 13:28
• If it is not code, then why use the code environment? Yes, as a crappy workaround to make a table. We actually do not need those workarounds, we have MathJax. In the worst case there is a bit more colour in a block that otherwise wouldn't have it... – Martin - マーチン Jul 26 '17 at 13:55
• This is maybe the correct answer for the wrong reason. Prettify (on Stack Overflow) doesn't figure out the language without 1. [tag:python] or 2. <!-- language: lang-python -->. See here. It is up to them to enable this feature, because the library can do automatic lexing and parsing to figure out the language. – pentavalentcarbon Jul 26 '17 at 14:21
• @Martin-マーチン Long delayed response, but things like comp chem software input files would be one example where Google Prettify probably wouldn't have knowledge of the format, and incorrect colorizing would be annoying, at least to me. If we do get auto-detection, I would like at least a way to disable the prettifying on a per-code block basis. – hBy2Py Aug 6 '17 at 11:56
• @hBy2Py <!-- language: lang-none --> but I really doubt that this would happen. Let's see what the developers respond. If it needs to be enabled on a by post basis, I'd rather have it not at all though. – Martin - マーチン Aug 6 '17 at 11:59
• @Martin-マーチン Why? Why would we need to bother with going back through all the old posts to enable prettification? It could be one more thing to keep in mind in the course of normal navigation of the site? And as for people discovering the capability, it could just be added to the 'how do I format my posts?' help center article that we already link to so much. – hBy2Py Aug 6 '17 at 12:07
• @hBy2Py Let me clarify, I don't think that prettify will cause input files to be rendered badly, they will probably not render at all with the default setting. I don't really understand what you mean when you say we don't have to bother with going though old posts to enable prettify. My stance is: if it's not enabled by default, it's usefulness is marginal, therefore I'd rather not have it installed. – Martin - マーチン Aug 6 '17 at 12:22
• Ah, I thought one of your objections was the feeling of a need to go through the site to manually enable prettify on all old posts with code, my mistake. My stance is: I hate it when a software tool does a thing that I don't want it to do, and gives me no way to either tune it to my liking, or disable the feature. <!-- language: lang-none --> addresses this; so, I'm much more open to auto-enabling the prettify, if it's an option and if (iff) it will still be responsive to explicit <!-- language ...> directives. – hBy2Py Aug 6 '17 at 12:31
• I doubt the implementation will or even can be very different from what they are using on the code based sites, with the only exception that prettify will by default have to determine which language is to be used. Therefore I think that all the commands that already work on stack overflow will still work here. I also think that these issues needs to be addressed by someone who has actual knowledge to whats happening under the hood. I'll try to elevate the proposal tomorrow, and then we'll sit back and wait what happens. – Martin - マーチン Aug 6 '17 at 13:04
• @Martin-マーチン Given your strong opposition, other discussion, and the lukewarm reception at best (+6/-2), despite my original success criterion I would consider this amendment not to have been accepted. Thoughts? – hBy2Py Aug 7 '17 at 10:46