Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making knitr code blocks more cleanly cut-and-pastable

Tags:

r

knitr

I would like to use knitr to produce pdf documents from which example code can be cleanly cut and pasted, but don't seem to be able to.

An example of the problems I run into:

The knitr manual pdf includes this code block (p.3):

## option tidy=TRUE
for (k in 1:10) {
j <- cos(sin(k) * kˆ2) + 3
print(j - 5)
} 

When copied from the pdf and then pasted into R (or SO, or etc.), it yields:

## option tidy=TRUE
for (k in 1:10) f j <- cos(sin(k) * kˆ2) + 3
print(j - 5)
g 

See how the first two code lines get combined onto one, and, worse, { and } get converted to f and g?

My questions:

First, I guess, is this something other folks experience? Does it happen just on Windows, or elsewhere as well?

If it's not just me, is there some easy workaround? Would using a different font when compiling the *.tex file produce a *.pdf document that is easier to copy-and-paste from?

(FWIW, if I instead use minted to highlight my R code, I don't have any of the same problems, so I know it's possible to get this right.)

like image 610
Josh O'Brien Avatar asked May 09 '13 18:05

Josh O'Brien


1 Answers

Based on clues in this question and its accepted answer, I found that using the LaTeX fontenc package to set the font encoding to T1 fixes the problems reported above. (See also here for some explanation of why using T1 is the more or less officially recommended best practice for LaTeX documents of all sorts. Improved copy-and-pastability is one of several good reasons noted at that link.)

Here's what the start of the preamble in the fixed document looks like:

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
like image 162
Josh O'Brien Avatar answered Sep 20 '22 04:09

Josh O'Brien