From c51be5dfc85024e68a4bd62c9ced748b27f968c0 Mon Sep 17 00:00:00 2001
From: John MacFarlane <jgm@berkeley.edu>
Date: Mon, 29 Oct 2018 22:20:14 -0700
Subject: LaTeX reader:  allow space at end of math after `\`.

Closes #5010.

Expose trimMath from T.P.Shared.
---
 src/Text/Pandoc/Parsing.hs       |  2 +-
 src/Text/Pandoc/Readers/LaTeX.hs |  4 ++--
 src/Text/Pandoc/Shared.hs        | 10 ++++++++++
 3 files changed, 13 insertions(+), 3 deletions(-)

(limited to 'src/Text')

diff --git a/src/Text/Pandoc/Parsing.hs b/src/Text/Pandoc/Parsing.hs
index da8cc6433..f6a9f530f 100644
--- a/src/Text/Pandoc/Parsing.hs
+++ b/src/Text/Pandoc/Parsing.hs
@@ -627,7 +627,7 @@ mathInlineWith op cl = try $ do
                           return " "
                     ) (try $ string cl)
   notFollowedBy digit  -- to prevent capture of $5
-  return $ trim $ concat words'
+  return $ trimMath $ concat words'
  where
   inBalancedBraces :: Stream s m Char => Int -> String -> ParserT s st m String
   inBalancedBraces 0 "" = do
diff --git a/src/Text/Pandoc/Readers/LaTeX.hs b/src/Text/Pandoc/Readers/LaTeX.hs
index 010cb3add..1d35cd662 100644
--- a/src/Text/Pandoc/Readers/LaTeX.hs
+++ b/src/Text/Pandoc/Readers/LaTeX.hs
@@ -605,10 +605,10 @@ accent combiningAccent fallBack = try $ do
        []                -> return $ str [fromMaybe combiningAccent fallBack]
        _                 -> return ils
 mathDisplay :: String -> Inlines
-mathDisplay = displayMath . trim
+mathDisplay = displayMath . trimMath
 
 mathInline :: String -> Inlines
-mathInline = math . trim
+mathInline = math . trimMath
 
 dollarsMath :: PandocMonad m => LP m Inlines
 dollarsMath = do
diff --git a/src/Text/Pandoc/Shared.hs b/src/Text/Pandoc/Shared.hs
index 78a5a6a54..5b88a7948 100644
--- a/src/Text/Pandoc/Shared.hs
+++ b/src/Text/Pandoc/Shared.hs
@@ -49,6 +49,7 @@ module Text.Pandoc.Shared (
                      trim,
                      triml,
                      trimr,
+                     trimMath,
                      stripFirstAndLast,
                      camelCaseToHyphenated,
                      toRomanNumeral,
@@ -224,6 +225,15 @@ triml = dropWhile (`elem` " \r\n\t")
 trimr :: String -> String
 trimr = reverse . triml . reverse
 
+-- | Trim leading space and trailing space unless after \.
+trimMath :: String -> String
+trimMath = triml . reverse . stripspace . reverse
+  where
+  stripspace (c1:c2:cs)
+    | c1  `elem` [' ','\t','\n','\r']
+    , c2 /= '\\' = stripspace (c2:cs)
+  stripspace cs = cs
+
 -- | Strip leading and trailing characters from string
 stripFirstAndLast :: String -> String
 stripFirstAndLast str =
-- 
cgit v1.2.3