From 44bcb5da518495a4aac3533d45adfb33df290ced Mon Sep 17 00:00:00 2001
From: John MacFarlane <fiddlosopher@gmail.com>
Date: Sat, 1 Oct 2011 22:21:39 -0700
Subject: [PATCH] LaTeX writer: don't escape # or ~ inside href{...}.

Closes #309.
---
 src/Text/Pandoc/Writers/LaTeX.hs | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/src/Text/Pandoc/Writers/LaTeX.hs b/src/Text/Pandoc/Writers/LaTeX.hs
index e307968f7..ed047333d 100644
--- a/src/Text/Pandoc/Writers/LaTeX.hs
+++ b/src/Text/Pandoc/Writers/LaTeX.hs
@@ -136,12 +136,16 @@ pandocToLaTeX options (Pandoc (Meta title authors date) blocks) = do
 
 -- escape things as needed for LaTeX
 
-stringToLaTeX :: String -> String
-stringToLaTeX = escapeStringUsing latexEscapes
-  where latexEscapes = backslashEscapes "{}$%&_#" ++ 
+stringToLaTeX :: Bool -> String -> String
+stringToLaTeX isUrl = escapeStringUsing latexEscapes
+  where latexEscapes = backslashEscapes "{}$%&_" ++
+                       if isUrl
+                          then []
+                          else [ ('~', "\\ensuremath{\\sim}")
+                               , ('#', "\\#")
+                               ] ++
                        [ ('^', "\\^{}")
                        , ('\\', "\\textbackslash{}")
-                       , ('~', "\\ensuremath{\\sim}")
                        , ('€', "\\euro{}")
                        , ('|', "\\textbar{}")
                        , ('<', "\\textless{}")
@@ -385,7 +389,7 @@ inlineToLaTeX (Code _ str) = do
       when (stInNote st) $ modify $ \s -> s{ stVerbInNote = True }
       let chr = ((enumFromTo '!' '~') \\ str) !! 0
       return $ text $ "\\lstinline" ++ [chr] ++ str ++ [chr]
-    else return $ text $ "\\texttt{" ++ stringToLaTeX str ++ "}"
+    else return $ text $ "\\texttt{" ++ stringToLaTeX False str ++ "}"
 inlineToLaTeX (Quoted SingleQuote lst) = do
   contents <- inlineListToLaTeX lst
   csquotes <- liftM stCsquotes get
@@ -416,7 +420,7 @@ inlineToLaTeX Apostrophe = return $ char '\''
 inlineToLaTeX EmDash = return "---"
 inlineToLaTeX EnDash = return "--"
 inlineToLaTeX Ellipses = return "\\ldots{}"
-inlineToLaTeX (Str str) = return $ text $ stringToLaTeX str
+inlineToLaTeX (Str str) = return $ text $ stringToLaTeX False str
 inlineToLaTeX (Math InlineMath str) = return $ char '$' <> text str <> char '$'
 inlineToLaTeX (Math DisplayMath str) = return $ "\\[" <> text str <> "\\]"
 inlineToLaTeX (RawInline "latex" str) = return $ text str
@@ -430,7 +434,7 @@ inlineToLaTeX (Link txt (src, _)) =
              do modify $ \s -> s{ stUrl = True }
                 return $ text $ "\\url{" ++ x ++ "}"
         _ -> do contents <- inlineListToLaTeX txt
-                return $ text ("\\href{" ++ stringToLaTeX src ++ "}{") <>
+                return $ text ("\\href{" ++ stringToLaTeX True src ++ "}{") <>
                          contents <> char '}'
 inlineToLaTeX (Image _ (source, _)) = do
   modify $ \s -> s{ stGraphics = True }