From 7119715a6af7d04d17e40bb76e901c11bf27d3f3 Mon Sep 17 00:00:00 2001
From: John MacFarlane <jgm@berkeley.edu>
Date: Wed, 30 May 2018 12:48:07 -0700
Subject: [PATCH] LaTeX reader `rawLaTeXBlock`: handle macros that resolve to
 a...

...`\begin` or `\end`.
Fixes #4667.
---
 src/Text/Pandoc/Readers/LaTeX.hs | 18 +++++++++++++++++-
 test/command/4667.md             | 20 ++++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 test/command/4667.md

diff --git a/src/Text/Pandoc/Readers/LaTeX.hs b/src/Text/Pandoc/Readers/LaTeX.hs
index 2fdb3d43c..fff628c46 100644
--- a/src/Text/Pandoc/Readers/LaTeX.hs
+++ b/src/Text/Pandoc/Readers/LaTeX.hs
@@ -286,7 +286,23 @@ rawLaTeXBlock :: (PandocMonad m, HasMacros s, HasReaderOptions s)
 rawLaTeXBlock = do
   lookAhead (try (char '\\' >> letter))
   snd <$> (rawLaTeXParser False macroDef blocks
-      <|> rawLaTeXParser True(environment <|> macroDef <|> blockCommand) blocks)
+      <|> rawLaTeXParser True
+           (environment <|> macroDef <|> blockCommand)
+           (mconcat <$> (many (block <|> beginOrEndCommand))))
+
+-- See #4667 for motivation; sometimes people write macros
+-- that just evaluate to a begin or end command, which blockCommand
+-- won't accept.
+beginOrEndCommand :: PandocMonad m => LP m Blocks
+beginOrEndCommand = try $ do
+  Tok _ (CtrlSeq name) txt <- anyControlSeq
+  guard $ name == "begin" || name == "end"
+  (envname, rawargs) <- withRaw braced
+  if M.member (untokenize envname)
+      (inlineEnvironments :: M.Map Text (LP PandocPure Inlines))
+     then mzero
+     else return $ rawBlock "latex"
+                    (T.unpack (txt <> untokenize rawargs))
 
 rawLaTeXInline :: (PandocMonad m, HasMacros s, HasReaderOptions s)
                => ParserT String s m String
diff --git a/test/command/4667.md b/test/command/4667.md
new file mode 100644
index 000000000..1fff3708d
--- /dev/null
+++ b/test/command/4667.md
@@ -0,0 +1,20 @@
+```
+pandoc -t latex
+---
+header-includes:
+- \newcommand{\blandscape}{\begin{landscape}}
+- \newcommand{\elandscape}{\end{landscape}}
+...
+
+\blandscape
+
+testing
+
+\elandscape
+^D
+\begin{landscape}
+
+testing
+
+\end{landscape}
+```