From 4778d034734e4848688c1fb5fa196b8bda8f08f2 Mon Sep 17 00:00:00 2001
From: John MacFarlane <jgm@berkeley.edu>
Date: Mon, 9 Sep 2019 21:33:16 -0700
Subject: [PATCH] LaTeX reader: Fix parsing of optional arguments that contain
 braced text.

Closes #5740.
---
 src/Text/Pandoc/Readers/LaTeX/Parsing.hs | 7 +++----
 test/command/5740.md                     | 9 +++++++++
 2 files changed, 12 insertions(+), 4 deletions(-)
 create mode 100644 test/command/5740.md

diff --git a/src/Text/Pandoc/Readers/LaTeX/Parsing.hs b/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
index 547b855e2..a0d604ea8 100644
--- a/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
+++ b/src/Text/Pandoc/Readers/LaTeX/Parsing.hs
@@ -93,8 +93,6 @@ import Text.Pandoc.Readers.LaTeX.Types (ExpansionPoint (..), Macro (..),
 import Text.Pandoc.Shared
 import Text.Parsec.Pos
 
--- import Debug.Trace (traceShowId)
-
 newtype DottedNum = DottedNum [Int]
   deriving (Show)
 
@@ -447,7 +445,7 @@ doMacros' n inp = do
                    args <- case optarg of
                              Nothing -> getargs M.empty argspecs
                              Just o  -> do
-                                x <- option o bracketedToks
+                                x <- option o $ bracketedToks
                                 getargs (M.singleton 1 x) $ drop 1 argspecs
                    rest <- getInput
                    return (args, rest)
@@ -644,7 +642,8 @@ bracketed parser = try $ do
 bracketedToks :: PandocMonad m => LP m [Tok]
 bracketedToks = do
   symbol '['
-  mconcat <$> manyTill (braced <|> (:[]) <$> anyTok) (symbol ']')
+  concat <$> manyTill ((snd <$> withRaw (try braced)) <|> count 1 anyTok)
+                      (symbol ']')
 
 parenWrapped :: PandocMonad m => Monoid a => LP m a -> LP m a
 parenWrapped parser = try $ do
diff --git a/test/command/5740.md b/test/command/5740.md
new file mode 100644
index 000000000..a9fb3ad97
--- /dev/null
+++ b/test/command/5740.md
@@ -0,0 +1,9 @@
+```
+% pandoc -t latex
+\newcommand\parenthesize[1][x]{(#1)}
+$\parenthesize$, $\parenthesize[y]$, $\parenthesize[\textsc{head}]$
+^D
+\newcommand\parenthesize[1][x]{(#1)}
+
+\((x)\), \((y)\), \((\textsc{head})\)
+```