Org-mode files get exported to PDF with the document preparation system LaTeX.
Code blocks by default get exported into verbatim environment which does not have line wrapping. You can see this by visiting the .tex
file created in the same folder when you export; your code blocks should look like this:
\begin{verbatim}
import socket
# etc
\end{verbatim}
You could tell Org-mode to use a different environment for code blocks.
listings
A commonly used environment for source code is lstlisting
, provided by the LaTeX package listings
. To get Org-mode to use it, add it to org-latex-packages-alist
and set the variable org-latex-listings
to t
:
(add-to-list 'org-latex-packages-alist '("" "listings" nil))
(setq org-latex-listings t)
to then get listings to wrap, the breaklines=true
option needs to be supplied to listings. Org-mode can do this:
(setq org-latex-listings-options '(("breaklines" "true")))
This will work for normal use, however your MWE will fail because of the long variable value which does not contain spaces; breaklines does not break lines in the middle of words.
Breaking lines in the middle of words is not trivial since it could result in unwanted line breaks elsewhere.
See
Here is one way to make your MWE work, using Werner’s literate one-to-one mapping of numerals:
(setq org-latex-listings-options '(("breaklines" "true")
("literate" "{0}{0}{1}%
{1}{1}{1}%
{2}{2}{1}%
{3}{3}{1}%
{4}{4}{1}%
{5}{5}{1}%
{6}{6}{1}%
{7}{7}{1}%
{8}{8}{1}%
{9}{9}{1}%
")))
minted
Another popular LaTeX package for this purpose is minted. In addition to installing the package you will need to install python and the python-based syntax highlighter pygments. The basic configuration to get Org-mode to then use minted is described in another SE question.
The package documentation describes the available options. One approach could be to use breaklines
and breakanywhere
.
(setq org-latex-minted-options '(("breaklines" "true")
("breakanywhere" "true")))
As an aside, I don’t see how setting org-startup-truncated
could have changed anything about how the document is exported. This only affects truncate-lines
in the buffer. LaTeX wraps the lines for you whether or not they are truncated in the buffer.