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

南笙酒味 提交于 2020-06-17 03:42:28

问题


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:

Is there a better way to do this highlighting?


回答1:


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:

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')}
```



来源:https://stackoverflow.com/questions/61760349/how-to-include-an-external-code-file-in-rmakdown-to-output-in-pdf-with-sintax-hi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!