Search code examples
rlatexpdf-generationr-markdownlistings

How to include an external code file in rmakdown to output in pdf with sintax highlight


My question is inspired from this one. However, the difference is that my output is PDF.

I have a C++ code saved in an external file. I want to print it into a r markdown PDF with syntax highlight.

My example.cpp code, which is in fact a TMB code:

// Fitting Bivariate Gaussian distribution.
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
  using namespace density;
  DATA_MATRIX(Y);
  PARAMETER_VECTOR(rho);
  PARAMETER_VECTOR(sigma);
  vector<Type> rho_temp(1);
  rho_temp = rho;
  vector<Type> sigma_temp(2);
  sigma_temp = sigma;
  Type res;
  for(int i = 0; i < 50; i++)
    res += VECSCALE(UNSTRUCTURED_CORR(rho_temp), sigma_temp)(Y.row(i));
  return res;
}

Minimal code:

---
title: "Code to PDF"
output: beamer_presentation
safe-columns: true # enables special latex macros for columns
header-includes:
- \usepackage{listings}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
setwd("/home/guilherme/Google Drive/Mestrado/dissertacao/TMB/Presentation")
```

## Slide1

\lstinputlisting[language=C++]{example.cpp}

result in the slide:

enter image description here

Is there a better way to do this highlighting?


Solution

  • You can run a lot of engines in Rmarkdown. You can find them here.

    In general case:

    My C++ archive, which I named as 'mycpp.cpp':

    # include <iostream>
    
    class Passaro                       // classe base
    {
    public:
       virtual void MostraNome()
       {
          std::cout << "um passaro";
       }
       virtual ~Passaro() {}
    };
    
    class Cisne: public Passaro         // Cisne é um pássaro
    {
    public:
       void MostraNome()
       {
          std::cout << "um cisne";        // sobrecarrega a função virtual
       }
    };
    
    int main()
    {
       Passaro* passaro = new Cisne;
    
       passaro->MostraNome();            // produz na saída "um cisne", e não "um pássaro"
    
       delete passaro;
    }
    
    

    My Rmd archive:

    
    ---
    title: "Code to PDF"
    output:
      pdf_document
    ---
    
    # Cats are nicer than dogs
    
    ```{Rcpp, code=readLines('mycpp.cpp')}
    ```
    
    

    Output:

    enter image description here

    Especific to your case, try this:

    ---
    title: "Code to PDF"
    output: beamer_presentation
    safe-columns: true # enables special latex macros for columns
    header-includes:
    - \usepackage{listings}
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    setwd("/home/guilherme/Google Drive/Mestrado/dissertacao/TMB/Presentation")
    ```
    
    ## Slide1
    
    ```{Rcpp, eval = FALSE, echo = TRUE, code=readLines('example.cpp')}
    ```