There is another option that has not been pointed out here. You can insert an HTML comment that will automatically turn on syntax highlighting within a post (see: What is syntax highlighting and how does it work?). The way it works is that you put
<!-- language: lang-r --> on its own line prior to the code. Then the next code block will be highlighted as R code. (Note that the comment itself will not be visible in the post.)
This can be done with a number of languages, including (at least),
lang-matlab, as well as the major programming languages (
java, etc.). I don't know if there is support for other statistical software languages (e.g.,
There are a couple of limitations with this. First, there will only be highlighting within code blocks; inline code is not highlighted. Second, this will only highlight the next code block, if there is text, or a figure, or something else between one code block and a subsequent code block, the subsequent code block will not be highlighted. Thus, you need to either add the comment prior to each code block, or use
<!-- language-all: lang-r --> to highlight all subsequent code blocks (note the addition of
-all in the comment). Third, these comments will not highlight code blocks prior to the comment. Lastly, the comment will only highlight the code blocks within that post (question or individual answer); other posts on the same thread will not be affected. (Adding, say, the r tag to the question will highlight all code blocks on the thread.)
You can also use these comments to locally override syntax highlighting on a thread. For example, if a question included the r tag, but a code block in an answer was not r code, highlighting could be turned off via
<!-- language: lang-none -->, or could be switched to highlighting for a different language, e.g.,
<!-- language: lang-python -->.
The following provides an example of how this can be done. Because the HTML comments will not show up, when I place them, I will subsequently place a copy of the comment as inline code to make it clear what was done. (Hmmm, annoyingly the syntax highlighting does not seem to be working on meta, although I just tested it and everything below shows up as it should on the main site.)
Here is some text answering a question.
here # is some non-highlighted code in a code block
Now I have more pearls of wisdom.
<!-- language: lang-r -->
this = "some highlighted code" # nifty!
Random crankiness and weird digressions from old man.
# once again, code is not highlighted
<!-- language-all: lang-r -->
highlighted # code
Increasingly tedious exposition with every other word inexplicably italicized.
code "still" # highlighted