Skip to content

Instantly share code, notes, and snippets.

@lgatto
Last active December 18, 2023 05:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lgatto/d9d0e3afcc0a4417e5084e5ca46a4d9e to your computer and use it in GitHub Desktop.
Save lgatto/d9d0e3afcc0a4417e5084e5ca46a4d9e to your computer and use it in GitHub Desktop.
Convert Rnw to Rmd
#!/usr/bin/perl
## Based on convert.txt by Mike Love
## https://gist.github.com/mikelove/5618f935ace6e389d3fbac03224860cd
## The script ignores labels and references, un-numbered sections
## (section*), quotes and probably a couple of more. It won't deal
## with the pre-amble, bibliography and document tags either. Still
## useful, though.
## Usage:
## rnw2rmd file.Rnw > file.Rmd
use warnings;
my $filename = $ARGV[0];
open (RNW, $filename);
while (<RNW>) {
s|\\Robject{(.+?)}|`$1`|g;
s|\\Rcode{(.+?)}|`$1`|g;
s|\\Rclass{(.+?)}|*$1*|g;
s|\\Rfunction{(.+?)}|`$1`|g;
s|\\texttt{(.+?)}|`$1`|g;
s|\\textit{(.+?)}|*$1*|g;
s|\\textbf{(.+?)}|**$1**|g;
s|\\emph{(.+?)}|*$1*|g;
s|<<|```{r |g;
s|>>=|}|g;
s|@|```|g;
s|\\section{(.+?)}|# $1|g;
s|\\subsection{(.+?)}|## $1|g;
s|\\subsubsection{(.+?)}|### $1|g;
s|\\Biocexptpkg{(.+?)}|`r Biocexptpkg("$1")`|g;
s|\\Biocannopkg{(.+?)}|`r Biocannopkg("$1")`|g;
s|\\Biocpkg{(.+?)}|`r Biocpkg("$1")`|g;
s|\\cite{(.+?)}|[\@$1]|g;
s|\\ref{(.+?)}|\\\@ref($1)|g;
s|\\url{(.+?)}|<$1>|g;
s|\\ldots|\.\.\.|g;
s|\\label{| {#|g; ## only for sections
print $_;
}
close (RNW);
@nxskok
Copy link

nxskok commented Feb 14, 2018

Nice work. But:

  • I think the curly brackets need to be escaped.
  • I apparently use itemize a lot; presumably one could replace begin/end{itemize} with nothing, and replace \item with - or similar. (If I get that to work, I'll let you know.)

@fernandomayer
Copy link

Thanks for this.

In Perl >= 5.26 the square brackets need to be escaped.

I would like to second the comment above: replace \begin{itemize}, \end{itemize}, etc with nothing would be very useful.

@fernandomayer
Copy link

I've tried to do something here.

This removes environments and most other unuseful things from LaTeX.

@lwaldron
Copy link

lwaldron commented Jul 9, 2018

Very useful. I found the @fernandomayer to be too aggressive, removing \myfun{} commands that really needed to be substituted, so I used this gist and made such substitutions and deletions manually.

@abalter
Copy link

abalter commented Dec 18, 2023

I came across this, but haven't tried it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment