# Org-mode: How to render latex inside ~code~

This seems a catch-22: I want to render code in an org-mode export (html or latex pdf) where the snippet below done as a ~code block

> (cons 1 nil) \to (1)


actually renders \to as a proper right arrow (yields). Of course if I do the snippet as inline latex

$> (cons 1 nil) \to (1)$


I get the properly rendered right arrow, but now it's not in the sans mono code font. What can I do to have my cake and eat it too?

• Why not just use the Unicode character? →? – PythonNut Feb 27 '16 at 22:52

I would use one of the following:

~> (cons 1 nil)~ \to ~(1)~

~> (cons 1 nil) → (1)~

• Could you explain how you insert the arrow character? (input method I guess) – JeanPierre Sep 27 '16 at 13:32
• @JeanPierre, as you guessed I used the TeX input method, C-\ TeX RET \to. You can also copy and paste from elsewhere. – Omar Sep 27 '16 at 21:29

From org mode manual:

You can make words bold, /italic/, underlined, ‘=verbatim=’ and ‘~code~’, and, if you must, ‘+strike-through+’. Text in the code and verbatim string is not processed for Org mode specific syntax, it is exported verbatim.

Indeed ~> (cons 1 nil) \to (1)~ is exported as LaTeX \texttt{> (cons 1 nil) \textbackslash{}to (1)}.

But this does suggest a workaround for LaTeX: use an export filter to undo the conversion of \ to \textbackslash{}.

(defun my-latex-filter-allow-latex-in-code (text backend info)
"Undo backslash escaping"
(when (org-export-derived-backend-p backend 'latex)
(replace-regexp-in-string "textbackslash{}" "" text)))

#'my-latex-filter-allow-latex-in-code)


The export filter can be extended for handling html as well. Here's a first draft handling only \to:

(defun my-filter-allow-latex-in-code (text backend info)
"Allow LaTeX symbols in code"
(cond
((org-export-derived-backend-p backend 'latex)
(replace-regexp-in-string "textbackslash{}" "" text))
((org-export-derived-backend-p backend 'html)
;; either extend this or find the html export function doing these conversions
(replace-regexp-in-string "\\\\to" "&rarr;" text))))