Add a language label to code chunks in pkgdown articles

[This article was first published on Thomas Hackl | Coding Biologist, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

pkgdown nicely renders code chunks in your package documentation. However, if
you mix in non-R snippets, it gets difficult to distinguish between
languages. So how about some nice labels for each code box.

pkgdown is super useful for documenting your R packages. It is particularly well
suited to showcase small code examples. In some of my projects, on top of R code
chunks, I also provide code examples in other languages such as short Linux
command line code snippets I used to preprocess data before loading it into R.

pkgdown renders code chunks in most common languages nicely, with syntax
highlighting, etc. However, it does not indicate what language is used in a
particular code chunk. For most projects, this is not a problem, because all
code chunks are R code anyway. But this behavior gets confusing when we mix
different languages in the same document.

pkgdown-no-code-labels.png

To solve this issue, I wrote a small javascript hook that adds small labels to
each code chunk, indicating the language of its content. The hook comprises a
short jQuery function and some CSS instructions. Simply add the two snippets
below to your pkgdown/extra.js and pkgdown/extra.css to add the labels to
your pkgdown projects.

pkgdown-code-labels.png

// add to extra.js
function addLang( jQuery ) {
    $("div.sourceCode").each(function(i, v){
        var lang = $(this).children("pre").attr("class").split(' ').pop()
        var Lang = lang[0].toUpperCase() + lang.slice(1)
        $(this).before('
'">' + Lang + ' code
'
+ '
'
) }) } $( document ).ready(addLang)
/* add to extra.css */
codelabel {
    border: 2px solid white;
    background-color: #eee;
    z-index: 100;
    position: absolute;
    font-size: 60%;
    font-weight: bold;
    padding: 2px;
    display: inline-block;
}
.codelabelspacer {
    height: 12px;
}

To leave a comment for the author, please follow the link and comment on their blog: Thomas Hackl | Coding Biologist.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)