Print with syntax color in R-Studio

Its not an R-Studio solution, but notepad++ will print R source with syntax highlighting.


RStudio will not print in colour, but it's easy to save the code as a PDF; in this case the syntax format is preserved. My favourite package is knitr.

library(knitr) 
stitch("file_name.R")

The default output is PDF/Markup in .tex. If you prefer not to typeset, running the below will export as .html

stitch(script="file_name.R", system.file("misc", "knitr-template.Rhtml", package="knitr"))

Brief explanation

The reason this is an answer to this question in because of the last line of the question:

Is there a way to print out the text with the highlighting I see in the editor?

so we are not limited to only and only using Rstudio software here.

After exploring the awesome answer by @rrg and realizing that it runs the code line by line, I wrote a comment below his answer and continued googling. My problem is that the code I wrote is so large and so time consuming to run that running it for the sake of having a syntax highlighted version is not feasible.

Most of the solution out there online involves having notepad++ which is a Windows application and I'm a dedicated Linux user, so I searched for a way I can do this in Linux (and possibly Mac)

The way I solved it:

Inspired by a blog post, I used the famous and beloved Vim to convert R to syntax highlighted HTML and then because you can open HTML in your browser, you can what ever you want with it (print, screenshot, etc.)

  1. Activate synax highlighting in Vim:

    • open terminal
    • then open the vim config file by typing vim ~/.vimrc
    • press i from keyboard to go to "insert mode"
    • go to the end of the file using arrow keys on your keyboard
    • type syntax on at the end of the file
    • now you need to save and exit. For this you need to press Esc button from keyboard to come out of "insert mode" and then type :x and press Enter to save and close the file.
    • if you want to change the color scheme of the syntax highlighting, visit the bottom part of this website
  2. From terminal open your file with Vim:

    vim YOUR_FILE_PATH
    
  3. Having you R code open in vim, you can turn on the line numbers if you like by pressing Esc and then write :set number and press Enter.

  4. For converting R to HTML, press Esc to make sure you are not in "insert mode" and then type :TOhtml and press Enter. This will result is having a split window in terminal, half is your R code and the other half id your new HTML code.

  5. For saving the files, type :x along with Enter button from keyboard twice to save both files (your R file will be unchanged if you have not typed anything extra in it and your HTML file will be created with the same name near your R code)

  6. Now open it with your favorite browser (in my case Vivaldi) and do what ever you want (in my case converting the whole HTML into PNG)

Tags:

R

Rstudio