如何在 r markdown 中包含外部代码文件以输出带有语法高亮的 pdf

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

我的问题灵感来自。但是,不同的是我的输出是PDF。

我有一个 C++ 代码保存在外部文件中。我想将它打印成带有语法高亮的 r markdown PDF。

我的example.cpp代码,实际上是一个TMB代码:

// 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;
}

最小代码:

---
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}

幻灯片中的结果:

有没有更好的方法来突出显示?

您可以 运行 Rmarkdown 中的许多引擎。你可以找到它们 here.

一般情况下:

我的 C++ 存档,我将其命名为 '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;
}

我的 Rmd 存档:


---
title: "Code to PDF"
output:
  pdf_document
---

# Cats are nicer than dogs

```{Rcpp, code=readLines('mycpp.cpp')}
```

输出:

具体到你的情况,试试这个:

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