Text FormattingUsing listings to create code that can be copied and pasted

Information and discussion about LaTeX's general text formatting features (e.g. bold, italic, enumerations, ...)
Post Reply
squiggle
Posts: 1
Joined: Fri Feb 25, 2011 5:01 am

Using listings to create code that can be copied and pasted

Post by squiggle »

Hello,
I would really like to make a pdf that has code that can be copied and pasted into an editor and run, however, when I use:

\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{language=C}
\begin{lstlisting}
// Basic command
fprintf("I'm sad this doesn't work");
\end{lstlisting}
\end{document}

And copy and paste from the resultant pdf into a text editor, it looks like this:

// B a s i c command
f p r i n t f ( ” I ’m sad t h i s doesn ’ t work ” ) ;

I'd like to not have those spaces between each letter. I have tried tweaking things with \lstset, however, nothing I have tried yet seems to work.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p

shadgrind
Posts: 140
Joined: Thu Jul 16, 2009 12:39 am

Using listings to create code that can be copied and pasted

Post by shadgrind »

Add this option to your \lstset command:

Code: Select all

columns=fullflexible
You may also want to use a monospaced font for your code listings; it just looks better. I use the beramono package for that. Here's how I would do your code:

Code: Select all

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[scaled=0.80]{beramono}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{code}{HTML}{ECF8F4}
\definecolor{comments}{HTML}{5269A5}

\lstloadlanguages{C}
\lstset{%
  language=C,
  showstringspaces=false,
  lineskip=1pt,
  xleftmargin=0.06\textwidth,
  linewidth=0.99\textwidth,
  columns=fullflexible,
  backgroundcolor=\color{code},
  keepspaces=true,
  breaklines=true,
  basicstyle={\small\fontfamily{fvm}\fontseries{m}\selectfont},
  keywordstyle={\small\fontfamily{fvm}\fontseries{b}\selectfont},
  commentstyle={\color{comments}\small\fontfamily{fvm}\itshape\selectfont},
  belowcaptionskip=10pt,
  float=h,
  label=lst:squiggle,
  caption={\quad Program listing for squiggle.c: no more spaces!}
}

\begin{document}
\begin{lstlisting}[frame=single,framerule=0pt]
// Basic command
fprintf("I'm sad this doesn't work");
\end{lstlisting}
\end{document}
System: TeX Live 2012, Fedora 18 x86_64, GNU Emacs 24.2
Post Reply