git.iko.soy/typeable/pandoc
on 548b444 help sign in
2 files changed+1957−1192
since splitsnapshots
unifiedsplit
src/Text/Pandoc/Parsing.hs+15−10 src/Text/Pandoc/Readers/LaTeX.hs+1942−1182
src/Text/Pandoc/Parsing.hs+15−10
@@ -130,6 +130,7 @@ module Text.Pandoc.Parsing ( anyLine,
130130 runParser,
131131 runParserT,
132132 parse,
133+ tokenPrim,
133134 anyToken,
134135 getInput,
135136 setInput,
@@ -178,7 +179,9 @@ module Text.Pandoc.Parsing ( anyLine,
178179 sourceLine,
179180 setSourceColumn,
180181 setSourceLine,
181− newPos
182+ newPos,
183+ Line,
184+ Column
182185 )
183186where
184187
@@ -1385,10 +1388,11 @@ extractIdClass (ident, cls, kvs) = (ident', cls', kvs')
13851388
13861389insertIncludedFile' :: (PandocMonad m, HasIncludeFiles st,
13871390 Functor mf, Applicative mf, Monad mf)
1388− => ParserT String st m (mf Blocks)
1391+ => ParserT [a] st m (mf Blocks)
1392+ -> (String -> [a])
13891393 -> [FilePath] -> FilePath
1390− -> ParserT String st m (mf Blocks)
1391−insertIncludedFile' blocks dirs f = do
1394+ -> ParserT [a] st m (mf Blocks)
1395+insertIncludedFile' blocks totoks dirs f = do
13921396 oldPos <- getPosition
13931397 oldInput <- getInput
13941398 containers <- getIncludeFiles <$> getState
@@ -1402,7 +1406,7 @@ insertIncludedFile' blocks dirs f = do
14021406 report $ CouldNotLoadIncludeFile f oldPos
14031407 return ""
14041408 setPosition $ newPos f 1 1
1405− setInput contents
1409+ setInput $ totoks contents
14061410 bs <- blocks
14071411 setInput oldInput
14081412 setPosition oldPos
@@ -1412,11 +1416,12 @@ insertIncludedFile' blocks dirs f = do
14121416-- | Parse content of include file as blocks. Circular includes result in an
14131417-- @PandocParseError@.
14141418insertIncludedFile :: (PandocMonad m, HasIncludeFiles st)
1415− => ParserT String st m Blocks
1419+ => ParserT [a] st m Blocks
1420+ -> (String -> [a])
14161421 -> [FilePath] -> FilePath
1417− -> ParserT String st m Blocks
1418−insertIncludedFile blocks dirs f =
1419− runIdentity <$> insertIncludedFile' (Identity <$> blocks) dirs f
1422+ -> ParserT [a] st m Blocks
1423+insertIncludedFile blocks totoks dirs f =
1424+ runIdentity <$> insertIncludedFile' (Identity <$> blocks) totoks dirs f
14201425
14211426-- | Parse content of include file as future blocks. Circular includes result in
14221427-- an @PandocParseError@.
@@ -1424,4 +1429,4 @@ insertIncludedFileF :: (PandocMonad m, HasIncludeFiles st)
14241429 => ParserT String st m (Future st Blocks)
14251430 -> [FilePath] -> FilePath
14261431 -> ParserT String st m (Future st Blocks)
1427−insertIncludedFileF = insertIncludedFile'
1432+insertIncludedFileF p = insertIncludedFile' p id
src/Text/Pandoc/Readers/LaTeX.hs+1942−1182
@@ -38,8 +38,9 @@ module Text.Pandoc.Readers.LaTeX ( readLaTeX,
3838import Control.Applicative (many, optional, (<|>))
3939import Control.Monad
4040import Control.Monad.Except (throwError)
41−import Data.Char (chr, isAlphaNum, isLetter, ord)
41+import Data.Char (chr, isAlphaNum, isLetter, ord, isDigit)
4242import Data.Text (Text, unpack)
43+import qualified Data.Text as T
4344import Data.List (intercalate, isPrefixOf)
4445import qualified Data.Map as M
4546import Data.Maybe (fromMaybe, maybeToList)
@@ -47,15 +48,21 @@ import Safe (minimumDef)
4748import System.FilePath (addExtension, replaceExtension, takeExtension)
4849import Text.Pandoc.Builder
4950import Text.Pandoc.Class (PandocMonad, PandocPure, lookupEnv, readFileFromDirs,
50− report, setResourcePath, getResourcePath)
51+ report, setResourcePath, getResourcePath,
52+ runIOorExplode, PandocIO)
5153import Text.Pandoc.Highlighting (fromListingsLanguage, languagesByExtension)
5254import Text.Pandoc.ImageSize (numUnit, showFl)
5355import Text.Pandoc.Logging
5456import Text.Pandoc.Options
55−import Text.Pandoc.Parsing hiding (many, mathDisplay, mathInline, optional,
56− space, (<|>))
57+import Text.Pandoc.Parsing hiding (many, optional, withRaw,
58+ mathInline, mathDisplay,
59+ space, (<|>), spaces, blankline)
5760import Text.Pandoc.Shared
5861import Text.Pandoc.Walk
62+import Text.Pandoc.Error (PandocError(PandocParsecError))
63+
64+import Text.Pandoc.Extensions (getDefaultExtensions)
65+import Debug.Trace (traceShowId)
5966
6067-- | Parse LaTeX from string and return 'Pandoc' document.
6168readLaTeX :: PandocMonad m
@@ -63,11 +70,11 @@ readLaTeX :: PandocMonad m
6370 -> Text -- ^ String to parse (assumes @'\n'@ line endings)
6471 -> m Pandoc
6572readLaTeX opts ltx = do
66− parsed <- readWithM parseLaTeX def{ stateOptions = opts }
67− (unpack (crFilter ltx))
73+ parsed <- runParserT parseLaTeX def{ stateOptions = opts } "source"
74+ (tokenize (crFilter ltx))
6875 case parsed of
6976 Right result -> return result
70− Left e -> throwError e
77+ Left e -> throwError $ PandocParsecError (T.unpack ltx) e
7178
7279parseLaTeX :: PandocMonad m => LP m Pandoc
7380parseLaTeX = do
@@ -88,177 +95,249 @@ parseLaTeX = do
8895 else id) doc'
8996 return $ Pandoc meta bs'
9097
91−type LP m = ParserT String ParserState m
92−
93−anyControlSeq :: PandocMonad m => LP m String
94−anyControlSeq = do
95− char '\\'
96− next <- option '\n' anyChar
97− case next of
98− '\n' -> return ""
99− c | isLetter c -> (c:) <$> (many letter <* optional sp)
100− | otherwise -> return [c]
101−
102−controlSeq :: PandocMonad m => String -> LP m String
103−controlSeq name = try $ do
104− char '\\'
105− case name of
106− "" -> mzero
107− [c] | not (isLetter c) -> string [c]
108− cs -> string cs <* notFollowedBy letter <* optional sp
109− return name
110−
111−dimenarg :: PandocMonad m => LP m String
112−dimenarg = try $ do
113− ch <- option "" $ string "="
114− num <- many1 digit
115− dim <- oneOfStrings ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
116− return $ ch ++ num ++ dim
98+testParser :: LP PandocIO a -> Text -> IO a
99+testParser p t = do
100+ res <- runIOorExplode (runParserT p defaultParserState{
101+ stateOptions = def{ readerExtensions =
102+ getDefaultExtensions "latex" }} "name" (tokenize t))
103+ case res of
104+ Left e -> error (show e)
105+ Right r -> return r
106+
107+type LP m = ParserT [Tok] ParserState m
108+
109+rawLaTeXBlock :: PandocMonad m => ParserT String ParserState m String
110+rawLaTeXBlock = mzero
111+
112+rawLaTeXInline :: PandocMonad m => ParserT String ParserState m Inline
113+rawLaTeXInline = mzero
114+
115+inlineCommand :: PandocMonad m => ParserT String ParserState m Inlines
116+inlineCommand = mzero
117+
118+data TokType = CtrlSeq | Spaces | Newline | Symbol | Word | Comment |
119+ Esc1 | Esc2
120+ deriving (Eq, Ord, Show)
121+
122+data Tok = Tok (Line, Column) TokType Text
123+ deriving (Eq, Ord, Show)
124+
125+tokenize :: Text -> [Tok]
126+tokenize = totoks (1, 1)
127+
128+totoks :: (Line, Column) -> Text -> [Tok]
129+totoks (lin,col) t =
130+ case T.uncons t of
131+ Nothing -> []
132+ Just (c, rest)
133+ | c == '\n' ->
134+ Tok (lin, col) Newline (T.singleton '\n')
135+ : totoks (lin + 1,1) rest
136+ | isSpaceOrTab c ->
137+ let (sps, rest') = T.span isSpaceOrTab t
138+ in Tok (lin, col) Spaces sps
139+ : totoks (lin, col + T.length sps) rest'
140+ | isAlphaNum c ->
141+ let (ws, rest') = T.span isAlphaNum t
142+ in Tok (lin, col) Word ws
143+ : totoks (lin, col + T.length ws) rest'
144+ | c == '%' ->
145+ let (cs, rest') = T.break (== '\n') rest
146+ in Tok (lin, col) Comment (T.singleton '%' <> cs)
147+ : totoks (lin, col + 1 + T.length cs) rest'
148+ | c == '\\' ->
149+ case T.uncons rest of
150+ Nothing -> [Tok (lin, col) Symbol (T.singleton c)]
151+ Just (d, rest')
152+ | isLetter d ->
153+ let (ws, rest'') = T.span isLetter rest
154+ in Tok (lin, col) CtrlSeq (T.singleton '\\' <> ws)
155+ : totoks (lin, col + 1 + T.length ws) rest''
156+ | d == '\t' || d == '\n' ->
157+ Tok (lin, col) Symbol (T.singleton '\\')
158+ : totoks (lin, col + 1) rest
159+ | otherwise ->
160+ Tok (lin, col) CtrlSeq (T.pack [c,d])
161+ : totoks (lin, col + 2) rest'
162+ | c == '^' ->
163+ case T.uncons rest of
164+ Just ('^', rest') ->
165+ case T.uncons rest' of
166+ Just (d, rest'')
167+ | isLowerHex d ->
168+ case T.uncons rest'' of
169+ Just (e, rest''') | isLowerHex e ->
170+ Tok (lin, col) Esc2 (T.pack ['^','^',d,e])
171+ : totoks (lin, col + 4) rest'''
172+ _ ->
173+ Tok (lin, col) Esc1 (T.pack ['^','^',d])
174+ : totoks (lin, col + 3) rest''
175+ | d < '\128' ->
176+ Tok (lin, col) Esc1 (T.pack ['^','^',d])
177+ : totoks (lin, col + 3) rest''
178+ _ -> [Tok (lin, col) Symbol (T.singleton '^'),
179+ Tok (lin, col + 1) Symbol (T.singleton '^')]
180+ _ -> Tok (lin, col) Symbol (T.singleton '^')
181+ : totoks (lin, col + 1) rest
182+ | otherwise ->
183+ Tok (lin, col) Symbol (T.singleton c) : totoks (lin, col + 1) rest
184+
185+ where isSpaceOrTab ' ' = True
186+ isSpaceOrTab '\t' = True
187+ isSpaceOrTab _ = False
188+
189+isLowerHex :: Char -> Bool
190+isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
191+
192+untokenize :: [Tok] -> Text
193+untokenize = mconcat . map untoken
194+
195+untoken :: Tok -> Text
196+untoken (Tok _ _ t) = t
197+
198+satisfyTok :: Monad m
199+ => (Tok -> Bool)
200+ -> ParserT [Tok] u m Tok
201+satisfyTok f = tokenPrim (T.unpack . untoken) updatePos matcher
202+ where matcher t | f t = Just t
203+ | otherwise = Nothing
204+ updatePos :: SourcePos -> Tok -> [Tok] -> SourcePos
205+ updatePos spos _ (Tok (lin,col) _ _ : _) =
206+ setSourceColumn (setSourceLine spos lin) col
207+ updatePos spos _ [] = spos
208+
209+anyControlSeq :: PandocMonad m => LP m Tok
210+anyControlSeq = satisfyTok isCtrlSeq <* optional sp
211+ where isCtrlSeq (Tok _ CtrlSeq _) = True
212+ isCtrlSeq _ = False
213+
214+anySymbol :: PandocMonad m => LP m Tok
215+anySymbol = satisfyTok isSym
216+ where isSym (Tok _ Symbol _) = True
217+ isSym _ = False
218+
219+spaces :: PandocMonad m => LP m ()
220+spaces = skipMany (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
221+
222+spaces1 :: PandocMonad m => LP m ()
223+spaces1 = skipMany1 (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
224+
225+tokTypeIn :: [TokType] -> Tok -> Bool
226+tokTypeIn toktypes (Tok _ tt _) = tt `elem` toktypes
227+
228+controlSeq :: PandocMonad m => Text -> LP m Tok
229+controlSeq name = satisfyTok isNamed
230+ where isNamed (Tok _ CtrlSeq n) = n == T.singleton '\\' <> name
231+ isNamed _ = False
232+
233+symbol :: PandocMonad m => Char -> LP m Tok
234+symbol c = satisfyTok isc
235+ where isc (Tok _ Symbol d) = case T.uncons d of
236+ Just (c',_) -> c == c'
237+ _ -> False
238+ isc _ = False
239+
240+symbolIn :: PandocMonad m => [Char] -> LP m Tok
241+symbolIn cs = satisfyTok isInCs
242+ where isInCs (Tok _ Symbol d) = case T.uncons d of
243+ Just (c,_) -> c `elem` cs
244+ _ -> False
245+ isInCs _ = False
117246
118247sp :: PandocMonad m => LP m ()
119248sp = whitespace <|> endline
120249
121250whitespace :: PandocMonad m => LP m ()
122−whitespace = skipMany1 $ satisfy (\c -> c == ' ' || c == '\t')
251+whitespace = () <$ satisfyTok isSpaceTok
252+ where isSpaceTok (Tok _ Spaces _) = True
253+ isSpaceTok _ = False
123254
124−endline :: PandocMonad m => LP m ()
125−endline = try (newline >> lookAhead anyChar >> notFollowedBy blankline)
255+newlineTok :: PandocMonad m => LP m ()
256+newlineTok = () <$ satisfyTok isNewlineTok
126257
127−isLowerHex :: Char -> Bool
128−isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
129−
130−tildeEscape :: PandocMonad m => LP m Char
131−tildeEscape = try $ do
132− string "^^"
133− c <- satisfy (\x -> x >= '\0' && x <= '\128')
134− d <- if isLowerHex c
135− then option "" $ count 1 (satisfy isLowerHex)
136− else return ""
137− if null d
138− then case ord c of
139− x | x >= 64 && x <= 127 -> return $ chr (x - 64)
140− | otherwise -> return $ chr (x + 64)
141− else return $ chr $ read ('0':'x':c:d)
258+isNewlineTok :: Tok -> Bool
259+isNewlineTok (Tok _ Newline _) = True
260+isNewlineTok _ = False
142261
143262comment :: PandocMonad m => LP m ()
144−comment = do
145− char '%'
146− skipMany (satisfy (/='\n'))
147− optional newline
148− return ()
263+comment = () <$ satisfyTok isCommentTok
264+ where isCommentTok (Tok _ Comment _) = True
265+ isCommentTok _ = False
266+
267+anyTok :: PandocMonad m => LP m Tok
268+anyTok = satisfyTok (const True)
269+
270+endline :: PandocMonad m => LP m ()
271+endline = try $ do
272+ newlineTok
273+ lookAhead anyTok
274+ notFollowedBy blankline
275+
276+blankline :: PandocMonad m => LP m ()
277+blankline = try $ do
278+ skipMany (satisfyTok (tokTypeIn [Spaces, Newline]))
279+ newlineTok
280+
281+primEscape :: PandocMonad m => LP m Char
282+primEscape = do
283+ Tok _ toktype t <- satisfyTok (tokTypeIn [Esc1, Esc2])
284+ case toktype of
285+ Esc1 -> case T.uncons t of
286+ Just (c, _)
287+ | c >= '\64' && c <= '\127' -> return (chr (ord c - 64))
288+ | otherwise -> return (chr (ord c + 64))
289+ Nothing -> fail "Empty content of Esc1"
290+ Esc2 -> case safeRead ('0':'x':T.unpack (T.drop 2 t)) of
291+ Just x -> return (chr x)
292+ Nothing -> fail $ "Could not read: " ++ T.unpack t
293+ _ -> fail "Expected an Esc1 or Esc2 token" -- should not happen
149294
150295bgroup :: PandocMonad m => LP m ()
151296bgroup = try $ do
152− skipMany (spaceChar <|> try (newline <* notFollowedBy blankline))
153− () <$ char '{'
154− <|> () <$ controlSeq "bgroup"
155− <|> () <$ controlSeq "begingroup"
297+ skipMany sp
298+ symbol '{' <|> controlSeq "bgroup" <|> controlSeq "begingroup"
299+ return ()
156300
157301egroup :: PandocMonad m => LP m ()
158−egroup = () <$ char '}'
159− <|> () <$ controlSeq "egroup"
160− <|> () <$ controlSeq "endgroup"
302+egroup = () <$ (symbol '}' <|> controlSeq "egroup" <|> controlSeq "endgroup")
161303
162−grouped :: PandocMonad m => Monoid a => LP m a -> LP m a
304+grouped :: (PandocMonad m, Monoid a) => LP m a -> LP m a
163305grouped parser = try $ do
164306 bgroup
165307 -- first we check for an inner 'grouped', because
166308 -- {{a,b}} should be parsed the same as {a,b}
167− try (grouped parser <* egroup)
168− <|> (mconcat <$> manyTill parser egroup)
169−
170−braced :: PandocMonad m => LP m String
171−braced = grouped chunk
172− where chunk =
173− many1 (satisfy (\c -> c /= '\\' && c /= '}' && c /= '{'))
174− <|> try (string "\\}")
175− <|> try (string "\\{")
176− <|> try (string "\\\\")
177− <|> ((\x -> "{" ++ x ++ "}") <$> braced)
178− <|> count 1 anyChar
309+ try (grouped parser <* egroup) <|> (mconcat <$> manyTill parser egroup)
310+
311+braced :: PandocMonad m => LP m [Tok]
312+braced = try $ do
313+ bgroup
314+ -- {{a,b}} should be parsed the same as {a,b}
315+ try (braced <* egroup) <|> manyTill anyTok egroup
179316
180317bracketed :: PandocMonad m => Monoid a => LP m a -> LP m a
181−bracketed parser = try $ char '[' *> (mconcat <$> manyTill parser (char ']'))
182−
183−mathDisplay :: PandocMonad m => LP m String -> LP m Inlines
184−mathDisplay p = displayMath <$> (try p >>= applyMacros' . trim)
185−
186−mathInline :: PandocMonad m => LP m String -> LP m Inlines
187−mathInline p = math <$> (try p >>= applyMacros')
188−
189−mathChars :: PandocMonad m => LP m String
190−mathChars =
191− concat <$> many (escapedChar
192− <|> (snd <$> withRaw braced)
193− <|> many1 (satisfy isOrdChar))
194− where escapedChar = try $ do char '\\'
195− c <- anyChar
196− return ['\\',c]
197− isOrdChar '$' = False
198− isOrdChar '{' = False
199− isOrdChar '}' = False
200− isOrdChar '\\' = False
201− isOrdChar _ = True
202−
203−quoted' :: PandocMonad m => (Inlines -> Inlines) -> LP m String -> LP m () -> LP m Inlines
204−quoted' f starter ender = do
205− startchs <- starter
206− smart <- extensionEnabled Ext_smart <$> getOption readerExtensions
207− if smart
208− then do
209− ils <- many (notFollowedBy ender >> inline)
210− (ender >> return (f (mconcat ils))) <|>
211− (<> mconcat ils) <$>
212− lit (case startchs of
213− "``" -> "“"
214− "`" -> "‘"
215− _ -> startchs)
216− else lit startchs
318+bracketed parser = try $ do
319+ symbol '['
320+ mconcat <$> manyTill parser (symbol ']')
217321
218−doubleQuote :: PandocMonad m => LP m Inlines
219−doubleQuote = do
220− quoted' doubleQuoted (try $ string "``") (void $ try $ string "''")
221− <|> quoted' doubleQuoted (string "“") (void $ char '”')
222− -- the following is used by babel for localized quotes:
223− <|> quoted' doubleQuoted (try $ string "\"`") (void $ try $ string "\"'")
224− <|> quoted' doubleQuoted (string "\"") (void $ char '"')
322+dimenarg :: PandocMonad m => LP m Text
323+dimenarg = try $ do
324+ ch <- option False $ True <$ symbol '='
325+ Tok _ _ s <- satisfyTok isWordTok
326+ guard $ (T.take 2 (T.reverse s)) `elem`
327+ ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
328+ let num = T.take (T.length s - 2) s
329+ guard $ T.length num > 0
330+ guard $ T.all isDigit num
331+ return $ T.pack ['=' | ch] <> s
225332
226−singleQuote :: PandocMonad m => LP m Inlines
227−singleQuote = do
228− smart <- extensionEnabled Ext_smart <$> getOption readerExtensions
229− if smart
230− then quoted' singleQuoted (string "`") (try $ char '\'' >> notFollowedBy letter)
231− <|> quoted' singleQuoted (string "‘") (try $ char '’' >> notFollowedBy letter)
232− else str <$> many1 (oneOf "`\'‘’")
333+-- inline elements:
233334
234−inline :: PandocMonad m => LP m Inlines
235−inline = (mempty <$ comment)
236− <|> (space <$ whitespace)
237− <|> (softbreak <$ endline)
238− <|> inlineText
239− <|> inlineCommand
240− <|> inlineEnvironment
241− <|> inlineGroup
242− <|> (char '-' *> option (str "-")
243− (char '-' *> option (str "–") (str "—" <$ char '-')))
244− <|> doubleQuote
245− <|> singleQuote
246− <|> (str "”" <$ try (string "''"))
247− <|> (str "”" <$ char '”')
248− <|> (str "’" <$ char '\'')
249− <|> (str "’" <$ char '’')
250− <|> (str "\160" <$ char '~')
251− <|> mathDisplay (string "$$" *> mathChars <* string "$$")
252− <|> mathInline (char '$' *> mathChars <* char '$')
253− <|> (guardEnabled Ext_literate_haskell *> char '|' *> doLHSverb)
254− <|> (str . (:[]) <$> tildeEscape)
255− <|> (do res <- oneOf "#&~^'`\"[]"
256− pos <- getPosition
257− report $ ParsingUnescaped [res] pos
258− return $ str [res])
335+inlineText :: PandocMonad m => LP m Inlines
336+inlineText = (str . T.unpack . untoken) <$> satisfyTok isWordTok
259337
260−inlines :: PandocMonad m => LP m Inlines
261−inlines = mconcat <$> many (notFollowedBy (char '}') *> inline)
338+isWordTok :: Tok -> Bool
339+isWordTok (Tok _ Word _) = True
340+isWordTok _ = False
262341
263342inlineGroup :: PandocMonad m => LP m Inlines
264343inlineGroup = do
@@ -269,460 +348,57 @@ inlineGroup = do
269348 -- we need the span so we can detitlecase bibtex entries;
270349 -- we need to know when something is {C}apitalized
271350
272−block :: PandocMonad m => LP m Blocks
273−block = (mempty <$ comment)
274− <|> (mempty <$ ((spaceChar <|> newline) *> spaces))
275− <|> environment
276− <|> include
277− <|> macro
278− <|> blockCommand
279− <|> paragraph
280− <|> grouped block
281−
282−blocks :: PandocMonad m => LP m Blocks
283−blocks = mconcat <$> many block
284−
285−getRawCommand :: PandocMonad m => String -> LP m String
286−getRawCommand name' = do
287− rawargs <- withRaw (many (try (optional sp *> opt)) *>
288− option "" (try (optional sp *> dimenarg)) *>
289− many braced)
290− return $ '\\' : name' ++ snd rawargs
291−
292−lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
293−lookupListDefault d = (fromMaybe d .) . lookupList
294− where
295− lookupList l m = msum $ map (`M.lookup` m) l
296−
297−blockCommand :: PandocMonad m => LP m Blocks
298−blockCommand = try $ do
299− name <- anyControlSeq
300− guard $ name /= "begin" && name /= "end"
301− star <- option "" (string "*" <* optional sp)
302− let name' = name ++ star
303− let raw = do
304− rawcommand <- getRawCommand name'
305− transformed <- applyMacros' rawcommand
306− guard $ transformed /= rawcommand
307− notFollowedBy $ parseFromString' inlines transformed
308− parseFromString' blocks transformed
309− lookupListDefault raw [name',name] blockCommands
310−
311−inBrackets :: Inlines -> Inlines
312−inBrackets x = str "[" <> x <> str "]"
313−
314−-- eat an optional argument and one or more arguments in braces
315−ignoreInlines :: PandocMonad m => String -> (String, LP m Inlines)
316−ignoreInlines name = (name, p)
317− where
318− p = do oa <- optargs
319− let rawCommand = '\\':name ++ oa
320− let doraw = guardRaw >> return (rawInline "latex" rawCommand)
321− doraw <|> ignore rawCommand
322−
323−guardRaw :: PandocMonad m => LP m ()
324−guardRaw = getOption readerExtensions >>= guard . extensionEnabled Ext_raw_tex
325−
326−optargs :: PandocMonad m => LP m String
327−optargs = snd <$> withRaw (skipopts *> skipMany (try $ optional sp *> braced))
328−
329−ignore :: (Monoid a, PandocMonad m) => String -> ParserT s u m a
330−ignore raw = do
331− pos <- getPosition
332− report $ SkippedContent raw pos
333− return mempty
334−
335−ignoreBlocks :: PandocMonad m => String -> (String, LP m Blocks)
336−ignoreBlocks name = (name, p)
337− where
338− p = do oa <- optargs
339− let rawCommand = '\\':name ++ oa
340− let doraw = guardRaw >> return (rawBlock "latex" rawCommand)
341− doraw <|> ignore rawCommand
342−
343−blockCommands :: PandocMonad m => M.Map String (LP m Blocks)
344−blockCommands = M.fromList $
345− [ ("par", mempty <$ skipopts)
346− , ("parbox", braced >> grouped blocks)
347− , ("title", mempty <$ (skipopts *>
348− (grouped inline >>= addMeta "title")
349− <|> (grouped block >>= addMeta "title")))
350− , ("subtitle", mempty <$ (skipopts *> tok >>= addMeta "subtitle"))
351− , ("author", mempty <$ (skipopts *> authors))
352− -- -- in letter class, temp. store address & sig as title, author
353− , ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
354− , ("signature", mempty <$ (skipopts *> authors))
355− , ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
356− -- Koma-script metadata commands
357− , ("dedication", mempty <$ (skipopts *> tok >>= addMeta "dedication"))
358− -- sectioning
359− , ("part", section nullAttr (-1))
360− , ("part*", section nullAttr (-1))
361− , ("chapter", section nullAttr 0)
362− , ("chapter*", section ("",["unnumbered"],[]) 0)
363− , ("section", section nullAttr 1)
364− , ("section*", section ("",["unnumbered"],[]) 1)
365− , ("subsection", section nullAttr 2)
366− , ("subsection*", section ("",["unnumbered"],[]) 2)
367− , ("subsubsection", section nullAttr 3)
368− , ("subsubsection*", section ("",["unnumbered"],[]) 3)
369− , ("paragraph", section nullAttr 4)
370− , ("paragraph*", section ("",["unnumbered"],[]) 4)
371− , ("subparagraph", section nullAttr 5)
372− , ("subparagraph*", section ("",["unnumbered"],[]) 5)
373− -- beamer slides
374− , ("frametitle", section nullAttr 3)
375− , ("framesubtitle", section nullAttr 4)
376− -- letters
377− , ("opening", (para . trimInlines) <$> (skipopts *> tok))
378− , ("closing", skipopts *> closing)
379− --
380− , ("hrule", pure horizontalRule)
381− , ("strut", pure mempty)
382− , ("rule", skipopts *> tok *> tok *> pure horizontalRule)
383− , ("item", skipopts *> looseItem)
384− , ("documentclass", skipopts *> braced *> preamble)
385− , ("centerline", (para . trimInlines) <$> (skipopts *> tok))
386− , ("caption", skipopts *> setCaption)
387− , ("bibliography", mempty <$ (skipopts *> braced >>=
388− addMeta "bibliography" . splitBibs))
389− , ("addbibresource", mempty <$ (skipopts *> braced >>=
390− addMeta "bibliography" . splitBibs))
391− -- includes
392− , ("lstinputlisting", inputListing)
393− , ("graphicspath", graphicsPath)
394− -- hyperlink
395− , ("hypertarget", braced >> grouped block)
396− ] ++ map ignoreBlocks
397− -- these commands will be ignored unless --parse-raw is specified,
398− -- in which case they will appear as raw latex blocks
399− [ "newcommand", "renewcommand", "newenvironment", "renewenvironment"
400− -- newcommand, etc. should be parsed by macro, but we need this
401− -- here so these aren't parsed as inline commands to ignore
402− , "special", "pdfannot", "pdfstringdef"
403− , "bibliographystyle"
404− , "maketitle", "makeindex", "makeglossary"
405− , "addcontentsline", "addtocontents", "addtocounter"
406− -- \ignore{} is used conventionally in literate haskell for definitions
407− -- that are to be processed by the compiler but not printed.
408− , "ignore"
409− , "hyperdef"
410− , "markboth", "markright", "markleft"
411− , "hspace", "vspace"
412− , "newpage"
413− , "clearpage"
414− , "pagebreak"
415− ]
416−
417−graphicsPath :: PandocMonad m => LP m Blocks
418−graphicsPath = do
419− ps <- bgroup *> (manyTill braced egroup)
420− getResourcePath >>= setResourcePath . (++ ps)
421− return mempty
422−
423−addMeta :: PandocMonad m => ToMetaValue a => String -> a -> LP m ()
424−addMeta field val = updateState $ \st ->
425− st{ stateMeta = addMetaField field val $ stateMeta st }
426−
427−splitBibs :: String -> [Inlines]
428−splitBibs = map (str . flip replaceExtension "bib" . trim) . splitBy (==',')
429−
430−setCaption :: PandocMonad m => LP m Blocks
431−setCaption = do
432− ils <- tok
433− mblabel <- option Nothing $
434− try $ spaces' >> controlSeq "label" >> (Just <$> tok)
435− let ils' = case mblabel of
436− Just lab -> ils <> spanWith
437− ("",[],[("data-label", stringify lab)]) mempty
438− Nothing -> ils
439− updateState $ \st -> st{ stateCaption = Just ils' }
440− return mempty
441−
442−resetCaption :: PandocMonad m => LP m ()
443−resetCaption = updateState $ \st -> st{ stateCaption = Nothing }
444−
445−authors :: PandocMonad m => LP m ()
446−authors = try $ do
447− bgroup
448− let oneAuthor = mconcat <$>
449− many1 (notFollowedBy' (controlSeq "and") >>
450− (inline <|> mempty <$ blockCommand))
451− -- skip e.g. \vspace{10pt}
452− auths <- sepBy oneAuthor (controlSeq "and")
453− egroup
454− addMeta "author" (map trimInlines auths)
455−
456−section :: PandocMonad m => Attr -> Int -> LP m Blocks
457−section (ident, classes, kvs) lvl = do
458− skipopts
459− contents <- grouped inline
460− lab <- option ident $ try (spaces' >> controlSeq "label" >> spaces' >> braced)
461− attr' <- registerHeader (lab, classes, kvs) contents
462− return $ headerWith attr' lvl contents
463−
464−inlineCommand :: PandocMonad m => LP m Inlines
465−inlineCommand = try $ do
466− (name, raw') <- withRaw anyControlSeq
467− guard $ name /= "begin" && name /= "end"
468− star <- option "" (string "*")
469− let name' = name ++ star
470− let raw = do
471− guard $ not (isBlockCommand name)
472− rawargs <- withRaw
473− (skipangles *> skipopts *> option "" dimenarg *> many braced)
474− let rawcommand = raw' ++ star ++ snd rawargs
475− transformed <- applyMacros' rawcommand
476− exts <- getOption readerExtensions
477− if transformed /= rawcommand
478− then parseFromString' inlines transformed
479− else if extensionEnabled Ext_raw_tex exts
480− then return $ rawInline "latex" rawcommand
481− else ignore rawcommand
482− (lookupListDefault raw [name',name] inlineCommands <*
483− optional (try (string "{}")))
484−
485−rawInlineOr :: PandocMonad m => String -> LP m Inlines -> LP m Inlines
486−rawInlineOr name' fallback = do
487− parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
488− if parseRaw
489− then rawInline "latex" <$> getRawCommand name'
490− else fallback
491−
492−isBlockCommand :: String -> Bool
493−isBlockCommand s = s `M.member` (blockCommands :: M.Map String (LP PandocPure Blocks))
494−
495−
496−inlineEnvironments :: PandocMonad m => M.Map String (LP m Inlines)
497−inlineEnvironments = M.fromList
498− [ ("displaymath", mathEnvWith id Nothing "displaymath")
499− , ("math", math <$> mathEnv "math")
500− , ("equation", mathEnvWith id Nothing "equation")
501− , ("equation*", mathEnvWith id Nothing "equation*")
502− , ("gather", mathEnvWith id (Just "gathered") "gather")
503− , ("gather*", mathEnvWith id (Just "gathered") "gather*")
504− , ("multline", mathEnvWith id (Just "gathered") "multline")
505− , ("multline*", mathEnvWith id (Just "gathered") "multline*")
506− , ("eqnarray", mathEnvWith id (Just "aligned") "eqnarray")
507− , ("eqnarray*", mathEnvWith id (Just "aligned") "eqnarray*")
508− , ("align", mathEnvWith id (Just "aligned") "align")
509− , ("align*", mathEnvWith id (Just "aligned") "align*")
510− , ("alignat", mathEnvWith id (Just "aligned") "alignat")
511− , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
512− ]
513−
514−inlineCommands :: PandocMonad m => M.Map String (LP m Inlines)
515−inlineCommands = M.fromList $
516− [ ("emph", extractSpaces emph <$> tok)
517− , ("textit", extractSpaces emph <$> tok)
518− , ("textsl", extractSpaces emph <$> tok)
519− , ("textsc", extractSpaces smallcaps <$> tok)
520− , ("textsf", extractSpaces (spanWith ("",["sans-serif"],[])) <$> tok)
521− , ("textmd", extractSpaces (spanWith ("",["medium"],[])) <$> tok)
522− , ("textrm", extractSpaces (spanWith ("",["roman"],[])) <$> tok)
523− , ("textup", extractSpaces (spanWith ("",["upright"],[])) <$> tok)
524− , ("texttt", ttfamily)
525− , ("sout", extractSpaces strikeout <$> tok)
526− , ("textsuperscript", extractSpaces superscript <$> tok)
527− , ("textsubscript", extractSpaces subscript <$> tok)
528− , ("textbackslash", lit "\\")
529− , ("backslash", lit "\\")
530− , ("slash", lit "/")
531− , ("textbf", extractSpaces strong <$> tok)
532− , ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
533− , ("ldots", lit "…")
534− , ("vdots", lit "\8942")
535− , ("dots", lit "…")
536− , ("mdots", lit "…")
537− , ("sim", lit "~")
538− , ("label", rawInlineOr "label" (inBrackets <$> tok))
539− , ("ref", rawInlineOr "ref" (inBrackets <$> tok))
540− , ("textgreek", tok)
541− , ("sep", lit ",")
542− , ("cref", rawInlineOr "cref" (inBrackets <$> tok)) -- from cleveref.sty
543− , ("(", mathInline $ manyTill anyChar (try $ string "\\)"))
544− , ("[", mathDisplay $ manyTill anyChar (try $ string "\\]"))
545− , ("ensuremath", mathInline braced)
546− , ("texorpdfstring", (\_ x -> x) <$> tok <*> tok)
547− , ("P", lit "¶")
548− , ("S", lit "§")
549− , ("$", lit "$")
550− , ("%", lit "%")
551− , ("&", lit "&")
552− , ("#", lit "#")
553− , ("_", lit "_")
554− , ("{", lit "{")
555− , ("}", lit "}")
556− -- old TeX commands
557− , ("em", extractSpaces emph <$> inlines)
558− , ("it", extractSpaces emph <$> inlines)
559− , ("sl", extractSpaces emph <$> inlines)
560− , ("bf", extractSpaces strong <$> inlines)
561− , ("rm", inlines)
562− , ("itshape", extractSpaces emph <$> inlines)
563− , ("slshape", extractSpaces emph <$> inlines)
564− , ("scshape", extractSpaces smallcaps <$> inlines)
565− , ("bfseries", extractSpaces strong <$> inlines)
566− , ("/", pure mempty) -- italic correction
567− , ("aa", lit "å")
568− , ("AA", lit "Å")
569− , ("ss", lit "ß")
570− , ("o", lit "ø")
571− , ("O", lit "Ø")
572− , ("L", lit "Ł")
573− , ("l", lit "ł")
574− , ("ae", lit "æ")
575− , ("AE", lit "Æ")
576− , ("oe", lit "œ")
577− , ("OE", lit "Œ")
578− , ("pounds", lit "£")
579− , ("euro", lit "€")
580− , ("copyright", lit "©")
581− , ("textasciicircum", lit "^")
582− , ("textasciitilde", lit "~")
583− , ("H", try $ tok >>= accent hungarumlaut)
584− , ("`", option (str "`") $ try $ tok >>= accent grave)
585− , ("'", option (str "'") $ try $ tok >>= accent acute)
586− , ("^", option (str "^") $ try $ tok >>= accent circ)
587− , ("~", option (str "~") $ try $ tok >>= accent tilde)
588− , ("\"", option (str "\"") $ try $ tok >>= accent umlaut)
589− , (".", option (str ".") $ try $ tok >>= accent dot)
590− , ("=", option (str "=") $ try $ tok >>= accent macron)
591− , ("c", option (str "c") $ try $ tok >>= accent cedilla)
592− , ("v", option (str "v") $ try $ tok >>= accent hacek)
593− , ("u", option (str "u") $ try $ tok >>= accent breve)
594− , ("i", lit "i")
595− , ("\\", linebreak <$ (optional (bracketed inline) *> spaces'))
596− , (",", lit "\8198")
597− , ("@", pure mempty)
598− , (" ", lit "\160")
599− , ("ps", pure $ str "PS." <> space)
600− , ("TeX", lit "TeX")
601− , ("LaTeX", lit "LaTeX")
602− , ("bar", lit "|")
603− , ("textless", lit "<")
604− , ("textgreater", lit ">")
605− , ("thanks", note <$> grouped block)
606− , ("footnote", note <$> grouped block)
607− , ("verb", doverb)
608− , ("lstinline", dolstinline)
609− , ("Verb", doverb)
610− , ("url", (unescapeURL <$> braced) >>= \url ->
611− pure (link url "" (str url)))
612− , ("href", (unescapeURL <$> braced <* optional sp) >>= \url ->
613− tok >>= \lab ->
614− pure (link url "" lab))
615− , ("includegraphics", do options <- option [] keyvals
616− src <- unescapeURL . removeDoubleQuotes <$> braced
617− mkImage options src)
618− , ("enquote", enquote)
619− , ("cite", citation "cite" NormalCitation False)
620− , ("Cite", citation "Cite" NormalCitation False)
621− , ("citep", citation "citep" NormalCitation False)
622− , ("citep*", citation "citep*" NormalCitation False)
623− , ("citeal", citation "citeal" NormalCitation False)
624− , ("citealp", citation "citealp" NormalCitation False)
625− , ("citealp*", citation "citealp*" NormalCitation False)
626− , ("autocite", citation "autocite" NormalCitation False)
627− , ("smartcite", citation "smartcite" NormalCitation False)
628− , ("footcite", inNote <$> citation "footcite" NormalCitation False)
629− , ("parencite", citation "parencite" NormalCitation False)
630− , ("supercite", citation "supercite" NormalCitation False)
631− , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
632− , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
633− , ("citeyear", citation "citeyear" SuppressAuthor False)
634− , ("autocite*", citation "autocite*" SuppressAuthor False)
635− , ("cite*", citation "cite*" SuppressAuthor False)
636− , ("parencite*", citation "parencite*" SuppressAuthor False)
637− , ("textcite", citation "textcite" AuthorInText False)
638− , ("citet", citation "citet" AuthorInText False)
639− , ("citet*", citation "citet*" AuthorInText False)
640− , ("citealt", citation "citealt" AuthorInText False)
641− , ("citealt*", citation "citealt*" AuthorInText False)
642− , ("textcites", citation "textcites" AuthorInText True)
643− , ("cites", citation "cites" NormalCitation True)
644− , ("autocites", citation "autocites" NormalCitation True)
645− , ("footcites", inNote <$> citation "footcites" NormalCitation True)
646− , ("parencites", citation "parencites" NormalCitation True)
647− , ("supercites", citation "supercites" NormalCitation True)
648− , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
649− , ("Autocite", citation "Autocite" NormalCitation False)
650− , ("Smartcite", citation "Smartcite" NormalCitation False)
651− , ("Footcite", citation "Footcite" NormalCitation False)
652− , ("Parencite", citation "Parencite" NormalCitation False)
653− , ("Supercite", citation "Supercite" NormalCitation False)
654− , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
655− , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
656− , ("Citeyear", citation "Citeyear" SuppressAuthor False)
657− , ("Autocite*", citation "Autocite*" SuppressAuthor False)
658− , ("Cite*", citation "Cite*" SuppressAuthor False)
659− , ("Parencite*", citation "Parencite*" SuppressAuthor False)
660− , ("Textcite", citation "Textcite" AuthorInText False)
661− , ("Textcites", citation "Textcites" AuthorInText True)
662− , ("Cites", citation "Cites" NormalCitation True)
663− , ("Autocites", citation "Autocites" NormalCitation True)
664− , ("Footcites", citation "Footcites" NormalCitation True)
665− , ("Parencites", citation "Parencites" NormalCitation True)
666− , ("Supercites", citation "Supercites" NormalCitation True)
667− , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
668− , ("citetext", complexNatbibCitation NormalCitation)
669− , ("citeauthor", (try (tok *> optional sp *> controlSeq "citetext") *>
670− complexNatbibCitation AuthorInText)
671− <|> citation "citeauthor" AuthorInText False)
672− , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
673− addMeta "nocite"))
674− , ("hypertarget", braced >> tok)
675− -- siuntix
676− , ("SI", dosiunitx)
677− -- hyphenat
678− , ("bshyp", lit "\\\173")
679− , ("fshyp", lit "/\173")
680− , ("dothyp", lit ".\173")
681− , ("colonhyp", lit ":\173")
682− , ("hyp", lit "-")
683− , ("nohyphens", tok)
684− , ("textnhtt", ttfamily)
685− , ("nhttfamily", ttfamily)
686− -- fontawesome
687− , ("faCheck", lit "\10003")
688− , ("faClose", lit "\10007")
689− ] ++ map ignoreInlines
690− -- these commands will be ignored unless --parse-raw is specified,
691− -- in which case they will appear as raw latex blocks:
692− [ "index"
693− , "hspace"
694− , "vspace"
695− , "newpage"
696− , "clearpage"
697− , "pagebreak"
698− ]
351+doLHSverb :: PandocMonad m => LP m Inlines
352+doLHSverb =
353+ (codeWith ("",["haskell"],[]) . T.unpack . untokenize)
354+ <$> manyTill (satisfyTok (not . isNewlineTok)) (symbol '|')
699355
700−ttfamily :: PandocMonad m => LP m Inlines
701−ttfamily = (code . stringify . toList) <$> tok
356+lit :: String -> LP m Inlines
357+lit = pure . str
702358
703−mkImage :: PandocMonad m => [(String, String)] -> String -> LP m Inlines
704−mkImage options src = do
705− let replaceTextwidth (k,v) = case numUnit v of
706− Just (num, "\\textwidth") -> (k, showFl (num * 100) ++ "%")
707− _ -> (k, v)
708− let kvs = map replaceTextwidth $ filter (\(k,_) -> k `elem` ["width", "height"]) options
709− let attr = ("",[], kvs)
710− let alt = str "image"
711− case takeExtension src of
712− "" -> do
713− defaultExt <- getOption readerDefaultImageExtension
714− return $ imageWith attr (addExtension src defaultExt) "" alt
715− _ -> return $ imageWith attr src "" alt
716−
717−inNote :: Inlines -> Inlines
718−inNote ils =
719− note $ para $ ils <> str "."
359+doubleQuote :: PandocMonad m => LP m Inlines
360+doubleQuote = do
361+ quoted' doubleQuoted (try $ count 2 $ symbol '`')
362+ (void $ try $ count 2 $ symbol '\'')
363+ <|> quoted' doubleQuoted ((:[]) <$> symbol '“') (void $ symbol '”')
364+ -- the following is used by babel for localized quotes:
365+ <|> quoted' doubleQuoted (try $ sequence [symbol '"', symbol '`'])
366+ (void $ try $ sequence [symbol '"', symbol '\''])
367+ <|> quoted' doubleQuoted ((:[]) <$> symbol '"')
368+ (void $ symbol '"')
720369
721−unescapeURL :: String -> String
722−unescapeURL ('\\':x:xs) | isEscapable x = x:unescapeURL xs
723− where isEscapable c = c `elem` ("#$%&~_^\\{}" :: String)
724−unescapeURL (x:xs) = x:unescapeURL xs
725−unescapeURL [] = ""
370+singleQuote :: PandocMonad m => LP m Inlines
371+singleQuote = do
372+ quoted' singleQuoted ((:[]) <$> symbol '`')
373+ (try $ symbol '\'' >>
374+ notFollowedBy (satisfyTok startsWithLetter))
375+ <|> quoted' singleQuoted ((:[]) <$> symbol '‘')
376+ (try $ symbol '’' >>
377+ notFollowedBy (satisfyTok startsWithLetter))
378+ where startsWithLetter (Tok _ Word t) =
379+ case T.uncons t of
380+ Just (c, _) | isLetter c -> True
381+ _ -> False
382+ startsWithLetter _ = False
383+
384+quoted' :: PandocMonad m
385+ => (Inlines -> Inlines)
386+ -> LP m [Tok]
387+ -> LP m ()
388+ -> LP m Inlines
389+quoted' f starter ender = do
390+ startchs <- (T.unpack . untokenize) <$> starter
391+ smart <- extensionEnabled Ext_smart <$> getOption readerExtensions
392+ if smart
393+ then do
394+ ils <- many (notFollowedBy ender >> inline)
395+ (ender >> return (f (mconcat ils))) <|>
396+ (<> mconcat ils) <$>
397+ lit (case startchs of
398+ "``" -> "“"
399+ "`" -> "‘"
400+ cs -> cs)
401+ else lit startchs
726402
727403enquote :: PandocMonad m => LP m Inlines
728404enquote = do
@@ -734,36 +410,51 @@ enquote = do
734410
735411doverb :: PandocMonad m => LP m Inlines
736412doverb = do
737− marker <- anyChar
738− code <$> manyTill (satisfy (/='\n')) (char marker)
413+ Tok _ Symbol t <- anySymbol
414+ marker <- case T.uncons t of
415+ Just (c, ts) | T.null ts -> return c
416+ _ -> mzero
417+ (code . T.unpack . untokenize) <$> manyTill (verbTok marker) (symbol marker)
418+
419+verbTok :: PandocMonad m => Char -> LP m Tok
420+verbTok stopchar = do
421+ t@(Tok (lin, col) toktype txt) <- satisfyTok (not . isNewlineTok)
422+ case T.findIndex (== stopchar) txt of
423+ Nothing -> return t
424+ Just i -> do
425+ let (t1, t2) = T.splitAt i txt
426+ inp <- getInput
427+ setInput $ Tok (lin, col + i) Symbol (T.singleton stopchar)
428+ : (totoks (lin, col + i + 1) (T.drop 1 t2)) ++ inp
429+ return $ Tok (lin, col) toktype t1
739430
740431dolstinline :: PandocMonad m => LP m Inlines
741432dolstinline = do
742433 options <- option [] keyvals
743434 let classes = maybeToList $ lookup "language" options >>= fromListingsLanguage
744− marker <- char '{' <|> anyChar
745− codeWith ("",classes,[]) <$> manyTill (satisfy (/='\n')) (char '}' <|> char marker)
435+ Tok _ Symbol t <- anySymbol
436+ marker <- case T.uncons t of
437+ Just (c, ts) | T.null ts -> return c
438+ _ -> mzero
439+ let stopchar = if marker == '{' then '}' else marker
440+ (codeWith ("",classes,[]) . T.unpack . untokenize) <$>
441+ manyTill (verbTok stopchar) (symbol stopchar)
746442
747−doLHSverb :: PandocMonad m => LP m Inlines
748−doLHSverb = codeWith ("",["haskell"],[]) <$> manyTill (satisfy (/='\n')) (char '|')
749−
750−-- converts e.g. \SI{1}[\$]{} to "$ 1" or \SI{1}{\euro} to "1 €"
751−dosiunitx :: PandocMonad m => LP m Inlines
752−dosiunitx = do
753− skipopts
754− value <- tok
755− valueprefix <- option "" $ char '[' >> (mconcat <$> manyTill tok (char ']'))
756− unit <- tok
757− let emptyOr160 "" = ""
758− emptyOr160 _ = "\160"
759− return . mconcat $ [valueprefix,
760− emptyOr160 valueprefix,
761− value,
762− emptyOr160 unit,
763− unit]
443+keyval :: PandocMonad m => LP m (String, String)
444+keyval = try $ do
445+ Tok _ Word key <- satisfyTok isWordTok
446+ let isSpecSym (Tok _ Symbol t) = t `elem` [".",":","-","|","\\"]
447+ isSpecSym _ = False
448+ val <- option [] $ do
449+ symbol '='
450+ braced <|> (many1 (satisfyTok isWordTok <|> satisfyTok isSpecSym))
451+ optional sp
452+ optional (symbol ',')
453+ optional sp
454+ return (T.unpack key, T.unpack . untokenize $ val)
764455
765−lit :: String -> LP m Inlines
766−lit = pure . str
456+keyvals :: PandocMonad m => LP m [(String, String)]
457+keyvals = try $ symbol '[' >> manyTill keyval (symbol ']')
767458
768459accent :: (Char -> String) -> Inlines -> LP m Inlines
769460accent f ils =
@@ -971,374 +662,393 @@ breve 'U' = "Ŭ"
971662breve 'u' = "ŭ"
972663breve c = [c]
973664
665+mathDisplay :: [Tok] -> Inlines
666+mathDisplay = displayMath . trim . T.unpack . untokenize
667+-- TODO we shouldn't need applyMacros
668+-- mathDisplay p = displayMath <$> (try p >>= applyMacros' . trim)
669+
670+mathInline :: [Tok] -> Inlines
671+mathInline = math . trim . T.unpack . untokenize
672+-- TODO we shouldn't need applyMacros
673+-- mathInline p = math <$> (try p >>= applyMacros')
674+
675+dollarsMath :: PandocMonad m => LP m Inlines
676+dollarsMath = do
677+ symbol '$'
678+ display <- option False (True <$ symbol '$')
679+ contents <- many1Till anyTok (symbol '$')
680+ when display (() <$ symbol '$')
681+ let constructor = if display then mathDisplay else mathInline
682+ return $ constructor contents
683+
684+inlineCommand' :: PandocMonad m => LP m Inlines
685+inlineCommand' = try $ do
686+ cs@(Tok _ CtrlSeq t) <- anyControlSeq
687+ let name = T.drop 1 t
688+ guard $ name /= "begin" && name /= "end"
689+ mbstar <- option Nothing (Just <$> symbol '*')
690+ let names = name : maybe [] (const [name <> "*"]) mbstar
691+ optional $ try $ symbol '{' >> symbol '}'
692+ let raw = do
693+ guard $ not (isBlockCommand name)
694+ (_, rawargs) <- withRaw
695+ (skipangles *> skipopts *> option "" dimenarg *> many braced)
696+ let rawcommand = T.unpack $ untokenize $
697+ cs : maybe [] (:[]) mbstar ++ rawargs
698+ (guardEnabled Ext_raw_tex >> return (rawInline "latex" rawcommand))
699+ <|> ignore rawcommand
700+ -- transformed <- applyMacros' rawcommand -- TODO or get rid of
701+ -- exts <- getOption readerExtensions
702+ -- if transformed /= rawcommand
703+ -- then parseFromString' inlines transformed
704+ -- else if extensionEnabled Ext_raw_tex exts
705+ -- then return $ rawInline "latex" rawcommand
706+ -- else ignore rawcommand
707+ lookupListDefault raw names inlineCommands
708+
974709tok :: PandocMonad m => LP m Inlines
975−tok = try $ grouped inline <|> inlineCommand <|> str <$> count 1 inlineChar
710+tok = try $ grouped inline <|> inlineCommand' <|> singleChar
711+ where singleChar = do
712+ Tok (lin,col) toktype t <- satisfyTok (tokTypeIn [Word, Symbol])
713+ if T.length t > 1
714+ then do
715+ let (t1, t2) = (T.take 1 t, T.drop 1 t)
716+ inp <- getInput
717+ setInput $ (Tok (lin, col + 1) toktype t2) : inp
718+ return $ str (T.unpack t1)
719+ else return $ str (T.unpack t)
976720
977721opt :: PandocMonad m => LP m Inlines
978722opt = bracketed inline
979723
980−rawopt :: PandocMonad m => LP m String
724+rawopt :: PandocMonad m => LP m Text
981725rawopt = do
982− contents <- bracketed (many1 (noneOf "[]") <|> try (string "\\]") <|>
983− try (string "\\[") <|> rawopt)
726+ symbol '['
727+ inner <- untokenize <$> manyTill anyTok (symbol ']')
984728 optional sp
985− return $ "[" ++ contents ++ "]"
729+ return $ "[" <> inner <> "]"
986730
987731skipopts :: PandocMonad m => LP m ()
988732skipopts = skipMany rawopt
989733
734+-- eat an optional argument and one or more arguments in braces
735+ignoreInlines :: PandocMonad m => Text -> (Text, LP m Inlines)
736+ignoreInlines name = (name, p)
737+ where p = do oa <- optargs
738+ let rawCommand = '\\' : T.unpack (name <> oa)
739+ let doraw = guardRaw >> return (rawInline "latex" rawCommand)
740+ doraw <|> ignore rawCommand
741+
742+guardRaw :: PandocMonad m => LP m ()
743+guardRaw = getOption readerExtensions >>= guard . extensionEnabled Ext_raw_tex
744+
745+optargs :: PandocMonad m => LP m Text
746+optargs = do
747+ (_, raw) <- withRaw (skipopts *> skipMany (try $ optional sp *> braced))
748+ return $ untokenize raw
749+
990750-- opts in angle brackets are used in beamer
991751rawangle :: PandocMonad m => LP m ()
992752rawangle = try $ do
993− char '<'
994− skipMany (noneOf ">")
995− char '>'
996− return ()
753+ symbol '<'
754+ () <$ manyTill anyTok (symbol '>')
997755
998756skipangles :: PandocMonad m => LP m ()
999757skipangles = skipMany rawangle
1000758
1001−inlineText :: PandocMonad m => LP m Inlines
1002−inlineText = str <$> many1 inlineChar
759+ignore :: (Monoid a, PandocMonad m) => String -> ParserT s u m a
760+ignore raw = do
761+ pos <- getPosition
762+ report $ SkippedContent raw pos
763+ return mempty
1003764
1004−inlineChar :: PandocMonad m => LP m Char
1005−inlineChar = noneOf "\\$%&~#{}^'`\"‘’“”-[] \t\n"
765+withRaw :: PandocMonad m => LP m a -> LP m (a, [Tok])
766+withRaw parser = do
767+ inp <- getInput
768+ result <- parser
769+ nxt <- option (Tok (0,0) Word "") (lookAhead anyTok)
770+ let raw = takeWhile (/= nxt) inp
771+ return (result, raw)
1006772
1007−environment :: PandocMonad m => LP m Blocks
1008−environment = do
1009− controlSeq "begin"
1010− name <- braced
1011− M.findWithDefault mzero name environments
1012− <|> rawEnv name
773+inBrackets :: Inlines -> Inlines
774+inBrackets x = str "[" <> x <> str "]"
775+
776+unescapeURL :: String -> String
777+unescapeURL ('\\':x:xs) | isEscapable x = x:unescapeURL xs
778+ where isEscapable c = c `elem` ("#$%&~_^\\{}" :: String)
779+unescapeURL (x:xs) = x:unescapeURL xs
780+unescapeURL [] = ""
1013781
1014782inlineEnvironment :: PandocMonad m => LP m Inlines
1015783inlineEnvironment = try $ do
1016784 controlSeq "begin"
1017− name <- braced
785+ name <- untokenize <$> braced
1018786 M.findWithDefault mzero name inlineEnvironments
1019787
1020−rawEnv :: PandocMonad m => String -> LP m Blocks
1021−rawEnv name = do
1022− exts <- getOption readerExtensions
1023− let parseRaw = extensionEnabled Ext_raw_tex exts
1024− rawOptions <- mconcat <$> many rawopt
1025− let beginCommand = "\\begin{" ++ name ++ "}" ++ rawOptions
1026− pos1 <- getPosition
1027− (bs, raw) <- withRaw $ env name blocks
1028− raw' <- applyMacros' $ beginCommand ++ raw
1029− if raw' /= beginCommand ++ raw
1030− then parseFromString' blocks raw'
1031− else if parseRaw
1032− then return $ rawBlock "latex" $ beginCommand ++ raw'
1033− else do
1034− unless parseRaw $ do
1035− report $ SkippedContent beginCommand pos1
1036− pos2 <- getPosition
1037− report $ SkippedContent ("\\end{" ++ name ++ "}") pos2
1038− return bs
1039−
1040−rawVerbEnv :: PandocMonad m => String -> LP m Blocks
1041−rawVerbEnv name = do
1042− pos <- getPosition
1043− (_, raw) <- withRaw $ verbEnv name
1044− let raw' = "\\begin{tikzpicture}" ++ raw
1045− exts <- getOption readerExtensions
1046− let parseRaw = extensionEnabled Ext_raw_tex exts
1047− if parseRaw
1048− then return $ rawBlock "latex" raw'
1049− else do
1050− report $ SkippedContent raw' pos
1051− return mempty
788+inlineEnvironments :: PandocMonad m => M.Map Text (LP m Inlines)
789+inlineEnvironments = M.fromList [
790+-- ("displaymath", mathEnvWith id Nothing "displaymath")
791+-- , ("math", math <$> mathEnv "math")
792+-- , ("equation", mathEnvWith id Nothing "equation")
793+-- , ("equation*", mathEnvWith id Nothing "equation*")
794+-- , ("gather", mathEnvWith id (Just "gathered") "gather")
795+-- , ("gather*", mathEnvWith id (Just "gathered") "gather*")
796+-- , ("multline", mathEnvWith id (Just "gathered") "multline")
797+-- , ("multline*", mathEnvWith id (Just "gathered") "multline*")
798+-- , ("eqnarray", mathEnvWith id (Just "aligned") "eqnarray")
799+-- , ("eqnarray*", mathEnvWith id (Just "aligned") "eqnarray*")
800+-- , ("align", mathEnvWith id (Just "aligned") "align")
801+-- , ("align*", mathEnvWith id (Just "aligned") "align*")
802+-- , ("alignat", mathEnvWith id (Just "aligned") "alignat")
803+-- , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
804+ ]
1052805
1053−----
806+inlineCommands :: PandocMonad m => M.Map Text (LP m Inlines)
807+inlineCommands = M.fromList $
808+ [ ("emph", extractSpaces emph <$> tok)
809+ , ("textit", extractSpaces emph <$> tok)
810+ , ("textsl", extractSpaces emph <$> tok)
811+ , ("textsc", extractSpaces smallcaps <$> tok)
812+ , ("textsf", extractSpaces (spanWith ("",["sans-serif"],[])) <$> tok)
813+ , ("textmd", extractSpaces (spanWith ("",["medium"],[])) <$> tok)
814+ , ("textrm", extractSpaces (spanWith ("",["roman"],[])) <$> tok)
815+ , ("textup", extractSpaces (spanWith ("",["upright"],[])) <$> tok)
816+ , ("texttt", ttfamily)
817+ , ("sout", extractSpaces strikeout <$> tok)
818+ , ("textsuperscript", extractSpaces superscript <$> tok)
819+ , ("textsubscript", extractSpaces subscript <$> tok)
820+ , ("textbackslash", lit "\\")
821+ , ("backslash", lit "\\")
822+ , ("slash", lit "/")
823+ , ("textbf", extractSpaces strong <$> tok)
824+ , ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
825+ , ("ldots", lit "…")
826+ , ("vdots", lit "\8942")
827+ , ("dots", lit "…")
828+ , ("mdots", lit "…")
829+ , ("sim", lit "~")
830+ , ("label", rawInlineOr "label" (inBrackets <$> tok))
831+ , ("ref", rawInlineOr "ref" (inBrackets <$> tok))
832+ , ("textgreek", tok)
833+ , ("sep", lit ",")
834+ , ("cref", rawInlineOr "cref" (inBrackets <$> tok)) -- from cleveref.sty
835+ , ("(", mathInline <$> manyTill anyTok (controlSeq ")"))
836+ , ("[", mathDisplay <$> manyTill anyTok (controlSeq "]"))
837+ , ("ensuremath", mathInline <$> braced)
838+ , ("texorpdfstring", (\_ x -> x) <$> tok <*> tok)
839+ , ("P", lit "¶")
840+ , ("S", lit "§")
841+ , ("$", lit "$")
842+ , ("%", lit "%")
843+ , ("&", lit "&")
844+ , ("#", lit "#")
845+ , ("_", lit "_")
846+ , ("{", lit "{")
847+ , ("}", lit "}")
848+ -- old TeX commands
849+ , ("em", extractSpaces emph <$> inlines)
850+ , ("it", extractSpaces emph <$> inlines)
851+ , ("sl", extractSpaces emph <$> inlines)
852+ , ("bf", extractSpaces strong <$> inlines)
853+ , ("rm", inlines)
854+ , ("itshape", extractSpaces emph <$> inlines)
855+ , ("slshape", extractSpaces emph <$> inlines)
856+ , ("scshape", extractSpaces smallcaps <$> inlines)
857+ , ("bfseries", extractSpaces strong <$> inlines)
858+ , ("/", pure mempty) -- italic correction
859+ , ("aa", lit "å")
860+ , ("AA", lit "Å")
861+ , ("ss", lit "ß")
862+ , ("o", lit "ø")
863+ , ("O", lit "Ø")
864+ , ("L", lit "Ł")
865+ , ("l", lit "ł")
866+ , ("ae", lit "æ")
867+ , ("AE", lit "Æ")
868+ , ("oe", lit "œ")
869+ , ("OE", lit "Œ")
870+ , ("pounds", lit "£")
871+ , ("euro", lit "€")
872+ , ("copyright", lit "©")
873+ , ("textasciicircum", lit "^")
874+ , ("textasciitilde", lit "~")
875+ , ("H", try $ tok >>= accent hungarumlaut)
876+ , ("`", option (str "`") $ try $ tok >>= accent grave)
877+ , ("'", option (str "'") $ try $ tok >>= accent acute)
878+ , ("^", option (str "^") $ try $ tok >>= accent circ)
879+ , ("~", option (str "~") $ try $ tok >>= accent tilde)
880+ , ("\"", option (str "\"") $ try $ tok >>= accent umlaut)
881+ , (".", option (str ".") $ try $ tok >>= accent dot)
882+ , ("=", option (str "=") $ try $ tok >>= accent macron)
883+ , ("c", option (str "c") $ try $ tok >>= accent cedilla)
884+ , ("v", option (str "v") $ try $ tok >>= accent hacek)
885+ , ("u", option (str "u") $ try $ tok >>= accent breve)
886+ , ("i", lit "i")
887+ , ("\\", linebreak <$ (optional (bracketed inline) *> spaces))
888+ , (",", lit "\8198")
889+ , ("@", pure mempty)
890+ , (" ", lit "\160")
891+ , ("ps", pure $ str "PS." <> space)
892+ , ("TeX", lit "TeX")
893+ , ("LaTeX", lit "LaTeX")
894+ , ("bar", lit "|")
895+ , ("textless", lit "<")
896+ , ("textgreater", lit ">")
897+ , ("thanks", note <$> grouped block)
898+ , ("footnote", note <$> grouped block)
899+ , ("verb", doverb)
900+ , ("lstinline", dolstinline)
901+ , ("Verb", doverb)
902+ , ("url", ((unescapeURL . T.unpack . untokenize) <$> braced) >>= \url ->
903+ pure (link url "" (str url)))
904+-- , ("href", (unescapeURL <$> braced <* optional sp) >>= \url ->
905+-- tok >>= \lab ->
906+-- pure (link url "" lab))
907+-- , ("includegraphics", do options <- option [] keyvals
908+-- src <- unescapeURL . removeDoubleQuotes <$> braced
909+-- mkImage options src)
910+ , ("enquote", enquote)
911+-- , ("cite", citation "cite" NormalCitation False)
912+-- , ("Cite", citation "Cite" NormalCitation False)
913+-- , ("citep", citation "citep" NormalCitation False)
914+-- , ("citep*", citation "citep*" NormalCitation False)
915+-- , ("citeal", citation "citeal" NormalCitation False)
916+-- , ("citealp", citation "citealp" NormalCitation False)
917+-- , ("citealp*", citation "citealp*" NormalCitation False)
918+-- , ("autocite", citation "autocite" NormalCitation False)
919+-- , ("smartcite", citation "smartcite" NormalCitation False)
920+-- , ("footcite", inNote <$> citation "footcite" NormalCitation False)
921+-- , ("parencite", citation "parencite" NormalCitation False)
922+-- , ("supercite", citation "supercite" NormalCitation False)
923+-- , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
924+-- , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
925+-- , ("citeyear", citation "citeyear" SuppressAuthor False)
926+-- , ("autocite*", citation "autocite*" SuppressAuthor False)
927+-- , ("cite*", citation "cite*" SuppressAuthor False)
928+-- , ("parencite*", citation "parencite*" SuppressAuthor False)
929+-- , ("textcite", citation "textcite" AuthorInText False)
930+-- , ("citet", citation "citet" AuthorInText False)
931+-- , ("citet*", citation "citet*" AuthorInText False)
932+-- , ("citealt", citation "citealt" AuthorInText False)
933+-- , ("citealt*", citation "citealt*" AuthorInText False)
934+-- , ("textcites", citation "textcites" AuthorInText True)
935+-- , ("cites", citation "cites" NormalCitation True)
936+-- , ("autocites", citation "autocites" NormalCitation True)
937+-- , ("footcites", inNote <$> citation "footcites" NormalCitation True)
938+-- , ("parencites", citation "parencites" NormalCitation True)
939+-- , ("supercites", citation "supercites" NormalCitation True)
940+-- , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
941+-- , ("Autocite", citation "Autocite" NormalCitation False)
942+-- , ("Smartcite", citation "Smartcite" NormalCitation False)
943+-- , ("Footcite", citation "Footcite" NormalCitation False)
944+-- , ("Parencite", citation "Parencite" NormalCitation False)
945+-- , ("Supercite", citation "Supercite" NormalCitation False)
946+-- , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
947+-- , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
948+-- , ("Citeyear", citation "Citeyear" SuppressAuthor False)
949+-- , ("Autocite*", citation "Autocite*" SuppressAuthor False)
950+-- , ("Cite*", citation "Cite*" SuppressAuthor False)
951+-- , ("Parencite*", citation "Parencite*" SuppressAuthor False)
952+-- , ("Textcite", citation "Textcite" AuthorInText False)
953+-- , ("Textcites", citation "Textcites" AuthorInText True)
954+-- , ("Cites", citation "Cites" NormalCitation True)
955+-- , ("Autocites", citation "Autocites" NormalCitation True)
956+-- , ("Footcites", citation "Footcites" NormalCitation True)
957+-- , ("Parencites", citation "Parencites" NormalCitation True)
958+-- , ("Supercites", citation "Supercites" NormalCitation True)
959+-- , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
960+-- , ("citetext", complexNatbibCitation NormalCitation)
961+-- , ("citeauthor", (try (tok *> optional sp *> controlSeq "citetext") *>
962+-- complexNatbibCitation AuthorInText)
963+-- <|> citation "citeauthor" AuthorInText False)
964+-- , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
965+-- addMeta "nocite"))
966+ , ("hypertarget", braced >> tok)
967+-- -- siuntix
968+-- , ("SI", dosiunitx)
969+ -- hyphenat
970+ , ("bshyp", lit "\\\173")
971+ , ("fshyp", lit "/\173")
972+ , ("dothyp", lit ".\173")
973+ , ("colonhyp", lit ":\173")
974+ , ("hyp", lit "-")
975+ , ("nohyphens", tok)
976+ , ("textnhtt", ttfamily)
977+ , ("nhttfamily", ttfamily)
978+ -- fontawesome
979+ , ("faCheck", lit "\10003")
980+ , ("faClose", lit "\10007")
981+ ] ++ map ignoreInlines
982+ -- these commands will be ignored unless --parse-raw is specified,
983+ -- in which case they will appear as raw latex blocks:
984+ [ "index"
985+ , "hspace"
986+ , "vspace"
987+ , "newpage"
988+ , "clearpage"
989+ , "pagebreak"
990+ ]
1054991
1055−maybeAddExtension :: String -> FilePath -> FilePath
1056−maybeAddExtension ext fp =
1057− if null (takeExtension fp)
1058− then addExtension fp ext
1059− else fp
992+ttfamily :: PandocMonad m => LP m Inlines
993+ttfamily = (code . stringify . toList) <$> tok
1060994
1061−include :: PandocMonad m => LP m Blocks
1062−include = do
1063− fs' <- try $ do
1064− char '\\'
1065− name <- try (string "include")
1066− <|> try (string "input")
1067− <|> try (string "subfile")
1068− <|> string "usepackage"
1069− -- skip options
1070− skipMany $ try $ char '[' *> manyTill anyChar (char ']')
1071− fs <- (map trim . splitBy (==',')) <$> braced
1072− return $ if name == "usepackage"
1073− then map (maybeAddExtension ".sty") fs
1074− else map (maybeAddExtension ".tex") fs
1075− dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
1076− mconcat <$> mapM (insertIncludedFile blocks dirs) fs'
995+rawInlineOr :: PandocMonad m => String -> LP m Inlines -> LP m Inlines
996+rawInlineOr name' fallback = do
997+ parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
998+ if parseRaw
999+ then rawInline "latex" <$> getRawCommand name'
1000+ else fallback
10771001
1078−inputListing :: PandocMonad m => LP m Blocks
1079−inputListing = do
1080− pos <- getPosition
1081− options <- option [] keyvals
1082− f <- filter (/='"') <$> braced
1083− dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
1084− mbCode <- readFileFromDirs dirs f
1085− codeLines <- case mbCode of
1086− Just s -> return $ lines s
1087− Nothing -> do
1088− report $ CouldNotLoadIncludeFile f pos
1089− return []
1090− let (ident,classes,kvs) = parseListingsOptions options
1091− let language = case lookup "language" options >>= fromListingsLanguage of
1092− Just l -> [l]
1093− Nothing -> take 1 $ languagesByExtension (takeExtension f)
1094− let firstline = fromMaybe 1 $ lookup "firstline" options >>= safeRead
1095− let lastline = fromMaybe (length codeLines) $
1096− lookup "lastline" options >>= safeRead
1097− let codeContents = intercalate "\n" $ take (1 + lastline - firstline) $
1098− drop (firstline - 1) codeLines
1099− return $ codeBlockWith (ident,ordNub (classes ++ language),kvs) codeContents
1100−
1101−parseListingsOptions :: [(String, String)] -> Attr
1102−parseListingsOptions options =
1103− let kvs = [ (if k == "firstnumber"
1104− then "startFrom"
1105− else k, v) | (k,v) <- options ]
1106− classes = [ "numberLines" |
1107− lookup "numbers" options == Just "left" ]
1108− ++ maybeToList (lookup "language" options
1109− >>= fromListingsLanguage)
1110− in (fromMaybe "" (lookup "label" options), classes, kvs)
1111−
1112−----
1002+getRawCommand :: PandocMonad m => String -> LP m String
1003+getRawCommand name' = do
1004+ (_, rawargs) <- withRaw
1005+ (many (try (optional sp *> opt)) *>
1006+ option "" (try (optional sp *> dimenarg)) *>
1007+ many braced)
1008+ return $ '\\' : name' ++ T.unpack (untokenize rawargs)
11131009
1114−keyval :: PandocMonad m => LP m (String, String)
1115−keyval = try $ do
1116− key <- many1 alphaNum
1117− val <- option "" $ char '=' >> braced <|> (many1 (alphaNum <|> oneOf ".:-|\\"))
1118− skipMany spaceChar
1119− optional (char ',')
1120− skipMany spaceChar
1121− return (key, val)
1010+isBlockCommand :: Text -> Bool
1011+isBlockCommand s =
1012+ s `M.member` (blockCommands :: M.Map Text (LP PandocPure Blocks))
11221013
1014+lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
1015+lookupListDefault d = (fromMaybe d .) . lookupList
1016+ where
1017+ lookupList l m = msum $ map (`M.lookup` m) l
11231018
1124−keyvals :: PandocMonad m => LP m [(String, String)]
1125−keyvals = try $ char '[' *> manyTill keyval (char ']')
1126−
1127−alltt :: PandocMonad m => String -> LP m Blocks
1128−alltt t = walk strToCode <$> parseFromString' blocks
1129− (substitute " " "\\ " $ substitute "%" "\\%" $
1130− intercalate "\\\\\n" $ lines t)
1131− where strToCode (Str s) = Code nullAttr s
1132− strToCode x = x
1133−
1134−rawLaTeXBlock :: PandocMonad m => LP m String
1135−rawLaTeXBlock = snd <$> try (withRaw (environment <|> blockCommand))
1136−
1137−rawLaTeXInline :: PandocMonad m => LP m Inline
1138−rawLaTeXInline = do
1139− raw <- (snd <$> withRaw inlineCommand)
1140− <|> (snd <$> withRaw inlineEnvironment)
1141− <|> (snd <$> withRaw blockCommand)
1142− RawInline "latex" <$> applyMacros' raw
1143−
1144−addImageCaption :: PandocMonad m => Blocks -> LP m Blocks
1145−addImageCaption = walkM go
1146− where go (Image attr alt (src,tit))
1147− | not ("fig:" `isPrefixOf` tit) = do
1148− mbcapt <- stateCaption <$> getState
1149− return $ case mbcapt of
1150− Just ils -> Image attr (toList ils) (src, "fig:" ++ tit)
1151− Nothing -> Image attr alt (src,tit)
1152− go x = return x
1153−
1154−addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
1155−addTableCaption = walkM go
1156− where go (Table c als ws hs rs) = do
1157− mbcapt <- stateCaption <$> getState
1158− return $ case mbcapt of
1159− Just ils -> Table (toList ils) als ws hs rs
1160− Nothing -> Table c als ws hs rs
1161− go x = return x
1162−
1163−environments :: PandocMonad m => M.Map String (LP m Blocks)
1164−environments = M.fromList
1165− [ ("document", env "document" blocks <* skipMany anyChar)
1166− , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
1167− , ("letter", env "letter" letterContents)
1168− , ("minipage", env "minipage" $
1169− skipopts *> spaces' *> optional braced *> spaces' *> blocks)
1170− , ("figure", env "figure" $ skipopts *> figure)
1171− , ("subfigure", env "subfigure" $ skipopts *> tok *> figure)
1172− , ("center", env "center" blocks)
1173− , ("longtable", env "longtable" $
1174− resetCaption *> simpTable "longtable" False >>= addTableCaption)
1175− , ("table", env "table" $
1176− resetCaption *> skipopts *> blocks >>= addTableCaption)
1177− , ("tabular*", env "tabular" $ simpTable "tabular*" True)
1178− , ("tabularx", env "tabularx" $ simpTable "tabularx" True)
1179− , ("tabular", env "tabular" $ simpTable "tabular" False)
1180− , ("quote", blockQuote <$> env "quote" blocks)
1181− , ("quotation", blockQuote <$> env "quotation" blocks)
1182− , ("verse", blockQuote <$> env "verse" blocks)
1183− , ("itemize", bulletList <$> listenv "itemize" (many item))
1184− , ("description", definitionList <$> listenv "description" (many descItem))
1185− , ("enumerate", orderedList')
1186− , ("alltt", alltt =<< verbEnv "alltt")
1187− , ("code", guardEnabled Ext_literate_haskell *>
1188− (codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
1189− verbEnv "code"))
1190− , ("comment", mempty <$ verbEnv "comment")
1191− , ("verbatim", codeBlock <$> verbEnv "verbatim")
1192− , ("Verbatim", fancyverbEnv "Verbatim")
1193− , ("BVerbatim", fancyverbEnv "BVerbatim")
1194− , ("lstlisting", do attr <- parseListingsOptions <$> option [] keyvals
1195− codeBlockWith attr <$> verbEnv "lstlisting")
1196− , ("minted", do options <- option [] keyvals
1197− lang <- grouped (many1 $ satisfy (/='}'))
1198− let kvs = [ (if k == "firstnumber"
1199− then "startFrom"
1200− else k, v) | (k,v) <- options ]
1201− let classes = [ lang | not (null lang) ] ++
1202− [ "numberLines" |
1203− lookup "linenos" options == Just "true" ]
1204− let attr = ("",classes,kvs)
1205− codeBlockWith attr <$> verbEnv "minted")
1206− , ("obeylines", parseFromString
1207− (para . trimInlines . mconcat <$> many inline) =<<
1208− intercalate "\\\\\n" . lines <$> verbEnv "obeylines")
1209− , ("displaymath", mathEnvWith para Nothing "displaymath")
1210− , ("equation", mathEnvWith para Nothing "equation")
1211− , ("equation*", mathEnvWith para Nothing "equation*")
1212− , ("gather", mathEnvWith para (Just "gathered") "gather")
1213− , ("gather*", mathEnvWith para (Just "gathered") "gather*")
1214− , ("multline", mathEnvWith para (Just "gathered") "multline")
1215− , ("multline*", mathEnvWith para (Just "gathered") "multline*")
1216− , ("eqnarray", mathEnvWith para (Just "aligned") "eqnarray")
1217− , ("eqnarray*", mathEnvWith para (Just "aligned") "eqnarray*")
1218− , ("align", mathEnvWith para (Just "aligned") "align")
1219− , ("align*", mathEnvWith para (Just "aligned") "align*")
1220− , ("alignat", mathEnvWith para (Just "aligned") "alignat")
1221− , ("alignat*", mathEnvWith para (Just "aligned") "alignat*")
1222− , ("tikzpicture", rawVerbEnv "tikzpicture")
1223− ]
1019+inline :: PandocMonad m => LP m Inlines
1020+inline = (mempty <$ comment)
1021+ <|> (space <$ whitespace)
1022+ <|> (softbreak <$ endline)
1023+ <|> inlineText
1024+ <|> inlineCommand'
1025+ <|> inlineEnvironment
1026+ <|> inlineGroup
1027+ <|> (symbol '-' *>
1028+ option (str "-") (symbol '-' *>
1029+ option (str "–") (str "—" <$ symbol '-')))
1030+ <|> doubleQuote
1031+ <|> singleQuote
1032+ <|> (str "”" <$ try (symbol '\'' >> symbol '\''))
1033+ <|> (str "”" <$ symbol '”')
1034+ <|> (str "’" <$ symbol '\'')
1035+ <|> (str "’" <$ symbol '’')
1036+ <|> (str "\160" <$ symbol '~')
1037+ <|> dollarsMath
1038+ <|> (guardEnabled Ext_literate_haskell *> symbol '|' *> doLHSverb)
1039+ <|> (str . (:[]) <$> primEscape)
1040+ <|> (do res <- symbolIn "#&~^'`\"[]"
1041+ pos <- getPosition
1042+ let s = T.unpack (untoken res)
1043+ report $ ParsingUnescaped s pos
1044+ return $ str s)
12241045
1225−figure :: PandocMonad m => LP m Blocks
1226−figure = try $ do
1227− resetCaption
1228− blocks >>= addImageCaption
1046+inlines :: PandocMonad m => LP m Inlines
1047+inlines = mconcat <$> many inline
12291048
1230−letterContents :: PandocMonad m => LP m Blocks
1231−letterContents = do
1232− bs <- blocks
1233− st <- getState
1234− -- add signature (author) and address (title)
1235− let addr = case lookupMeta "address" (stateMeta st) of
1236− Just (MetaBlocks [Plain xs]) ->
1237− para $ trimInlines $ fromList xs
1238− _ -> mempty
1239− return $ addr <> bs -- sig added by \closing
1240−
1241−closing :: PandocMonad m => LP m Blocks
1242−closing = do
1243− contents <- tok
1244− st <- getState
1245− let extractInlines (MetaBlocks [Plain ys]) = ys
1246− extractInlines (MetaBlocks [Para ys ]) = ys
1247− extractInlines _ = []
1248− let sigs = case lookupMeta "author" (stateMeta st) of
1249− Just (MetaList xs) ->
1250− para $ trimInlines $ fromList $
1251− intercalate [LineBreak] $ map extractInlines xs
1252− _ -> mempty
1253− return $ para (trimInlines contents) <> sigs
1254−
1255−item :: PandocMonad m => LP m Blocks
1256−item = blocks *> controlSeq "item" *> skipopts *> blocks
1257−
1258−looseItem :: PandocMonad m => LP m Blocks
1259−looseItem = do
1260− ctx <- stateParserContext `fmap` getState
1261− if ctx == ListItemState
1262− then mzero
1263− else return mempty
1264−
1265−descItem :: PandocMonad m => LP m (Inlines, [Blocks])
1266−descItem = do
1267− blocks -- skip blocks before item
1268− controlSeq "item"
1269− optional sp
1270− ils <- opt
1271− bs <- blocks
1272− return (ils, [bs])
1273−
1274−env :: PandocMonad m => String -> LP m a -> LP m a
1275−env name p = p <*
1276− (try (controlSeq "end" *> braced >>= guard . (== name))
1277− <?> ("\\end{" ++ name ++ "}"))
1278−
1279−listenv :: PandocMonad m => String -> LP m a -> LP m a
1280−listenv name p = try $ do
1281− oldCtx <- stateParserContext `fmap` getState
1282− updateState $ \st -> st{ stateParserContext = ListItemState }
1283− res <- env name p
1284− updateState $ \st -> st{ stateParserContext = oldCtx }
1285− return res
1286−
1287−mathEnvWith :: PandocMonad m
1288− => (Inlines -> a) -> Maybe String -> String -> LP m a
1289−mathEnvWith f innerEnv name = f <$> mathDisplay (inner <$> mathEnv name)
1290− where inner x = case innerEnv of
1291− Nothing -> x
1292− Just y -> "\\begin{" ++ y ++ "}\n" ++ x ++
1293− "\\end{" ++ y ++ "}"
1294−
1295−mathEnv :: PandocMonad m => String -> LP m String
1296−mathEnv name = do
1297− skipopts
1298− optional blankline
1299− let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
1300− charMuncher = skipMany comment *>
1301− (many1 (noneOf "\\%") <|> try (string "\\%")
1302− <|> try (string "\\\\") <|> count 1 anyChar)
1303− res <- concat <$> manyTill charMuncher endEnv
1304− return $ stripTrailingNewlines res
1305−
1306−verbEnv :: PandocMonad m => String -> LP m String
1307−verbEnv name = do
1308− skipopts
1309− optional blankline
1310− let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
1311− charMuncher = anyChar
1312− res <- manyTill charMuncher endEnv
1313− return $ stripTrailingNewlines res
1314−
1315−fancyverbEnv :: PandocMonad m => String -> LP m Blocks
1316−fancyverbEnv name = do
1317− options <- option [] keyvals
1318− let kvs = [ (if k == "firstnumber"
1319− then "startFrom"
1320− else k, v) | (k,v) <- options ]
1321− let classes = [ "numberLines" |
1322− lookup "numbers" options == Just "left" ]
1323− let attr = ("",classes,kvs)
1324− codeBlockWith attr <$> verbEnv name
1325−
1326−orderedList' :: PandocMonad m => LP m Blocks
1327−orderedList' = try $ do
1328− optional sp
1329− (_, style, delim) <- option (1, DefaultStyle, DefaultDelim) $
1330− try $ char '[' *> anyOrderedListMarker <* char ']'
1331− spaces
1332− optional $ try $ controlSeq "setlength" *> grouped (controlSeq "itemindent") *> braced
1333− spaces
1334− start <- option 1 $ try $ do controlSeq "setcounter"
1335− grouped (string "enum" *> many1 (oneOf "iv"))
1336− optional sp
1337− num <- grouped (many1 digit)
1338− spaces
1339− return (read num + 1 :: Int)
1340− bs <- listenv "enumerate" (many item)
1341− return $ orderedListWith (start, style, delim) bs
1049+-- PREVIOUSLY HAD (notFollowedBy (char '}') *> inline)
1050+
1051+-- block elements:
13421052
13431053paragraph :: PandocMonad m => LP m Blocks
13441054paragraph = do
@@ -1347,226 +1057,1276 @@ paragraph = do
13471057 then return mempty
13481058 else return $ para x
13491059
1350−preamble :: PandocMonad m => LP m Blocks
1351−preamble = mempty <$> manyTill preambleBlock beginDoc
1352− where beginDoc = lookAhead $ try $ controlSeq "begin" *> string "{document}"
1353− preambleBlock = void comment
1354− <|> void sp
1355− <|> void blanklines
1356− <|> void include
1357− <|> void macro
1358− <|> void blockCommand
1359− <|> void anyControlSeq
1360− <|> void braced
1361− <|> void anyChar
1362−
1363−-------
1364−
1365−-- citations
1366−
1367−addPrefix :: [Inline] -> [Citation] -> [Citation]
1368−addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
1369−addPrefix _ _ = []
1370−
1371−addSuffix :: [Inline] -> [Citation] -> [Citation]
1372−addSuffix s ks@(_:_) =
1373− let k = last ks
1374− in init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
1375−addSuffix _ _ = []
1376−
1377−simpleCiteArgs :: PandocMonad m => LP m [Citation]
1378−simpleCiteArgs = try $ do
1379− first <- optionMaybe $ toList <$> opt
1380− second <- optionMaybe $ toList <$> opt
1381− keys <- try $ bgroup *> (manyTill citationLabel egroup)
1382− let (pre, suf) = case (first , second ) of
1383− (Just s , Nothing) -> (mempty, s )
1384− (Just s , Just t ) -> (s , t )
1385− _ -> (mempty, mempty)
1386− conv k = Citation { citationId = k
1387− , citationPrefix = []
1388− , citationSuffix = []
1389− , citationMode = NormalCitation
1390− , citationHash = 0
1391− , citationNoteNum = 0
1392− }
1393− return $ addPrefix pre $ addSuffix suf $ map conv keys
1394−
1395−citationLabel :: PandocMonad m => LP m String
1396−citationLabel = optional sp *>
1397− (many1 (satisfy isBibtexKeyChar)
1398− <* optional sp
1399− <* optional (char ',')
1400− <* optional sp)
1401− where isBibtexKeyChar c = isAlphaNum c || c `elem` (".:;?!`'()/*@_+=-[]" :: String)
1402−
1403−cites :: PandocMonad m => CitationMode -> Bool -> LP m [Citation]
1404−cites mode multi = try $ do
1405− cits <- if multi
1406− then many1 simpleCiteArgs
1407− else count 1 simpleCiteArgs
1408− let cs = concat cits
1409− return $ case mode of
1410− AuthorInText -> case cs of
1411− (c:rest) -> c {citationMode = mode} : rest
1412− [] -> []
1413− _ -> map (\a -> a {citationMode = mode}) cs
1414−
1415−citation :: PandocMonad m => String -> CitationMode -> Bool -> LP m Inlines
1416−citation name mode multi = do
1417− (c,raw) <- withRaw $ cites mode multi
1418− return $ cite c (rawInline "latex" $ "\\" ++ name ++ raw)
1419−
1420−complexNatbibCitation :: PandocMonad m => CitationMode -> LP m Inlines
1421−complexNatbibCitation mode = try $ do
1422− let ils = (toList . trimInlines . mconcat) <$>
1423− many (notFollowedBy (oneOf "\\};") >> inline)
1424− let parseOne = try $ do
1425− skipSpaces
1426− pref <- ils
1427− cit' <- inline -- expect a citation
1428− let citlist = toList cit'
1429− cits' <- case citlist of
1430− [Cite cs _] -> return cs
1431− _ -> mzero
1432− suff <- ils
1433− skipSpaces
1434− optional $ char ';'
1435− return $ addPrefix pref $ addSuffix suff cits'
1436− (c:cits, raw) <- withRaw $ grouped parseOne
1437− return $ cite (c{ citationMode = mode }:cits)
1438− (rawInline "latex" $ "\\citetext" ++ raw)
1439−
1440−-- tables
1441−
1442−parseAligns :: PandocMonad m => LP m [(Alignment, Double, (String, String))]
1443−parseAligns = try $ do
1444− bgroup
1445− let maybeBar = skipMany $ sp <|> () <$ char '|' <|> () <$ (char '@' >> braced)
1446− maybeBar
1447− let cAlign = AlignCenter <$ char 'c'
1448− let lAlign = AlignLeft <$ char 'l'
1449− let rAlign = AlignRight <$ char 'r'
1450− let parAlign = AlignLeft <$ char 'p'
1451− -- algins from tabularx
1452− let xAlign = AlignLeft <$ char 'X'
1453− let mAlign = AlignLeft <$ char 'm'
1454− let bAlign = AlignLeft <$ char 'b'
1455− let alignChar = cAlign <|> lAlign <|> rAlign <|> parAlign
1456− <|> xAlign <|> mAlign <|> bAlign
1457− let alignPrefix = char '>' >> braced
1458− let alignSuffix = char '<' >> braced
1459− let colWidth = try $ do
1460− char '{'
1461− ds <- many1 (oneOf "0123456789.")
1462− spaces
1463− string "\\linewidth"
1464− char '}'
1465− case safeRead ds of
1466− Just w -> return w
1467− Nothing -> return 0.0
1468− let alignSpec = do
1469− spaces
1470− pref <- option "" alignPrefix
1471− spaces
1472− al <- alignChar
1473− width <- colWidth <|> option 0.0 (do s <- braced
1474− pos <- getPosition
1475− report $ SkippedContent s pos
1476− return 0.0)
1477− spaces
1478− suff <- option "" alignSuffix
1479− return (al, width, (pref, suff))
1480− aligns' <- sepEndBy alignSpec maybeBar
1481− spaces
1482− egroup
1483− spaces
1484− return $ aligns'
1485−
1486−hline :: PandocMonad m => LP m ()
1487−hline = try $ do
1488− spaces'
1489− controlSeq "hline" <|>
1490− -- booktabs rules:
1491− controlSeq "toprule" <|>
1492− controlSeq "bottomrule" <|>
1493− controlSeq "midrule" <|>
1494− controlSeq "endhead" <|>
1495− controlSeq "endfirsthead"
1496− spaces'
1497− optional $ bracketed (many1 (satisfy (/=']')))
1498− return ()
1060+include :: PandocMonad m => LP m Blocks
1061+include = do
1062+ (Tok _ _ name) <- controlSeq "include" <|> controlSeq "input" <|>
1063+ controlSeq "subfile" <|> controlSeq "usepackage"
1064+ skipMany $ bracketed inline -- skip options
1065+ fs <- (map trim . splitBy (==',') . T.unpack . untokenize) <$> braced
1066+ let fs' = if name == "\\usepackage"
1067+ then map (maybeAddExtension ".sty") fs
1068+ else map (maybeAddExtension ".tex") fs
1069+ dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
1070+ mconcat <$> mapM (insertIncludedFile blocks (tokenize . T.pack) dirs) fs'
14991071
1500−lbreak :: PandocMonad m => LP m ()
1501−lbreak = () <$ try (spaces' *>
1502− (controlSeq "\\" <|> controlSeq "tabularnewline") <*
1503− spaces')
1504−
1505−amp :: PandocMonad m => LP m ()
1506−amp = () <$ try (spaces' *> char '&' <* spaces')
1507−
1508−parseTableRow :: PandocMonad m
1509− => String -- ^ table environment name
1510− -> [(String, String)] -- ^ pref/suffixes
1511− -> LP m [Blocks]
1512−parseTableRow envname prefsufs = try $ do
1513− let cols = length prefsufs
1514− let tableCellRaw = concat <$> many
1515− (do notFollowedBy amp
1516− notFollowedBy lbreak
1517− notFollowedBy $ () <$ try (string ("\\end{" ++ envname ++ "}"))
1518− many1 (noneOf "&%\n\r\\")
1519− <|> try (string "\\&")
1520− <|> count 1 anyChar)
1521− let plainify bs = case toList bs of
1522− [Para ils] -> plain (fromList ils)
1523− _ -> bs
1524− rawcells <- sepBy1 tableCellRaw amp
1525− guard $ length rawcells == cols
1526− let rawcells' = zipWith (\c (p, s) -> p ++ trim c ++ s) rawcells prefsufs
1527− let tableCell = plainify <$> blocks
1528− cells' <- mapM (parseFromString' tableCell) rawcells'
1529− let numcells = length cells'
1530− guard $ numcells <= cols && numcells >= 1
1531− guard $ cells' /= [mempty]
1532− -- note: a & b in a three-column table leaves an empty 3rd cell:
1533− let cells'' = cells' ++ replicate (cols - numcells) mempty
1534− spaces'
1535− return cells''
1536−
1537−spaces' :: PandocMonad m => LP m ()
1538−spaces' = spaces *> skipMany (comment *> spaces)
1539−
1540−simpTable :: PandocMonad m => String -> Bool -> LP m Blocks
1541−simpTable envname hasWidthParameter = try $ do
1542− when hasWidthParameter $ () <$ (spaces' >> tok)
1543− skipopts
1544− colspecs <- parseAligns
1545− let (aligns, widths, prefsufs) = unzip3 colspecs
1546− let cols = length colspecs
1547− optional $ controlSeq "caption" *> skipopts *> setCaption
1548− optional lbreak
1549− spaces'
1550− skipMany hline
1551− spaces'
1552− header' <- option [] $ try (parseTableRow envname prefsufs <*
1553− lbreak <* many1 hline)
1554− spaces'
1555− rows <- sepEndBy (parseTableRow envname prefsufs)
1556− (lbreak <* optional (skipMany hline))
1557− spaces'
1558− optional $ controlSeq "caption" *> skipopts *> setCaption
1559− optional lbreak
1560− spaces'
1561− let header'' = if null header'
1562− then replicate cols mempty
1563− else header'
1564− lookAhead $ controlSeq "end" -- make sure we're at end
1565− return $ table mempty (zip aligns widths) header'' rows
1566−
1567−removeDoubleQuotes :: String -> String
1568−removeDoubleQuotes ('"':xs) =
1569− case reverse xs of
1570− '"':ys -> reverse ys
1571− _ -> '"':xs
1572−removeDoubleQuotes xs = xs
1072+maybeAddExtension :: String -> FilePath -> FilePath
1073+maybeAddExtension ext fp =
1074+ if null (takeExtension fp)
1075+ then addExtension fp ext
1076+ else fp
1077+
1078+blockCommands :: PandocMonad m => M.Map Text (LP m Blocks)
1079+blockCommands = M.empty
1080+
1081+block :: PandocMonad m => LP m Blocks
1082+block = (mempty <$ spaces1)
1083+ -- <|> environment
1084+ <|> include
1085+ -- <|> macro
1086+ -- <|> blockCommand
1087+ <|> paragraph
1088+ <|> grouped block
1089+
1090+blocks :: PandocMonad m => LP m Blocks
1091+blocks = mconcat <$> many block
1092+
1093+{-
1094+-- -- | Parse LaTeX from string and return 'Pandoc' document.
1095+-- readLaTeX :: PandocMonad m
1096+-- => ReaderOptions -- ^ Reader options
1097+-- -> Text -- ^ String to parse (assumes @'\n'@ line endings)
1098+-- -> m Pandoc
1099+-- readLaTeX opts ltx = do
1100+-- parsed <- readWithM parseLaTeX def{ stateOptions = opts }
1101+-- (unpack (crFilter ltx))
1102+-- case parsed of
1103+-- Right result -> return result
1104+-- Left e -> throwError e
1105+--
1106+--
1107+-- parseLaTeX :: PandocMonad m => LP m Pandoc
1108+-- parseLaTeX = do
1109+-- bs <- blocks
1110+-- eof
1111+-- st <- getState
1112+-- let meta = stateMeta st
1113+-- let doc' = doc bs
1114+-- let headerLevel (Header n _ _) = [n]
1115+-- headerLevel _ = []
1116+-- let bottomLevel = minimumDef 1 $ query headerLevel doc'
1117+-- let adjustHeaders m (Header n attr ils) = Header (n+m) attr ils
1118+-- adjustHeaders _ x = x
1119+-- let (Pandoc _ bs') =
1120+-- -- handle the case where you have \part or \chapter
1121+-- (if bottomLevel < 1
1122+-- then walk (adjustHeaders (1 - bottomLevel))
1123+-- else id) doc'
1124+-- return $ Pandoc meta bs'
1125+--
1126+-- anyControlSeq :: PandocMonad m => LP m String
1127+-- anyControlSeq = do
1128+-- char '\\'
1129+-- next <- option '\n' anyChar
1130+-- case next of
1131+-- '\n' -> return ""
1132+-- c | isLetter c -> (c:) <$> (many letter <* optional sp)
1133+-- | otherwise -> return [c]
1134+--
1135+-- controlSeq :: PandocMonad m => String -> LP m String
1136+-- controlSeq name = try $ do
1137+-- char '\\'
1138+-- case name of
1139+-- "" -> mzero
1140+-- [c] | not (isLetter c) -> string [c]
1141+-- cs -> string cs <* notFollowedBy letter <* optional sp
1142+-- return name
1143+--
1144+-- dimenarg :: PandocMonad m => LP m String
1145+-- dimenarg = try $ do
1146+-- ch <- option "" $ string "="
1147+-- num <- many1 digit
1148+-- dim <- oneOfStrings ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
1149+-- return $ ch ++ num ++ dim
1150+--
1151+-- sp :: PandocMonad m => LP m ()
1152+-- sp = whitespace <|> endline
1153+--
1154+-- whitespace :: PandocMonad m => LP m ()
1155+-- whitespace = skipMany1 $ satisfy (\c -> c == ' ' || c == '\t')
1156+--
1157+-- endline :: PandocMonad m => LP m ()
1158+-- endline = try (newline >> lookAhead anyChar >> notFollowedBy blankline)
1159+--
1160+-- isLowerHex :: Char -> Bool
1161+-- isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
1162+--
1163+-- primEscape :: PandocMonad m => LP m Char
1164+-- primEscape = try $ do
1165+-- string "^^"
1166+-- c <- satisfy (\x -> x >= '\0' && x <= '\128')
1167+-- d <- if isLowerHex c
1168+-- then option "" $ count 1 (satisfy isLowerHex)
1169+-- else return ""
1170+-- if null d
1171+-- then case ord c of
1172+-- x | x >= 64 && x <= 127 -> return $ chr (x - 64)
1173+-- | otherwise -> return $ chr (x + 64)
1174+-- else return $ chr $ read ('0':'x':c:d)
1175+--
1176+-- comment :: PandocMonad m => LP m ()
1177+-- comment = do
1178+-- char '%'
1179+-- skipMany (satisfy (/='\n'))
1180+-- optional newline
1181+-- return ()
1182+--
1183+-- bgroup :: PandocMonad m => LP m ()
1184+-- bgroup = try $ do
1185+-- skipMany (spaceChar <|> try (newline <* notFollowedBy blankline))
1186+-- () <$ char '{'
1187+-- <|> () <$ controlSeq "bgroup"
1188+-- <|> () <$ controlSeq "begingroup"
1189+--
1190+-- egroup :: PandocMonad m => LP m ()
1191+-- egroup = () <$ char '}'
1192+-- <|> () <$ controlSeq "egroup"
1193+-- <|> () <$ controlSeq "endgroup"
1194+--
1195+-- grouped :: PandocMonad m => Monoid a => LP m a -> LP m a
1196+-- grouped parser = try $ do
1197+-- bgroup
1198+-- -- first we check for an inner 'grouped', because
1199+-- -- {{a,b}} should be parsed the same as {a,b}
1200+-- try (grouped parser <* egroup)
1201+-- <|> (mconcat <$> manyTill parser egroup)
1202+--
1203+-- braced :: PandocMonad m => LP m String
1204+-- braced = grouped chunk
1205+-- where chunk =
1206+-- many1 (satisfy (\c -> c /= '\\' && c /= '}' && c /= '{'))
1207+-- <|> try (string "\\}")
1208+-- <|> try (string "\\{")
1209+-- <|> try (string "\\\\")
1210+-- <|> ((\x -> "{" ++ x ++ "}") <$> braced)
1211+-- <|> count 1 anyChar
1212+--
1213+-- bracketed :: PandocMonad m => Monoid a => LP m a -> LP m a
1214+-- bracketed parser = try $ char '[' *> (mconcat <$> manyTill parser (char ']'))
1215+--
1216+-- mathDisplay :: PandocMonad m => LP m String -> LP m Inlines
1217+-- mathDisplay p = displayMath <$> (try p >>= applyMacros' . trim)
1218+--
1219+-- mathInline :: PandocMonad m => LP m String -> LP m Inlines
1220+-- mathInline p = math <$> (try p >>= applyMacros')
1221+--
1222+-- mathChars :: PandocMonad m => LP m String
1223+-- mathChars =
1224+-- concat <$> many (escapedChar
1225+-- <|> (snd <$> withRaw braced)
1226+-- <|> many1 (satisfy isOrdChar))
1227+-- where escapedChar = try $ do char '\\'
1228+-- c <- anyChar
1229+-- return ['\\',c]
1230+-- isOrdChar '$' = False
1231+-- isOrdChar '{' = False
1232+-- isOrdChar '}' = False
1233+-- isOrdChar '\\' = False
1234+-- isOrdChar _ = True
1235+--
1236+-- inline :: PandocMonad m => LP m Inlines
1237+-- inline = (mempty <$ comment)
1238+-- <|> (space <$ whitespace)
1239+-- <|> (softbreak <$ endline)
1240+-- <|> inlineText
1241+-- <|> inlineCommand
1242+-- <|> inlineEnvironment
1243+-- <|> inlineGroup
1244+-- <|> (char '-' *> option (str "-")
1245+-- (char '-' *> option (str "–") (str "—" <$ char '-')))
1246+-- <|> doubleQuote
1247+-- <|> singleQuote
1248+-- <|> (str "”" <$ try (string "''"))
1249+-- <|> (str "”" <$ char '”')
1250+-- <|> (str "’" <$ char '\'')
1251+-- <|> (str "’" <$ char '’')
1252+-- <|> (str "\160" <$ char '~')
1253+-- <|> mathDisplay (string "$$" *> mathChars <* string "$$")
1254+-- <|> mathInline (char '$' *> mathChars <* char '$')
1255+-- <|> (guardEnabled Ext_literate_haskell *> char '|' *> doLHSverb)
1256+-- <|> (str . (:[]) <$> primEscape)
1257+-- <|> (do res <- oneOf "#&~^'`\"[]"
1258+-- pos <- getPosition
1259+-- report $ ParsingUnescaped [res] pos
1260+-- return $ str [res])
1261+--
1262+-- inlines :: PandocMonad m => LP m Inlines
1263+-- inlines = mconcat <$> many (notFollowedBy (char '}') *> inline)
1264+--
1265+-- inlineGroup :: PandocMonad m => LP m Inlines
1266+-- inlineGroup = do
1267+-- ils <- grouped inline
1268+-- if isNull ils
1269+-- then return mempty
1270+-- else return $ spanWith nullAttr ils
1271+-- -- we need the span so we can detitlecase bibtex entries;
1272+-- -- we need to know when something is {C}apitalized
1273+--
1274+-- block :: PandocMonad m => LP m Blocks
1275+-- block = (mempty <$ comment)
1276+-- <|> (mempty <$ ((spaceChar <|> newline) *> spaces))
1277+-- <|> environment
1278+-- <|> include
1279+-- <|> macro
1280+-- <|> blockCommand
1281+-- <|> paragraph
1282+-- <|> grouped block
1283+--
1284+-- blocks :: PandocMonad m => LP m Blocks
1285+-- blocks = mconcat <$> many block
1286+--
1287+-- getRawCommand :: PandocMonad m => String -> LP m String
1288+-- getRawCommand name' = do
1289+-- rawargs <- withRaw (many (try (optional sp *> opt)) *>
1290+-- option "" (try (optional sp *> dimenarg)) *>
1291+-- many braced)
1292+-- return $ '\\' : name' ++ snd rawargs
1293+--
1294+-- lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
1295+-- lookupListDefault d = (fromMaybe d .) . lookupList
1296+-- where
1297+-- lookupList l m = msum $ map (`M.lookup` m) l
1298+--
1299+-- blockCommand :: PandocMonad m => LP m Blocks
1300+-- blockCommand = try $ do
1301+-- name <- anyControlSeq
1302+-- guard $ name /= "begin" && name /= "end"
1303+-- star <- option "" (string "*" <* optional sp)
1304+-- let name' = name ++ star
1305+-- let raw = do
1306+-- rawcommand <- getRawCommand name'
1307+-- transformed <- applyMacros' rawcommand
1308+-- guard $ transformed /= rawcommand
1309+-- notFollowedBy $ parseFromString' inlines transformed
1310+-- parseFromString' blocks transformed
1311+-- lookupListDefault raw [name',name] blockCommands
1312+--
1313+-- inBrackets :: Inlines -> Inlines
1314+-- inBrackets x = str "[" <> x <> str "]"
1315+--
1316+-- -- eat an optional argument and one or more arguments in braces
1317+-- ignoreInlines :: PandocMonad m => Text -> (Text, LP m Inlines)
1318+-- ignoreInlines name = (name, p)
1319+-- where
1320+-- p = do oa <- optargs
1321+-- let rawCommand = '\\':name ++ oa
1322+-- let doraw = guardRaw >> return (rawInline "latex" rawCommand)
1323+-- doraw <|> ignore rawCommand
1324+--
1325+-- guardRaw :: PandocMonad m => LP m ()
1326+-- guardRaw = getOption readerExtensions >>= guard . extensionEnabled Ext_raw_tex
1327+--
1328+-- optargs :: PandocMonad m => LP m String
1329+-- optargs = snd <$> withRaw (skipopts *> skipMany (try $ optional sp *> braced))
1330+--
1331+-- ignore :: (Monoid a, PandocMonad m) => String -> ParserT s u m a
1332+-- ignore raw = do
1333+-- pos <- getPosition
1334+-- report $ SkippedContent raw pos
1335+-- return mempty
1336+--
1337+-- ignoreBlocks :: PandocMonad m => String -> (String, LP m Blocks)
1338+-- ignoreBlocks name = (name, p)
1339+-- where
1340+-- p = do oa <- optargs
1341+-- let rawCommand = '\\':name ++ oa
1342+-- let doraw = guardRaw >> return (rawBlock "latex" rawCommand)
1343+-- doraw <|> ignore rawCommand
1344+--
1345+-- blockCommands :: PandocMonad m => M.Map String (LP m Blocks)
1346+-- blockCommands = M.fromList $
1347+-- [ ("par", mempty <$ skipopts)
1348+-- , ("parbox", braced >> grouped blocks)
1349+-- , ("title", mempty <$ (skipopts *>
1350+-- (grouped inline >>= addMeta "title")
1351+-- <|> (grouped block >>= addMeta "title")))
1352+-- , ("subtitle", mempty <$ (skipopts *> tok >>= addMeta "subtitle"))
1353+-- , ("author", mempty <$ (skipopts *> authors))
1354+-- -- -- in letter class, temp. store address & sig as title, author
1355+-- , ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
1356+-- , ("signature", mempty <$ (skipopts *> authors))
1357+-- , ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
1358+-- -- Koma-script metadata commands
1359+-- , ("dedication", mempty <$ (skipopts *> tok >>= addMeta "dedication"))
1360+-- -- sectioning
1361+-- , ("part", section nullAttr (-1))
1362+-- , ("part*", section nullAttr (-1))
1363+-- , ("chapter", section nullAttr 0)
1364+-- , ("chapter*", section ("",["unnumbered"],[]) 0)
1365+-- , ("section", section nullAttr 1)
1366+-- , ("section*", section ("",["unnumbered"],[]) 1)
1367+-- , ("subsection", section nullAttr 2)
1368+-- , ("subsection*", section ("",["unnumbered"],[]) 2)
1369+-- , ("subsubsection", section nullAttr 3)
1370+-- , ("subsubsection*", section ("",["unnumbered"],[]) 3)
1371+-- , ("paragraph", section nullAttr 4)
1372+-- , ("paragraph*", section ("",["unnumbered"],[]) 4)
1373+-- , ("subparagraph", section nullAttr 5)
1374+-- , ("subparagraph*", section ("",["unnumbered"],[]) 5)
1375+-- -- beamer slides
1376+-- , ("frametitle", section nullAttr 3)
1377+-- , ("framesubtitle", section nullAttr 4)
1378+-- -- letters
1379+-- , ("opening", (para . trimInlines) <$> (skipopts *> tok))
1380+-- , ("closing", skipopts *> closing)
1381+-- --
1382+-- , ("hrule", pure horizontalRule)
1383+-- , ("strut", pure mempty)
1384+-- , ("rule", skipopts *> tok *> tok *> pure horizontalRule)
1385+-- , ("item", skipopts *> looseItem)
1386+-- , ("documentclass", skipopts *> braced *> preamble)
1387+-- , ("centerline", (para . trimInlines) <$> (skipopts *> tok))
1388+-- , ("caption", skipopts *> setCaption)
1389+-- , ("bibliography", mempty <$ (skipopts *> braced >>=
1390+-- addMeta "bibliography" . splitBibs))
1391+-- , ("addbibresource", mempty <$ (skipopts *> braced >>=
1392+-- addMeta "bibliography" . splitBibs))
1393+-- -- includes
1394+-- , ("lstinputlisting", inputListing)
1395+-- , ("graphicspath", graphicsPath)
1396+-- -- hyperlink
1397+-- , ("hypertarget", braced >> grouped block)
1398+-- ] ++ map ignoreBlocks
1399+-- -- these commands will be ignored unless --parse-raw is specified,
1400+-- -- in which case they will appear as raw latex blocks
1401+-- [ "newcommand", "renewcommand", "newenvironment", "renewenvironment"
1402+-- -- newcommand, etc. should be parsed by macro, but we need this
1403+-- -- here so these aren't parsed as inline commands to ignore
1404+-- , "special", "pdfannot", "pdfstringdef"
1405+-- , "bibliographystyle"
1406+-- , "maketitle", "makeindex", "makeglossary"
1407+-- , "addcontentsline", "addtocontents", "addtocounter"
1408+-- -- \ignore{} is used conventionally in literate haskell for definitions
1409+-- -- that are to be processed by the compiler but not printed.
1410+-- , "ignore"
1411+-- , "hyperdef"
1412+-- , "markboth", "markright", "markleft"
1413+-- , "hspace", "vspace"
1414+-- , "newpage"
1415+-- , "clearpage"
1416+-- , "pagebreak"
1417+-- ]
1418+--
1419+-- graphicsPath :: PandocMonad m => LP m Blocks
1420+-- graphicsPath = do
1421+-- ps <- bgroup *> (manyTill braced egroup)
1422+-- getResourcePath >>= setResourcePath . (++ ps)
1423+-- return mempty
1424+--
1425+-- addMeta :: PandocMonad m => ToMetaValue a => String -> a -> LP m ()
1426+-- addMeta field val = updateState $ \st ->
1427+-- st{ stateMeta = addMetaField field val $ stateMeta st }
1428+--
1429+-- splitBibs :: String -> [Inlines]
1430+-- splitBibs = map (str . flip replaceExtension "bib" . trim) . splitBy (==',')
1431+--
1432+-- setCaption :: PandocMonad m => LP m Blocks
1433+-- setCaption = do
1434+-- ils <- tok
1435+-- mblabel <- option Nothing $
1436+-- try $ spaces' >> controlSeq "label" >> (Just <$> tok)
1437+-- let ils' = case mblabel of
1438+-- Just lab -> ils <> spanWith
1439+-- ("",[],[("data-label", stringify lab)]) mempty
1440+-- Nothing -> ils
1441+-- updateState $ \st -> st{ stateCaption = Just ils' }
1442+-- return mempty
1443+--
1444+-- resetCaption :: PandocMonad m => LP m ()
1445+-- resetCaption = updateState $ \st -> st{ stateCaption = Nothing }
1446+--
1447+-- authors :: PandocMonad m => LP m ()
1448+-- authors = try $ do
1449+-- bgroup
1450+-- let oneAuthor = mconcat <$>
1451+-- many1 (notFollowedBy' (controlSeq "and") >>
1452+-- (inline <|> mempty <$ blockCommand))
1453+-- -- skip e.g. \vspace{10pt}
1454+-- auths <- sepBy oneAuthor (controlSeq "and")
1455+-- egroup
1456+-- addMeta "author" (map trimInlines auths)
1457+--
1458+-- section :: PandocMonad m => Attr -> Int -> LP m Blocks
1459+-- section (ident, classes, kvs) lvl = do
1460+-- skipopts
1461+-- contents <- grouped inline
1462+-- lab <- option ident $ try (spaces' >> controlSeq "label" >> spaces' >> braced)
1463+-- attr' <- registerHeader (lab, classes, kvs) contents
1464+-- return $ headerWith attr' lvl contents
1465+--
1466+-- inlineCommand :: PandocMonad m => LP m Inlines
1467+-- inlineCommand = try $ do
1468+-- (name, raw') <- withRaw anyControlSeq
1469+-- guard $ name /= "begin" && name /= "end"
1470+-- star <- option "" (string "*")
1471+-- let name' = name ++ star
1472+-- let raw = do
1473+-- guard $ not (isBlockCommand name)
1474+-- rawargs <- withRaw
1475+-- (skipangles *> skipopts *> option "" dimenarg *> many braced)
1476+-- let rawcommand = raw' ++ star ++ snd rawargs
1477+-- transformed <- applyMacros' rawcommand
1478+-- exts <- getOption readerExtensions
1479+-- if transformed /= rawcommand
1480+-- then parseFromString' inlines transformed
1481+-- else if extensionEnabled Ext_raw_tex exts
1482+-- then return $ rawInline "latex" rawcommand
1483+-- else ignore rawcommand
1484+-- (lookupListDefault raw [name',name] inlineCommands <*
1485+-- optional (try (string "{}")))
1486+--
1487+-- rawInlineOr :: PandocMonad m => String -> LP m Inlines -> LP m Inlines
1488+-- rawInlineOr name' fallback = do
1489+-- parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
1490+-- if parseRaw
1491+-- then rawInline "latex" <$> getRawCommand name'
1492+-- else fallback
1493+--
1494+-- isBlockCommand :: String -> Bool
1495+-- isBlockCommand s = s `M.member` (blockCommands :: M.Map String (LP PandocPure Blocks))
1496+--
1497+--
1498+-- inlineEnvironments :: PandocMonad m => M.Map String (LP m Inlines)
1499+-- inlineEnvironments = M.fromList
1500+-- [ ("displaymath", mathEnvWith id Nothing "displaymath")
1501+-- , ("math", math <$> mathEnv "math")
1502+-- , ("equation", mathEnvWith id Nothing "equation")
1503+-- , ("equation*", mathEnvWith id Nothing "equation*")
1504+-- , ("gather", mathEnvWith id (Just "gathered") "gather")
1505+-- , ("gather*", mathEnvWith id (Just "gathered") "gather*")
1506+-- , ("multline", mathEnvWith id (Just "gathered") "multline")
1507+-- , ("multline*", mathEnvWith id (Just "gathered") "multline*")
1508+-- , ("eqnarray", mathEnvWith id (Just "aligned") "eqnarray")
1509+-- , ("eqnarray*", mathEnvWith id (Just "aligned") "eqnarray*")
1510+-- , ("align", mathEnvWith id (Just "aligned") "align")
1511+-- , ("align*", mathEnvWith id (Just "aligned") "align*")
1512+-- , ("alignat", mathEnvWith id (Just "aligned") "alignat")
1513+-- , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
1514+-- ]
1515+--
1516+-- mkImage :: PandocMonad m => [(String, String)] -> String -> LP m Inlines
1517+-- mkImage options src = do
1518+-- let replaceTextwidth (k,v) = case numUnit v of
1519+-- Just (num, "\\textwidth") -> (k, showFl (num * 100) ++ "%")
1520+-- _ -> (k, v)
1521+-- let kvs = map replaceTextwidth $ filter (\(k,_) -> k `elem` ["width", "height"]) options
1522+-- let attr = ("",[], kvs)
1523+-- let alt = str "image"
1524+-- case takeExtension src of
1525+-- "" -> do
1526+-- defaultExt <- getOption readerDefaultImageExtension
1527+-- return $ imageWith attr (addExtension src defaultExt) "" alt
1528+-- _ -> return $ imageWith attr src "" alt
1529+--
1530+-- inNote :: Inlines -> Inlines
1531+-- inNote ils =
1532+-- note $ para $ ils <> str "."
1533+--
1534+-
1535+-- -- converts e.g. \SI{1}[\$]{} to "$ 1" or \SI{1}{\euro} to "1 €"
1536+-- dosiunitx :: PandocMonad m => LP m Inlines
1537+-- dosiunitx = do
1538+-- skipopts
1539+-- value <- tok
1540+-- valueprefix <- option "" $ char '[' >> (mconcat <$> manyTill tok (char ']'))
1541+-- unit <- tok
1542+-- let emptyOr160 "" = ""
1543+-- emptyOr160 _ = "\160"
1544+-- return . mconcat $ [valueprefix,
1545+-- emptyOr160 valueprefix,
1546+-- value,
1547+-- emptyOr160 unit,
1548+-- unit]
1549+--
1550+-- accent :: (Char -> String) -> Inlines -> LP m Inlines
1551+-- accent f ils =
1552+-- case toList ils of
1553+-- (Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)
1554+-- [] -> mzero
1555+-- _ -> return ils
1556+--
1557+-- grave :: Char -> String
1558+-- grave 'A' = "À"
1559+-- grave 'E' = "È"
1560+-- grave 'I' = "Ì"
1561+-- grave 'O' = "Ò"
1562+-- grave 'U' = "Ù"
1563+-- grave 'a' = "à"
1564+-- grave 'e' = "è"
1565+-- grave 'i' = "ì"
1566+-- grave 'o' = "ò"
1567+-- grave 'u' = "ù"
1568+-- grave c = [c]
1569+--
1570+-- acute :: Char -> String
1571+-- acute 'A' = "Á"
1572+-- acute 'E' = "É"
1573+-- acute 'I' = "Í"
1574+-- acute 'O' = "Ó"
1575+-- acute 'U' = "Ú"
1576+-- acute 'Y' = "Ý"
1577+-- acute 'a' = "á"
1578+-- acute 'e' = "é"
1579+-- acute 'i' = "í"
1580+-- acute 'o' = "ó"
1581+-- acute 'u' = "ú"
1582+-- acute 'y' = "ý"
1583+-- acute 'C' = "Ć"
1584+-- acute 'c' = "ć"
1585+-- acute 'L' = "Ĺ"
1586+-- acute 'l' = "ĺ"
1587+-- acute 'N' = "Ń"
1588+-- acute 'n' = "ń"
1589+-- acute 'R' = "Ŕ"
1590+-- acute 'r' = "ŕ"
1591+-- acute 'S' = "Ś"
1592+-- acute 's' = "ś"
1593+-- acute 'Z' = "Ź"
1594+-- acute 'z' = "ź"
1595+-- acute c = [c]
1596+--
1597+-- circ :: Char -> String
1598+-- circ 'A' = "Â"
1599+-- circ 'E' = "Ê"
1600+-- circ 'I' = "Î"
1601+-- circ 'O' = "Ô"
1602+-- circ 'U' = "Û"
1603+-- circ 'a' = "â"
1604+-- circ 'e' = "ê"
1605+-- circ 'i' = "î"
1606+-- circ 'o' = "ô"
1607+-- circ 'u' = "û"
1608+-- circ 'C' = "Ĉ"
1609+-- circ 'c' = "ĉ"
1610+-- circ 'G' = "Ĝ"
1611+-- circ 'g' = "ĝ"
1612+-- circ 'H' = "Ĥ"
1613+-- circ 'h' = "ĥ"
1614+-- circ 'J' = "Ĵ"
1615+-- circ 'j' = "ĵ"
1616+-- circ 'S' = "Ŝ"
1617+-- circ 's' = "ŝ"
1618+-- circ 'W' = "Ŵ"
1619+-- circ 'w' = "ŵ"
1620+-- circ 'Y' = "Ŷ"
1621+-- circ 'y' = "ŷ"
1622+-- circ c = [c]
1623+--
1624+-- tilde :: Char -> String
1625+-- tilde 'A' = "Ã"
1626+-- tilde 'a' = "ã"
1627+-- tilde 'O' = "Õ"
1628+-- tilde 'o' = "õ"
1629+-- tilde 'I' = "Ĩ"
1630+-- tilde 'i' = "ĩ"
1631+-- tilde 'U' = "Ũ"
1632+-- tilde 'u' = "ũ"
1633+-- tilde 'N' = "Ñ"
1634+-- tilde 'n' = "ñ"
1635+-- tilde c = [c]
1636+--
1637+-- umlaut :: Char -> String
1638+-- umlaut 'A' = "Ä"
1639+-- umlaut 'E' = "Ë"
1640+-- umlaut 'I' = "Ï"
1641+-- umlaut 'O' = "Ö"
1642+-- umlaut 'U' = "Ü"
1643+-- umlaut 'a' = "ä"
1644+-- umlaut 'e' = "ë"
1645+-- umlaut 'i' = "ï"
1646+-- umlaut 'o' = "ö"
1647+-- umlaut 'u' = "ü"
1648+-- umlaut c = [c]
1649+--
1650+-- hungarumlaut :: Char -> String
1651+-- hungarumlaut 'A' = "A̋"
1652+-- hungarumlaut 'E' = "E̋"
1653+-- hungarumlaut 'I' = "I̋"
1654+-- hungarumlaut 'O' = "Ő"
1655+-- hungarumlaut 'U' = "Ű"
1656+-- hungarumlaut 'Y' = "ӳ"
1657+-- hungarumlaut 'a' = "a̋"
1658+-- hungarumlaut 'e' = "e̋"
1659+-- hungarumlaut 'i' = "i̋"
1660+-- hungarumlaut 'o' = "ő"
1661+-- hungarumlaut 'u' = "ű"
1662+-- hungarumlaut 'y' = "ӳ"
1663+-- hungarumlaut c = [c]
1664+--
1665+-- dot :: Char -> String
1666+-- dot 'C' = "Ċ"
1667+-- dot 'c' = "ċ"
1668+-- dot 'E' = "Ė"
1669+-- dot 'e' = "ė"
1670+-- dot 'G' = "Ġ"
1671+-- dot 'g' = "ġ"
1672+-- dot 'I' = "İ"
1673+-- dot 'Z' = "Ż"
1674+-- dot 'z' = "ż"
1675+-- dot c = [c]
1676+--
1677+-- macron :: Char -> String
1678+-- macron 'A' = "Ā"
1679+-- macron 'E' = "Ē"
1680+-- macron 'I' = "Ī"
1681+-- macron 'O' = "Ō"
1682+-- macron 'U' = "Ū"
1683+-- macron 'a' = "ā"
1684+-- macron 'e' = "ē"
1685+-- macron 'i' = "ī"
1686+-- macron 'o' = "ō"
1687+-- macron 'u' = "ū"
1688+-- macron c = [c]
1689+--
1690+-- cedilla :: Char -> String
1691+-- cedilla 'c' = "ç"
1692+-- cedilla 'C' = "Ç"
1693+-- cedilla 's' = "ş"
1694+-- cedilla 'S' = "Ş"
1695+-- cedilla 't' = "ţ"
1696+-- cedilla 'T' = "Ţ"
1697+-- cedilla 'e' = "ȩ"
1698+-- cedilla 'E' = "Ȩ"
1699+-- cedilla 'h' = "ḩ"
1700+-- cedilla 'H' = "Ḩ"
1701+-- cedilla 'o' = "o̧"
1702+-- cedilla 'O' = "O̧"
1703+-- cedilla c = [c]
1704+--
1705+-- hacek :: Char -> String
1706+-- hacek 'A' = "Ǎ"
1707+-- hacek 'a' = "ǎ"
1708+-- hacek 'C' = "Č"
1709+-- hacek 'c' = "č"
1710+-- hacek 'D' = "Ď"
1711+-- hacek 'd' = "ď"
1712+-- hacek 'E' = "Ě"
1713+-- hacek 'e' = "ě"
1714+-- hacek 'G' = "Ǧ"
1715+-- hacek 'g' = "ǧ"
1716+-- hacek 'H' = "Ȟ"
1717+-- hacek 'h' = "ȟ"
1718+-- hacek 'I' = "Ǐ"
1719+-- hacek 'i' = "ǐ"
1720+-- hacek 'j' = "ǰ"
1721+-- hacek 'K' = "Ǩ"
1722+-- hacek 'k' = "ǩ"
1723+-- hacek 'L' = "Ľ"
1724+-- hacek 'l' = "ľ"
1725+-- hacek 'N' = "Ň"
1726+-- hacek 'n' = "ň"
1727+-- hacek 'O' = "Ǒ"
1728+-- hacek 'o' = "ǒ"
1729+-- hacek 'R' = "Ř"
1730+-- hacek 'r' = "ř"
1731+-- hacek 'S' = "Š"
1732+-- hacek 's' = "š"
1733+-- hacek 'T' = "Ť"
1734+-- hacek 't' = "ť"
1735+-- hacek 'U' = "Ǔ"
1736+-- hacek 'u' = "ǔ"
1737+-- hacek 'Z' = "Ž"
1738+-- hacek 'z' = "ž"
1739+-- hacek c = [c]
1740+--
1741+-- breve :: Char -> String
1742+-- breve 'A' = "Ă"
1743+-- breve 'a' = "ă"
1744+-- breve 'E' = "Ĕ"
1745+-- breve 'e' = "ĕ"
1746+-- breve 'G' = "Ğ"
1747+-- breve 'g' = "ğ"
1748+-- breve 'I' = "Ĭ"
1749+-- breve 'i' = "ĭ"
1750+-- breve 'O' = "Ŏ"
1751+-- breve 'o' = "ŏ"
1752+-- breve 'U' = "Ŭ"
1753+-- breve 'u' = "ŭ"
1754+-- breve c = [c]
1755+--
1756+-- tok :: PandocMonad m => LP m Inlines
1757+-- tok = try $ grouped inline <|> inlineCommand <|> str <$> count 1 inlineChar
1758+--
1759+-- opt :: PandocMonad m => LP m Inlines
1760+-- opt = bracketed inline
1761+--
1762+-- rawopt :: PandocMonad m => LP m String
1763+-- rawopt = do
1764+-- contents <- bracketed (many1 (noneOf "[]") <|> try (string "\\]") <|>
1765+-- try (string "\\[") <|> rawopt)
1766+-- optional sp
1767+-- return $ "[" ++ contents ++ "]"
1768+--
1769+-- skipopts :: PandocMonad m => LP m ()
1770+-- skipopts = skipMany rawopt
1771+--
1772+-- -- opts in angle brackets are used in beamer
1773+-- rawangle :: PandocMonad m => LP m ()
1774+-- rawangle = try $ do
1775+-- char '<'
1776+-- skipMany (noneOf ">")
1777+-- char '>'
1778+-- return ()
1779+--
1780+-- skipangles :: PandocMonad m => LP m ()
1781+-- skipangles = skipMany rawangle
1782+--
1783+-- inlineText :: PandocMonad m => LP m Inlines
1784+-- inlineText = str <$> many1 inlineChar
1785+--
1786+-- inlineChar :: PandocMonad m => LP m Char
1787+-- inlineChar = noneOf "\\$%&~#{}^'`\"‘’“”-[] \t\n"
1788+--
1789+-- environment :: PandocMonad m => LP m Blocks
1790+-- environment = do
1791+-- controlSeq "begin"
1792+-- name <- braced
1793+-- M.findWithDefault mzero name environments
1794+-- <|> rawEnv name
1795+--
1796+-- inlineEnvironment :: PandocMonad m => LP m Inlines
1797+-- inlineEnvironment = try $ do
1798+-- controlSeq "begin"
1799+-- name <- braced
1800+-- M.findWithDefault mzero name inlineEnvironments
1801+--
1802+-- rawEnv :: PandocMonad m => String -> LP m Blocks
1803+-- rawEnv name = do
1804+-- exts <- getOption readerExtensions
1805+-- let parseRaw = extensionEnabled Ext_raw_tex exts
1806+-- rawOptions <- mconcat <$> many rawopt
1807+-- let beginCommand = "\\begin{" ++ name ++ "}" ++ rawOptions
1808+-- pos1 <- getPosition
1809+-- (bs, raw) <- withRaw $ env name blocks
1810+-- raw' <- applyMacros' $ beginCommand ++ raw
1811+-- if raw' /= beginCommand ++ raw
1812+-- then parseFromString' blocks raw'
1813+-- else if parseRaw
1814+-- then return $ rawBlock "latex" $ beginCommand ++ raw'
1815+-- else do
1816+-- unless parseRaw $ do
1817+-- report $ SkippedContent beginCommand pos1
1818+-- pos2 <- getPosition
1819+-- report $ SkippedContent ("\\end{" ++ name ++ "}") pos2
1820+-- return bs
1821+--
1822+-- rawVerbEnv :: PandocMonad m => String -> LP m Blocks
1823+-- rawVerbEnv name = do
1824+-- pos <- getPosition
1825+-- (_, raw) <- withRaw $ verbEnv name
1826+-- let raw' = "\\begin{tikzpicture}" ++ raw
1827+-- exts <- getOption readerExtensions
1828+-- let parseRaw = extensionEnabled Ext_raw_tex exts
1829+-- if parseRaw
1830+-- then return $ rawBlock "latex" raw'
1831+-- else do
1832+-- report $ SkippedContent raw' pos
1833+-- return mempty
1834+--
1835+-- ----
1836+--
1837+-- ----
1838+--
1839+-- keyval :: PandocMonad m => LP m (String, String)
1840+-- keyval = try $ do
1841+-- key <- many1 alphaNum
1842+-- val <- option "" $ char '=' >> braced <|> (many1 (alphaNum <|> oneOf ".:-|\\"))
1843+-- skipMany spaceChar
1844+-- optional (char ',')
1845+-- skipMany spaceChar
1846+-- return (key, val)
1847+--
1848+--
1849+-- keyvals :: PandocMonad m => LP m [(String, String)]
1850+-- keyvals = try $ char '[' *> manyTill keyval (char ']')
1851+--
1852+-- alltt :: PandocMonad m => String -> LP m Blocks
1853+-- alltt t = walk strToCode <$> parseFromString' blocks
1854+-- (substitute " " "\\ " $ substitute "%" "\\%" $
1855+-- intercalate "\\\\\n" $ lines t)
1856+-- where strToCode (Str s) = Code nullAttr s
1857+-- strToCode x = x
1858+--
1859+-- rawLaTeXBlock :: PandocMonad m => ParserT String ParserState String
1860+-- rawLaTeXBlock = snd <$> try (withRaw (environment <|> blockCommand))
1861+--
1862+-- rawLaTeXInline :: PandocMonad m => ParserT String ParserState Inline
1863+-- rawLaTeXInline = do
1864+-- raw <- (snd <$> withRaw inlineCommand)
1865+-- <|> (snd <$> withRaw inlineEnvironment)
1866+-- <|> (snd <$> withRaw blockCommand)
1867+-- RawInline "latex" <$> applyMacros' raw
1868+--
1869+-- addImageCaption :: PandocMonad m => Blocks -> LP m Blocks
1870+-- addImageCaption = walkM go
1871+-- where go (Image attr alt (src,tit))
1872+-- | not ("fig:" `isPrefixOf` tit) = do
1873+-- mbcapt <- stateCaption <$> getState
1874+-- return $ case mbcapt of
1875+-- Just ils -> Image attr (toList ils) (src, "fig:" ++ tit)
1876+-- Nothing -> Image attr alt (src,tit)
1877+-- go x = return x
1878+--
1879+-- addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
1880+-- addTableCaption = walkM go
1881+-- where go (Table c als ws hs rs) = do
1882+-- mbcapt <- stateCaption <$> getState
1883+-- return $ case mbcapt of
1884+-- Just ils -> Table (toList ils) als ws hs rs
1885+-- Nothing -> Table c als ws hs rs
1886+-- go x = return x
1887+--
1888+-- environments :: PandocMonad m => M.Map String (LP m Blocks)
1889+-- environments = M.fromList
1890+-- [ ("document", env "document" blocks <* skipMany anyChar)
1891+-- , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
1892+-- , ("letter", env "letter" letterContents)
1893+-- , ("minipage", env "minipage" $
1894+-- skipopts *> spaces' *> optional braced *> spaces' *> blocks)
1895+-- , ("figure", env "figure" $ skipopts *> figure)
1896+-- , ("subfigure", env "subfigure" $ skipopts *> tok *> figure)
1897+-- , ("center", env "center" blocks)
1898+-- , ("longtable", env "longtable" $
1899+-- resetCaption *> simpTable "longtable" False >>= addTableCaption)
1900+-- , ("table", env "table" $
1901+-- resetCaption *> skipopts *> blocks >>= addTableCaption)
1902+-- , ("tabular*", env "tabular" $ simpTable "tabular*" True)
1903+-- , ("tabularx", env "tabularx" $ simpTable "tabularx" True)
1904+-- , ("tabular", env "tabular" $ simpTable "tabular" False)
1905+-- , ("quote", blockQuote <$> env "quote" blocks)
1906+-- , ("quotation", blockQuote <$> env "quotation" blocks)
1907+-- , ("verse", blockQuote <$> env "verse" blocks)
1908+-- , ("itemize", bulletList <$> listenv "itemize" (many item))
1909+-- , ("description", definitionList <$> listenv "description" (many descItem))
1910+-- , ("enumerate", orderedList')
1911+-- , ("alltt", alltt =<< verbEnv "alltt")
1912+-- , ("code", guardEnabled Ext_literate_haskell *>
1913+-- (codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
1914+-- verbEnv "code"))
1915+-- , ("comment", mempty <$ verbEnv "comment")
1916+-- , ("verbatim", codeBlock <$> verbEnv "verbatim")
1917+-- , ("Verbatim", fancyverbEnv "Verbatim")
1918+-- , ("BVerbatim", fancyverbEnv "BVerbatim")
1919+-- , ("lstlisting", do attr <- parseListingsOptions <$> option [] keyvals
1920+-- codeBlockWith attr <$> verbEnv "lstlisting")
1921+-- , ("minted", do options <- option [] keyvals
1922+-- lang <- grouped (many1 $ satisfy (/='}'))
1923+-- let kvs = [ (if k == "firstnumber"
1924+-- then "startFrom"
1925+-- else k, v) | (k,v) <- options ]
1926+-- let classes = [ lang | not (null lang) ] ++
1927+-- [ "numberLines" |
1928+-- lookup "linenos" options == Just "true" ]
1929+-- let attr = ("",classes,kvs)
1930+-- codeBlockWith attr <$> verbEnv "minted")
1931+-- , ("obeylines", parseFromString
1932+-- (para . trimInlines . mconcat <$> many inline) =<<
1933+-- intercalate "\\\\\n" . lines <$> verbEnv "obeylines")
1934+-- , ("displaymath", mathEnvWith para Nothing "displaymath")
1935+-- , ("equation", mathEnvWith para Nothing "equation")
1936+-- , ("equation*", mathEnvWith para Nothing "equation*")
1937+-- , ("gather", mathEnvWith para (Just "gathered") "gather")
1938+-- , ("gather*", mathEnvWith para (Just "gathered") "gather*")
1939+-- , ("multline", mathEnvWith para (Just "gathered") "multline")
1940+-- , ("multline*", mathEnvWith para (Just "gathered") "multline*")
1941+-- , ("eqnarray", mathEnvWith para (Just "aligned") "eqnarray")
1942+-- , ("eqnarray*", mathEnvWith para (Just "aligned") "eqnarray*")
1943+-- , ("align", mathEnvWith para (Just "aligned") "align")
1944+-- , ("align*", mathEnvWith para (Just "aligned") "align*")
1945+-- , ("alignat", mathEnvWith para (Just "aligned") "alignat")
1946+-- , ("alignat*", mathEnvWith para (Just "aligned") "alignat*")
1947+-- , ("tikzpicture", rawVerbEnv "tikzpicture")
1948+-- ]
1949+--
1950+-- figure :: PandocMonad m => LP m Blocks
1951+-- figure = try $ do
1952+-- resetCaption
1953+-- blocks >>= addImageCaption
1954+--
1955+-- letterContents :: PandocMonad m => LP m Blocks
1956+-- letterContents = do
1957+-- bs <- blocks
1958+-- st <- getState
1959+-- -- add signature (author) and address (title)
1960+-- let addr = case lookupMeta "address" (stateMeta st) of
1961+-- Just (MetaBlocks [Plain xs]) ->
1962+-- para $ trimInlines $ fromList xs
1963+-- _ -> mempty
1964+-- return $ addr <> bs -- sig added by \closing
1965+--
1966+-- closing :: PandocMonad m => LP m Blocks
1967+-- closing = do
1968+-- contents <- tok
1969+-- st <- getState
1970+-- let extractInlines (MetaBlocks [Plain ys]) = ys
1971+-- extractInlines (MetaBlocks [Para ys ]) = ys
1972+-- extractInlines _ = []
1973+-- let sigs = case lookupMeta "author" (stateMeta st) of
1974+-- Just (MetaList xs) ->
1975+-- para $ trimInlines $ fromList $
1976+-- intercalate [LineBreak] $ map extractInlines xs
1977+-- _ -> mempty
1978+-- return $ para (trimInlines contents) <> sigs
1979+--
1980+-- item :: PandocMonad m => LP m Blocks
1981+-- item = blocks *> controlSeq "item" *> skipopts *> blocks
1982+--
1983+-- looseItem :: PandocMonad m => LP m Blocks
1984+-- looseItem = do
1985+-- ctx <- stateParserContext `fmap` getState
1986+-- if ctx == ListItemState
1987+-- then mzero
1988+-- else return mempty
1989+--
1990+-- descItem :: PandocMonad m => LP m (Inlines, [Blocks])
1991+-- descItem = do
1992+-- blocks -- skip blocks before item
1993+-- controlSeq "item"
1994+-- optional sp
1995+-- ils <- opt
1996+-- bs <- blocks
1997+-- return (ils, [bs])
1998+--
1999+-- env :: PandocMonad m => String -> LP m a -> LP m a
2000+-- env name p = p <*
2001+-- (try (controlSeq "end" *> braced >>= guard . (== name))
2002+-- <?> ("\\end{" ++ name ++ "}"))
2003+--
2004+-- listenv :: PandocMonad m => String -> LP m a -> LP m a
2005+-- listenv name p = try $ do
2006+-- oldCtx <- stateParserContext `fmap` getState
2007+-- updateState $ \st -> st{ stateParserContext = ListItemState }
2008+-- res <- env name p
2009+-- updateState $ \st -> st{ stateParserContext = oldCtx }
2010+-- return res
2011+--
2012+-- mathEnvWith :: PandocMonad m
2013+-- => (Inlines -> a) -> Maybe String -> String -> LP m a
2014+-- mathEnvWith f innerEnv name = f <$> mathDisplay (inner <$> mathEnv name)
2015+-- where inner x = case innerEnv of
2016+-- Nothing -> x
2017+-- Just y -> "\\begin{" ++ y ++ "}\n" ++ x ++
2018+-- "\\end{" ++ y ++ "}"
2019+--
2020+-- mathEnv :: PandocMonad m => String -> LP m String
2021+-- mathEnv name = do
2022+-- skipopts
2023+-- optional blankline
2024+-- let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
2025+-- charMuncher = skipMany comment *>
2026+-- (many1 (noneOf "\\%") <|> try (string "\\%")
2027+-- <|> try (string "\\\\") <|> count 1 anyChar)
2028+-- res <- concat <$> manyTill charMuncher endEnv
2029+-- return $ stripTrailingNewlines res
2030+--
2031+-- verbEnv :: PandocMonad m => String -> LP m String
2032+-- verbEnv name = do
2033+-- skipopts
2034+-- optional blankline
2035+-- let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
2036+-- charMuncher = anyChar
2037+-- res <- manyTill charMuncher endEnv
2038+-- return $ stripTrailingNewlines res
2039+--
2040+-- fancyverbEnv :: PandocMonad m => String -> LP m Blocks
2041+-- fancyverbEnv name = do
2042+-- options <- option [] keyvals
2043+-- let kvs = [ (if k == "firstnumber"
2044+-- then "startFrom"
2045+-- else k, v) | (k,v) <- options ]
2046+-- let classes = [ "numberLines" |
2047+-- lookup "numbers" options == Just "left" ]
2048+-- let attr = ("",classes,kvs)
2049+-- codeBlockWith attr <$> verbEnv name
2050+--
2051+-- orderedList' :: PandocMonad m => LP m Blocks
2052+-- orderedList' = try $ do
2053+-- optional sp
2054+-- (_, style, delim) <- option (1, DefaultStyle, DefaultDelim) $
2055+-- try $ char '[' *> anyOrderedListMarker <* char ']'
2056+-- spaces
2057+-- optional $ try $ controlSeq "setlength" *> grouped (controlSeq "itemindent") *> braced
2058+-- spaces
2059+-- start <- option 1 $ try $ do controlSeq "setcounter"
2060+-- grouped (string "enum" *> many1 (oneOf "iv"))
2061+-- optional sp
2062+-- num <- grouped (many1 digit)
2063+-- spaces
2064+-- return (read num + 1 :: Int)
2065+-- bs <- listenv "enumerate" (many item)
2066+-- return $ orderedListWith (start, style, delim) bs
2067+--
2068+-- paragraph :: PandocMonad m => LP m Blocks
2069+-- paragraph = do
2070+-- x <- trimInlines . mconcat <$> many1 inline
2071+-- if x == mempty
2072+-- then return mempty
2073+-- else return $ para x
2074+--
2075+-- preamble :: PandocMonad m => LP m Blocks
2076+-- preamble = mempty <$> manyTill preambleBlock beginDoc
2077+-- where beginDoc = lookAhead $ try $ controlSeq "begin" *> string "{document}"
2078+-- preambleBlock = void comment
2079+-- <|> void sp
2080+-- <|> void blanklines
2081+-- <|> void include
2082+-- <|> void macro
2083+-- <|> void blockCommand
2084+-- <|> void anyControlSeq
2085+-- <|> void braced
2086+-- <|> void anyChar
2087+--
2088+-- -------
2089+--
2090+-- -- citations
2091+--
2092+-- addPrefix :: [Inline] -> [Citation] -> [Citation]
2093+-- addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
2094+-- addPrefix _ _ = []
2095+--
2096+-- addSuffix :: [Inline] -> [Citation] -> [Citation]
2097+-- addSuffix s ks@(_:_) =
2098+-- let k = last ks
2099+-- in init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
2100+-- addSuffix _ _ = []
2101+--
2102+-- simpleCiteArgs :: PandocMonad m => LP m [Citation]
2103+-- simpleCiteArgs = try $ do
2104+-- first <- optionMaybe $ toList <$> opt
2105+-- second <- optionMaybe $ toList <$> opt
2106+-- keys <- try $ bgroup *> (manyTill citationLabel egroup)
2107+-- let (pre, suf) = case (first , second ) of
2108+-- (Just s , Nothing) -> (mempty, s )
2109+-- (Just s , Just t ) -> (s , t )
2110+-- _ -> (mempty, mempty)
2111+-- conv k = Citation { citationId = k
2112+-- , citationPrefix = []
2113+-- , citationSuffix = []
2114+-- , citationMode = NormalCitation
2115+-- , citationHash = 0
2116+-- , citationNoteNum = 0
2117+-- }
2118+-- return $ addPrefix pre $ addSuffix suf $ map conv keys
2119+--
2120+-- citationLabel :: PandocMonad m => LP m String
2121+-- citationLabel = optional sp *>
2122+-- (many1 (satisfy isBibtexKeyChar)
2123+-- <* optional sp
2124+-- <* optional (char ',')
2125+-- <* optional sp)
2126+-- where isBibtexKeyChar c = isAlphaNum c || c `elem` (".:;?!`'()/*@_+=-[]" :: String)
2127+--
2128+-- cites :: PandocMonad m => CitationMode -> Bool -> LP m [Citation]
2129+-- cites mode multi = try $ do
2130+-- cits <- if multi
2131+-- then many1 simpleCiteArgs
2132+-- else count 1 simpleCiteArgs
2133+-- let cs = concat cits
2134+-- return $ case mode of
2135+-- AuthorInText -> case cs of
2136+-- (c:rest) -> c {citationMode = mode} : rest
2137+-- [] -> []
2138+-- _ -> map (\a -> a {citationMode = mode}) cs
2139+--
2140+-- citation :: PandocMonad m => String -> CitationMode -> Bool -> LP m Inlines
2141+-- citation name mode multi = do
2142+-- (c,raw) <- withRaw $ cites mode multi
2143+-- return $ cite c (rawInline "latex" $ "\\" ++ name ++ raw)
2144+--
2145+-- complexNatbibCitation :: PandocMonad m => CitationMode -> LP m Inlines
2146+-- complexNatbibCitation mode = try $ do
2147+-- let ils = (toList . trimInlines . mconcat) <$>
2148+-- many (notFollowedBy (oneOf "\\};") >> inline)
2149+-- let parseOne = try $ do
2150+-- skipSpaces
2151+-- pref <- ils
2152+-- cit' <- inline -- expect a citation
2153+-- let citlist = toList cit'
2154+-- cits' <- case citlist of
2155+-- [Cite cs _] -> return cs
2156+-- _ -> mzero
2157+-- suff <- ils
2158+-- skipSpaces
2159+-- optional $ char ';'
2160+-- return $ addPrefix pref $ addSuffix suff cits'
2161+-- (c:cits, raw) <- withRaw $ grouped parseOne
2162+-- return $ cite (c{ citationMode = mode }:cits)
2163+-- (rawInline "latex" $ "\\citetext" ++ raw)
2164+--
2165+-- -- tables
2166+--
2167+-- parseAligns :: PandocMonad m => LP m [(Alignment, Double, (String, String))]
2168+-- parseAligns = try $ do
2169+-- bgroup
2170+-- let maybeBar = skipMany $ sp <|> () <$ char '|' <|> () <$ (char '@' >> braced)
2171+-- maybeBar
2172+-- let cAlign = AlignCenter <$ char 'c'
2173+-- let lAlign = AlignLeft <$ char 'l'
2174+-- let rAlign = AlignRight <$ char 'r'
2175+-- let parAlign = AlignLeft <$ char 'p'
2176+-- -- algins from tabularx
2177+-- let xAlign = AlignLeft <$ char 'X'
2178+-- let mAlign = AlignLeft <$ char 'm'
2179+-- let bAlign = AlignLeft <$ char 'b'
2180+-- let alignChar = cAlign <|> lAlign <|> rAlign <|> parAlign
2181+-- <|> xAlign <|> mAlign <|> bAlign
2182+-- let alignPrefix = char '>' >> braced
2183+-- let alignSuffix = char '<' >> braced
2184+-- let colWidth = try $ do
2185+-- char '{'
2186+-- ds <- many1 (oneOf "0123456789.")
2187+-- spaces
2188+-- string "\\linewidth"
2189+-- char '}'
2190+-- case safeRead ds of
2191+-- Just w -> return w
2192+-- Nothing -> return 0.0
2193+-- let alignSpec = do
2194+-- spaces
2195+-- pref <- option "" alignPrefix
2196+-- spaces
2197+-- al <- alignChar
2198+-- width <- colWidth <|> option 0.0 (do s <- braced
2199+-- pos <- getPosition
2200+-- report $ SkippedContent s pos
2201+-- return 0.0)
2202+-- spaces
2203+-- suff <- option "" alignSuffix
2204+-- return (al, width, (pref, suff))
2205+-- aligns' <- sepEndBy alignSpec maybeBar
2206+-- spaces
2207+-- egroup
2208+-- spaces
2209+-- return $ aligns'
2210+--
2211+-- hline :: PandocMonad m => LP m ()
2212+-- hline = try $ do
2213+-- spaces'
2214+-- controlSeq "hline" <|>
2215+-- -- booktabs rules:
2216+-- controlSeq "toprule" <|>
2217+-- controlSeq "bottomrule" <|>
2218+-- controlSeq "midrule" <|>
2219+-- controlSeq "endhead" <|>
2220+-- controlSeq "endfirsthead"
2221+-- spaces'
2222+-- optional $ bracketed (many1 (satisfy (/=']')))
2223+-- return ()
2224+--
2225+-- lbreak :: PandocMonad m => LP m ()
2226+-- lbreak = () <$ try (spaces' *>
2227+-- (controlSeq "\\" <|> controlSeq "tabularnewline") <*
2228+-- spaces')
2229+--
2230+-- amp :: PandocMonad m => LP m ()
2231+-- amp = () <$ try (spaces' *> char '&' <* spaces')
2232+--
2233+-- parseTableRow :: PandocMonad m
2234+-- => String -- ^ table environment name
2235+-- -> [(String, String)] -- ^ pref/suffixes
2236+-- -> LP m [Blocks]
2237+-- parseTableRow envname prefsufs = try $ do
2238+-- let cols = length prefsufs
2239+-- let tableCellRaw = concat <$> many
2240+-- (do notFollowedBy amp
2241+-- notFollowedBy lbreak
2242+-- notFollowedBy $ () <$ try (string ("\\end{" ++ envname ++ "}"))
2243+-- many1 (noneOf "&%\n\r\\")
2244+-- <|> try (string "\\&")
2245+-- <|> count 1 anyChar)
2246+-- let plainify bs = case toList bs of
2247+-- [Para ils] -> plain (fromList ils)
2248+-- _ -> bs
2249+-- rawcells <- sepBy1 tableCellRaw amp
2250+-- guard $ length rawcells == cols
2251+-- let rawcells' = zipWith (\c (p, s) -> p ++ trim c ++ s) rawcells prefsufs
2252+-- let tableCell = plainify <$> blocks
2253+-- cells' <- mapM (parseFromString' tableCell) rawcells'
2254+-- let numcells = length cells'
2255+-- guard $ numcells <= cols && numcells >= 1
2256+-- guard $ cells' /= [mempty]
2257+-- -- note: a & b in a three-column table leaves an empty 3rd cell:
2258+-- let cells'' = cells' ++ replicate (cols - numcells) mempty
2259+-- spaces'
2260+-- return cells''
2261+--
2262+-- spaces' :: PandocMonad m => LP m ()
2263+-- spaces' = spaces *> skipMany (comment *> spaces)
2264+--
2265+-- simpTable :: PandocMonad m => String -> Bool -> LP m Blocks
2266+-- simpTable envname hasWidthParameter = try $ do
2267+-- when hasWidthParameter $ () <$ (spaces' >> tok)
2268+-- skipopts
2269+-- colspecs <- parseAligns
2270+-- let (aligns, widths, prefsufs) = unzip3 colspecs
2271+-- let cols = length colspecs
2272+-- optional $ controlSeq "caption" *> skipopts *> setCaption
2273+-- optional lbreak
2274+-- spaces'
2275+-- skipMany hline
2276+-- spaces'
2277+-- header' <- option [] $ try (parseTableRow envname prefsufs <*
2278+-- lbreak <* many1 hline)
2279+-- spaces'
2280+-- rows <- sepEndBy (parseTableRow envname prefsufs)
2281+-- (lbreak <* optional (skipMany hline))
2282+-- spaces'
2283+-- optional $ controlSeq "caption" *> skipopts *> setCaption
2284+-- optional lbreak
2285+-- spaces'
2286+-- let header'' = if null header'
2287+-- then replicate cols mempty
2288+-- else header'
2289+-- lookAhead $ controlSeq "end" -- make sure we're at end
2290+-- return $ table mempty (zip aligns widths) header'' rows
2291+--
2292+-- removeDoubleQuotes :: String -> String
2293+-- removeDoubleQuotes ('"':xs) =
2294+-- case reverse xs of
2295+-- '"':ys -> reverse ys
2296+-- _ -> '"':xs
2297+-- removeDoubleQuotes xs = xs
2298+--
2299+-- inputListing :: PandocMonad m => LP m Blocks
2300+-- inputListing = do
2301+-- pos <- getPosition
2302+-- options <- option [] keyvals
2303+-- f <- filter (/='"') <$> braced
2304+-- dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
2305+-- mbCode <- readFileFromDirs dirs f
2306+-- codeLines <- case mbCode of
2307+-- Just s -> return $ lines s
2308+-- Nothing -> do
2309+-- report $ CouldNotLoadIncludeFile f pos
2310+-- return []
2311+-- let (ident,classes,kvs) = parseListingsOptions options
2312+-- let language = case lookup "language" options >>= fromListingsLanguage of
2313+-- Just l -> [l]
2314+-- Nothing -> take 1 $ languagesByExtension (takeExtension f)
2315+-- let firstline = fromMaybe 1 $ lookup "firstline" options >>= safeRead
2316+-- let lastline = fromMaybe (length codeLines) $
2317+-- lookup "lastline" options >>= safeRead
2318+-- let codeContents = intercalate "\n" $ take (1 + lastline - firstline) $
2319+-- drop (firstline - 1) codeLines
2320+-- return $ codeBlockWith (ident,ordNub (classes ++ language),kvs) codeContents
2321+--
2322+-- parseListingsOptions :: [(String, String)] -> Attr
2323+-- parseListingsOptions options =
2324+-- let kvs = [ (if k == "firstnumber"
2325+-- then "startFrom"
2326+-- else k, v) | (k,v) <- options ]
2327+-- classes = [ "numberLines" |
2328+-- lookup "numbers" options == Just "left" ]
2329+-- ++ maybeToList (lookup "language" options
2330+-- >>= fromListingsLanguage)
2331+-- in (fromMaybe "" (lookup "label" options), classes, kvs)
2332+-}