Skip to content

Instantly share code, notes, and snippets.

@manhtai
Last active August 29, 2015 14:07
Show Gist options
  • Save manhtai/66544c778dd5d817a673 to your computer and use it in GitHub Desktop.
Save manhtai/66544c778dd5d817a673 to your computer and use it in GitHub Desktop.
R Markdown to Markdown on Jekyll
# Copied from <http://jason.bryer.org/posts/2012-12-10/Markdown_Jekyll_R_for_Blogging.html>
jekyll_it <- function(dir=getwd(), images.dir=dir, images.url='../', out_ext='.md', in_ext='.rmd', recursive=FALSE) {
require(knitr, quietly=TRUE, warn.conflicts=FALSE)
files <- list.files(path=dir, pattern=in_ext, ignore.case=TRUE, recursive=recursive)
for(f in files) {
message(paste("Processing ", f, sep=''))
content <- readLines(f)
frontMatter <- which(substr(content, 1, 3) == '---')
if(length(frontMatter) >= 2 & 1 %in% frontMatter) {
statusLine <- which(substr(content, 1, 10) == 'published:')
if(statusLine > frontMatter[1] & statusLine < frontMatter[2]) {
status <- unlist(strsplit(content[statusLine], ':'))[2]
status <- sub('[[:space:]]+$', '', status)
status <- sub('^[[:space:]]+', '', status)
if(tolower(status) == 'true') {
message(paste('Processing ', f, sep=''))
#Write 'published: false' to original files to prevent overwrite
#converted files in next time we run this script.
content[statusLine] <- 'published: false'
writeLines( content, f)
#Generate content to new files
content[nchar(content) == 0] <- ' '
content[statusLine] <- paste('converted:',format(Sys.time(), "%d/%m/%Y %H:%M:%S"))
outFile <- paste0("../_posts/",substr(f, 1, (nchar(f)-(nchar(in_ext)))), out_ext, sep='')
render_markdown(strict=TRUE)
render_jekyll(highlight='pygments')
opts_knit$set(out.format='markdown')
opts_knit$set(base.dir=images.dir)
opts_knit$set(base.url=images.url)
opts_chunk$set(fig.path='../figures/')
try(knit(text=content, output=outFile), silent=FALSE)
} else {
warning(paste("Not processing ", f, ", status is '", status,
"'. Set status to 'true' to convert.", sep=''))
}
} else {
warning("'published:' status not found in front matter.")
}
} else {
warning("No front matter found. Will not process this file.")
}
}
invisible()
}
jekyll_it()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment